Initial update
|
|
@ -0,0 +1,15 @@
|
|||
# ============================================================
|
||||
# Panacea Mobile App (Expo) Environment Configuration
|
||||
# Copy this file to .env:
|
||||
# cp .env.example .env
|
||||
# ============================================================
|
||||
|
||||
# ---- Production Backend API ----
|
||||
# EXPO_PUBLIC_API_URL=https://api.acupedia.in/api
|
||||
|
||||
# ---- Local Standalone Backend (FastAPI on Port 8000) ----
|
||||
# For Local Web: http://localhost:8000/api
|
||||
# For Physical Mobile Devices: http://YOUR_LOCAL_IP:8000/api
|
||||
EXPO_PUBLIC_API_URL=http://localhost:8000/api
|
||||
EXPO_PUBLIC_BACKEND_PORT=8000
|
||||
EXPO_PUBLIC_MEDIA_BASE_URL=http://localhost:9000/
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# Expo
|
||||
.expo/
|
||||
dist/
|
||||
web-build/
|
||||
expo-env.d.ts
|
||||
|
||||
# Native
|
||||
.kotlin/
|
||||
*.orig.*
|
||||
*.jks
|
||||
*.p8
|
||||
*.p12
|
||||
*.key
|
||||
*.mobileprovision
|
||||
|
||||
# Metro
|
||||
.metro-health-check*
|
||||
|
||||
# debug
|
||||
npm-debug.*
|
||||
yarn-debug.*
|
||||
yarn-error.*
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
|
||||
example
|
||||
|
||||
# generated native folders
|
||||
/ios
|
||||
/android
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
56
README.md
|
|
@ -0,0 +1,56 @@
|
|||
# Welcome to your Expo app 👋
|
||||
|
||||
This is an [Expo](https://expo.dev) project created with [`create-expo-app`](https://www.npmjs.com/package/create-expo-app).
|
||||
|
||||
## Get started
|
||||
|
||||
1. Install dependencies
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Start the app
|
||||
|
||||
```bash
|
||||
npx expo start
|
||||
```
|
||||
|
||||
In the output, you'll find options to open the app in a
|
||||
|
||||
- [development build](https://docs.expo.dev/develop/development-builds/introduction/)
|
||||
- [Android emulator](https://docs.expo.dev/workflow/android-studio-emulator/)
|
||||
- [iOS simulator](https://docs.expo.dev/workflow/ios-simulator/)
|
||||
- [Expo Go](https://expo.dev/go), a limited sandbox for trying out app development with Expo
|
||||
|
||||
You can start developing by editing the files inside the **app** directory. This project uses [file-based routing](https://docs.expo.dev/router/introduction).
|
||||
|
||||
## Get a fresh project
|
||||
|
||||
When you're ready, run:
|
||||
|
||||
```bash
|
||||
npm run reset-project
|
||||
```
|
||||
|
||||
This command will move the starter code to the **app-example** directory and create a blank **app** directory where you can start developing.
|
||||
|
||||
### Other setup steps
|
||||
|
||||
- To set up ESLint for linting, run `npx expo lint`, or follow our guide on ["Using ESLint and Prettier"](https://docs.expo.dev/guides/using-eslint/)
|
||||
- If you'd like to set up unit testing, follow our guide on ["Unit Testing with Jest"](https://docs.expo.dev/develop/unit-testing/)
|
||||
- Learn more about the TypeScript setup in this template in our guide on ["Using TypeScript"](https://docs.expo.dev/guides/typescript/)
|
||||
|
||||
## Learn more
|
||||
|
||||
To learn more about developing your project with Expo, look at the following resources:
|
||||
|
||||
- [Expo documentation](https://docs.expo.dev/): Learn fundamentals, or go into advanced topics with our [guides](https://docs.expo.dev/guides).
|
||||
- [Learn Expo tutorial](https://docs.expo.dev/tutorial/introduction/): Follow a step-by-step tutorial where you'll create a project that runs on Android, iOS, and the web.
|
||||
|
||||
## Join the community
|
||||
|
||||
Join our community of developers creating universal apps.
|
||||
|
||||
- [Expo on GitHub](https://github.com/expo/expo): View our open source platform and contribute.
|
||||
- [Discord community](https://chat.expo.dev): Chat with Expo users and ask questions.
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
{
|
||||
"expo": {
|
||||
"name": "acupedia",
|
||||
"slug": "acupedia",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/images/icon.png",
|
||||
"scheme": "myapp",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"ios": {
|
||||
"icon": "./assets/expo.icon"
|
||||
},
|
||||
"android": {
|
||||
"adaptiveIcon": {
|
||||
"backgroundColor": "#E6F4FE",
|
||||
"foregroundImage": "./assets/images/android-icon-foreground.png",
|
||||
"backgroundImage": "./assets/images/android-icon-background.png",
|
||||
"monochromeImage": "./assets/images/android-icon-monochrome.png"
|
||||
},
|
||||
"predictiveBackGestureEnabled": false
|
||||
},
|
||||
"web": {
|
||||
"output": "static",
|
||||
"favicon": "./assets/images/favicon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
"backgroundColor": "#208AEF",
|
||||
"image": "./assets/images/splash-icon.png",
|
||||
"imageWidth": 76
|
||||
}
|
||||
]
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true,
|
||||
"reactCompiler": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="652" height="606" viewBox="0 0 652 606" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M353.554 0H298.446C273.006 0 249.684 14.6347 237.962 37.9539L4.37994 502.646C-1.04325 513.435 -1.45067 526.178 3.2716 537.313L22.6123 582.918C34.6475 611.297 72.5404 614.156 88.4414 587.885L309.863 222.063C313.34 216.317 319.439 212.826 326 212.826C332.561 212.826 338.659 216.317 342.137 222.063L563.559 587.885C579.46 614.156 617.352 611.297 629.388 582.918L648.728 537.313C653.451 526.178 653.043 513.435 647.62 502.646L414.038 37.9539C402.316 14.6347 378.994 0 353.554 0Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 608 B |
|
After Width: | Height: | Size: 52 KiB |
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"fill" : {
|
||||
"automatic-gradient" : "extended-srgb:0.00000,0.47843,1.00000,1.00000"
|
||||
},
|
||||
"groups" : [
|
||||
{
|
||||
"layers" : [
|
||||
{
|
||||
"image-name" : "expo-symbol 2.svg",
|
||||
"name" : "expo-symbol 2",
|
||||
"position" : {
|
||||
"scale" : 1,
|
||||
"translation-in-points" : [
|
||||
1.1008400065293245e-05,
|
||||
-16.046875
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"image-name" : "grid.png",
|
||||
"name" : "grid"
|
||||
}
|
||||
],
|
||||
"shadow" : {
|
||||
"kind" : "neutral",
|
||||
"opacity" : 0.5
|
||||
},
|
||||
"translucency" : {
|
||||
"enabled" : true,
|
||||
"value" : 0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"supported-platforms" : {
|
||||
"circles" : [
|
||||
"watchOS"
|
||||
],
|
||||
"squares" : "shared"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 780 KiB |
|
After Width: | Height: | Size: 324 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 215 B |
|
After Width: | Height: | Size: 347 B |
|
After Width: | Height: | Size: 468 B |
|
After Width: | Height: | Size: 253 B |
|
After Width: | Height: | Size: 343 B |
|
After Width: | Height: | Size: 479 B |
|
After Width: | Height: | Size: 58 KiB |
|
|
@ -0,0 +1,54 @@
|
|||
{
|
||||
"name": "my-app",
|
||||
"main": "expo-router/entry",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@expo/ui": "~57.0.16",
|
||||
"expo": "~57.0.20",
|
||||
"expo-constants": "~57.0.17",
|
||||
"expo-device": "~57.0.1",
|
||||
"expo-font": "~57.0.3",
|
||||
"expo-glass-effect": "~57.0.1",
|
||||
"expo-image": "~57.0.4",
|
||||
"expo-linking": "~57.0.9",
|
||||
"expo-router": "~57.0.19",
|
||||
"expo-splash-screen": "~57.0.8",
|
||||
"expo-status-bar": "~57.0.1",
|
||||
"expo-symbols": "~57.0.2",
|
||||
"expo-system-ui": "~57.0.3",
|
||||
"expo-web-browser": "~57.0.2",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-native": "0.86.3",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-reanimated": "4.5.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "~4.26.0",
|
||||
"react-native-web": "~0.21.0",
|
||||
"react-native-worklets": "0.10.1",
|
||||
"@expo-google-fonts/inter": "^0.4.2",
|
||||
"@expo/vector-icons": "^15.0.2",
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"@react-native-community/netinfo": "12.0.1",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"axios": "^1.18.1",
|
||||
"expo-linear-gradient": "~57.0.1",
|
||||
"expo-secure-store": "~57.0.2",
|
||||
"react-native-size-matters": "^0.4.2",
|
||||
"react-native-toast-message": "^2.3.3",
|
||||
"zustand": "^4.5.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.2",
|
||||
"typescript": "~6.0.3"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"reset-project": "node ./scripts/reset-project.js",
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web",
|
||||
"lint": "expo lint"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* Process-local access-token bridge used by the HTTP client.
|
||||
*
|
||||
* IMPORTANT:
|
||||
* - This module must never import Zustand or any API client.
|
||||
* - The auth store writes the current access token here.
|
||||
* - api/client.ts reads it from here.
|
||||
*
|
||||
* This deliberately breaks the dependency cycle:
|
||||
* auth.store -> api client -> auth.store
|
||||
*/
|
||||
|
||||
let currentAccessToken: string | null = null;
|
||||
|
||||
export function setApiAccessToken(token: string | null | undefined): void {
|
||||
const normalized = typeof token === "string" ? token.trim() : "";
|
||||
currentAccessToken = normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
export function getApiAccessToken(): string | null {
|
||||
return currentAccessToken;
|
||||
}
|
||||
|
||||
export function clearApiAccessToken(): void {
|
||||
currentAccessToken = null;
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import axios from "axios";
|
||||
|
||||
import { getApiAccessToken } from "@/api/access-token";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL:
|
||||
process.env.EXPO_PUBLIC_API_URL ??
|
||||
process.env.EXPO_PUBLIC_API_BASE_URL ??
|
||||
"http://localhost:8000/api",
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"Bypass-Tunnel-Reminder": "true",
|
||||
},
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = getApiAccessToken();
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error),
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
export const API_ENDPOINTS = {
|
||||
AUTH: {
|
||||
REGISTER: "/auth/register",
|
||||
LOGIN: "/auth/login",
|
||||
ME: "/auth/me",
|
||||
PROFILE: "/auth/profile",
|
||||
CHANGE_PASSWORD: "/auth/change-password",
|
||||
FORGOT_PASSWORD: "/auth/forgot-password",
|
||||
RESET_PASSWORD: "/auth/reset-password",
|
||||
},
|
||||
|
||||
ACCESS: {
|
||||
ME: "/access/me",
|
||||
},
|
||||
|
||||
CART: {
|
||||
CALCULATE: "/cart/calculate",
|
||||
},
|
||||
|
||||
CHECKOUT: {
|
||||
CONFIG: "/checkout/config",
|
||||
CREATE_ORDER: "/checkout/create-order",
|
||||
VERIFY: "/checkout/verify",
|
||||
INVOICE: (paymentId: string) => `/checkout/payment/${encodeURIComponent(paymentId)}/invoice`,
|
||||
},
|
||||
|
||||
MODULE: "/module",
|
||||
CONTENTS: "/contents",
|
||||
MODULES: "/contents/modules",
|
||||
MODULE_CONTENTS: "/contents/module-contents",
|
||||
MODULE_TEMPLATE_CONTENTS: "/contents/module-template-contents",
|
||||
MODULE_TEMPLATE_CONTENT_DETAILS: "/contents/module-template-content-details",
|
||||
TEMPLATES: "/contents/templates",
|
||||
|
||||
} as const;
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
import axios, { AxiosError, AxiosHeaders, AxiosInstance, AxiosRequestConfig } from "axios";
|
||||
import { ApiError, ApiErrorPayload } from "./types";
|
||||
|
||||
export type AccessTokenProvider = () => string | null | Promise<string | null>;
|
||||
|
||||
export interface HttpClientOptions {
|
||||
baseURL: string;
|
||||
timeoutMs?: number;
|
||||
accessTokenProvider?: AccessTokenProvider;
|
||||
}
|
||||
|
||||
function normalizeApiError(error: unknown): ApiError {
|
||||
if (!axios.isAxiosError(error)) {
|
||||
return new ApiError({
|
||||
message: "Unexpected client error.",
|
||||
status: null,
|
||||
code: null,
|
||||
details: null,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const axiosError = error as AxiosError<ApiErrorPayload>;
|
||||
const payload = axiosError.response?.data;
|
||||
const detail = payload?.detail ?? null;
|
||||
|
||||
return new ApiError({
|
||||
message:
|
||||
typeof detail === "string" && detail.trim()
|
||||
? detail
|
||||
: axiosError.message || "Request failed.",
|
||||
status: axiosError.response?.status ?? null,
|
||||
code: payload?.code ?? axiosError.code ?? null,
|
||||
details: detail,
|
||||
cause: axiosError,
|
||||
});
|
||||
}
|
||||
|
||||
export function createHttpClient(options: HttpClientOptions): AxiosInstance {
|
||||
const client = axios.create({
|
||||
baseURL: options.baseURL.replace(/\/+$/, ""),
|
||||
timeout: options.timeoutMs ?? 20_000,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
client.interceptors.request.use(async (config) => {
|
||||
if (!options.accessTokenProvider) return config;
|
||||
|
||||
const token = await options.accessTokenProvider();
|
||||
if (!token) return config;
|
||||
|
||||
const headers = AxiosHeaders.from(config.headers);
|
||||
headers.set("Authorization", `Bearer ${token}`);
|
||||
config.headers = headers;
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
client.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error: unknown) => Promise.reject(normalizeApiError(error)),
|
||||
);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
export async function request<T>(
|
||||
client: AxiosInstance,
|
||||
config: AxiosRequestConfig,
|
||||
): Promise<T> {
|
||||
const response = await client.request<T>(config);
|
||||
return response.data;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export { default as apiClient } from "./client";
|
||||
export * from "./endpoints";
|
||||
export * from "./types";
|
||||
|
||||
import "./interceptors";
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import apiClient from "./client";
|
||||
|
||||
apiClient.interceptors.request.use(
|
||||
async (config) => {
|
||||
return config;
|
||||
},
|
||||
async (error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
export interface ApiValidationIssue {
|
||||
type?: string;
|
||||
loc?: Array<string | number>;
|
||||
msg?: string;
|
||||
input?: unknown;
|
||||
ctx?: unknown;
|
||||
}
|
||||
|
||||
export interface ApiErrorPayload {
|
||||
detail?: string | ApiValidationIssue[] | unknown;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number | null;
|
||||
readonly code: string | null;
|
||||
readonly details: unknown;
|
||||
readonly cause?: unknown;
|
||||
|
||||
constructor(init: {
|
||||
message: string;
|
||||
status: number | null;
|
||||
code: string | null;
|
||||
details: unknown;
|
||||
cause?: unknown;
|
||||
}) {
|
||||
super(init.message);
|
||||
this.name = "ApiError";
|
||||
this.status = init.status;
|
||||
this.code = init.code;
|
||||
this.details = init.details;
|
||||
this.cause = init.cause;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
import { Tabs, router } from "expo-router";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { Alert } from "react-native";
|
||||
import { AuthColors } from "@/features/auth/constants/colors";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useAuthStore } from "@/store/auth.store";
|
||||
|
||||
export default function TabsLayout() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const bottomPadding = insets.bottom > 0 ? insets.bottom : 8;
|
||||
const tabBarHeight = 52 + bottomPadding;
|
||||
|
||||
const { accessToken, logout } = useAuthStore();
|
||||
const isAuthenticated = !!accessToken;
|
||||
|
||||
const handleAuthAction = () => {
|
||||
if (isAuthenticated) {
|
||||
Alert.alert(
|
||||
"Logout",
|
||||
"Are you sure you want to logout?",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Yes",
|
||||
style: "destructive",
|
||||
onPress: () => {
|
||||
logout();
|
||||
router.replace("/login");
|
||||
},
|
||||
},
|
||||
],
|
||||
{ cancelable: true }
|
||||
);
|
||||
} else {
|
||||
router.push("/login");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
tabBarActiveTintColor: AuthColors.primary,
|
||||
tabBarInactiveTintColor: AuthColors.textSecondary,
|
||||
tabBarStyle: {
|
||||
backgroundColor: "#FFFFFF",
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: "#E5E7EB",
|
||||
height: tabBarHeight,
|
||||
paddingBottom: bottomPadding,
|
||||
paddingTop: 8,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
options={{
|
||||
title: "Home",
|
||||
tabBarIcon: ({ color, focused }) => (
|
||||
<Ionicons
|
||||
name={focused ? "home" : "home-outline"}
|
||||
size={22}
|
||||
color={color}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Tabs.Screen
|
||||
name="auth-action"
|
||||
options={{
|
||||
title: isAuthenticated ? "Logout" : "Login",
|
||||
tabBarIcon: ({ color, focused }) => (
|
||||
<Ionicons
|
||||
name={
|
||||
focused
|
||||
? isAuthenticated
|
||||
? "log-out"
|
||||
: "log-in"
|
||||
: isAuthenticated
|
||||
? "log-out-outline"
|
||||
: "log-in-outline"
|
||||
}
|
||||
size={22}
|
||||
color={color}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
listeners={{
|
||||
tabPress: (e) => {
|
||||
e.preventDefault();
|
||||
handleAuthAction();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import React from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
export default function AuthActionScreen() {
|
||||
return <View style={{ flex: 1, backgroundColor: "#FFFFFF" }} />;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import HomeScreen from "@/screens/home/HomeScreen";
|
||||
|
||||
export default function TabsIndex() {
|
||||
return <HomeScreen />;
|
||||
}
|
||||
|
|
@ -0,0 +1,304 @@
|
|||
import React, { useCallback, useEffect, useMemo } from "react";
|
||||
import {
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
TouchableOpacity,
|
||||
} from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { router, useFocusEffect } from "expo-router";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
import { useAuthStore } from "@/store/auth.store";
|
||||
import { useModulesQuery } from "@/features/content/hooks/use-content-queries";
|
||||
import { buildContentReferenceRoute } from "@/features/content/utils/content-reference";
|
||||
import { isModuleUnlockedByAccess } from "@/features/access/module-access";
|
||||
import {
|
||||
ModuleIndexItem,
|
||||
normalizeModuleListResponse,
|
||||
toModuleIndexItem,
|
||||
} from "@/features/modules/module-index";
|
||||
|
||||
export default function LibraryScreen() {
|
||||
const {
|
||||
access,
|
||||
accessToken,
|
||||
refreshAccess,
|
||||
setModules,
|
||||
setLastViewedModule,
|
||||
} = useAuthStore();
|
||||
|
||||
const modulesQuery = useModulesQuery();
|
||||
const modules = useMemo(
|
||||
() => normalizeModuleListResponse(modulesQuery.data),
|
||||
[modulesQuery.data],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setModules(
|
||||
modules.map((module) => {
|
||||
const item = toModuleIndexItem(module);
|
||||
return {
|
||||
id: module.id,
|
||||
code: module.code,
|
||||
slug: module.slug,
|
||||
isDefaultFree: item.isDefaultFree,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}, [modules, setModules]);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (accessToken) {
|
||||
void refreshAccess();
|
||||
}
|
||||
}, [accessToken, refreshAccess]),
|
||||
);
|
||||
|
||||
const items = useMemo(
|
||||
() => modules.filter((module) => module.is_active).map(toModuleIndexItem),
|
||||
[modules],
|
||||
);
|
||||
|
||||
const unlockedModules = useMemo(() => {
|
||||
if (!accessToken) return [];
|
||||
|
||||
return items.filter((item) =>
|
||||
isModuleUnlockedByAccess(item.module, access),
|
||||
);
|
||||
}, [access, accessToken, items]);
|
||||
|
||||
const categories = useMemo(
|
||||
() => Array.from(new Set(unlockedModules.map((item) => item.category))),
|
||||
[unlockedModules],
|
||||
);
|
||||
|
||||
const handleModulePress = useCallback(
|
||||
(item: ModuleIndexItem) => {
|
||||
setLastViewedModule({
|
||||
moduleId: item.module.id,
|
||||
moduleCode: item.module.code,
|
||||
moduleSlug: item.module.slug,
|
||||
entryTemplateCode: item.reference.target.template_code,
|
||||
title: item.title,
|
||||
description: item.description,
|
||||
icon: item.icon,
|
||||
color: item.color,
|
||||
category: item.category,
|
||||
});
|
||||
|
||||
router.push(buildContentReferenceRoute(item.reference) as never);
|
||||
},
|
||||
[setLastViewedModule],
|
||||
);
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.safeArea}>
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.title}>Your Library</Text>
|
||||
|
||||
<View style={styles.unlockedBox}>
|
||||
<Text style={styles.unlockedCount}>{unlockedModules.length}</Text>
|
||||
<Text style={styles.unlockedText}>Modules Unlocked</Text>
|
||||
</View>
|
||||
|
||||
{unlockedModules.length === 0 ? (
|
||||
<View style={styles.emptyContainer}>
|
||||
<View style={styles.iconWrapper}>
|
||||
<Ionicons name="book-outline" size={48} color={Colors.textSecondary} />
|
||||
</View>
|
||||
<Text style={styles.emptyTitle}>Your Library is Empty</Text>
|
||||
<Text style={styles.emptySubtitle}>
|
||||
Explore all modules on the Home dashboard to unlock premium content.
|
||||
</Text>
|
||||
<TouchableOpacity onPress={() => router.push("/modules")}>
|
||||
<Text style={styles.exploreText}>Explore Modules</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
) : (
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
>
|
||||
{categories.map((category) => {
|
||||
const categoryModules = unlockedModules.filter(
|
||||
(item) => item.category === category,
|
||||
);
|
||||
|
||||
return (
|
||||
<View key={category} style={styles.categorySection}>
|
||||
<Text style={styles.categoryTitle}>{category}</Text>
|
||||
<View style={styles.card}>
|
||||
{categoryModules.map((item, index) => (
|
||||
<View key={item.module.id}>
|
||||
<TouchableOpacity
|
||||
style={styles.row}
|
||||
onPress={() => handleModulePress(item)}
|
||||
>
|
||||
<View
|
||||
style={[
|
||||
styles.iconWrapperSmall,
|
||||
{ backgroundColor: `${item.color}15` },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={item.icon as never}
|
||||
size={22}
|
||||
color={item.color}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.textContainer}>
|
||||
<Text style={styles.moduleTitle}>{item.title}</Text>
|
||||
<Text style={styles.moduleDesc} numberOfLines={1}>
|
||||
{item.description}
|
||||
</Text>
|
||||
</View>
|
||||
<Ionicons
|
||||
name="chevron-forward"
|
||||
size={18}
|
||||
color={Colors.textSecondary}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
{index < categoryModules.length - 1 ? (
|
||||
<View style={styles.separator} />
|
||||
) : null}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
)}
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
safeArea: {
|
||||
flex: 1,
|
||||
backgroundColor: Colors.background,
|
||||
},
|
||||
container: {
|
||||
flex: 1,
|
||||
paddingHorizontal: moderateScale(24),
|
||||
paddingTop: verticalScale(20),
|
||||
},
|
||||
title: {
|
||||
fontSize: moderateScale(22),
|
||||
fontWeight: "700",
|
||||
color: Colors.textPrimary,
|
||||
marginBottom: verticalScale(16),
|
||||
},
|
||||
unlockedBox: {
|
||||
backgroundColor: "#F3F4F6",
|
||||
borderRadius: moderateScale(14),
|
||||
padding: moderateScale(14),
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
marginBottom: verticalScale(24),
|
||||
},
|
||||
unlockedCount: {
|
||||
fontSize: moderateScale(22),
|
||||
fontWeight: "800",
|
||||
color: Colors.primary,
|
||||
marginRight: moderateScale(12),
|
||||
},
|
||||
unlockedText: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "600",
|
||||
color: Colors.textPrimary,
|
||||
},
|
||||
emptyContainer: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
paddingBottom: verticalScale(80),
|
||||
},
|
||||
iconWrapper: {
|
||||
width: moderateScale(90),
|
||||
height: moderateScale(90),
|
||||
borderRadius: moderateScale(45),
|
||||
backgroundColor: "#F3F4F6",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
marginBottom: verticalScale(16),
|
||||
},
|
||||
emptyTitle: {
|
||||
fontSize: moderateScale(18),
|
||||
fontWeight: "700",
|
||||
color: Colors.textPrimary,
|
||||
marginBottom: verticalScale(6),
|
||||
},
|
||||
emptySubtitle: {
|
||||
fontSize: moderateScale(13),
|
||||
color: Colors.textSecondary,
|
||||
textAlign: "center",
|
||||
lineHeight: 18,
|
||||
paddingHorizontal: moderateScale(16),
|
||||
marginBottom: verticalScale(16),
|
||||
},
|
||||
exploreText: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "700",
|
||||
color: Colors.primary,
|
||||
},
|
||||
scrollContent: {
|
||||
paddingBottom: verticalScale(24),
|
||||
},
|
||||
card: {
|
||||
backgroundColor: "#FFFFFF",
|
||||
borderRadius: moderateScale(16),
|
||||
borderWidth: 1,
|
||||
borderColor: "#E5E7EB",
|
||||
overflow: "hidden",
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
padding: moderateScale(14),
|
||||
},
|
||||
iconWrapperSmall: {
|
||||
width: moderateScale(40),
|
||||
height: moderateScale(40),
|
||||
borderRadius: moderateScale(20),
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
textContainer: {
|
||||
flex: 1,
|
||||
marginLeft: moderateScale(12),
|
||||
marginRight: moderateScale(12),
|
||||
},
|
||||
moduleTitle: {
|
||||
fontSize: moderateScale(15),
|
||||
fontWeight: "600",
|
||||
color: Colors.textPrimary,
|
||||
marginBottom: 2,
|
||||
},
|
||||
moduleDesc: {
|
||||
fontSize: moderateScale(12),
|
||||
color: Colors.textSecondary,
|
||||
},
|
||||
separator: {
|
||||
height: 1,
|
||||
backgroundColor: "#F3F4F6",
|
||||
},
|
||||
categorySection: {
|
||||
marginBottom: verticalScale(20),
|
||||
},
|
||||
categoryTitle: {
|
||||
fontSize: moderateScale(12),
|
||||
fontWeight: "700",
|
||||
color: Colors.textSecondary,
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: 1,
|
||||
marginBottom: verticalScale(8),
|
||||
marginLeft: moderateScale(4),
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import ProfileOverviewScreen from "@/screens/profile/ProfileOverviewScreen";
|
||||
|
||||
export default function ProfileScreen() {
|
||||
return <ProfileOverviewScreen />;
|
||||
}
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
import { Stack } from "expo-router";
|
||||
import React from "react";
|
||||
import * as RN from "react-native";
|
||||
import {
|
||||
useFonts,
|
||||
Inter_400Regular,
|
||||
Inter_500Medium,
|
||||
Inter_600SemiBold,
|
||||
Inter_700Bold,
|
||||
} from "@expo-google-fonts/inter";
|
||||
|
||||
import { AppProvider } from "@/providers";
|
||||
|
||||
// Helper to resolve font family based on styles
|
||||
const resolveCustomStyle = (style: any) => {
|
||||
if (!style) {
|
||||
return { fontFamily: "Inter-Regular" };
|
||||
}
|
||||
|
||||
const flat = RN.StyleSheet.flatten(style);
|
||||
|
||||
// If fontFamily is already specified (like icons), don't override it!
|
||||
if (flat && flat.fontFamily && flat.fontFamily !== "System" && flat.fontFamily !== "sans-serif") {
|
||||
return style;
|
||||
}
|
||||
|
||||
// Map font weight to Inter weights
|
||||
const weight = flat?.fontWeight;
|
||||
let fontFamily = "Inter-Regular";
|
||||
|
||||
if (weight === "bold" || weight === "700" || weight === "800" || weight === "900") {
|
||||
fontFamily = "Inter-Bold";
|
||||
} else if (weight === "600") {
|
||||
fontFamily = "Inter-SemiBold";
|
||||
} else if (weight === "500") {
|
||||
fontFamily = "Inter-Medium";
|
||||
}
|
||||
|
||||
// Merge the new fontFamily with the rest of the styles
|
||||
return [
|
||||
style,
|
||||
{ fontFamily }
|
||||
];
|
||||
};
|
||||
|
||||
const OriginalText = RN.Text;
|
||||
const OriginalTextInput = RN.TextInput;
|
||||
|
||||
// Custom Text HOC
|
||||
const CustomText = React.forwardRef((props: any, ref: any) => {
|
||||
const { style, allowFontScaling, ...rest } = props;
|
||||
const newStyle = resolveCustomStyle(style);
|
||||
return (
|
||||
<OriginalText
|
||||
{...rest}
|
||||
ref={ref}
|
||||
style={newStyle}
|
||||
allowFontScaling={false}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
// Bind static props/methods if any
|
||||
Object.assign(CustomText, OriginalText);
|
||||
|
||||
try {
|
||||
const rnExports = require("react-native");
|
||||
const descText = Object.getOwnPropertyDescriptor(rnExports, "Text");
|
||||
if (descText && descText.configurable) {
|
||||
Object.defineProperty(rnExports, "Text", {
|
||||
get: () => CustomText,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// Silently ignore if module exports are immutable in web bundle environment
|
||||
}
|
||||
|
||||
// Custom TextInput HOC
|
||||
const CustomTextInput = React.forwardRef((props: any, ref: any) => {
|
||||
const { style, allowFontScaling, ...rest } = props;
|
||||
const newStyle = resolveCustomStyle(style);
|
||||
return (
|
||||
<OriginalTextInput
|
||||
{...rest}
|
||||
ref={ref}
|
||||
style={newStyle}
|
||||
allowFontScaling={false}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
Object.assign(CustomTextInput, OriginalTextInput);
|
||||
|
||||
try {
|
||||
const rnExports = require("react-native");
|
||||
const descInput = Object.getOwnPropertyDescriptor(rnExports, "TextInput");
|
||||
if (descInput && descInput.configurable) {
|
||||
Object.defineProperty(rnExports, "TextInput", {
|
||||
get: () => CustomTextInput,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// Silently ignore if module exports are immutable in web bundle environment
|
||||
}
|
||||
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
|
||||
export default function RootLayout() {
|
||||
const [fontsLoaded] = useFonts({
|
||||
"Inter-Regular": Inter_400Regular,
|
||||
"Inter-Medium": Inter_500Medium,
|
||||
"Inter-SemiBold": Inter_600SemiBold,
|
||||
"Inter-Bold": Inter_700Bold,
|
||||
});
|
||||
|
||||
if (!fontsLoaded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<AppProvider>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
</AppProvider>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { Redirect } from "expo-router";
|
||||
|
||||
export default function Index() {
|
||||
return <Redirect href="/(tabs)" />;
|
||||
}
|
||||
|
|
@ -0,0 +1,308 @@
|
|||
import React, { useState } from "react";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
Alert,
|
||||
Pressable,
|
||||
} from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { router } from "expo-router";
|
||||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||||
import { Colors } from "@/theme";
|
||||
import { AuthColors } from "@/features/auth/constants/colors";
|
||||
import BaseTextInput from "@/components/forms/BaseTextInput";
|
||||
import PasswordInput from "@/components/forms/PasswordInput";
|
||||
import PrimaryButton from "@/components/buttons/PrimaryButton";
|
||||
import FieldLabel from "@/components/forms/FieldLabel";
|
||||
import { forgotPassword, resetPassword } from "@/features/auth/api/auth.api";
|
||||
|
||||
export default function ForgotPasswordScreen() {
|
||||
const [step, setStep] = useState<"request" | "verify">("request");
|
||||
const [email, setEmail] = useState("");
|
||||
const [otpCode, setOtpCode] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
|
||||
const [emailError, setEmailError] = useState("");
|
||||
const [otpError, setOtpError] = useState("");
|
||||
const [passwordError, setPasswordError] = useState("");
|
||||
const [confirmError, setConfirmError] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleRequestOtp = async () => {
|
||||
setEmailError("");
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
if (!cleanEmail) {
|
||||
setEmailError("Email is required");
|
||||
return;
|
||||
}
|
||||
if (!/\S+@\S+\.\S+/.test(cleanEmail)) {
|
||||
setEmailError("Please enter a valid email address");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await forgotPassword({ email: cleanEmail });
|
||||
const msg = res.message || "Verification code sent! Check your inbox.";
|
||||
if (Platform.OS === "web") {
|
||||
window.alert(msg);
|
||||
} else {
|
||||
Alert.alert("Code Sent", msg);
|
||||
}
|
||||
setStep("verify");
|
||||
} catch (err: any) {
|
||||
const errMsg = err?.response?.data?.detail || "Failed to send verification code.";
|
||||
setEmailError(errMsg);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
setOtpError("");
|
||||
setPasswordError("");
|
||||
setConfirmError("");
|
||||
|
||||
let hasError = false;
|
||||
if (!otpCode.trim() || otpCode.trim().length !== 6) {
|
||||
setOtpError("Please enter the 6-digit code");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (!newPassword) {
|
||||
setPasswordError("New password is required");
|
||||
hasError = true;
|
||||
} else if (newPassword.length < 8) {
|
||||
setPasswordError("Must be at least 8 characters");
|
||||
hasError = true;
|
||||
} else if (!/[A-Z]/.test(newPassword)) {
|
||||
setPasswordError("Must contain at least one uppercase letter");
|
||||
hasError = true;
|
||||
} else if (!/[0-9]/.test(newPassword)) {
|
||||
setPasswordError("Must contain at least one number");
|
||||
hasError = true;
|
||||
} else if (!/[^A-Za-z0-9]/.test(newPassword)) {
|
||||
setPasswordError("Must contain at least one special character");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (!confirmPassword) {
|
||||
setConfirmError("Please confirm your password");
|
||||
hasError = true;
|
||||
} else if (newPassword !== confirmPassword) {
|
||||
setConfirmError("Passwords do not match");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (hasError) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await resetPassword({
|
||||
email: email.trim().toLowerCase(),
|
||||
otp_code: otpCode.trim(),
|
||||
new_password: newPassword,
|
||||
});
|
||||
|
||||
const successMsg = res.message || "Password reset successfully! You can now log in.";
|
||||
if (Platform.OS === "web") {
|
||||
window.alert(successMsg);
|
||||
router.replace("/login");
|
||||
} else {
|
||||
Alert.alert("Success", successMsg, [
|
||||
{ text: "Log In", onPress: () => router.replace("/login") },
|
||||
]);
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errMsg = err?.response?.data?.detail || "Invalid code or reset failed.";
|
||||
setOtpError(errMsg);
|
||||
if (Platform.OS === "web") {
|
||||
window.alert(errMsg);
|
||||
} else {
|
||||
Alert.alert("Error", errMsg);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.safeArea}>
|
||||
<KeyboardAvoidingView
|
||||
style={styles.keyboardContainer}
|
||||
behavior={Platform.OS === "ios" ? "padding" : undefined}
|
||||
>
|
||||
<ScrollView
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={styles.contentContainer}
|
||||
>
|
||||
<View style={styles.container}>
|
||||
{/* Header */}
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.title}>Reset Password</Text>
|
||||
<Text style={styles.subtitle}>
|
||||
{step === "request"
|
||||
? "Enter your registered email to receive a 6-digit verification code."
|
||||
: `Enter the 6-digit code sent to ${email} and your new password.`}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{step === "request" ? (
|
||||
<View style={styles.form}>
|
||||
<View style={styles.field}>
|
||||
<FieldLabel label="Registered Email" required />
|
||||
<BaseTextInput
|
||||
value={email}
|
||||
onChangeText={setEmail}
|
||||
placeholder="doctor@example.com"
|
||||
keyboardType="email-address"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
leftIcon="mail-outline"
|
||||
error={emailError}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.buttonSpacing}>
|
||||
<PrimaryButton
|
||||
title="Send Verification Code"
|
||||
loading={isLoading}
|
||||
onPress={handleRequestOtp}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<Pressable
|
||||
style={styles.backButton}
|
||||
onPress={() => router.back()}
|
||||
>
|
||||
<Text style={styles.backButtonText}>← Back to Log In</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.form}>
|
||||
<View style={styles.field}>
|
||||
<FieldLabel label="6-Digit Verification Code" required />
|
||||
<BaseTextInput
|
||||
value={otpCode}
|
||||
onChangeText={(val) => setOtpCode(val.replace(/\D/g, "").slice(0, 6))}
|
||||
placeholder="123456"
|
||||
keyboardType="number-pad"
|
||||
autoCapitalize="none"
|
||||
leftIcon="key-outline"
|
||||
error={otpError}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.field}>
|
||||
<FieldLabel label="New Password" required />
|
||||
<PasswordInput
|
||||
value={newPassword}
|
||||
onChangeText={setNewPassword}
|
||||
placeholder="Min 8 chars (1 uppercase, 1 digit, 1 special)"
|
||||
error={passwordError}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.field}>
|
||||
<FieldLabel label="Confirm New Password" required />
|
||||
<PasswordInput
|
||||
value={confirmPassword}
|
||||
onChangeText={setConfirmPassword}
|
||||
placeholder="Confirm new password"
|
||||
error={confirmError}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.buttonSpacing}>
|
||||
<PrimaryButton
|
||||
title="Reset Password"
|
||||
loading={isLoading}
|
||||
onPress={handleResetPassword}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.footerRow}>
|
||||
<Pressable onPress={() => setStep("request")}>
|
||||
<Text style={styles.resendText}>Resend code</Text>
|
||||
</Pressable>
|
||||
<Pressable onPress={() => router.replace("/login")}>
|
||||
<Text style={styles.backButtonText}>Back to Log In</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
safeArea: {
|
||||
flex: 1,
|
||||
backgroundColor: Colors.background,
|
||||
},
|
||||
keyboardContainer: {
|
||||
flex: 1,
|
||||
},
|
||||
contentContainer: {
|
||||
flexGrow: 1,
|
||||
paddingBottom: verticalScale(32),
|
||||
},
|
||||
container: {
|
||||
flex: 1,
|
||||
paddingHorizontal: moderateScale(24),
|
||||
paddingTop: verticalScale(30),
|
||||
},
|
||||
header: {
|
||||
marginBottom: verticalScale(24),
|
||||
},
|
||||
title: {
|
||||
fontSize: moderateScale(26),
|
||||
fontWeight: "800",
|
||||
color: Colors.text,
|
||||
marginBottom: verticalScale(8),
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: moderateScale(14),
|
||||
color: Colors.textSecondary,
|
||||
lineHeight: moderateScale(20),
|
||||
},
|
||||
form: {
|
||||
marginTop: verticalScale(8),
|
||||
},
|
||||
field: {
|
||||
marginBottom: verticalScale(16),
|
||||
},
|
||||
buttonSpacing: {
|
||||
marginTop: verticalScale(12),
|
||||
},
|
||||
backButton: {
|
||||
alignSelf: "center",
|
||||
marginTop: verticalScale(20),
|
||||
padding: moderateScale(8),
|
||||
},
|
||||
backButtonText: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "700",
|
||||
color: AuthColors.primary,
|
||||
},
|
||||
footerRow: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginTop: verticalScale(20),
|
||||
},
|
||||
resendText: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "600",
|
||||
color: Colors.textSecondary,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import LoginScreen from "@/screens/auth/LoginScreen";
|
||||
|
||||
export default function Login() {
|
||||
return <LoginScreen />;
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { useLocalSearchParams } from "expo-router";
|
||||
|
||||
import { ModuleAccessGate } from "@/features/access/components/ModuleAccessGate";
|
||||
import { ContentDetailScreen } from "@/features/content/screens/ContentDetailScreen";
|
||||
|
||||
export default function ContentDetailRoute() {
|
||||
const { moduleCode, templateCode, contentId } = useLocalSearchParams<{
|
||||
moduleCode: string;
|
||||
templateCode: string;
|
||||
contentId: string;
|
||||
}>();
|
||||
|
||||
return (
|
||||
<ModuleAccessGate moduleCode={moduleCode}>
|
||||
<ContentDetailScreen
|
||||
moduleCode={moduleCode}
|
||||
templateCode={templateCode}
|
||||
contentId={contentId}
|
||||
/>
|
||||
</ModuleAccessGate>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { useLocalSearchParams } from "expo-router";
|
||||
|
||||
import { ModuleAccessGate } from "@/features/access/components/ModuleAccessGate";
|
||||
import { TemplateScreen } from "@/features/content/screens/TemplateScreen";
|
||||
|
||||
export default function TemplateRoute() {
|
||||
const { moduleCode, templateCode } = useLocalSearchParams<{
|
||||
moduleCode: string;
|
||||
templateCode: string;
|
||||
}>();
|
||||
|
||||
return (
|
||||
<ModuleAccessGate moduleCode={moduleCode}>
|
||||
<TemplateScreen moduleCode={moduleCode} templateCode={templateCode} />
|
||||
</ModuleAccessGate>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { useLocalSearchParams } from "expo-router";
|
||||
|
||||
import { ModuleAccessGate } from "@/features/access/components/ModuleAccessGate";
|
||||
import { useModuleDisplayName } from "@/features/content/hooks/use-module-display-name";
|
||||
import FacetedSearchScreen from "@/features/search/screens/FacetedSearchScreen";
|
||||
|
||||
export default function ModuleSearchRoute() {
|
||||
const { moduleCode } = useLocalSearchParams<{ moduleCode: string }>();
|
||||
const module = typeof moduleCode === "string" ? moduleCode.trim() : "";
|
||||
const moduleDisplay = useModuleDisplayName(module);
|
||||
|
||||
return (
|
||||
<ModuleAccessGate moduleCode={module}>
|
||||
<FacetedSearchScreen
|
||||
mode="module"
|
||||
fixedModuleCode={module}
|
||||
fixedModuleName={moduleDisplay.name}
|
||||
/>
|
||||
</ModuleAccessGate>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import ModulesIndexScreen from "@/screens/modules/ModulesIndexScreen";
|
||||
|
||||
export default function ModulesIndexRoute() {
|
||||
return <ModulesIndexScreen />;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import SignUpScreen from "@/screens/auth/SignUpScreen";
|
||||
|
||||
export default function Register() {
|
||||
return <SignUpScreen />;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import FacetedSearchScreen from "@/features/search/screens/FacetedSearchScreen";
|
||||
|
||||
export default function GlobalSearchRoute() {
|
||||
return <FacetedSearchScreen mode="global" />;
|
||||
}
|
||||
|
|
@ -0,0 +1,326 @@
|
|||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Linking,
|
||||
Platform,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { router, useFocusEffect, useLocalSearchParams } from "expo-router";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||||
import Constants from "expo-constants";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
import { useAuthStore } from "@/store/auth.store";
|
||||
import { calculateCart } from "@/features/commerce";
|
||||
import type { CartCalculationResponse } from "@/features/commerce";
|
||||
import PrimaryButton from "@/components/buttons/PrimaryButton";
|
||||
|
||||
function param(value: string | string[] | undefined): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function money(value: number, currency: string): string {
|
||||
try {
|
||||
return new Intl.NumberFormat("en-IN", {
|
||||
style: "currency",
|
||||
currency,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(value);
|
||||
} catch {
|
||||
return `${currency} ${value.toFixed(2)}`;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveStorefrontUrl(): string {
|
||||
const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim();
|
||||
if (envUrl) return envUrl;
|
||||
|
||||
const apiUrl = process.env.EXPO_PUBLIC_API_URL ?? "";
|
||||
if (apiUrl.startsWith("https://")) {
|
||||
try {
|
||||
const parsed = new URL(apiUrl);
|
||||
if (!parsed.hostname.includes("localhost") && !parsed.hostname.includes("127.0.0.1")) {
|
||||
return parsed.origin;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const hostUri = Constants.expoConfig?.hostUri;
|
||||
const metroHost = hostUri?.split(":")[0];
|
||||
if (metroHost && /^[0-9.]+$/.test(metroHost) && metroHost !== "127.0.0.1") {
|
||||
return `http://${metroHost}:3000`;
|
||||
}
|
||||
|
||||
if (Platform.OS === "web" && typeof window !== "undefined") {
|
||||
return `${window.location.protocol}//${window.location.hostname}`;
|
||||
}
|
||||
|
||||
const ipMatch = apiUrl.match(/http:\/\/([0-9.]+)/);
|
||||
if (ipMatch?.[1]) return `http://${ipMatch[1]}:3000`;
|
||||
|
||||
return "http://localhost:3000";
|
||||
}
|
||||
|
||||
export default function SubscriptionScreen() {
|
||||
const params = useLocalSearchParams();
|
||||
const accessToken = useAuthStore((state) => state.accessToken);
|
||||
const access = useAuthStore((state) => state.access);
|
||||
const refreshAccess = useAuthStore((state) => state.refreshAccess);
|
||||
|
||||
const moduleId = param(params.moduleId);
|
||||
const moduleCode = param(params.moduleCode);
|
||||
const title = param(params.title) || "Clinical Module";
|
||||
const category = param(params.category);
|
||||
const description = param(params.desc);
|
||||
const planCode = param(params.planCode).trim().toUpperCase();
|
||||
|
||||
const [couponCode, setCouponCode] = useState("");
|
||||
const [pricing, setPricing] = useState<CartCalculationResponse | null>(null);
|
||||
const [loadingPricing, setLoadingPricing] = useState(false);
|
||||
const [openingCheckout, setOpeningCheckout] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const unlocked = useMemo(() => {
|
||||
if (!accessToken) return false;
|
||||
if (moduleCode && access?.unlocked_module_codes.includes(moduleCode)) return true;
|
||||
return false;
|
||||
}, [access, accessToken, moduleCode]);
|
||||
|
||||
const loadPricing = useCallback(async (coupon?: string) => {
|
||||
if (!planCode) {
|
||||
setPricing(null);
|
||||
setError("This module does not have a commerce plan configured.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingPricing(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await calculateCart({
|
||||
cart_item_codes: [planCode],
|
||||
coupon_code: coupon?.trim() || null,
|
||||
currency: "INR",
|
||||
});
|
||||
setPricing(response);
|
||||
} catch (err: any) {
|
||||
const detail = err?.response?.data?.detail;
|
||||
setError(typeof detail === "string" ? detail : "Unable to load current subscription pricing.");
|
||||
setPricing(null);
|
||||
} finally {
|
||||
setLoadingPricing(false);
|
||||
}
|
||||
}, [planCode]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadPricing();
|
||||
}, [loadPricing]);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (accessToken) void refreshAccess();
|
||||
}, [accessToken, refreshAccess]),
|
||||
);
|
||||
|
||||
const showAlert = (alertTitle: string, message: string, onConfirm?: () => void) => {
|
||||
if (Platform.OS === "web") {
|
||||
alert(`${alertTitle}\n\n${message}`);
|
||||
onConfirm?.();
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
alertTitle,
|
||||
message,
|
||||
onConfirm ? [{ text: "Cancel", style: "cancel" }, { text: "Continue", onPress: onConfirm }] : [{ text: "OK" }],
|
||||
);
|
||||
};
|
||||
|
||||
const handleCheckout = async () => {
|
||||
if (!accessToken) {
|
||||
router.push("/login");
|
||||
return;
|
||||
}
|
||||
if (!planCode) {
|
||||
showAlert("Subscription unavailable", "No access plan is configured for this module.");
|
||||
return;
|
||||
}
|
||||
|
||||
setOpeningCheckout(true);
|
||||
try {
|
||||
const storefrontUrl = resolveStorefrontUrl();
|
||||
const query = new URLSearchParams();
|
||||
query.set("token", accessToken);
|
||||
query.set("planCode", planCode);
|
||||
if (couponCode.trim()) query.set("couponCode", couponCode.trim().toUpperCase());
|
||||
const apiUrl = process.env.EXPO_PUBLIC_API_URL;
|
||||
if (apiUrl) query.set("apiUrl", apiUrl);
|
||||
if (moduleId) query.set("moduleId", moduleId);
|
||||
if (moduleCode) query.set("moduleCode", moduleCode);
|
||||
|
||||
const checkoutUrl = `${storefrontUrl}?${query.toString()}`;
|
||||
showAlert(
|
||||
"Complete payment",
|
||||
"Checkout will open in the secure web storefront. Return to AcuPedia after payment; access will refresh automatically.",
|
||||
() => { void Linking.openURL(checkoutUrl); },
|
||||
);
|
||||
} catch {
|
||||
showAlert("Unable to open checkout", "Please try again.");
|
||||
} finally {
|
||||
setOpeningCheckout(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.safeArea}>
|
||||
<View style={styles.header}>
|
||||
<TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
|
||||
<Ionicons name="chevron-back" size={24} color={Colors.textPrimary} />
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.headerTitle}>Subscription</Text>
|
||||
<View style={styles.placeholder} />
|
||||
</View>
|
||||
|
||||
<ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
|
||||
<View style={styles.iconContainer}>
|
||||
<Ionicons name={unlocked ? "checkmark-circle-outline" : "card-outline"} size={58} color={Colors.primary} />
|
||||
</View>
|
||||
<Text style={styles.title}>{unlocked ? `${title} is unlocked` : `Unlock ${title}`}</Text>
|
||||
<Text style={styles.subtitle}>
|
||||
{unlocked
|
||||
? "Your current entitlement already includes this module."
|
||||
: "Pricing and discounts below are calculated by the current commerce API."}
|
||||
</Text>
|
||||
|
||||
{(category || description) ? (
|
||||
<View style={styles.infoBox}>
|
||||
<Ionicons name="information-circle-outline" size={20} color={Colors.primary} />
|
||||
<View style={styles.infoText}>
|
||||
{category ? <Text style={styles.infoTitle}>{category}</Text> : null}
|
||||
{description ? <Text style={styles.infoDescription}>{description}</Text> : null}
|
||||
{planCode ? <Text style={styles.planCode}>Plan: {planCode}</Text> : null}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!unlocked ? (
|
||||
<>
|
||||
<View style={styles.pricingCard}>
|
||||
{loadingPricing ? (
|
||||
<View style={styles.loadingRow}>
|
||||
<ActivityIndicator color={Colors.primary} />
|
||||
<Text style={styles.loadingText}>Loading current pricing…</Text>
|
||||
</View>
|
||||
) : pricing ? (
|
||||
<>
|
||||
{pricing.cart_items.map((item) => (
|
||||
<View key={item.code} style={styles.priceRow}>
|
||||
<Text style={styles.priceLabel}>{item.name}</Text>
|
||||
<Text style={styles.priceValue}>{money(item.price, pricing.currency)}</Text>
|
||||
</View>
|
||||
))}
|
||||
<View style={styles.divider} />
|
||||
<View style={styles.priceRow}><Text style={styles.secondaryLabel}>Subtotal</Text><Text style={styles.secondaryValue}>{money(pricing.base_subtotal, pricing.currency)}</Text></View>
|
||||
{pricing.total_discounts > 0 ? <View style={styles.priceRow}><Text style={styles.discountLabel}>Discounts</Text><Text style={styles.discountValue}>− {money(pricing.total_discounts, pricing.currency)}</Text></View> : null}
|
||||
{pricing.convenience_fee > 0 ? <View style={styles.priceRow}><Text style={styles.secondaryLabel}>Convenience fee</Text><Text style={styles.secondaryValue}>{money(pricing.convenience_fee, pricing.currency)}</Text></View> : null}
|
||||
<View style={styles.priceRow}><Text style={styles.secondaryLabel}>GST</Text><Text style={styles.secondaryValue}>{money(pricing.gst_amount, pricing.currency)}</Text></View>
|
||||
<View style={styles.divider} />
|
||||
<View style={styles.priceRow}><Text style={styles.totalLabel}>Total</Text><Text style={styles.totalValue}>{money(pricing.grand_total, pricing.currency)}</Text></View>
|
||||
{pricing.coupon_applied ? <Text style={styles.appliedText}>Coupon applied: {pricing.coupon_applied}</Text> : null}
|
||||
</>
|
||||
) : (
|
||||
<Text style={styles.errorText}>{error ?? "Pricing is unavailable."}</Text>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={styles.couponRow}>
|
||||
<TextInput
|
||||
value={couponCode}
|
||||
onChangeText={setCouponCode}
|
||||
autoCapitalize="characters"
|
||||
placeholder="Coupon code"
|
||||
style={styles.couponInput}
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={styles.applyButton}
|
||||
onPress={() => void loadPricing(couponCode)}
|
||||
disabled={loadingPricing}
|
||||
>
|
||||
<Text style={styles.applyText}>Apply</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{error && pricing ? <Text style={styles.inlineError}>{error}</Text> : null}
|
||||
|
||||
<View style={styles.buttonContainer}>
|
||||
{openingCheckout ? <ActivityIndicator color={Colors.primary} /> : (
|
||||
<PrimaryButton
|
||||
title={accessToken ? "Continue to Checkout" : "Log In to Subscribe"}
|
||||
onPress={() => void handleCheckout()}
|
||||
disabled={loadingPricing || !planCode}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
</>
|
||||
) : (
|
||||
<View style={styles.buttonContainer}>
|
||||
<PrimaryButton title="Back to Modules" onPress={() => router.replace("/modules/list")} />
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
safeArea: { flex: 1, backgroundColor: Colors.background },
|
||||
header: {
|
||||
height: 60,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingHorizontal: moderateScale(16),
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: "#ECECEC",
|
||||
backgroundColor: "#FFFFFF",
|
||||
},
|
||||
backButton: { padding: 4 },
|
||||
headerTitle: { fontSize: moderateScale(18), fontWeight: "700", color: Colors.textPrimary },
|
||||
placeholder: { width: 32 },
|
||||
content: { paddingHorizontal: moderateScale(24), paddingTop: verticalScale(28), paddingBottom: verticalScale(40) },
|
||||
iconContainer: { alignItems: "center", marginBottom: verticalScale(16) },
|
||||
title: { fontSize: moderateScale(24), fontWeight: "800", color: Colors.textPrimary, textAlign: "center" },
|
||||
subtitle: { fontSize: moderateScale(14), color: Colors.textSecondary, textAlign: "center", lineHeight: 20, marginTop: verticalScale(8), marginBottom: verticalScale(22) },
|
||||
infoBox: { flexDirection: "row", backgroundColor: "#EEF2FF", borderRadius: moderateScale(14), padding: moderateScale(14), marginBottom: verticalScale(18) },
|
||||
infoText: { flex: 1, marginLeft: moderateScale(10) },
|
||||
infoTitle: { fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary },
|
||||
infoDescription: { marginTop: 3, fontSize: moderateScale(12), color: Colors.textSecondary, lineHeight: 18 },
|
||||
planCode: { marginTop: 5, fontSize: moderateScale(11), color: Colors.primary, fontWeight: "600" },
|
||||
pricingCard: { backgroundColor: "#FFFFFF", borderRadius: moderateScale(16), borderWidth: 1, borderColor: "#E5E7EB", padding: moderateScale(16) },
|
||||
loadingRow: { flexDirection: "row", alignItems: "center", justifyContent: "center", paddingVertical: verticalScale(16) },
|
||||
loadingText: { marginLeft: moderateScale(10), color: Colors.textSecondary, fontSize: moderateScale(13) },
|
||||
priceRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginVertical: verticalScale(5) },
|
||||
priceLabel: { flex: 1, fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary, marginRight: 10 },
|
||||
priceValue: { fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary },
|
||||
secondaryLabel: { fontSize: moderateScale(13), color: Colors.textSecondary },
|
||||
secondaryValue: { fontSize: moderateScale(13), color: Colors.textPrimary },
|
||||
discountLabel: { fontSize: moderateScale(13), color: "#15803D" },
|
||||
discountValue: { fontSize: moderateScale(13), color: "#15803D", fontWeight: "600" },
|
||||
totalLabel: { fontSize: moderateScale(15), fontWeight: "800", color: Colors.textPrimary },
|
||||
totalValue: { fontSize: moderateScale(18), fontWeight: "800", color: Colors.primary },
|
||||
divider: { height: 1, backgroundColor: "#ECECEC", marginVertical: verticalScale(8) },
|
||||
appliedText: { marginTop: verticalScale(8), fontSize: moderateScale(12), color: "#15803D", fontWeight: "600" },
|
||||
errorText: { fontSize: moderateScale(13), color: "#B91C1C", textAlign: "center", paddingVertical: verticalScale(14) },
|
||||
couponRow: { flexDirection: "row", marginTop: verticalScale(14) },
|
||||
couponInput: { flex: 1, minHeight: 46, backgroundColor: "#FFFFFF", borderWidth: 1, borderColor: "#D1D5DB", borderRadius: moderateScale(12), paddingHorizontal: moderateScale(12), color: Colors.textPrimary },
|
||||
applyButton: { marginLeft: moderateScale(10), minWidth: 78, minHeight: 46, alignItems: "center", justifyContent: "center", backgroundColor: "#EEF2FF", borderRadius: moderateScale(12) },
|
||||
applyText: { fontSize: moderateScale(13), fontWeight: "700", color: Colors.primary },
|
||||
inlineError: { marginTop: verticalScale(8), fontSize: moderateScale(12), color: "#B91C1C" },
|
||||
buttonContainer: { marginTop: verticalScale(24) },
|
||||
});
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
import React from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
ViewStyle,
|
||||
} from "react-native";
|
||||
import { LinearGradient } from "expo-linear-gradient";
|
||||
import {
|
||||
moderateScale,
|
||||
scale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import { AuthColors } from "@/features/auth/constants/colors";
|
||||
|
||||
interface PrimaryButtonProps {
|
||||
title: string;
|
||||
onPress: () => void;
|
||||
loading?: boolean;
|
||||
disabled?: boolean;
|
||||
style?: ViewStyle;
|
||||
}
|
||||
|
||||
export default function PrimaryButton({
|
||||
title,
|
||||
onPress,
|
||||
loading = false,
|
||||
disabled = false,
|
||||
style,
|
||||
}: PrimaryButtonProps) {
|
||||
const isDisabled = disabled || loading;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={title}
|
||||
accessibilityState={{
|
||||
disabled: isDisabled,
|
||||
busy: loading,
|
||||
}}
|
||||
disabled={isDisabled}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [
|
||||
styles.pressable,
|
||||
style,
|
||||
pressed && !isDisabled && styles.pressed,
|
||||
isDisabled && styles.disabled,
|
||||
]}
|
||||
>
|
||||
<LinearGradient
|
||||
colors={[
|
||||
AuthColors.primary,
|
||||
AuthColors.primaryDark,
|
||||
]}
|
||||
start={{ x: 0, y: 0 }}
|
||||
end={{ x: 1, y: 0 }}
|
||||
style={styles.gradient}
|
||||
>
|
||||
{loading ? (
|
||||
<ActivityIndicator
|
||||
color={AuthColors.white}
|
||||
size="small"
|
||||
/>
|
||||
) : (
|
||||
<Text style={styles.title}>
|
||||
{title}
|
||||
</Text>
|
||||
)}
|
||||
</LinearGradient>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
pressable: {
|
||||
width: "100%",
|
||||
borderRadius: moderateScale(18),
|
||||
overflow: "hidden",
|
||||
marginTop: verticalScale(24),
|
||||
},
|
||||
|
||||
gradient: {
|
||||
height: verticalScale(56),
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
title: {
|
||||
color: AuthColors.white,
|
||||
fontSize: moderateScale(16),
|
||||
fontWeight: "700",
|
||||
letterSpacing: 0.3,
|
||||
},
|
||||
|
||||
pressed: {
|
||||
opacity: 0.9,
|
||||
transform: [{ scale: 0.98 }],
|
||||
},
|
||||
|
||||
disabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
import React, { forwardRef } from "react";
|
||||
import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
TextInputProps,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
moderateScale,
|
||||
scale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
|
||||
import { AuthColors } from "@/features/auth/constants/colors";
|
||||
|
||||
interface BaseTextInputProps extends TextInputProps {
|
||||
label?: string;
|
||||
error?: string;
|
||||
leftIcon?: keyof typeof Ionicons.glyphMap;
|
||||
rightElement?: React.ReactNode;
|
||||
}
|
||||
|
||||
const BaseTextInput = forwardRef<TextInput, BaseTextInputProps>(
|
||||
(
|
||||
{
|
||||
label,
|
||||
error,
|
||||
leftIcon,
|
||||
rightElement,
|
||||
style,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
return (
|
||||
<View style={styles.wrapper}>
|
||||
{label ? (
|
||||
<Text style={styles.label}>
|
||||
{label}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
<View
|
||||
style={[
|
||||
styles.inputContainer,
|
||||
error && styles.errorBorder,
|
||||
]}
|
||||
>
|
||||
{leftIcon && (
|
||||
<Ionicons
|
||||
name={leftIcon}
|
||||
size={moderateScale(20)}
|
||||
color={AuthColors.textSecondary}
|
||||
style={styles.leftIcon}
|
||||
/>
|
||||
)}
|
||||
|
||||
<TextInput
|
||||
ref={ref}
|
||||
placeholderTextColor={
|
||||
AuthColors.textSecondary
|
||||
}
|
||||
style={[
|
||||
styles.input,
|
||||
style,
|
||||
]}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
{rightElement}
|
||||
</View>
|
||||
|
||||
{error ? (
|
||||
<Text style={styles.errorText}>
|
||||
{error}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
BaseTextInput.displayName = "BaseTextInput";
|
||||
|
||||
export default BaseTextInput;
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
wrapper: {
|
||||
marginBottom: verticalScale(18),
|
||||
},
|
||||
|
||||
label: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "600",
|
||||
color: AuthColors.textPrimary,
|
||||
marginBottom: verticalScale(8),
|
||||
},
|
||||
|
||||
inputContainer: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
backgroundColor:
|
||||
AuthColors.inputBackground,
|
||||
|
||||
borderWidth: 1,
|
||||
|
||||
borderColor: AuthColors.border,
|
||||
|
||||
borderRadius: moderateScale(16),
|
||||
|
||||
paddingHorizontal: scale(16),
|
||||
|
||||
height: verticalScale(56),
|
||||
},
|
||||
|
||||
leftIcon: {
|
||||
marginRight: scale(12),
|
||||
},
|
||||
|
||||
input: {
|
||||
flex: 1,
|
||||
|
||||
fontSize: moderateScale(16),
|
||||
|
||||
color: AuthColors.textPrimary,
|
||||
|
||||
paddingVertical: 0,
|
||||
},
|
||||
|
||||
errorBorder: {
|
||||
borderColor: AuthColors.danger,
|
||||
},
|
||||
|
||||
errorText: {
|
||||
color: AuthColors.danger,
|
||||
|
||||
fontSize: moderateScale(12),
|
||||
|
||||
marginTop: verticalScale(6),
|
||||
|
||||
marginLeft: scale(6),
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import React from "react";
|
||||
import {
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import {
|
||||
moderateScale,
|
||||
scale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
|
||||
interface DropdownFieldProps {
|
||||
value?: string;
|
||||
placeholder?: string;
|
||||
onPress?: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export default function DropdownField({
|
||||
value,
|
||||
placeholder = "Select",
|
||||
onPress,
|
||||
disabled = false,
|
||||
}: DropdownFieldProps) {
|
||||
const displayText = value?.trim() || placeholder;
|
||||
const isPlaceholder = !value?.trim();
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={placeholder}
|
||||
accessibilityState={{ disabled }}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [
|
||||
styles.container,
|
||||
pressed && !disabled && styles.pressed,
|
||||
disabled && styles.disabled,
|
||||
]}
|
||||
>
|
||||
<View style={styles.content}>
|
||||
<Text
|
||||
numberOfLines={1}
|
||||
style={[
|
||||
styles.value,
|
||||
isPlaceholder && styles.placeholder,
|
||||
]}
|
||||
>
|
||||
{displayText}
|
||||
</Text>
|
||||
|
||||
<Ionicons
|
||||
name="chevron-down-outline"
|
||||
size={moderateScale(20)}
|
||||
color="#9CA3AF"
|
||||
/>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
height: verticalScale(56),
|
||||
backgroundColor: "#FFFFFF",
|
||||
borderWidth: 1,
|
||||
borderColor: "#E5E7EB",
|
||||
borderRadius: moderateScale(16),
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: scale(16),
|
||||
},
|
||||
|
||||
content: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
},
|
||||
|
||||
value: {
|
||||
flex: 1,
|
||||
marginRight: scale(12),
|
||||
fontSize: moderateScale(16),
|
||||
color: Colors.text,
|
||||
},
|
||||
|
||||
placeholder: {
|
||||
color: "#9CA3AF",
|
||||
},
|
||||
|
||||
pressed: {
|
||||
opacity: 0.85,
|
||||
},
|
||||
|
||||
disabled: {
|
||||
opacity: 0.6,
|
||||
backgroundColor: "#F9FAFB",
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import React from "react";
|
||||
import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
moderateScale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
|
||||
interface FieldLabelProps {
|
||||
label: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export default function FieldLabel({
|
||||
label,
|
||||
required = false,
|
||||
}: FieldLabelProps) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.label}>
|
||||
{label}
|
||||
{required && (
|
||||
<Text style={styles.required}> *</Text>
|
||||
)}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginBottom: verticalScale(8),
|
||||
},
|
||||
|
||||
label: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "600",
|
||||
color: Colors.text,
|
||||
lineHeight: moderateScale(20),
|
||||
},
|
||||
|
||||
required: {
|
||||
color: "#EF4444",
|
||||
fontWeight: "700",
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import React, { useState } from "react";
|
||||
import { Pressable } from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { moderateScale } from "react-native-size-matters";
|
||||
|
||||
import BaseTextInput from "./BaseTextInput";
|
||||
import { AuthColors } from "@/features/auth/constants/colors";
|
||||
|
||||
interface PasswordInputProps {
|
||||
value: string;
|
||||
onChangeText: (text: string) => void;
|
||||
placeholder?: string;
|
||||
error?: string;
|
||||
editable?: boolean;
|
||||
}
|
||||
|
||||
export default function PasswordInput({
|
||||
value,
|
||||
onChangeText,
|
||||
placeholder = "Password",
|
||||
error,
|
||||
editable = true,
|
||||
}: PasswordInputProps) {
|
||||
const [secureTextEntry, setSecureTextEntry] = useState(true);
|
||||
|
||||
return (
|
||||
<BaseTextInput
|
||||
value={value}
|
||||
onChangeText={onChangeText}
|
||||
placeholder={placeholder}
|
||||
error={error}
|
||||
editable={editable}
|
||||
secureTextEntry={secureTextEntry}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="password"
|
||||
leftIcon="lock-closed-outline"
|
||||
rightElement={
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
secureTextEntry
|
||||
? "Show password"
|
||||
: "Hide password"
|
||||
}
|
||||
hitSlop={10}
|
||||
onPress={() =>
|
||||
setSecureTextEntry(!secureTextEntry)
|
||||
}
|
||||
>
|
||||
<Ionicons
|
||||
name={
|
||||
secureTextEntry
|
||||
? "eye-off-outline"
|
||||
: "eye-outline"
|
||||
}
|
||||
size={moderateScale(20)}
|
||||
color={AuthColors.textSecondary}
|
||||
/>
|
||||
</Pressable>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
import React from "react";
|
||||
import {
|
||||
Text,
|
||||
type StyleProp,
|
||||
type TextProps,
|
||||
type TextStyle,
|
||||
} from "react-native";
|
||||
|
||||
import {
|
||||
fonts,
|
||||
Typography,
|
||||
type FontWeight,
|
||||
type TypographyVariant,
|
||||
} from "@/theme";
|
||||
|
||||
export interface AppTextProps extends TextProps {
|
||||
variant?: TypographyVariant;
|
||||
weight?: FontWeight;
|
||||
style?: StyleProp<TextStyle>;
|
||||
}
|
||||
|
||||
export const AppText = React.forwardRef<
|
||||
React.ElementRef<typeof Text>,
|
||||
AppTextProps
|
||||
>(
|
||||
(
|
||||
{
|
||||
variant = "body",
|
||||
weight,
|
||||
style,
|
||||
allowFontScaling = true,
|
||||
maxFontSizeMultiplier = 1.4,
|
||||
...rest
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const typographyStyle = Typography[variant];
|
||||
|
||||
const weightStyle: TextStyle | undefined = weight
|
||||
? {
|
||||
fontFamily: fonts[weight],
|
||||
}
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Text
|
||||
ref={ref}
|
||||
{...rest}
|
||||
allowFontScaling={allowFontScaling}
|
||||
maxFontSizeMultiplier={maxFontSizeMultiplier}
|
||||
style={[
|
||||
typographyStyle,
|
||||
weightStyle,
|
||||
style,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
AppText.displayName = "AppText";
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import React from "react";
|
||||
import {
|
||||
TextInput,
|
||||
type TextInputProps,
|
||||
type TextStyle,
|
||||
type StyleProp,
|
||||
StyleSheet,
|
||||
} from "react-native";
|
||||
|
||||
import { fonts } from "@/theme";
|
||||
|
||||
export interface AppTextInputProps extends TextInputProps {
|
||||
style?: StyleProp<TextStyle>;
|
||||
|
||||
/**
|
||||
* Controls accessibility font scaling.
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
allowFontScaling?: boolean;
|
||||
|
||||
/**
|
||||
* Maximum accessibility font scaling multiplier.
|
||||
*
|
||||
* @default 1.4
|
||||
*/
|
||||
maxFontSizeMultiplier?: number;
|
||||
}
|
||||
|
||||
export const AppTextInput = React.forwardRef<
|
||||
React.ElementRef<typeof TextInput>,
|
||||
AppTextInputProps
|
||||
>(
|
||||
(
|
||||
{
|
||||
style,
|
||||
allowFontScaling = true,
|
||||
maxFontSizeMultiplier = 1.4,
|
||||
...rest
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
return (
|
||||
<TextInput
|
||||
ref={ref}
|
||||
{...rest}
|
||||
allowFontScaling={allowFontScaling}
|
||||
maxFontSizeMultiplier={maxFontSizeMultiplier}
|
||||
style={[
|
||||
styles.base,
|
||||
style,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
AppTextInput.displayName = "AppTextInput";
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
base: {
|
||||
fontFamily: fonts.regular,
|
||||
fontSize: 16,
|
||||
lineHeight: 22,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,268 @@
|
|||
export interface ModuleItem {
|
||||
id: string;
|
||||
code?: string; // Canonical Module Code from config.json (e.g. M0001, M0011)
|
||||
title: string;
|
||||
desc: string;
|
||||
taxonomyId: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
category: string;
|
||||
isDefaultFree: boolean;
|
||||
planCode: string;
|
||||
}
|
||||
|
||||
export const CLINICAL_MODULES: ModuleItem[] = [
|
||||
{
|
||||
id: "acupoints",
|
||||
code: "M0001",
|
||||
title: "Acupuncture",
|
||||
desc: "All points, locations, indications & more",
|
||||
taxonomyId: "6d4b0290-d44c-4d87-a9c3-89f8c8a8632c",
|
||||
icon: "water-outline",
|
||||
color: "#2563EB",
|
||||
category: "point",
|
||||
isDefaultFree: true,
|
||||
planCode: "POINTS_ACU",
|
||||
},
|
||||
{
|
||||
id: "ear-acupuncture",
|
||||
code: "M0002",
|
||||
title: "Ear-acupuncture",
|
||||
desc: "Ear Points & Point Category",
|
||||
taxonomyId: "89136bd9-50f1-437a-ac7f-8ed36ef723b6",
|
||||
icon: "ear-outline",
|
||||
color: "#F59E0B",
|
||||
category: "point",
|
||||
isDefaultFree: false,
|
||||
planCode: "POINTS_EAR",
|
||||
},
|
||||
{
|
||||
id: "scalp-acupuncture",
|
||||
code: "M0003",
|
||||
title: "Scalp acupuncture",
|
||||
desc: "Scalp zones, points & protocols",
|
||||
taxonomyId: "a625b5b3-b0c4-4559-87bc-397277f2765e",
|
||||
icon: "accessibility-outline",
|
||||
color: "#EF4444",
|
||||
category: "point",
|
||||
isDefaultFree: false,
|
||||
planCode: "POINTS_SCALP",
|
||||
},
|
||||
{
|
||||
id: "points_tung",
|
||||
code: "M0004",
|
||||
title: "Master Tung",
|
||||
desc: "Master Tung points and treatments",
|
||||
taxonomyId: "64ec885d-652a-43e2-90ea-648a8884784b",
|
||||
icon: "analytics-outline",
|
||||
color: "#10B981",
|
||||
category: "point",
|
||||
isDefaultFree: false,
|
||||
planCode: "POINTS_TUNG",
|
||||
},
|
||||
{
|
||||
id: "auriculotherapy",
|
||||
code: "M0041",
|
||||
title: "Microsystem",
|
||||
desc: "Auriculotherapy reflexology systems",
|
||||
taxonomyId: "55f6a101-9b4d-40c9-8316-6389a598e831",
|
||||
icon: "body-outline",
|
||||
color: "#8B5CF6",
|
||||
category: "point",
|
||||
isDefaultFree: false,
|
||||
planCode: "THERAPEUTICS_EAR",
|
||||
},
|
||||
{
|
||||
id: "eight-principles",
|
||||
code: "M0011",
|
||||
title: "Eight principle",
|
||||
desc: "Exterior/Interior, Cold/Heat, Deficiency/Excess, Yin/Yang patterns",
|
||||
taxonomyId: "c75e115a-88f0-4989-a4de-29fd64d0f099",
|
||||
icon: "git-network-outline",
|
||||
color: "#7C3AED",
|
||||
category: "Patterns",
|
||||
isDefaultFree: true,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "twelve-channels",
|
||||
code: "M0018",
|
||||
title: "zangfu",
|
||||
desc: "Zangfu organ and channel identification",
|
||||
taxonomyId: "e14c36ec-ca17-4f68-a34f-11e0e4baf01b",
|
||||
icon: "pulse-outline",
|
||||
color: "#06B6D4",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "qi-blood-body-fluids",
|
||||
code: "M0013",
|
||||
title: "Qi-Blood-body fluid",
|
||||
desc: "Qi, Blood, and Body Fluid identification of patterns",
|
||||
taxonomyId: "6eed9ead-a685-4d24-bd02-94c45e5cd26d",
|
||||
icon: "water-outline",
|
||||
color: "#3B82F6",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "pathogenic-factors",
|
||||
code: "M0014",
|
||||
title: "pathogenic factors",
|
||||
desc: "Wind, Cold, Summer-Heat, Dampness, Dryness, Fire patterns",
|
||||
taxonomyId: "ac78f54a-1f39-4c6d-bf9a-670a6267fe29",
|
||||
icon: "flame-outline",
|
||||
color: "#F59E0B",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "six-stages",
|
||||
code: "M0015",
|
||||
title: "six stages",
|
||||
desc: "Tai Yang, Yang Ming, Shao Yang, Tai Yin, Shao Yin, Jue Yin",
|
||||
taxonomyId: "25aac40d-d336-4780-99b9-385c7833bd61",
|
||||
icon: "layers-outline",
|
||||
color: "#10B981",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "four-levels",
|
||||
code: "M0016",
|
||||
title: "four level",
|
||||
desc: "Wei, Qi, Ying, Xue level pattern identification",
|
||||
taxonomyId: "3c54841a-68be-4bb4-bd48-436e60c2033c",
|
||||
icon: "trending-up-outline",
|
||||
color: "#EF4444",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "three-burners",
|
||||
code: "M0017",
|
||||
title: "three burners",
|
||||
desc: "Upper, Middle, and Lower Burner pattern identification",
|
||||
taxonomyId: "d03c5393-8634-4993-b944-50c1d68c096e",
|
||||
icon: "thermometer-outline",
|
||||
color: "#EC4899",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "five-elements",
|
||||
code: "M0019",
|
||||
title: "five elements",
|
||||
desc: "Wood, Fire, Earth, Metal, Water relationships and patterns",
|
||||
taxonomyId: "e5ef08e9-7ddf-4f6b-b96e-846e729eb89f",
|
||||
icon: "flower-outline",
|
||||
color: "#6366F1",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "extra-ordinary-vessel",
|
||||
code: "M0020",
|
||||
title: "Extraordinary Vessels",
|
||||
desc: "Eight Extraordinary Vessels and Confluent points",
|
||||
taxonomyId: "9c3c8612-9c16-41ea-bf7c-65db4058d88e",
|
||||
icon: "git-commit-outline",
|
||||
color: "#8B5CF6",
|
||||
category: "Patterns",
|
||||
isDefaultFree: false,
|
||||
planCode: "PATTERN_CORE",
|
||||
},
|
||||
{
|
||||
id: "food-category",
|
||||
code: "M0031",
|
||||
title: "Food category",
|
||||
desc: "Nutritional food category classifications",
|
||||
taxonomyId: "ea249c2e-5dd7-46ce-a27f-c2f5d200f03c",
|
||||
icon: "nutrition-outline",
|
||||
color: "#10B981",
|
||||
category: "Nutrition",
|
||||
isDefaultFree: true,
|
||||
planCode: "NUTRITION_CORE",
|
||||
},
|
||||
{
|
||||
id: "food-items",
|
||||
code: "M0031",
|
||||
title: "food items",
|
||||
desc: "Individual food item properties and indications",
|
||||
taxonomyId: "e632204d-1dae-4f3c-9ce7-df25c4002b74",
|
||||
icon: "leaf-outline",
|
||||
color: "#059669",
|
||||
category: "Nutrition",
|
||||
isDefaultFree: false,
|
||||
planCode: "NUTRITION_CORE",
|
||||
},
|
||||
{
|
||||
id: "gynecology",
|
||||
code: "M0042",
|
||||
title: "Gynecology",
|
||||
desc: "Menstrual irregularities and pregnancy patterns",
|
||||
taxonomyId: "b492d8ac-79d7-4210-9454-3438e9bf3fa1",
|
||||
icon: "woman-outline",
|
||||
color: "#EC4899",
|
||||
category: "Therapeutics",
|
||||
isDefaultFree: false,
|
||||
planCode: "THERAPEUTICS_GYNAE",
|
||||
},
|
||||
{
|
||||
id: "neurology",
|
||||
code: "M0043",
|
||||
title: "Neurology",
|
||||
desc: "Nervous system therapeutic protocols",
|
||||
taxonomyId: "a82323eb-e055-4d2d-aaaa-6c641c67a3d5",
|
||||
icon: "hardware-chip-outline",
|
||||
color: "#6366F1",
|
||||
category: "Therapeutics",
|
||||
isDefaultFree: false,
|
||||
planCode: "THERAPEUTICS_CORE",
|
||||
},
|
||||
{
|
||||
id: "pediatric",
|
||||
code: "M0044",
|
||||
title: "Pediatric",
|
||||
desc: "Pediatric clinical treatments and protocols",
|
||||
taxonomyId: "a5867f97-7358-4699-9bb5-ce61a74aeb30",
|
||||
icon: "people-outline",
|
||||
color: "#F59E0B",
|
||||
category: "Therapeutics",
|
||||
isDefaultFree: false,
|
||||
planCode: "THERAPEUTICS_CORE",
|
||||
},
|
||||
{
|
||||
id: "musculo-skeletal",
|
||||
code: "M0045",
|
||||
title: "Musculo-skeletal",
|
||||
desc: "Locomotor system treatment protocols",
|
||||
taxonomyId: "8ab31d7c-c309-4682-a3be-e4a8cd13a3ea",
|
||||
icon: "body-outline",
|
||||
color: "#3B82F6",
|
||||
category: "Therapeutics",
|
||||
isDefaultFree: false,
|
||||
planCode: "THERAPEUTICS_CORE",
|
||||
},
|
||||
{
|
||||
id: "ophthalmic",
|
||||
code: "M0046",
|
||||
title: "Ophthalmic",
|
||||
desc: "Eye and vision therapeutic protocols",
|
||||
taxonomyId: "3f4a71cf-aa99-4ac7-ac59-0c0df42f74e7",
|
||||
icon: "eye-outline",
|
||||
color: "#06B6D4",
|
||||
category: "Therapeutics",
|
||||
isDefaultFree: false,
|
||||
planCode: "THERAPEUTICS_CORE",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import apiClient from "@/api/client";
|
||||
import { API_ENDPOINTS } from "@/api/endpoints";
|
||||
import type { AccessMeResponse } from "@/store/types";
|
||||
|
||||
export async function getAccessMe(): Promise<AccessMeResponse> {
|
||||
const response = await apiClient.get<AccessMeResponse>(
|
||||
API_ENDPOINTS.ACCESS.ME,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
import React, { PropsWithChildren, useEffect, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, StyleSheet, Text, TouchableOpacity, View } from "react-native";
|
||||
import { router } from "expo-router";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
import { useAuthStore } from "@/store/auth.store";
|
||||
import { useModulesQuery } from "@/features/content/hooks/use-content-queries";
|
||||
import {
|
||||
normalizeModuleListResponse,
|
||||
toModuleIndexItem,
|
||||
} from "@/features/modules/module-index";
|
||||
import { isModuleUnlockedByAccess } from "@/features/access/module-access";
|
||||
|
||||
interface ModuleAccessGateProps extends PropsWithChildren {
|
||||
moduleCode: string;
|
||||
}
|
||||
|
||||
export function ModuleAccessGate({ moduleCode, children }: ModuleAccessGateProps) {
|
||||
const accessToken = useAuthStore((state) => state.accessToken);
|
||||
const access = useAuthStore((state) => state.access);
|
||||
const refreshAccess = useAuthStore((state) => state.refreshAccess);
|
||||
const modulesQuery = useModulesQuery();
|
||||
const [accessChecked, setAccessChecked] = useState(false);
|
||||
const [accessRefreshSucceeded, setAccessRefreshSucceeded] = useState(false);
|
||||
const [accessError, setAccessError] = useState(false);
|
||||
|
||||
const modules = useMemo(
|
||||
() => normalizeModuleListResponse(modulesQuery.data),
|
||||
[modulesQuery.data],
|
||||
);
|
||||
const module = useMemo(
|
||||
() => modules.find((item) => item.code === moduleCode),
|
||||
[moduleCode, modules],
|
||||
);
|
||||
const item = useMemo(
|
||||
() => (module ? toModuleIndexItem(module) : null),
|
||||
[module],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
setAccessChecked(false);
|
||||
setAccessRefreshSucceeded(false);
|
||||
setAccessError(false);
|
||||
|
||||
if (!accessToken) {
|
||||
setAccessChecked(true);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}
|
||||
|
||||
void refreshAccess()
|
||||
.then(() => {
|
||||
if (active) setAccessRefreshSucceeded(true);
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setAccessError(true);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setAccessChecked(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [accessToken, refreshAccess]);
|
||||
|
||||
const unlocked = Boolean(
|
||||
module && isModuleUnlockedByAccess(module, access),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (modulesQuery.isLoading || !accessChecked) return;
|
||||
|
||||
if (!accessToken) {
|
||||
router.replace("/register");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!accessRefreshSucceeded || !item || unlocked) return;
|
||||
|
||||
router.replace({
|
||||
pathname: "/subscription",
|
||||
params: {
|
||||
moduleId: item.module.id,
|
||||
moduleCode: item.module.code,
|
||||
title: item.title,
|
||||
category: item.category,
|
||||
desc: item.description,
|
||||
planCode: item.planCode,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
accessChecked,
|
||||
accessRefreshSucceeded,
|
||||
accessToken,
|
||||
item,
|
||||
modulesQuery.isLoading,
|
||||
unlocked,
|
||||
]);
|
||||
|
||||
|
||||
if (accessChecked && accessToken && accessError) {
|
||||
return (
|
||||
<View style={styles.loadingContainer}>
|
||||
<Text style={styles.errorTitle}>Unable to verify module access</Text>
|
||||
<Text style={styles.errorText}>Connect to the internet and try again.</Text>
|
||||
<TouchableOpacity style={styles.retryButton} onPress={() => router.replace("/modules")}>
|
||||
<Text style={styles.retryText}>Back to Modules</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
modulesQuery.isLoading ||
|
||||
!accessChecked ||
|
||||
!accessRefreshSucceeded ||
|
||||
!accessToken ||
|
||||
!item ||
|
||||
!unlocked
|
||||
) {
|
||||
return (
|
||||
<View style={styles.loadingContainer}>
|
||||
<ActivityIndicator size="large" color={Colors.primary} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
loadingContainer: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: Colors.background,
|
||||
paddingHorizontal: 24,
|
||||
},
|
||||
errorTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: "700",
|
||||
color: Colors.textPrimary,
|
||||
textAlign: "center",
|
||||
},
|
||||
errorText: {
|
||||
marginTop: 8,
|
||||
fontSize: 14,
|
||||
color: Colors.textSecondary,
|
||||
textAlign: "center",
|
||||
},
|
||||
retryButton: {
|
||||
marginTop: 18,
|
||||
paddingHorizontal: 18,
|
||||
paddingVertical: 10,
|
||||
borderRadius: 12,
|
||||
backgroundColor: Colors.primary,
|
||||
},
|
||||
retryText: {
|
||||
color: "#FFFFFF",
|
||||
fontWeight: "700",
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import type { AccessMeResponse } from "@/store/types";
|
||||
|
||||
export interface ModuleAccessIdentity {
|
||||
code?: string | null;
|
||||
slug?: string | null;
|
||||
}
|
||||
|
||||
export function isModuleUnlockedByAccess(
|
||||
module: ModuleAccessIdentity,
|
||||
access: AccessMeResponse | null,
|
||||
): boolean {
|
||||
if (!access) return false;
|
||||
|
||||
const code = module.code?.trim();
|
||||
const slug = module.slug?.trim();
|
||||
|
||||
if (code && access.unlocked_module_codes.includes(code)) return true;
|
||||
if (slug && access.unlocked_module_slugs.includes(slug)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
import apiClient from "@/api/client";
|
||||
import { API_ENDPOINTS } from "@/api/endpoints";
|
||||
import type {
|
||||
AuthTokenResponse,
|
||||
ForgotPasswordRequest,
|
||||
LoginRequest,
|
||||
RegisterRequest,
|
||||
ResetPasswordRequest,
|
||||
StatusMessageResponse,
|
||||
UserIdentity,
|
||||
} from "@/store/types";
|
||||
|
||||
export async function login(
|
||||
payload: LoginRequest,
|
||||
): Promise<AuthTokenResponse> {
|
||||
const response = await apiClient.post<AuthTokenResponse>(
|
||||
API_ENDPOINTS.AUTH.LOGIN,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function register(
|
||||
payload: RegisterRequest,
|
||||
): Promise<AuthTokenResponse> {
|
||||
const response = await apiClient.post<AuthTokenResponse>(
|
||||
API_ENDPOINTS.AUTH.REGISTER,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getMe(): Promise<UserIdentity> {
|
||||
const response = await apiClient.get<UserIdentity>(
|
||||
API_ENDPOINTS.AUTH.ME,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function forgotPassword(
|
||||
payload: ForgotPasswordRequest,
|
||||
): Promise<StatusMessageResponse> {
|
||||
const response = await apiClient.post<StatusMessageResponse>(
|
||||
API_ENDPOINTS.AUTH.FORGOT_PASSWORD,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function resetPassword(
|
||||
payload: ResetPasswordRequest,
|
||||
): Promise<StatusMessageResponse> {
|
||||
const response = await apiClient.post<StatusMessageResponse>(
|
||||
API_ENDPOINTS.AUTH.RESET_PASSWORD,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export interface ProfileUpdatePayload {
|
||||
full_name?: string | null;
|
||||
email?: string | null;
|
||||
phone_number?: string | null;
|
||||
}
|
||||
|
||||
export async function updateProfile(
|
||||
payload: ProfileUpdatePayload,
|
||||
): Promise<{ status: string; message: string; user: AuthTokenResponse["user"] }> {
|
||||
const response = await apiClient.put<{ status: string; message: string; user: AuthTokenResponse["user"] }>(
|
||||
API_ENDPOINTS.AUTH.PROFILE,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
import React from "react";
|
||||
import {
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
moderateScale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import { AuthColors } from "../constants/colors";
|
||||
|
||||
interface LoginFooterProps {
|
||||
onSignUpPress?: () => void;
|
||||
}
|
||||
|
||||
export default function LoginFooter({
|
||||
onSignUpPress,
|
||||
}: LoginFooterProps) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.text}>
|
||||
Don't have an account?
|
||||
</Text>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Sign Up"
|
||||
onPress={onSignUpPress}
|
||||
hitSlop={10}
|
||||
>
|
||||
<Text style={styles.signUp}>
|
||||
Sign Up
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(36),
|
||||
flexDirection: "row",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
text: {
|
||||
fontSize: moderateScale(14),
|
||||
color: AuthColors.textSecondary,
|
||||
},
|
||||
|
||||
signUp: {
|
||||
marginLeft: moderateScale(6),
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "700",
|
||||
color: AuthColors.primary,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
import React, { useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
import {
|
||||
moderateScale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import BaseTextInput from "@/components/forms/BaseTextInput";
|
||||
import PasswordInput from "@/components/forms/PasswordInput";
|
||||
import PrimaryButton from "@/components/buttons/PrimaryButton";
|
||||
|
||||
import { AuthColors } from "../constants/colors";
|
||||
import { useAuthStore } from "@/store/auth.store";
|
||||
import { LoginMethod } from "./LoginTabs";
|
||||
import { login } from "@/features/auth/api/auth.api";
|
||||
|
||||
interface LoginFormProps {
|
||||
activeTab: LoginMethod;
|
||||
}
|
||||
|
||||
export default function LoginForm({
|
||||
activeTab,
|
||||
}: LoginFormProps) {
|
||||
const router = useRouter();
|
||||
const establishSession = useAuthStore((state) => state.establishSession);
|
||||
|
||||
const [email, setEmail] = useState("");
|
||||
const [phone, setPhone] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
|
||||
const [emailError, setEmailError] = useState("");
|
||||
const [phoneError, setPhoneError] = useState("");
|
||||
const [passwordError, setPasswordError] = useState("");
|
||||
|
||||
const handlePhoneChange = (text: string) => {
|
||||
const digits = text.replace(/\D/g, "");
|
||||
setPhone(digits.slice(0, 10));
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
let hasError = false;
|
||||
setEmailError("");
|
||||
setPhoneError("");
|
||||
setPasswordError("");
|
||||
|
||||
if (activeTab === "email") {
|
||||
if (!email.trim()) {
|
||||
setEmailError("Email is required");
|
||||
hasError = true;
|
||||
} else if (!/\S+@\S+\.\S+/.test(email)) {
|
||||
setEmailError("Please enter a valid email address");
|
||||
hasError = true;
|
||||
}
|
||||
} else {
|
||||
if (!phone.trim()) {
|
||||
setPhoneError("Phone number is required");
|
||||
hasError = true;
|
||||
} else if (phone.length < 10) {
|
||||
setPhoneError("Phone number must be 10 digits");
|
||||
hasError = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
setPasswordError("Password is required");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (hasError) return;
|
||||
|
||||
try {
|
||||
// Prepare login payload
|
||||
const payload: any = { password };
|
||||
if (activeTab === "email") {
|
||||
payload.email = email.trim().toLowerCase();
|
||||
} else {
|
||||
payload.phone_number = phone.trim();
|
||||
}
|
||||
|
||||
const response = await login(payload);
|
||||
await establishSession(response);
|
||||
|
||||
// Navigate to Home only after the token is installed and initial
|
||||
// identity/access refresh has been attempted.
|
||||
router.replace("/");
|
||||
} catch (err: any) {
|
||||
let errMsg = "Invalid credentials. Please try again.";
|
||||
const detail = err.response?.data?.detail;
|
||||
if (typeof detail === "string") {
|
||||
errMsg = detail;
|
||||
} else if (Array.isArray(detail) && detail.length > 0) {
|
||||
errMsg = detail[0].msg || JSON.stringify(detail[0]);
|
||||
} else if (err.message) {
|
||||
errMsg = err.message;
|
||||
}
|
||||
alert("Login Failed: " + errMsg);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
{activeTab === "email" ? (
|
||||
<BaseTextInput
|
||||
value={email}
|
||||
onChangeText={setEmail}
|
||||
placeholder="Email Address"
|
||||
keyboardType="email-address"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="emailAddress"
|
||||
leftIcon="mail-outline"
|
||||
error={emailError}
|
||||
/>
|
||||
) : (
|
||||
<BaseTextInput
|
||||
value={phone}
|
||||
onChangeText={handlePhoneChange}
|
||||
placeholder="Phone Number"
|
||||
keyboardType="number-pad"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="telephoneNumber"
|
||||
maxLength={10}
|
||||
leftIcon="call-outline"
|
||||
error={phoneError}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PasswordInput
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
error={passwordError}
|
||||
/>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
style={styles.forgotButton}
|
||||
onPress={() => {
|
||||
router.push("/login/forgot-password");
|
||||
}}
|
||||
>
|
||||
<Text style={styles.forgotText}>
|
||||
Forgot Password?
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
<PrimaryButton
|
||||
title="Log In"
|
||||
onPress={handleLogin}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(10),
|
||||
},
|
||||
|
||||
forgotButton: {
|
||||
alignSelf: "flex-end",
|
||||
marginTop: verticalScale(4),
|
||||
marginBottom: verticalScale(20),
|
||||
},
|
||||
|
||||
forgotText: {
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "600",
|
||||
color: AuthColors.primary,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
import React from "react";
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import { AuthColors } from "../constants/colors";
|
||||
import {
|
||||
moderateScale,
|
||||
scale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
export default function LoginHeader() {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Go Back"
|
||||
hitSlop={10}
|
||||
onPress={() => router.back()}
|
||||
style={styles.backButton}
|
||||
>
|
||||
<Ionicons
|
||||
name="arrow-back"
|
||||
size={moderateScale(24)}
|
||||
/>
|
||||
</Pressable>
|
||||
|
||||
<View style={styles.textContainer}>
|
||||
<Text style={styles.title}>Welcome Back!</Text>
|
||||
|
||||
<Text style={styles.subtitle}>
|
||||
Login to continue
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(8),
|
||||
marginBottom: verticalScale(32),
|
||||
},
|
||||
|
||||
backButton: {
|
||||
width: scale(40),
|
||||
height: scale(40),
|
||||
justifyContent: "center",
|
||||
marginBottom: verticalScale(28),
|
||||
},
|
||||
|
||||
textContainer: {
|
||||
gap: moderateScale(8),
|
||||
},
|
||||
|
||||
title: {
|
||||
fontSize: moderateScale(32),
|
||||
fontWeight: "700",
|
||||
color: AuthColors.textPrimary,
|
||||
},
|
||||
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
color: AuthColors.textSecondary,
|
||||
fontWeight: "500",
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
import React from "react";
|
||||
import {
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
moderateScale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import { AuthColors } from "../constants/colors";
|
||||
|
||||
export type LoginMethod = "email" | "phone";
|
||||
|
||||
interface LoginTabsProps {
|
||||
activeTab: LoginMethod;
|
||||
onTabChange: (tab: LoginMethod) => void;
|
||||
}
|
||||
|
||||
export default function LoginTabs({
|
||||
activeTab,
|
||||
onTabChange,
|
||||
}: LoginTabsProps) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Login with Email"
|
||||
style={styles.tab}
|
||||
onPress={() => onTabChange("email")}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.text,
|
||||
activeTab === "email" && styles.activeText,
|
||||
]}
|
||||
>
|
||||
Email
|
||||
</Text>
|
||||
|
||||
{activeTab === "email" && (
|
||||
<View style={styles.indicator} />
|
||||
)}
|
||||
</Pressable>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Login with Phone"
|
||||
style={styles.tab}
|
||||
onPress={() => onTabChange("phone")}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.text,
|
||||
activeTab === "phone" && styles.activeText,
|
||||
]}
|
||||
>
|
||||
Phone
|
||||
</Text>
|
||||
|
||||
{activeTab === "phone" && (
|
||||
<View style={styles.indicator} />
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: "row",
|
||||
marginBottom: verticalScale(30),
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: "#ECECEC",
|
||||
},
|
||||
|
||||
tab: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingBottom: verticalScale(12),
|
||||
position: "relative",
|
||||
},
|
||||
|
||||
text: {
|
||||
fontSize: moderateScale(16),
|
||||
fontWeight: "500",
|
||||
color: AuthColors.textSecondary,
|
||||
},
|
||||
|
||||
activeText: {
|
||||
color: AuthColors.primary,
|
||||
fontWeight: "700",
|
||||
},
|
||||
|
||||
indicator: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: -1,
|
||||
height: verticalScale(3),
|
||||
borderRadius: moderateScale(2),
|
||||
backgroundColor: AuthColors.primary,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
import React from "react";
|
||||
import {
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
moderateScale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import { AuthColors } from "../constants/colors";
|
||||
|
||||
interface SignUpFooterProps {
|
||||
onLogInPress?: () => void;
|
||||
}
|
||||
|
||||
export default function SignUpFooter({
|
||||
onLogInPress,
|
||||
}: SignUpFooterProps) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.text}>
|
||||
Already have an account?
|
||||
</Text>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Log In"
|
||||
onPress={onLogInPress}
|
||||
hitSlop={10}
|
||||
>
|
||||
<Text style={styles.logIn}>
|
||||
Log In
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(28),
|
||||
flexDirection: "row",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
text: {
|
||||
fontSize: moderateScale(14),
|
||||
color: AuthColors.textSecondary,
|
||||
},
|
||||
|
||||
logIn: {
|
||||
marginLeft: moderateScale(6),
|
||||
fontSize: moderateScale(14),
|
||||
fontWeight: "700",
|
||||
color: AuthColors.primary,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
import React, { useState } from "react";
|
||||
import { Alert, StyleSheet, View } from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
import { verticalScale } from "react-native-size-matters";
|
||||
|
||||
import BaseTextInput from "@/components/forms/BaseTextInput";
|
||||
import PasswordInput from "@/components/forms/PasswordInput";
|
||||
import PrimaryButton from "@/components/buttons/PrimaryButton";
|
||||
|
||||
import { useAuthStore } from "@/store/auth.store";
|
||||
import { register } from "@/features/auth/api/auth.api";
|
||||
|
||||
export default function SignUpForm() {
|
||||
const router = useRouter();
|
||||
const setRegisteredUser = useAuthStore((state) => state.setRegisteredUser);
|
||||
|
||||
const [fullName, setFullName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [phone, setPhone] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
|
||||
const [fullNameError, setFullNameError] = useState("");
|
||||
const [emailError, setEmailError] = useState("");
|
||||
const [phoneError, setPhoneError] = useState("");
|
||||
const [passwordError, setPasswordError] = useState("");
|
||||
const [confirmPasswordError, setConfirmPasswordError] = useState("");
|
||||
|
||||
const handlePhoneChange = (text: string) => {
|
||||
const digits = text.replace(/\D/g, "");
|
||||
setPhone(digits.slice(0, 10));
|
||||
};
|
||||
|
||||
const handleSignUp = async () => {
|
||||
let hasError = false;
|
||||
setFullNameError("");
|
||||
setEmailError("");
|
||||
setPhoneError("");
|
||||
setPasswordError("");
|
||||
setConfirmPasswordError("");
|
||||
|
||||
if (!fullName.trim()) {
|
||||
setFullNameError("Full name is required");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (!email.trim()) {
|
||||
setEmailError("Email is required");
|
||||
hasError = true;
|
||||
} else if (!/\S+@\S+\.\S+/.test(email)) {
|
||||
setEmailError("Please enter a valid email address");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (phone.trim() && phone.length < 10) {
|
||||
setPhoneError("Phone number must be 10 digits");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
setPasswordError("Password is required");
|
||||
hasError = true;
|
||||
} else if (password.length < 8) {
|
||||
setPasswordError("Password must be at least 8 characters");
|
||||
hasError = true;
|
||||
} else if (!/[A-Z]/.test(password)) {
|
||||
setPasswordError("Password must contain at least one uppercase letter (A-Z)");
|
||||
hasError = true;
|
||||
} else if (!/[0-9]/.test(password)) {
|
||||
setPasswordError("Password must contain at least one number (0-9)");
|
||||
hasError = true;
|
||||
} else if (!/[^A-Za-z0-9]/.test(password)) {
|
||||
setPasswordError("Password must contain at least one special character (!@#$)");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (!confirmPassword) {
|
||||
setConfirmPasswordError("Please confirm your password");
|
||||
hasError = true;
|
||||
} else if (password !== confirmPassword) {
|
||||
setConfirmPasswordError("Passwords do not match");
|
||||
hasError = true;
|
||||
}
|
||||
|
||||
if (hasError) return;
|
||||
|
||||
try {
|
||||
const response = await register({
|
||||
email: email.trim().toLowerCase(),
|
||||
password,
|
||||
full_name: fullName.trim(),
|
||||
phone_number: phone.trim() ? phone.trim() : undefined,
|
||||
});
|
||||
|
||||
const { user } = response;
|
||||
|
||||
setRegisteredUser({
|
||||
id: user.id,
|
||||
name: user.display_name,
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
// Redirect directly to login screen without alert block
|
||||
router.replace("/login");
|
||||
} catch (err: any) {
|
||||
let errMsg = "Something went wrong. Please try again.";
|
||||
const detail = err.response?.data?.detail;
|
||||
if (typeof detail === "string") {
|
||||
errMsg = detail;
|
||||
} else if (Array.isArray(detail) && detail.length > 0) {
|
||||
errMsg = detail[0].msg || JSON.stringify(detail[0]);
|
||||
}
|
||||
alert("Registration Failed: " + errMsg);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<BaseTextInput
|
||||
value={fullName}
|
||||
onChangeText={setFullName}
|
||||
placeholder="Full Name"
|
||||
autoCapitalize="words"
|
||||
autoCorrect={false}
|
||||
leftIcon="person-outline"
|
||||
error={fullNameError}
|
||||
/>
|
||||
|
||||
<BaseTextInput
|
||||
value={email}
|
||||
onChangeText={setEmail}
|
||||
placeholder="Email Address"
|
||||
keyboardType="email-address"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="emailAddress"
|
||||
leftIcon="mail-outline"
|
||||
error={emailError}
|
||||
/>
|
||||
|
||||
<BaseTextInput
|
||||
value={phone}
|
||||
onChangeText={handlePhoneChange}
|
||||
placeholder="Phone Number (Optional)"
|
||||
keyboardType="number-pad"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="telephoneNumber"
|
||||
maxLength={10}
|
||||
leftIcon="call-outline"
|
||||
error={phoneError}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Password"
|
||||
error={passwordError}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
value={confirmPassword}
|
||||
onChangeText={setConfirmPassword}
|
||||
placeholder="Confirm Password"
|
||||
error={confirmPasswordError}
|
||||
/>
|
||||
|
||||
<View style={styles.buttonSpacing}>
|
||||
<PrimaryButton
|
||||
title="Sign Up"
|
||||
onPress={handleSignUp}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(10),
|
||||
},
|
||||
buttonSpacing: {
|
||||
marginTop: verticalScale(10),
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
import React from "react";
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import { AuthColors } from "../constants/colors";
|
||||
import {
|
||||
moderateScale,
|
||||
scale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
export default function SignUpHeader() {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Go Back"
|
||||
hitSlop={10}
|
||||
onPress={() => router.back()}
|
||||
style={styles.backButton}
|
||||
>
|
||||
<Ionicons
|
||||
name="arrow-back"
|
||||
size={moderateScale(24)}
|
||||
/>
|
||||
</Pressable>
|
||||
|
||||
<View style={styles.textContainer}>
|
||||
<Text style={styles.title}>Create Account</Text>
|
||||
|
||||
<Text style={styles.subtitle}>
|
||||
Sign up to get started
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(8),
|
||||
marginBottom: verticalScale(24),
|
||||
},
|
||||
|
||||
backButton: {
|
||||
width: scale(40),
|
||||
height: scale(40),
|
||||
justifyContent: "center",
|
||||
marginBottom: verticalScale(20),
|
||||
},
|
||||
|
||||
textContainer: {
|
||||
gap: moderateScale(8),
|
||||
},
|
||||
|
||||
title: {
|
||||
fontSize: moderateScale(32),
|
||||
fontWeight: "700",
|
||||
color: AuthColors.textPrimary,
|
||||
},
|
||||
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
color: AuthColors.textSecondary,
|
||||
fontWeight: "500",
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import React from "react";
|
||||
import {
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
moderateScale,
|
||||
scale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
interface SocialButtonProps {
|
||||
icon: React.ReactNode;
|
||||
onPress?: () => void;
|
||||
}
|
||||
|
||||
export default function SocialButton({
|
||||
icon,
|
||||
onPress,
|
||||
}: SocialButtonProps) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
style={({ pressed }) => [
|
||||
styles.container,
|
||||
pressed && styles.pressed,
|
||||
]}
|
||||
onPress={onPress}
|
||||
>
|
||||
<View style={styles.iconContainer}>
|
||||
{icon}
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
width: scale(58),
|
||||
height: scale(58),
|
||||
borderRadius: moderateScale(29),
|
||||
|
||||
backgroundColor: "#FFFFFF",
|
||||
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
|
||||
borderWidth: 1,
|
||||
borderColor: "#ECECEC",
|
||||
|
||||
marginHorizontal: scale(8),
|
||||
},
|
||||
|
||||
iconContainer: {
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
pressed: {
|
||||
opacity: 0.8,
|
||||
transform: [{ scale: 0.96 }],
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
import React from "react";
|
||||
import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
|
||||
import {
|
||||
moderateScale,
|
||||
verticalScale,
|
||||
} from "react-native-size-matters";
|
||||
|
||||
import {
|
||||
Ionicons,
|
||||
FontAwesome,
|
||||
} from "@expo/vector-icons";
|
||||
|
||||
import SocialButton from "./SocialButton";
|
||||
import { AuthColors } from "../constants/colors";
|
||||
|
||||
export default function SocialLogin() {
|
||||
return null;
|
||||
// return (
|
||||
// <View style={styles.container}>
|
||||
// <View style={styles.dividerRow}>
|
||||
// <View style={styles.line} />
|
||||
//
|
||||
// <Text style={styles.text}>
|
||||
// or continue with
|
||||
// </Text>
|
||||
//
|
||||
// <View style={styles.line} />
|
||||
// </View>
|
||||
//
|
||||
// <View style={styles.iconsRow}>
|
||||
// <SocialButton
|
||||
// icon={
|
||||
// <FontAwesome
|
||||
// name="google"
|
||||
// size={24}
|
||||
// color="#DB4437"
|
||||
// />
|
||||
// }
|
||||
// />
|
||||
//
|
||||
// <SocialButton
|
||||
// icon={
|
||||
// <Ionicons
|
||||
// name="logo-apple"
|
||||
// size={26}
|
||||
// color="#000"
|
||||
// />
|
||||
// }
|
||||
// />
|
||||
//
|
||||
// <SocialButton
|
||||
// icon={
|
||||
// <Ionicons
|
||||
// name="mail-outline"
|
||||
// size={24}
|
||||
// color={AuthColors.primary}
|
||||
// />
|
||||
// }
|
||||
// />
|
||||
// </View>
|
||||
// </View>
|
||||
// );
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
marginTop: verticalScale(34),
|
||||
},
|
||||
|
||||
dividerRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
line: {
|
||||
flex: 1,
|
||||
height: 1,
|
||||
backgroundColor: "#ECECEC",
|
||||
},
|
||||
|
||||
text: {
|
||||
marginHorizontal: moderateScale(12),
|
||||
|
||||
fontSize: moderateScale(14),
|
||||
|
||||
color: AuthColors.textSecondary,
|
||||
},
|
||||
|
||||
iconsRow: {
|
||||
marginTop: verticalScale(24),
|
||||
|
||||
flexDirection: "row",
|
||||
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
export const AuthColors = {
|
||||
primary: "#4F46E5",
|
||||
primaryDark: "#4338CA",
|
||||
primaryLight: "#EEF2FF",
|
||||
|
||||
background: "#FFFFFF",
|
||||
|
||||
textPrimary: "#171717",
|
||||
textSecondary: "#6B7280",
|
||||
|
||||
border: "#E5E7EB",
|
||||
|
||||
inputBackground: "#FFFFFF",
|
||||
|
||||
divider: "#E5E7EB",
|
||||
|
||||
disabled: "#C7C7C7",
|
||||
|
||||
white: "#FFFFFF",
|
||||
|
||||
danger: "#EF4444",
|
||||
} as const;
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import apiClient from "@/api/client";
|
||||
import { API_ENDPOINTS } from "@/api/endpoints";
|
||||
import type {
|
||||
CartCalculationRequest,
|
||||
CartCalculationResponse,
|
||||
CheckoutOrderRequest,
|
||||
CheckoutOrderResponse,
|
||||
CheckoutVerifyRequest,
|
||||
CheckoutVerifyResponse,
|
||||
} from "../types/commerce.types";
|
||||
|
||||
export async function calculateCart(
|
||||
payload: CartCalculationRequest,
|
||||
): Promise<CartCalculationResponse> {
|
||||
const response = await apiClient.post<CartCalculationResponse>(
|
||||
API_ENDPOINTS.CART.CALCULATE,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getCheckoutConfig(): Promise<{ razorpay_key_id: string }> {
|
||||
const response = await apiClient.get<{ razorpay_key_id: string }>(
|
||||
API_ENDPOINTS.CHECKOUT.CONFIG,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function createCheckoutOrder(
|
||||
payload: CheckoutOrderRequest,
|
||||
): Promise<CheckoutOrderResponse> {
|
||||
const response = await apiClient.post<CheckoutOrderResponse>(
|
||||
API_ENDPOINTS.CHECKOUT.CREATE_ORDER,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function verifyCheckoutPayment(
|
||||
payload: CheckoutVerifyRequest,
|
||||
): Promise<CheckoutVerifyResponse> {
|
||||
const response = await apiClient.post<CheckoutVerifyResponse>(
|
||||
API_ENDPOINTS.CHECKOUT.VERIFY,
|
||||
payload,
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getInvoiceUrl(
|
||||
paymentId: string,
|
||||
): Promise<{ short_url: string }> {
|
||||
const response = await apiClient.get<{ short_url: string }>(
|
||||
API_ENDPOINTS.CHECKOUT.INVOICE(paymentId),
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export * from "./api/commerce.api";
|
||||
export * from "./types/commerce.types";
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
export interface CartCalculationRequest {
|
||||
cart_item_codes: string[];
|
||||
owned_category_names?: string[];
|
||||
coupon_code?: string | null;
|
||||
currency?: string;
|
||||
is_first_purchase?: boolean;
|
||||
}
|
||||
|
||||
export interface CartItemResponse {
|
||||
code: string;
|
||||
name: string;
|
||||
category: string;
|
||||
price: number;
|
||||
}
|
||||
|
||||
export interface CartCalculationResponse {
|
||||
currency: string;
|
||||
base_subtotal: number;
|
||||
discount_policy: string;
|
||||
bundle_discount_amount: number;
|
||||
coupon_applied: string;
|
||||
coupon_discount_amount: number;
|
||||
total_discounts: number;
|
||||
convenience_fee_rate: number;
|
||||
convenience_fee: number;
|
||||
taxable_amount: number;
|
||||
gst_amount: number;
|
||||
grand_total: number;
|
||||
cart_items: CartItemResponse[];
|
||||
}
|
||||
|
||||
export interface CheckoutOrderRequest {
|
||||
cart_item_codes: string[];
|
||||
coupon_code?: string | null;
|
||||
currency?: string;
|
||||
}
|
||||
|
||||
export interface CheckoutOrderResponse {
|
||||
razorpay_order_id: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
receipt: string;
|
||||
base_subtotal: number;
|
||||
total_discounts: number;
|
||||
convenience_fee: number;
|
||||
convenience_fee_rate: number;
|
||||
taxable_amount: number;
|
||||
gst_amount: number;
|
||||
grand_total: number;
|
||||
}
|
||||
|
||||
export interface CheckoutVerifyRequest {
|
||||
razorpay_order_id: string;
|
||||
razorpay_payment_id: string;
|
||||
razorpay_signature: string;
|
||||
billing_profile_id?: string | null;
|
||||
currency?: string;
|
||||
}
|
||||
|
||||
export interface CheckoutVerifyResponse {
|
||||
status: string;
|
||||
message: string;
|
||||
razorpay_payment_id: string;
|
||||
invoice_number?: string | null;
|
||||
invoice_url?: string | null;
|
||||
}
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { StyleSheet, Text, View } from "react-native";
|
||||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
import { ContentPageHeader } from "../components/layout/ContentPageHeader";
|
||||
import { ContractSortModal } from "../components/search/ContractSortModal";
|
||||
import { SearchAttributeModal } from "../components/search/SearchAttributeModal";
|
||||
import { FilterSummary } from "../components/search/FilterSummary";
|
||||
import { SearchHeader } from "../components/search/SearchHeader";
|
||||
import { ModuleFilterBuilderModal } from "../components/search/ModuleFilterBuilderModal";
|
||||
import { ModuleFilterChips } from "../components/search/ModuleFilterChips";
|
||||
import { ModuleSearchResults } from "../components/search/ModuleSearchResults";
|
||||
import { ScreenError } from "../components/ContentScreenState";
|
||||
import { useContentSearchInfiniteQuery } from "../hooks/use-content-search-infinite-query";
|
||||
import { useModuleContentSearchInfiniteQuery } from "../hooks/use-module-content-search-infinite-query";
|
||||
import { useModuleSearchContractQuery } from "../hooks/use-module-search-contract-query";
|
||||
import { useTemplateSearchController } from "../hooks/use-template-search-controller";
|
||||
import { useDebouncedValue } from "../hooks/use-debounced-value";
|
||||
import { resolveCollectionItemRenderer, resolveCollectionRenderer } from "../renderers/registry";
|
||||
import type { LogicalOperator, ModuleSearchContentItem, SearchContentItem, SearchCriterion, SortCriterion, TemplateContractResponse } from "../types/presentation.types";
|
||||
|
||||
export interface CollectionTemplateScreenProps {
|
||||
moduleCode: string;
|
||||
moduleName: string;
|
||||
templateCode: string;
|
||||
contract: TemplateContractResponse;
|
||||
onItemPress: (item: SearchContentItem) => void;
|
||||
onModuleSearchItemPress: (item: ModuleSearchContentItem) => void;
|
||||
onOpenSort?: () => void;
|
||||
}
|
||||
|
||||
export function CollectionTemplateScreen({ moduleCode, moduleName, templateCode, contract, onItemPress, onModuleSearchItemPress, onOpenSort }: CollectionTemplateScreenProps) {
|
||||
const [filterBuilderVisible, setFilterBuilderVisible] = useState(false);
|
||||
const [sortVisible, setSortVisible] = useState(false);
|
||||
const [searchAttributesVisible, setSearchAttributesVisible] = useState(false);
|
||||
const [moduleQuery, setModuleQuery] = useState("");
|
||||
const debouncedModuleQuery = useDebouncedValue(moduleQuery.trim(), 350);
|
||||
const [moduleLogic, setModuleLogic] = useState<LogicalOperator>("and");
|
||||
const [moduleFilters, setModuleFilters] = useState<SearchCriterion[]>([]);
|
||||
const [moduleSearchAttributes, setModuleSearchAttributes] = useState<string[]>([]);
|
||||
const [moduleSort, setModuleSort] = useState<SortCriterion[]>([]);
|
||||
|
||||
const moduleContractQuery = useModuleSearchContractQuery(moduleCode);
|
||||
const moduleContract = moduleContractQuery.data;
|
||||
|
||||
useEffect(() => {
|
||||
if (!moduleContract) return;
|
||||
setModuleSort((current) =>
|
||||
current.length > 0 ? current : moduleContract.default_sort,
|
||||
);
|
||||
}, [moduleContract]);
|
||||
const searchableFields = useMemo(() => (moduleContract?.fields ?? []).filter((field) => field.is_searchable).map((field) => ({ attribute_key: field.attribute_key, label: `${field.label} · ${field.template_name}` })), [moduleContract?.fields]);
|
||||
const filterableFields = useMemo(() => (moduleContract?.fields ?? []).filter((field) => field.is_filterable), [moduleContract?.fields]);
|
||||
const moduleSearchActive = Boolean(debouncedModuleQuery) || moduleFilters.length > 0;
|
||||
|
||||
const templateSearch = useTemplateSearchController({ moduleCode, templateCode, contract });
|
||||
const templateQuery = useContentSearchInfiniteQuery({ module_code: moduleCode, template_code: templateCode, logic: contract.search.default_logic, filters: [], sort: templateSearch.sort, page_size: 25 }, { enabled: !moduleSearchActive });
|
||||
const moduleQueryResult = useModuleContentSearchInfiniteQuery({ module_code: moduleCode, query: debouncedModuleQuery || undefined, search_attributes: moduleSearchAttributes.length ? moduleSearchAttributes : undefined, logic: moduleLogic, filters: moduleFilters, sort: moduleSort, page_size: 25 }, { enabled: moduleSearchActive });
|
||||
|
||||
const templateMerged = useMemo(() => { const pages = templateQuery.data?.pages ?? []; return { total: pages[0]?.total ?? 0, items: pages.flatMap((page) => page.items) }; }, [templateQuery.data]);
|
||||
const moduleMerged = useMemo(() => { const pages = moduleQueryResult.data?.pages ?? []; return { total: pages[0]?.total ?? 0, items: pages.flatMap((page) => page.items) }; }, [moduleQueryResult.data]);
|
||||
|
||||
const rendererResolution = useMemo(() => {
|
||||
try {
|
||||
const collectionCode = contract.presentation.renderers.collection;
|
||||
const itemCode = contract.presentation.renderers.collection_item;
|
||||
if (!collectionCode || !itemCode) throw new Error("This content collection is missing its renderer configuration.");
|
||||
return { CollectionRenderer: resolveCollectionRenderer(collectionCode), ItemRenderer: resolveCollectionItemRenderer(itemCode), error: null as Error | null };
|
||||
} catch (error) {
|
||||
return { CollectionRenderer: null, ItemRenderer: null, error: error instanceof Error ? error : new Error("Renderer resolution failed.") };
|
||||
}
|
||||
}, [contract.presentation.renderers.collection, contract.presentation.renderers.collection_item]);
|
||||
|
||||
if (rendererResolution.error || !rendererResolution.CollectionRenderer || !rendererResolution.ItemRenderer) return <ScreenError title="Renderer configuration error" message={rendererResolution.error?.message} />;
|
||||
if (moduleContractQuery.isError) return <ScreenError title="Unable to load search options" message="The module search configuration request failed." onRetry={() => void moduleContractQuery.refetch()} />;
|
||||
if (moduleSearchActive && moduleQueryResult.isError) return <ScreenError title="Unable to search module" message="The module-wide content search request failed." onRetry={() => void moduleQueryResult.refetch()} />;
|
||||
if (!moduleSearchActive && templateQuery.isError) return <ScreenError title="Unable to load content" message="The content request failed." onRetry={() => void templateQuery.refetch()} />;
|
||||
|
||||
const CollectionRenderer = rendererResolution.CollectionRenderer;
|
||||
const ItemRenderer = rendererResolution.ItemRenderer;
|
||||
const hasFilters = filterableFields.length > 0;
|
||||
const hasSearchAttributes = searchableFields.length > 0;
|
||||
const hasSort = contract.search.sort_fields.length > 0;
|
||||
|
||||
return <SafeAreaView style={styles.safeArea} edges={["top","left","right"]}>
|
||||
<ContentPageHeader title={moduleName || "Content"} />
|
||||
<SearchHeader value={moduleQuery} onChangeText={setModuleQuery} placeholder="Search across this module…" />
|
||||
<FilterSummary filterCount={moduleFilters.length} searchAttributeCount={moduleSearchAttributes.length} sortCount={moduleSearchActive ? moduleSort.length : templateSearch.sort.length} showFilters={hasFilters} showSearchAttributes={hasSearchAttributes} showSort={hasSort} onFilter={() => setFilterBuilderVisible(true)} onSearchAttributes={() => setSearchAttributesVisible(true)} onSort={() => { if (onOpenSort) onOpenSort(); else setSortVisible(true); }} />
|
||||
<ModuleFilterChips fields={filterableFields} filters={moduleFilters} logic={moduleLogic} onLogicChange={setModuleLogic} onRemove={(index) => setModuleFilters((current) => current.filter((_, itemIndex) => itemIndex !== index))} onClear={() => setModuleFilters([])} />
|
||||
{moduleQuery !== debouncedModuleQuery ? <View style={styles.searchingRow}><Text style={styles.searchingText}>Searching…</Text></View> : null}
|
||||
<View style={styles.collectionContainer}>
|
||||
{moduleSearchActive ? <ModuleSearchResults items={moduleMerged.items} total={moduleMerged.total} isLoading={moduleQueryResult.isLoading} isRefreshing={moduleQueryResult.isRefetching && !moduleQueryResult.isFetchingNextPage} isFetchingNextPage={moduleQueryResult.isFetchingNextPage} onRefresh={() => void moduleQueryResult.refetch()} onLoadMore={() => { if (moduleQueryResult.hasNextPage && !moduleQueryResult.isFetchingNextPage) void moduleQueryResult.fetchNextPage(); }} onItemPress={onModuleSearchItemPress} /> : <CollectionRenderer items={templateMerged.items} total={templateMerged.total} isLoading={templateQuery.isLoading} isRefreshing={templateQuery.isRefetching && !templateQuery.isFetchingNextPage} isFetchingNextPage={templateQuery.isFetchingNextPage} onRefresh={() => void templateQuery.refetch()} onLoadMore={() => { if (templateQuery.hasNextPage && !templateQuery.isFetchingNextPage) void templateQuery.fetchNextPage(); }} onItemPress={onItemPress} renderItem={({item,onPress}) => <ItemRenderer item={item} onPress={onPress} />} />}
|
||||
</View>
|
||||
{hasFilters ? <ModuleFilterBuilderModal visible={filterBuilderVisible} fields={filterableFields} onClose={() => setFilterBuilderVisible(false)} onAdd={(criterion) => setModuleFilters((current) => [...current, criterion])} /> : null}
|
||||
{hasSearchAttributes ? <SearchAttributeModal visible={searchAttributesVisible} fields={searchableFields} selected={moduleSearchAttributes} onClose={() => setSearchAttributesVisible(false)} onApply={setModuleSearchAttributes} /> : null}
|
||||
{hasSort && !onOpenSort ? <ContractSortModal visible={sortVisible} fields={moduleSearchActive ? (moduleContract?.sort_fields ?? []) : contract.search.sort_fields} sort={moduleSearchActive ? moduleSort : templateSearch.sort} defaultSort={moduleSearchActive ? (moduleContract?.default_sort ?? []) : contract.search.default_sort} onClose={() => setSortVisible(false)} onApply={moduleSearchActive ? setModuleSort : templateSearch.setSort} /> : null}
|
||||
</SafeAreaView>;
|
||||
}
|
||||
|
||||
const styles=StyleSheet.create({safeArea:{flex:1,backgroundColor:Colors.surface},searchingRow:{paddingHorizontal:moderateScale(24),paddingBottom:verticalScale(6)},searchingText:{fontSize:moderateScale(12),color:Colors.textSecondary},collectionContainer:{flex:1}});
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
import React from "react";
|
||||
import { useRouter } from "expo-router";
|
||||
import { ScreenError, ScreenLoading } from "../components/ContentScreenState";
|
||||
import { useTemplateContractQuery } from "../hooks/use-template-contract-query";
|
||||
import { useModuleDisplayName } from "../hooks/use-module-display-name";
|
||||
import type { ModuleSearchContentItem, SearchContentItem, TemplateContractResponse } from "../types/presentation.types";
|
||||
import { buildContentReferenceRoute, getSingleNavigableContentReference } from "../utils/content-reference";
|
||||
import { CollectionTemplateScreen } from "./CollectionTemplateScreen";
|
||||
import { SingleTemplateScreen } from "./SingleTemplateScreen";
|
||||
|
||||
export interface TemplateScreenProps {
|
||||
moduleCode: string;
|
||||
templateCode: string;
|
||||
onContentPress?: (contentId: string) => void;
|
||||
onOpenFilters?: () => void;
|
||||
onOpenSort?: () => void;
|
||||
}
|
||||
|
||||
function normalized(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function buildItemTarget(
|
||||
moduleCode: string,
|
||||
templateCode: string,
|
||||
contract: TemplateContractResponse,
|
||||
item: SearchContentItem,
|
||||
): string {
|
||||
// Data-level hydrated content references are authoritative for the selected
|
||||
// content row when exactly one valid target exists. Multiple row links are
|
||||
// intentionally not guessed; semantic renderers should expose them explicitly.
|
||||
const rowReference = getSingleNavigableContentReference(item.attributes.link);
|
||||
if (rowReference) {
|
||||
return buildContentReferenceRoute(rowReference);
|
||||
}
|
||||
|
||||
const itemLink = contract.presentation.item_link;
|
||||
const targetTemplate = itemLink?.target_template_code?.trim() || templateCode;
|
||||
|
||||
if (itemLink?.action === "template") {
|
||||
return `/modules/${encodeURIComponent(moduleCode)}/${encodeURIComponent(targetTemplate)}`;
|
||||
}
|
||||
|
||||
const configuredContentIdKey = itemLink?.target_content_id_attribute?.trim();
|
||||
const configuredContentId = configuredContentIdKey
|
||||
? item.attributes[configuredContentIdKey]
|
||||
: undefined;
|
||||
const targetContentId =
|
||||
typeof configuredContentId === "string" && configuredContentId.trim()
|
||||
? configuredContentId.trim()
|
||||
: item.id;
|
||||
|
||||
return `/modules/${encodeURIComponent(moduleCode)}/${encodeURIComponent(targetTemplate)}/${encodeURIComponent(targetContentId)}`;
|
||||
}
|
||||
|
||||
export function TemplateScreen({
|
||||
moduleCode,
|
||||
templateCode,
|
||||
onContentPress,
|
||||
onOpenFilters,
|
||||
onOpenSort,
|
||||
}: TemplateScreenProps) {
|
||||
const router = useRouter();
|
||||
const module = normalized(moduleCode);
|
||||
const template = normalized(templateCode);
|
||||
|
||||
if (!module || !template) {
|
||||
return <ScreenError title="Invalid content route" message="Required content route information is missing." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<TemplateScreenResolved
|
||||
moduleCode={module}
|
||||
templateCode={template}
|
||||
onContentPress={onContentPress}
|
||||
onOpenFilters={onOpenFilters}
|
||||
onOpenSort={onOpenSort}
|
||||
navigate={(target) => router.push(target as never)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplateScreenResolved({
|
||||
moduleCode,
|
||||
templateCode,
|
||||
onContentPress,
|
||||
onOpenFilters,
|
||||
onOpenSort,
|
||||
navigate,
|
||||
}: TemplateScreenProps & { navigate: (target: string) => void }) {
|
||||
const contractQuery = useTemplateContractQuery(templateCode);
|
||||
const moduleDisplay = useModuleDisplayName(moduleCode);
|
||||
|
||||
if (contractQuery.isLoading) return <ScreenLoading message="Loading content…" />;
|
||||
|
||||
if (contractQuery.isError) {
|
||||
return (
|
||||
<ScreenError
|
||||
title="Unable to load content"
|
||||
message="The content configuration request failed."
|
||||
onRetry={() => void contractQuery.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const contract = contractQuery.data;
|
||||
if (!contract) return <ScreenError title="Content unavailable" message="The content configuration response was empty." />;
|
||||
|
||||
if (contract.template_code !== templateCode) {
|
||||
return <ScreenError title="Content configuration mismatch" message="The requested content screen does not match its configured template." />;
|
||||
}
|
||||
|
||||
if (contract.module_code && contract.module_code !== moduleCode) {
|
||||
return <ScreenError title="Content configuration mismatch" message="This content screen is not configured for the selected module." />;
|
||||
}
|
||||
|
||||
if (contract.presentation.mode === "single") {
|
||||
return <SingleTemplateScreen moduleCode={moduleCode} templateCode={templateCode} contract={contract} />;
|
||||
}
|
||||
|
||||
if (contract.presentation.mode === "collection") {
|
||||
return (
|
||||
<CollectionTemplateScreen
|
||||
moduleCode={moduleCode}
|
||||
moduleName={moduleDisplay.name}
|
||||
templateCode={templateCode}
|
||||
contract={contract}
|
||||
onModuleSearchItemPress={(item: ModuleSearchContentItem) => {
|
||||
navigate(`/modules/${encodeURIComponent(moduleCode)}/${encodeURIComponent(item.template_code)}/${encodeURIComponent(item.id)}`);
|
||||
}}
|
||||
onItemPress={(item) => {
|
||||
const rowReference = getSingleNavigableContentReference(item.attributes.link);
|
||||
|
||||
// A hydrated data-level reference is more specific than the optional
|
||||
// legacy callback because it identifies the actual destination content.
|
||||
if (rowReference) {
|
||||
navigate(buildContentReferenceRoute(rowReference));
|
||||
return;
|
||||
}
|
||||
|
||||
if (onContentPress && !contract.presentation.item_link) {
|
||||
onContentPress(item.id);
|
||||
return;
|
||||
}
|
||||
|
||||
navigate(buildItemTarget(moduleCode, templateCode, contract, item));
|
||||
}}
|
||||
onOpenSort={onOpenSort}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <ScreenError title="Unsupported content layout" message="This content screen returned an unsupported presentation mode." />;
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import type { AxiosInstance } from "axios";
|
||||
import { request } from "@/api/http-client";
|
||||
import type {
|
||||
ContentSearchRequest,
|
||||
ContentSearchResponse,
|
||||
TemplateContractResponse,
|
||||
} from "../types/presentation.types";
|
||||
|
||||
export class ContentPresentationApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
getTemplateContract(templateCode: string): Promise<TemplateContractResponse> {
|
||||
return request(this.client, {
|
||||
method: "GET",
|
||||
url: `/contents/templates/${encodeURIComponent(templateCode)}/contract`,
|
||||
});
|
||||
}
|
||||
|
||||
searchContents(payload: ContentSearchRequest): Promise<ContentSearchResponse> {
|
||||
return request(this.client, {
|
||||
method: "POST",
|
||||
url: "/contents/search",
|
||||
data: payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import apiClient from "@/api/client";
|
||||
import { ContentPresentationApi } from "./content-presentation.api";
|
||||
|
||||
export const contentPresentationApi = new ContentPresentationApi(apiClient);
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import type {
|
||||
ContentSearchRequest,
|
||||
SearchCriterion,
|
||||
SortCriterion,
|
||||
} from "../types/presentation.types";
|
||||
|
||||
function normalizeFilters(filters: SearchCriterion[]) {
|
||||
return filters.map((item) => ({
|
||||
attribute_key: item.attribute_key,
|
||||
operator: item.operator,
|
||||
value: item.value,
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizeSort(sort: SortCriterion[]) {
|
||||
return sort.map((item) => ({
|
||||
field: item.field,
|
||||
direction: item.direction,
|
||||
}));
|
||||
}
|
||||
|
||||
export const contentPresentationQueryKeys = {
|
||||
root: ["content", "presentation"] as const,
|
||||
|
||||
templateContract: (templateCode: string) =>
|
||||
["content", "presentation", "template", templateCode, "contract"] as const,
|
||||
|
||||
search: (request: Omit<ContentSearchRequest, "page">) =>
|
||||
[
|
||||
"content",
|
||||
"presentation",
|
||||
"search",
|
||||
request.module_id ?? null,
|
||||
request.module_code ?? null,
|
||||
request.template_code,
|
||||
request.query ?? "",
|
||||
request.logic,
|
||||
normalizeFilters(request.filters),
|
||||
normalizeSort(request.sort),
|
||||
request.page_size,
|
||||
] as const,
|
||||
};
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import { AxiosInstance } from "axios";
|
||||
import { request } from "@/api/http-client";
|
||||
import {
|
||||
ContentDetailResponse,
|
||||
ModuleContentListResponse,
|
||||
ModuleListResponse,
|
||||
ModuleRequest,
|
||||
ModuleTemplateContentDetailResponse,
|
||||
ModuleTemplateContentRequest,
|
||||
ModuleTemplateContentResponse,
|
||||
PublishContentResponse,
|
||||
ReconstructedContentResponse,
|
||||
TemplateAttributeDefinitionsResponse,
|
||||
} from "../types/content.types";
|
||||
|
||||
export class ContentApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
getModules(): Promise<ModuleListResponse> {
|
||||
return request(this.client, {
|
||||
method: "GET",
|
||||
url: "/contents/modules",
|
||||
});
|
||||
}
|
||||
|
||||
getModuleContents(payload: ModuleRequest): Promise<ModuleContentListResponse> {
|
||||
return request(this.client, {
|
||||
method: "POST",
|
||||
url: "/contents/module-contents",
|
||||
data: payload,
|
||||
});
|
||||
}
|
||||
|
||||
getModuleTemplateContents(
|
||||
payload: ModuleTemplateContentRequest,
|
||||
): Promise<ModuleTemplateContentResponse> {
|
||||
return request(this.client, {
|
||||
method: "POST",
|
||||
url: "/contents/module-template-contents",
|
||||
data: payload,
|
||||
});
|
||||
}
|
||||
|
||||
getModuleTemplateContentDetails(
|
||||
payload: ModuleTemplateContentRequest,
|
||||
): Promise<ModuleTemplateContentDetailResponse> {
|
||||
return request(this.client, {
|
||||
method: "POST",
|
||||
url: "/contents/module-template-content-details",
|
||||
data: payload,
|
||||
});
|
||||
}
|
||||
|
||||
getContent(contentId: string): Promise<ReconstructedContentResponse> {
|
||||
return request(this.client, {
|
||||
method: "GET",
|
||||
url: `/contents/${encodeURIComponent(contentId)}`,
|
||||
});
|
||||
}
|
||||
|
||||
getModuleContentDetail(
|
||||
payload: ModuleRequest,
|
||||
contentId: string,
|
||||
): Promise<ContentDetailResponse> {
|
||||
return request(this.client, {
|
||||
method: "POST",
|
||||
url: `/contents/module-contents/${encodeURIComponent(contentId)}`,
|
||||
data: payload,
|
||||
});
|
||||
}
|
||||
|
||||
getTemplateDefinitions(
|
||||
templateCode: string,
|
||||
): Promise<TemplateAttributeDefinitionsResponse> {
|
||||
return request(this.client, {
|
||||
method: "GET",
|
||||
url: `/contents/templates/${encodeURIComponent(templateCode)}/attributes`,
|
||||
});
|
||||
}
|
||||
|
||||
publishContent(
|
||||
contentId: string,
|
||||
actorId: string,
|
||||
): Promise<PublishContentResponse> {
|
||||
return request(this.client, {
|
||||
method: "POST",
|
||||
url: `/contents/${encodeURIComponent(contentId)}/publish`,
|
||||
params: { actor_id: actorId },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import apiClient from "@/api/client";
|
||||
import { ContentApi } from "./content.api";
|
||||
|
||||
/**
|
||||
* Canonical content API client.
|
||||
*
|
||||
* Content now shares the same Axios instance as auth/access/search so:
|
||||
* - the current bearer token is attached consistently;
|
||||
* - EXPO_PUBLIC_API_URL is the single API base URL;
|
||||
* - there is no second unauthenticated content client.
|
||||
*/
|
||||
export const httpClient = apiClient;
|
||||
export const contentApi = new ContentApi(apiClient);
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import { ModuleRequest } from "../types/content.types";
|
||||
|
||||
function moduleIdentity(request: ModuleRequest): string {
|
||||
if (request.module_id) return `id:${request.module_id}`;
|
||||
if (request.module_code) return `code:${request.module_code}`;
|
||||
return "unresolved";
|
||||
}
|
||||
|
||||
export const contentQueryKeys = {
|
||||
root: ["content"] as const,
|
||||
modules: () => ["content", "modules"] as const,
|
||||
moduleContents: (request: ModuleRequest) =>
|
||||
["content", "module", moduleIdentity(request), "contents"] as const,
|
||||
moduleTemplateContents: (request: ModuleRequest, templateCode: string) =>
|
||||
["content", "module", moduleIdentity(request), "template", templateCode, "contents"] as const,
|
||||
moduleTemplateDetails: (request: ModuleRequest, templateCode: string) =>
|
||||
["content", "module", moduleIdentity(request), "template", templateCode, "details"] as const,
|
||||
contentDetail: (contentId: string) =>
|
||||
["content", "detail", contentId] as const,
|
||||
moduleContentDetail: (request: ModuleRequest, contentId: string) =>
|
||||
["content", "module", moduleIdentity(request), "content", contentId] as const,
|
||||
templateDefinitions: (templateCode: string) =>
|
||||
["content", "template", templateCode, "definitions"] as const,
|
||||
};
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import { AxiosInstance } from "axios";
|
||||
import { request } from "@/api/http-client";
|
||||
import { ContentSearchRequest, ContentSearchResponse, TemplateContractResponse } from "../types/presentation.types";
|
||||
export class ContentPresentationApi { constructor(private readonly client:AxiosInstance){}
|
||||
getTemplateContract(templateCode:string):Promise<TemplateContractResponse>{return request(this.client,{method:"GET",url:`/contents/templates/${encodeURIComponent(templateCode)}/contract`});}
|
||||
searchContents(payload:ContentSearchRequest):Promise<ContentSearchResponse>{return request(this.client,{method:"POST",url:"/contents/search",data:payload});}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import apiClient from "@/api/client";
|
||||
import { ContentPresentationApi } from "./presentation.api";
|
||||
|
||||
export const contentPresentationApi = new ContentPresentationApi(apiClient);
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
import type {
|
||||
TemplateAttributePresentationContract,
|
||||
TemplatePresentationContract,
|
||||
} from "../types/presentation.types";
|
||||
|
||||
/**
|
||||
* Default required by the backend/frontend presentation contract.
|
||||
* A missing rule must never make an empty attribute visible implicitly.
|
||||
*/
|
||||
export const DEFAULT_EMPTY_BEHAVIOR = "hide" as const;
|
||||
export const DEFAULT_ATTRIBUTE_VISIBILITY = "show" as const;
|
||||
|
||||
export type AttributePresentationMap = ReadonlyMap<
|
||||
string,
|
||||
TemplateAttributePresentationContract
|
||||
>;
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
if (value === null || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a content value is semantically empty for presentation.
|
||||
*
|
||||
* Empty:
|
||||
* - null / undefined
|
||||
* - empty or whitespace-only strings
|
||||
* - arrays whose elements are all empty
|
||||
* - plain objects whose values are all empty
|
||||
*
|
||||
* Not empty:
|
||||
* - 0
|
||||
* - false
|
||||
* - non-empty strings
|
||||
* - numbers, including NaN/Infinity if they reached the presentation layer
|
||||
* - non-plain objects (they are treated as concrete values)
|
||||
*/
|
||||
export function isEmptyValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
return value.trim().length === 0;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.length === 0 || value.every(isEmptyValue);
|
||||
}
|
||||
|
||||
if (isPlainObject(value)) {
|
||||
const values = Object.values(value);
|
||||
return values.length === 0 || values.every(isEmptyValue);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an immutable, O(1)-lookup index for a template contract's attribute
|
||||
* presentation rules. Duplicate keys indicate a broken backend contract and
|
||||
* are rejected rather than silently allowing the last value to win.
|
||||
*/
|
||||
export function createAttributePresentationMap(
|
||||
attributes: readonly TemplateAttributePresentationContract[] | null | undefined,
|
||||
): AttributePresentationMap {
|
||||
const map = new Map<string, TemplateAttributePresentationContract>();
|
||||
|
||||
for (const rule of attributes ?? []) {
|
||||
const key = rule.attribute_key.trim();
|
||||
if (!key) {
|
||||
throw new Error("Attribute presentation rule contains a blank attribute_key.");
|
||||
}
|
||||
if (map.has(key)) {
|
||||
throw new Error(`Duplicate attribute presentation rule: ${key}`);
|
||||
}
|
||||
map.set(key, rule);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/** Convenience overload for callers holding the complete presentation contract. */
|
||||
export function createPresentationAttributeMap(
|
||||
presentation:
|
||||
| Pick<TemplatePresentationContract, "attributes">
|
||||
| null
|
||||
| undefined,
|
||||
): AttributePresentationMap {
|
||||
return createAttributePresentationMap(presentation?.attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the effective presentation rule for a canonical attribute key.
|
||||
*
|
||||
* The backend normally sends an effective rule for every active definition.
|
||||
* The fallback remains `hide` defensively for older/cached contracts.
|
||||
*/
|
||||
export function getAttributePresentationRule(
|
||||
attributeKey: string,
|
||||
rules: AttributePresentationMap | readonly TemplateAttributePresentationContract[] | null | undefined,
|
||||
): TemplateAttributePresentationContract {
|
||||
const normalizedKey = attributeKey.trim();
|
||||
if (!normalizedKey) {
|
||||
throw new Error("attributeKey is required.");
|
||||
}
|
||||
|
||||
const rule = rules instanceof Map
|
||||
? rules.get(normalizedKey)
|
||||
: (rules ?? []).find((item) => item.attribute_key === normalizedKey);
|
||||
|
||||
return rule ?? {
|
||||
attribute_key: normalizedKey,
|
||||
visibility: DEFAULT_ATTRIBUTE_VISIBILITY,
|
||||
empty_behavior: DEFAULT_EMPTY_BEHAVIOR,
|
||||
empty_text: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether an attribute should be rendered.
|
||||
* Non-empty values always render. Empty values render only when explicitly
|
||||
* configured with `empty_behavior: "show"`.
|
||||
*/
|
||||
export function shouldRenderAttribute(
|
||||
value: unknown,
|
||||
rule?: Pick<TemplateAttributePresentationContract, "visibility" | "empty_behavior"> | null,
|
||||
): boolean {
|
||||
if (rule?.visibility === "hide") return false;
|
||||
if (!isEmptyValue(value)) return true;
|
||||
return rule?.empty_behavior === "show";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns display text for an empty value when the rule explicitly permits
|
||||
* rendering it. A null result means no placeholder text should be displayed.
|
||||
*
|
||||
* This helper intentionally returns null for non-empty values: formatting real
|
||||
* values is the semantic renderer's responsibility.
|
||||
*/
|
||||
export function getEmptyDisplayText(
|
||||
value: unknown,
|
||||
rule?: Pick<
|
||||
TemplateAttributePresentationContract,
|
||||
"empty_behavior" | "empty_text"
|
||||
> | null,
|
||||
): string | null {
|
||||
if (!isEmptyValue(value) || rule?.empty_behavior !== "show") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const text = rule.empty_text?.trim();
|
||||
return text ? text : null;
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import React from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
SafeAreaView,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
|
||||
export function ScreenLoading({ message = "Loading content…" }: { message?: string }) {
|
||||
return (
|
||||
<SafeAreaView style={{ flex: 1 }}>
|
||||
<View style={{ flex: 1, alignItems: "center", justifyContent: "center", gap: 12, padding: 24 }}>
|
||||
<ActivityIndicator size="large" />
|
||||
<Text accessibilityLiveRegion="polite">{message}</Text>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScreenError({
|
||||
title = "Unable to load content",
|
||||
message,
|
||||
onRetry,
|
||||
}: {
|
||||
title?: string;
|
||||
message?: string;
|
||||
onRetry?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<SafeAreaView style={{ flex: 1 }}>
|
||||
<View style={{ flex: 1, alignItems: "center", justifyContent: "center", gap: 10, padding: 24 }}>
|
||||
<Text style={{ fontSize: 20, fontWeight: "700", textAlign: "center" }}>{title}</Text>
|
||||
{message ? <Text style={{ textAlign: "center" }}>{message}</Text> : null}
|
||||
{onRetry ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={onRetry}
|
||||
style={{ borderWidth: 1, borderRadius: 8, paddingHorizontal: 16, paddingVertical: 10, marginTop: 8 }}
|
||||
>
|
||||
<Text style={{ fontWeight: "600" }}>Retry</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScreenEmpty({
|
||||
title = "No content available",
|
||||
message,
|
||||
}: {
|
||||
title?: string;
|
||||
message?: string;
|
||||
}) {
|
||||
return (
|
||||
<SafeAreaView style={{ flex: 1 }}>
|
||||
<View style={{ flex: 1, alignItems: "center", justifyContent: "center", gap: 8, padding: 24 }}>
|
||||
<Text style={{ fontSize: 20, fontWeight: "700", textAlign: "center" }}>{title}</Text>
|
||||
{message ? <Text style={{ textAlign: "center" }}>{message}</Text> : null}
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
import React, { type ReactNode } from "react";
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { router } from "expo-router";
|
||||
import { moderateScale } from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
|
||||
export interface ContentPageHeaderProps {
|
||||
title: string;
|
||||
right?: ReactNode;
|
||||
fallbackRoute?: string;
|
||||
onTitlePress?: () => void;
|
||||
titleAccessibilityLabel?: string;
|
||||
}
|
||||
|
||||
export function ContentPageHeader({
|
||||
title,
|
||||
right,
|
||||
fallbackRoute = "/modules",
|
||||
onTitlePress,
|
||||
titleAccessibilityLabel,
|
||||
}: ContentPageHeaderProps) {
|
||||
const handleBack = () => {
|
||||
if (router.canGoBack()) {
|
||||
router.back();
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(fallbackRoute as never);
|
||||
};
|
||||
|
||||
const titleContent = (
|
||||
<Text numberOfLines={1} style={styles.title}>
|
||||
{title}
|
||||
</Text>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.header}>
|
||||
<View style={styles.sideSlot}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Go back"
|
||||
hitSlop={10}
|
||||
onPress={handleBack}
|
||||
style={({ pressed }) => [
|
||||
styles.iconButton,
|
||||
pressed && styles.pressed,
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="chevron-back"
|
||||
size={24}
|
||||
color={Colors.textPrimary}
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{onTitlePress ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
titleAccessibilityLabel || `Open ${title} home`
|
||||
}
|
||||
hitSlop={8}
|
||||
onPress={onTitlePress}
|
||||
style={({ pressed }) => [
|
||||
styles.titleButton,
|
||||
pressed && styles.pressed,
|
||||
]}
|
||||
>
|
||||
{titleContent}
|
||||
</Pressable>
|
||||
) : (
|
||||
<View style={styles.titleButton}>{titleContent}</View>
|
||||
)}
|
||||
|
||||
<View style={[styles.sideSlot, styles.rightSlot]}>
|
||||
{right}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
header: {
|
||||
height: 60,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: moderateScale(12),
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: "#ECECEC",
|
||||
backgroundColor: "#FFFFFF",
|
||||
},
|
||||
sideSlot: {
|
||||
width: 88,
|
||||
height: 40,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-start",
|
||||
},
|
||||
rightSlot: {
|
||||
justifyContent: "flex-end",
|
||||
},
|
||||
iconButton: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 20,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
pressed: {
|
||||
opacity: 0.65,
|
||||
},
|
||||
titleButton: {
|
||||
flex: 1,
|
||||
minHeight: 40,
|
||||
marginHorizontal: moderateScale(4),
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
title: {
|
||||
width: "100%",
|
||||
textAlign: "center",
|
||||
fontSize: moderateScale(18),
|
||||
fontWeight: "700",
|
||||
color: Colors.textPrimary,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import React from "react";
|
||||
import { asString } from "../../renderers/helpers/value";
|
||||
import { Hero } from "../../renderers/shared/Hero";
|
||||
import { DescriptionList, ObjectArrayCards, ObjectArrayTable, ObjectCard, PointCodes, Strings } from "../../renderers/details/categoryParts";
|
||||
export const CategoryHero=({data,title}:{data:Record<string,unknown>;title:string})=><Hero eyebrow={asString(data.code)} title={asString(data.title)||asString(data.name)||title}/>;
|
||||
export const SourcePointTable=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Source Points" value={data.source_point} columns={["meridian","point"]}/>;
|
||||
export const ClinicalFeatureList=({data}:{data:Record<string,unknown>})=><Strings title="Key Clinical Features" value={data.key_clinical_feature}/>;
|
||||
export const YinYangSection=({data}:{data:Record<string,unknown>})=><Strings title="Yin vs Yang" value={data.yin_vs_yang}/>;
|
||||
export const DiagnosticUtilityList=({data}:{data:Record<string,unknown>})=><Strings title="Diagnostic Utility" value={data.diagnostic_utility}/>;
|
||||
export const MajorLuoCards=({data}:{data:Record<string,unknown>})=><><ObjectArrayCards title="Major Luo Point of the Spleen" value={data.major_luo_point_of_the_spleen}/><ObjectArrayCards title="Major Luo Point of the Stomach" value={data.major_luo_point_of_the_stomach}/></>;
|
||||
export const RelatedChannelDisordersTable=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Interior-Exterior Related Disorders" value={data.treating_disorders_of_their_interiorly_exteriorly_related_channel_or_zangfu}/>;
|
||||
export const RegionalDisordersTable=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Regional Disorders" value={data.treating_disorders_in_regions_reached_b_the_luo_connecting_channel}/>;
|
||||
export const PsychoEmotionalTable=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Psycho-emotional Disorders" value={data.treating_psycho_emotional_disorders}/>;
|
||||
export const TwelveChannelXiList=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Xi-Cleft Points of the Twelve Channels" value={data.xi_cleft_points_of_the_twelve_channels}/>;
|
||||
export const ExtraordinaryChannelXiList=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Xi-Cleft Points of Extraordinary Channels" value={data.xi_cleft_points_of_extraordinary_channels}/>;
|
||||
export const ClinicalApplicationSections=({data}:{data:Record<string,unknown>})=><ObjectCard title="Clinical Application" value={data.clinical_application}/>;
|
||||
export const OrganPointMatrix=({title,value}:{title:string;value:unknown})=><ObjectArrayTable title={title} value={value}/>;
|
||||
export const PhaseLegend=({data}:{data:Record<string,unknown>})=><><ObjectArrayTable title="Phases of Yin Channels" value={data.phases_of_yin_channels}/><ObjectArrayTable title="Phases of Yang Channels" value={data.phases_of_yang_channels}/></>;
|
||||
export const YinFiveShuMatrix=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Points of Yin Channels" value={data.points_of_yin_channels}/>;
|
||||
export const YangFiveShuMatrix=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Points of Yang Channels" value={data.points_of_yang_channels}/>;
|
||||
export const HoraryPointMatrix=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Horary Points" value={data.horary_points}/>;
|
||||
export const HuiMeetingPointCards=({data}:{data:Record<string,unknown>})=><ObjectArrayCards title="Hui-Meeting Points" value={data.points}/>;
|
||||
export const ConfluentPointCards=({data}:{data:Record<string,unknown>})=><ObjectArrayCards title="Confluent Points" value={data.confluent_points}/>;
|
||||
export const LowerHeSeaPointCards=({data}:{data:Record<string,unknown>})=><ObjectArrayCards title="Lower He-Sea Points" value={data.lower_he_sea_points}/>;
|
||||
export const GaoWuCommandRows=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Gao Wu Command Points" value={data.gao_wu_command_points}/>;
|
||||
export const FourSeaCards=({data}:{data:Record<string,unknown>})=><ObjectArrayCards title="The Four Seas" value={data.four_seas}/>;
|
||||
export const GhostPointTable=({data}:{data:Record<string,unknown>})=><ObjectArrayTable title="Ghost Points" value={data.ghost_points} columns={["point_name","point_code"]}/>;
|
||||
export const HistoricalNotes=({data}:{data:Record<string,unknown>})=><Strings title="Historical Notes" value={data.historical_notes}/>;
|
||||
export const AlternativeListSection=({data}:{data:Record<string,unknown>})=><ObjectCard title="Gao Wu Alternative List" value={data.gao_wu_alternative_list}/>;
|
||||
export const EntryExitMatrix=({data}:{data:Record<string,unknown>})=><ObjectCard title="Entry / Exit Points" value={data.entry_exit_points}/>;
|
||||
export const ClinicalSignificanceSection=({data}:{data:Record<string,unknown>})=><ObjectCard title="Clinical Significance" value={data.clinical_significance}/>;
|
||||
export const ReturningYangPointGrid=({data}:{data:Record<string,unknown>})=><Strings title="Returning Yang Points" value={data.points}/>;
|
||||
export { DescriptionList, PointCodes };
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import React from "react"; import { Text } from "react-native";
|
||||
import { asRecordArray, asString, asStringArray } from "../../renderers/helpers/value";
|
||||
import { Hero } from "../../renderers/shared/Hero"; import { SectionCard } from "../../renderers/shared/SectionCard"; import { KeyValueGrid } from "../../renderers/shared/KeyValueGrid"; import { ChipList } from "../../renderers/shared/ChipList"; import { BulletList } from "../../renderers/shared/BulletList"; import { ImageGallery } from "../../renderers/shared/ImageGallery";
|
||||
export const VesselHero=({data,title}:{data:Record<string,unknown>;title:string})=><Hero eyebrow={asString(data.code)} title={asString(data.name)||title} subtitle={asStringArray(data.alt_name).join(" · ")}/>;
|
||||
export const PointRelationsGrid=({data}:{data:Record<string,unknown>})=><SectionCard title="Point Relationships"><KeyValueGrid rows={[{label:"Master Point",value:asString(data.master_point)},{label:"Coupled Point",value:asString(data.coupled_point)},{label:"Luo Point",value:asString(data.luo_point)},{label:"Xi-Cleft Point",value:asString(data.xi_cleft_point)},{label:"Paired Meridian",value:asString(data.paired_meridian)}]}/><ChipList items={asStringArray(data.intersection_points)}/></SectionCard>;
|
||||
export const AreasOfEffectChips=({data}:{data:Record<string,unknown>})=><SectionCard title="Areas of Effect"><ChipList items={asStringArray(data.areas_of_effect)}/></SectionCard>;
|
||||
export const FunctionsList=({data}:{data:Record<string,unknown>})=><SectionCard title="Functions"><BulletList items={asStringArray(data.functions)}/></SectionCard>;
|
||||
export const PathwaySection=({data}:{data:Record<string,unknown>})=><SectionCard title="Pathway"><Text>{asString(data.pathway)}</Text></SectionCard>;
|
||||
export const EovImageGallery=({data}:{data:Record<string,unknown>})=><ImageGallery images={asRecordArray(data.images)}/>;
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import React from "react";
|
||||
import { asRecord, asRecordArray, asString, asStringArray } from "../../renderers/helpers/value";
|
||||
import { Hero } from "../../renderers/shared/Hero"; import { SectionCard } from "../../renderers/shared/SectionCard"; import { BulletList } from "../../renderers/shared/BulletList"; import { ObjectSections } from "../../renderers/shared/ObjectSections"; import { ChipList } from "../../renderers/shared/ChipList"; import { RecordCards } from "../../renderers/shared/RecordCards";
|
||||
export const MeridianHero=({data,title}:{data:Record<string,unknown>;title:string})=><Hero eyebrow={asString(data.code)} title={asString(data.title)||title} subtitle={asString(data.name)}/>;
|
||||
export const PrimaryChannelPathway=({data}:{data:Record<string,unknown>})=><SectionCard title="Primary Channel Pathway"><BulletList items={asStringArray(data.primary_channel_pathway)}/></SectionCard>;
|
||||
export const SecondaryBranches=({data}:{data:Record<string,unknown>})=><SectionCard title="Secondary Branches"><ObjectSections value={asRecord(data.secondary_branches)}/></SectionCard>;
|
||||
export const DivergentChannel=({data}:{data:Record<string,unknown>})=><SectionCard title="Divergent Channel"><BulletList items={asStringArray(data.divergent_channel)}/></SectionCard>;
|
||||
export const LuoChannel=({data}:{data:Record<string,unknown>})=><SectionCard title="Luo-Connecting Channel"><BulletList items={asStringArray(data.luo_connecting_channel)}/><ObjectSections value={asRecord(data.luo_connecting_vessel)}/></SectionCard>;
|
||||
export const SinewChannel=({data}:{data:Record<string,unknown>})=><SectionCard title="Sinew Channel"><BulletList items={asStringArray(data.sinew_channel)}/></SectionCard>;
|
||||
export const SymptomsSections=({data}:{data:Record<string,unknown>})=><SectionCard title="Symptoms"><ObjectSections value={asRecord(data.symptoms)}/></SectionCard>;
|
||||
export const MeetingPoints=({data}:{data:Record<string,unknown>})=><SectionCard title="Meeting Points"><ChipList items={asStringArray(data.meeting_points)}/></SectionCard>;
|
||||
export const PointCategoriesGrid=({data}:{data:Record<string,unknown>})=><SectionCard title="Point Categories"><RecordCards rows={asRecordArray(data.point_categories)}/></SectionCard>;
|
||||
export const ClinicalManifestations=({data}:{data:Record<string,unknown>})=><SectionCard title="Clinical Manifestations"><RecordCards rows={asRecordArray(data.indications_clinical_manifestations)}/></SectionCard>;
|
||||
export const SpecificPoints=({data}:{data:Record<string,unknown>})=><SectionCard title="Specific Points"><RecordCards rows={asRecordArray(data.specific_points_according_to_functions)}/></SectionCard>;
|
||||
export const FiveShuTable=({data}:{data:Record<string,unknown>})=><SectionCard title="Five-Shu Transporting Points"><RecordCards rows={asRecordArray(data.five_shu_transporting_points)}/></SectionCard>;
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import React from "react";
|
||||
import { Text } from "react-native";
|
||||
import { asRecord, asRecordArray, asString, asStringArray } from "../../renderers/helpers/value";
|
||||
import { Hero } from "../../renderers/shared/Hero";
|
||||
import { ChipList } from "../../renderers/shared/ChipList";
|
||||
import { BulletList } from "../../renderers/shared/BulletList";
|
||||
import { KeyValueGrid } from "../../renderers/shared/KeyValueGrid";
|
||||
import { ObjectSections } from "../../renderers/shared/ObjectSections";
|
||||
import { ImageGallery } from "../../renderers/shared/ImageGallery";
|
||||
import { SectionCard } from "../../renderers/shared/SectionCard";
|
||||
export const PointHero=({data,title}:{data:Record<string,unknown>;title:string})=><Hero eyebrow={asString(data.code)} title={title} subtitle={[asString(data.alt_name_1),asString(data.alt_name_2)].filter(Boolean).join(" · ")}/>;
|
||||
export const AlternativeNames=({data}:{data:Record<string,unknown>})=><ChipList items={[asString(data.alt_name_1),asString(data.alt_name_2)].filter(Boolean)}/>;
|
||||
export const PointTypeChips=({data}:{data:Record<string,unknown>})=><ChipList items={asStringArray(data.point_type)}/>;
|
||||
export const ChannelSection=({data}:{data:Record<string,unknown>})=>asString(data.channel)?<SectionCard title="Channel"><Text>{asString(data.channel)}</Text></SectionCard>:null;
|
||||
export const LocationSection=({data}:{data:Record<string,unknown>})=><SectionCard title="Location"><Text>{asString(data.location)}</Text>{asString(data.location_note)?<Text>{asString(data.location_note)}</Text>:null}</SectionCard>;
|
||||
export const IndicationsList=({data}:{data:Record<string,unknown>})=><SectionCard title="Indications"><BulletList items={asStringArray(data.indications)}/></SectionCard>;
|
||||
export const ActionsList=({data}:{data:Record<string,unknown>})=><SectionCard title="Actions"><BulletList items={asStringArray(data.actions)}/></SectionCard>;
|
||||
export const MethodsSection=({data}:{data:Record<string,unknown>})=>{const m=asRecord(data.methods);return <SectionCard title="Methods"><KeyValueGrid rows={[{label:"Needling",value:asString(m.needling)||asString(data.needling)},{label:"Response",value:asString(m.needling_response)||asString(data.needling_response)},{label:"Moxibustion",value:asString(m.moxibustion)||asString(data.moxibustion)},{label:"Additional",value:asString(m.additional_method)||asString(data.additional_method)}]}/></SectionCard>};
|
||||
export const RegionalAnatomySection=({data}:{data:Record<string,unknown>})=><SectionCard title="Regional Anatomy"><ObjectSections value={asRecord(data.regional_anatomy)}/></SectionCard>;
|
||||
export const CautionSection=({data}:{data:Record<string,unknown>})=>asString(data.caution)?<SectionCard title="Caution"><Text>{asString(data.caution)}</Text></SectionCard>:null;
|
||||
export const PointImageGallery=({data}:{data:Record<string,unknown>})=><ImageGallery images={asRecordArray(data.point_images)}/>;
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
import React, { type ReactNode } from "react";
|
||||
import { Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
import { Colors } from "@/theme/colors";
|
||||
import { Radius } from "@/theme/radius";
|
||||
import { Spacing } from "@/theme/spacing";
|
||||
import type { NavigableContentReference } from "../../types/content-reference.types";
|
||||
import { buildContentReferenceRoute } from "../../utils/content-reference";
|
||||
|
||||
export interface ContentLinkProps {
|
||||
reference: NavigableContentReference;
|
||||
/** Optional custom child content. When omitted, the reference label is rendered. */
|
||||
children?: ReactNode;
|
||||
/** Optional accessibility label override. */
|
||||
accessibilityLabel?: string;
|
||||
/** Optional wrapper style for renderer-specific placement. */
|
||||
style?: StyleProp<ViewStyle>;
|
||||
/** Called immediately before navigation. */
|
||||
onPress?: (reference: NavigableContentReference) => void;
|
||||
/** Disable navigation while retaining the visual content. */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function ContentLink({
|
||||
reference,
|
||||
children,
|
||||
accessibilityLabel,
|
||||
style,
|
||||
onPress,
|
||||
disabled = false,
|
||||
}: ContentLinkProps) {
|
||||
const router = useRouter();
|
||||
const label = reference.label?.trim() || defaultReferenceLabel(reference);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
accessibilityState={{ disabled }}
|
||||
disabled={disabled}
|
||||
onPress={() => {
|
||||
onPress?.(reference);
|
||||
router.push(buildContentReferenceRoute(reference) as never);
|
||||
}}
|
||||
style={({ pressed }) => [
|
||||
styles.container,
|
||||
style,
|
||||
pressed && !disabled ? styles.pressed : null,
|
||||
disabled ? styles.disabled : null,
|
||||
]}
|
||||
>
|
||||
{children ?? (
|
||||
<View style={styles.defaultContent}>
|
||||
<Text style={styles.label}>{label}</Text>
|
||||
<Ionicons name="chevron-forward" size={18} color={Colors.primary} />
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function defaultReferenceLabel(reference: NavigableContentReference): string {
|
||||
if (reference.type === "content_ref") {
|
||||
return reference.target.source_key?.trim() || "Open content";
|
||||
}
|
||||
return "Open section";
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
borderRadius: Radius.md,
|
||||
},
|
||||
defaultContent: {
|
||||
minHeight: 44,
|
||||
paddingHorizontal: Spacing.md,
|
||||
paddingVertical: Spacing.sm,
|
||||
borderRadius: Radius.md,
|
||||
backgroundColor: "#E8F5E9",
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: Spacing.sm,
|
||||
},
|
||||
label: {
|
||||
flex: 1,
|
||||
color: Colors.primaryDark,
|
||||
fontSize: 15,
|
||||
lineHeight: 20,
|
||||
fontWeight: "700",
|
||||
},
|
||||
pressed: {
|
||||
opacity: 0.78,
|
||||
},
|
||||
disabled: {
|
||||
opacity: 0.5,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
import React from "react";
|
||||
import { TextInput, View } from "react-native";
|
||||
export function ContentSearchBar({value,onChangeText}:{value:string;onChangeText:(v:string)=>void}){return <View style={{padding:16}}><TextInput value={value} onChangeText={onChangeText} placeholder="Search..." autoCapitalize="none" autoCorrect={false} style={{borderWidth:1,borderRadius:10,padding:10}}/></View>}
|
||||
|
|
@ -0,0 +1,538 @@
|
|||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
Modal,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
import type {
|
||||
LogicalOperator,
|
||||
SearchCriterion,
|
||||
SearchFieldContract,
|
||||
SearchOperator,
|
||||
} from "../../types/presentation.types";
|
||||
|
||||
interface ContractFilterModalProps {
|
||||
visible: boolean;
|
||||
fields: SearchFieldContract[];
|
||||
logic: LogicalOperator;
|
||||
filters: SearchCriterion[];
|
||||
onApply: (value: {
|
||||
logic: LogicalOperator;
|
||||
filters: SearchCriterion[];
|
||||
}) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface DraftCriterion {
|
||||
id: string;
|
||||
attribute_key: string;
|
||||
operator: SearchOperator;
|
||||
valueText: string;
|
||||
valueChoice?: unknown;
|
||||
}
|
||||
|
||||
const OPERATOR_LABELS: Record<SearchOperator, string> = {
|
||||
eq: "Equals",
|
||||
neq: "Not equal",
|
||||
contains: "Contains",
|
||||
starts_with: "Starts with",
|
||||
in: "Any of",
|
||||
gt: "Greater than",
|
||||
gte: "Greater or equal",
|
||||
lt: "Less than",
|
||||
lte: "Less or equal",
|
||||
};
|
||||
|
||||
function createId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||
}
|
||||
|
||||
function stringifyValue(value: unknown): string {
|
||||
if (Array.isArray(value)) return value.map(String).join(", ");
|
||||
if (value === null || value === undefined) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function fromCriterion(criterion: SearchCriterion): DraftCriterion {
|
||||
return {
|
||||
id: createId(),
|
||||
attribute_key: criterion.attribute_key,
|
||||
operator: criterion.operator,
|
||||
valueText: stringifyValue(criterion.value),
|
||||
valueChoice: Array.isArray(criterion.value) ? undefined : criterion.value,
|
||||
};
|
||||
}
|
||||
|
||||
function defaultDraft(field: SearchFieldContract): DraftCriterion {
|
||||
return {
|
||||
id: createId(),
|
||||
attribute_key: field.attribute_key,
|
||||
operator: field.operators[0] ?? "eq",
|
||||
valueText: "",
|
||||
};
|
||||
}
|
||||
|
||||
function parseTextValue(operator: SearchOperator, value: string): unknown {
|
||||
const trimmed = value.trim();
|
||||
|
||||
if (operator === "in") {
|
||||
return trimmed
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
if (["gt", "gte", "lt", "lte"].includes(operator)) {
|
||||
const numeric = Number(trimmed);
|
||||
return Number.isFinite(numeric) ? numeric : trimmed;
|
||||
}
|
||||
|
||||
if (trimmed.toLowerCase() === "true") return true;
|
||||
if (trimmed.toLowerCase() === "false") return false;
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function displayAllowedValue(value: unknown): string {
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||
if (value && typeof value === "object") {
|
||||
const record = value as Record<string, unknown>;
|
||||
const label = record.label ?? record.name ?? record.value ?? record.code;
|
||||
if (label !== undefined) return String(label);
|
||||
}
|
||||
return stringifyValue(value);
|
||||
}
|
||||
|
||||
export function ContractFilterModal({
|
||||
visible,
|
||||
fields,
|
||||
logic,
|
||||
filters,
|
||||
onApply,
|
||||
onClose,
|
||||
}: ContractFilterModalProps) {
|
||||
const [draftLogic, setDraftLogic] = useState<LogicalOperator>(logic);
|
||||
const [drafts, setDrafts] = useState<DraftCriterion[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
setDraftLogic(logic);
|
||||
setDrafts(filters.map(fromCriterion));
|
||||
}, [filters, logic, visible]);
|
||||
|
||||
const fieldsByKey = useMemo(
|
||||
() => new Map(fields.map((field) => [field.attribute_key, field])),
|
||||
[fields],
|
||||
);
|
||||
|
||||
const addCondition = () => {
|
||||
const field = fields[0];
|
||||
if (!field) return;
|
||||
setDrafts((current) => [...current, defaultDraft(field)]);
|
||||
};
|
||||
|
||||
const updateDraft = (id: string, patch: Partial<DraftCriterion>) => {
|
||||
setDrafts((current) =>
|
||||
current.map((item) => (item.id === id ? { ...item, ...patch } : item)),
|
||||
);
|
||||
};
|
||||
|
||||
const apply = () => {
|
||||
const next = drafts.flatMap<SearchCriterion>((draft) => {
|
||||
const field = fieldsByKey.get(draft.attribute_key);
|
||||
if (!field || !field.operators.includes(draft.operator)) return [];
|
||||
|
||||
const hasAllowedValues = Boolean(field.allowed_values?.length);
|
||||
const rawValue = hasAllowedValues && draft.valueChoice !== undefined
|
||||
? draft.valueChoice
|
||||
: parseTextValue(draft.operator, draft.valueText);
|
||||
|
||||
if (draft.operator === "in") {
|
||||
const values = Array.isArray(rawValue) ? rawValue : [rawValue];
|
||||
const cleaned = values.filter(
|
||||
(value) => value !== "" && value !== null && value !== undefined,
|
||||
);
|
||||
if (cleaned.length === 0) return [];
|
||||
return [{
|
||||
attribute_key: draft.attribute_key,
|
||||
operator: draft.operator,
|
||||
value: cleaned,
|
||||
}];
|
||||
}
|
||||
|
||||
if (rawValue === "" || rawValue === null || rawValue === undefined) return [];
|
||||
|
||||
return [{
|
||||
attribute_key: draft.attribute_key,
|
||||
operator: draft.operator,
|
||||
value: rawValue,
|
||||
}];
|
||||
});
|
||||
|
||||
onApply({ logic: draftLogic, filters: next });
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal visible={visible} animationType="slide" transparent onRequestClose={onClose}>
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : undefined}
|
||||
style={styles.overlay}
|
||||
>
|
||||
<Pressable style={styles.scrim} onPress={onClose} />
|
||||
<View style={styles.sheet}>
|
||||
<View style={styles.handle} />
|
||||
<View style={styles.header}>
|
||||
<View>
|
||||
<Text style={styles.title}>Filters</Text>
|
||||
<Text style={styles.subtitle}>Use the fields defined by this content template.</Text>
|
||||
</View>
|
||||
<Pressable onPress={onClose} hitSlop={10} style={styles.closeButton}>
|
||||
<Ionicons name="close" size={22} color={Colors.textPrimary} />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View style={styles.logicSection}>
|
||||
<Text style={styles.sectionLabel}>Match conditions</Text>
|
||||
<View style={styles.segmented}>
|
||||
{(["and", "or"] as const).map((option) => (
|
||||
<Pressable
|
||||
key={option}
|
||||
onPress={() => setDraftLogic(option)}
|
||||
style={[
|
||||
styles.segment,
|
||||
draftLogic === option && styles.segmentActive,
|
||||
]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.segmentText,
|
||||
draftLogic === option && styles.segmentTextActive,
|
||||
]}
|
||||
>
|
||||
{option === "and" ? "All (AND)" : "Any (OR)"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
<Text style={styles.sectionLabel}>Available filters</Text>
|
||||
<View style={styles.chipWrap}>
|
||||
{fields.map((field) => (
|
||||
<Pressable
|
||||
key={field.attribute_key}
|
||||
onPress={() =>
|
||||
setDrafts((current) => [
|
||||
...current,
|
||||
defaultDraft(field),
|
||||
])
|
||||
}
|
||||
style={styles.chip}
|
||||
>
|
||||
<Text style={styles.chipText}>{field.label}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
{drafts.length === 0 ? (
|
||||
<View style={styles.emptyCard}>
|
||||
<Ionicons name="options-outline" size={24} color={Colors.primary} />
|
||||
<Text style={styles.emptyTitle}>No filters applied</Text>
|
||||
<Text style={styles.emptyText}>Add one or more conditions to narrow the content list.</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{drafts.map((draft, index) => {
|
||||
const field = fieldsByKey.get(draft.attribute_key) ?? fields[0];
|
||||
if (!field) return null;
|
||||
const allowedValues = field.allowed_values ?? [];
|
||||
|
||||
return (
|
||||
<View key={draft.id} style={styles.conditionCard}>
|
||||
<View style={styles.conditionHeader}>
|
||||
<Text style={styles.conditionTitle}>Condition {index + 1}</Text>
|
||||
<Pressable
|
||||
onPress={() => setDrafts((current) => current.filter((item) => item.id !== draft.id))}
|
||||
hitSlop={8}
|
||||
>
|
||||
<Ionicons name="trash-outline" size={18} color={Colors.error} />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<Text style={styles.sectionLabel}>Field</Text>
|
||||
<View style={styles.chipWrap}>
|
||||
{fields.map((candidate) => {
|
||||
const selected = candidate.attribute_key === draft.attribute_key;
|
||||
return (
|
||||
<Pressable
|
||||
key={candidate.attribute_key}
|
||||
onPress={() =>
|
||||
updateDraft(draft.id, {
|
||||
attribute_key: candidate.attribute_key,
|
||||
operator: candidate.operators[0] ?? "eq",
|
||||
valueText: "",
|
||||
valueChoice: undefined,
|
||||
})
|
||||
}
|
||||
style={[styles.chip, selected && styles.chipActive]}
|
||||
>
|
||||
<Text style={[styles.chipText, selected && styles.chipTextActive]}>
|
||||
{candidate.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
<Text style={styles.sectionLabel}>Operator</Text>
|
||||
<View style={styles.chipWrap}>
|
||||
{field.operators.map((operator) => {
|
||||
const selected = operator === draft.operator;
|
||||
return (
|
||||
<Pressable
|
||||
key={operator}
|
||||
onPress={() =>
|
||||
updateDraft(draft.id, {
|
||||
operator,
|
||||
valueText: "",
|
||||
valueChoice: undefined,
|
||||
})
|
||||
}
|
||||
style={[styles.chip, selected && styles.chipActive]}
|
||||
>
|
||||
<Text style={[styles.chipText, selected && styles.chipTextActive]}>
|
||||
{OPERATOR_LABELS[operator]}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
<Text style={styles.sectionLabel}>Value</Text>
|
||||
{allowedValues.length > 0 ? (
|
||||
<View style={styles.chipWrap}>
|
||||
{allowedValues.map((value, valueIndex) => {
|
||||
const valueText = stringifyValue(value);
|
||||
const selected =
|
||||
draft.operator === "in"
|
||||
? draft.valueText.split(",").map((item) => item.trim()).includes(valueText)
|
||||
: stringifyValue(draft.valueChoice) === valueText;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={`${valueText}-${valueIndex}`}
|
||||
onPress={() => {
|
||||
if (draft.operator === "in") {
|
||||
const current = draft.valueText
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
const next = selected
|
||||
? current.filter((item) => item !== valueText)
|
||||
: [...current, valueText];
|
||||
updateDraft(draft.id, { valueText: next.join(", "), valueChoice: undefined });
|
||||
} else {
|
||||
updateDraft(draft.id, { valueChoice: value, valueText });
|
||||
}
|
||||
}}
|
||||
style={[styles.chip, selected && styles.chipActive]}
|
||||
>
|
||||
<Text style={[styles.chipText, selected && styles.chipTextActive]}>
|
||||
{displayAllowedValue(value)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
) : (
|
||||
<TextInput
|
||||
value={draft.valueText}
|
||||
onChangeText={(valueText) => updateDraft(draft.id, { valueText, valueChoice: undefined })}
|
||||
placeholder={draft.operator === "in" ? "Enter comma-separated values" : "Enter value"}
|
||||
placeholderTextColor="#94A3B8"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
<Pressable onPress={addCondition} style={styles.addButton}>
|
||||
<Ionicons name="add" size={18} color={Colors.primaryDark} />
|
||||
<Text style={styles.addButtonText}>Add condition</Text>
|
||||
</Pressable>
|
||||
</ScrollView>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
setDraftLogic(logic);
|
||||
setDrafts([]);
|
||||
}}
|
||||
style={styles.secondaryButton}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>Clear</Text>
|
||||
</Pressable>
|
||||
<Pressable onPress={apply} style={styles.primaryButton}>
|
||||
<Text style={styles.primaryButtonText}>Apply filters</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: { flex: 1, justifyContent: "flex-end" },
|
||||
scrim: { ...StyleSheet.absoluteFillObject, backgroundColor: "rgba(15,23,42,0.38)" },
|
||||
sheet: {
|
||||
maxHeight: "88%",
|
||||
minHeight: "55%",
|
||||
backgroundColor: "#F8FAFC",
|
||||
borderTopLeftRadius: moderateScale(24),
|
||||
borderTopRightRadius: moderateScale(24),
|
||||
overflow: "hidden",
|
||||
},
|
||||
handle: {
|
||||
alignSelf: "center",
|
||||
width: moderateScale(42),
|
||||
height: 4,
|
||||
borderRadius: 2,
|
||||
backgroundColor: "#CBD5E1",
|
||||
marginTop: verticalScale(9),
|
||||
},
|
||||
header: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "flex-start",
|
||||
paddingHorizontal: moderateScale(20),
|
||||
paddingTop: verticalScale(14),
|
||||
paddingBottom: verticalScale(12),
|
||||
backgroundColor: "#FFFFFF",
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: "#E2E8F0",
|
||||
},
|
||||
title: { fontSize: moderateScale(19), fontWeight: "800", color: Colors.textPrimary },
|
||||
subtitle: { marginTop: 3, fontSize: moderateScale(12), color: Colors.textSecondary },
|
||||
closeButton: { width: 36, height: 36, alignItems: "center", justifyContent: "center" },
|
||||
logicSection: { paddingHorizontal: moderateScale(20), paddingTop: verticalScale(14) },
|
||||
sectionLabel: {
|
||||
marginTop: verticalScale(10),
|
||||
marginBottom: verticalScale(7),
|
||||
fontSize: moderateScale(12),
|
||||
fontWeight: "700",
|
||||
color: Colors.textSecondary,
|
||||
},
|
||||
segmented: { flexDirection: "row", padding: 3, borderRadius: 12, backgroundColor: "#E2E8F0" },
|
||||
segment: { flex: 1, alignItems: "center", paddingVertical: verticalScale(8), borderRadius: 10 },
|
||||
segmentActive: { backgroundColor: "#FFFFFF" },
|
||||
segmentText: { fontSize: moderateScale(12), fontWeight: "700", color: Colors.textSecondary },
|
||||
segmentTextActive: { color: Colors.primaryDark },
|
||||
scrollContent: { paddingHorizontal: moderateScale(20), paddingBottom: verticalScale(18) },
|
||||
emptyCard: {
|
||||
marginTop: verticalScale(14),
|
||||
alignItems: "center",
|
||||
padding: moderateScale(18),
|
||||
borderRadius: 14,
|
||||
borderWidth: 1,
|
||||
borderColor: "#E2E8F0",
|
||||
backgroundColor: "#FFFFFF",
|
||||
},
|
||||
emptyTitle: { marginTop: 8, fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary },
|
||||
emptyText: { marginTop: 4, textAlign: "center", fontSize: moderateScale(12), lineHeight: 18, color: Colors.textSecondary },
|
||||
conditionCard: {
|
||||
marginTop: verticalScale(14),
|
||||
padding: moderateScale(14),
|
||||
borderRadius: 14,
|
||||
borderWidth: 1,
|
||||
borderColor: "#E2E8F0",
|
||||
backgroundColor: "#FFFFFF",
|
||||
},
|
||||
conditionHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
|
||||
conditionTitle: { fontSize: moderateScale(14), fontWeight: "800", color: Colors.textPrimary },
|
||||
chipWrap: { flexDirection: "row", flexWrap: "wrap", gap: moderateScale(7) },
|
||||
chip: {
|
||||
paddingHorizontal: moderateScale(10),
|
||||
paddingVertical: verticalScale(7),
|
||||
borderRadius: 999,
|
||||
borderWidth: 1,
|
||||
borderColor: "#CBD5E1",
|
||||
backgroundColor: "#FFFFFF",
|
||||
},
|
||||
chipActive: { borderColor: "#A7D7A9", backgroundColor: "#E8F5E9" },
|
||||
chipText: { fontSize: moderateScale(11.5), fontWeight: "600", color: Colors.textSecondary },
|
||||
chipTextActive: { color: Colors.primaryDark },
|
||||
input: {
|
||||
minHeight: verticalScale(42),
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: "#CBD5E1",
|
||||
backgroundColor: "#FFFFFF",
|
||||
paddingHorizontal: moderateScale(12),
|
||||
fontSize: moderateScale(13),
|
||||
color: Colors.textPrimary,
|
||||
},
|
||||
addButton: {
|
||||
marginTop: verticalScale(14),
|
||||
minHeight: verticalScale(42),
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 6,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: "#A7D7A9",
|
||||
backgroundColor: "#E8F5E9",
|
||||
},
|
||||
addButtonText: { fontSize: moderateScale(13), fontWeight: "800", color: Colors.primaryDark },
|
||||
footer: {
|
||||
flexDirection: "row",
|
||||
gap: moderateScale(10),
|
||||
paddingHorizontal: moderateScale(20),
|
||||
paddingTop: verticalScale(12),
|
||||
paddingBottom: verticalScale(16),
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: "#E2E8F0",
|
||||
backgroundColor: "#FFFFFF",
|
||||
},
|
||||
secondaryButton: {
|
||||
minWidth: moderateScale(92),
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: moderateScale(16),
|
||||
paddingVertical: verticalScale(11),
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: "#CBD5E1",
|
||||
},
|
||||
secondaryButtonText: { fontSize: moderateScale(13), fontWeight: "700", color: Colors.textPrimary },
|
||||
primaryButton: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: moderateScale(16),
|
||||
paddingVertical: verticalScale(11),
|
||||
borderRadius: 12,
|
||||
backgroundColor: Colors.primary,
|
||||
},
|
||||
primaryButtonText: { fontSize: moderateScale(13), fontWeight: "800", color: "#FFFFFF" },
|
||||
});
|
||||
|
|
@ -0,0 +1,229 @@
|
|||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Modal,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||||
|
||||
import { Colors } from "@/theme";
|
||||
import type {
|
||||
SortCriterion,
|
||||
SortDirection,
|
||||
SortFieldContract,
|
||||
} from "../../types/presentation.types";
|
||||
|
||||
interface ContractSortModalProps {
|
||||
visible: boolean;
|
||||
fields: SortFieldContract[];
|
||||
sort: SortCriterion[];
|
||||
defaultSort: SortCriterion[];
|
||||
onApply: (sort: SortCriterion[]) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ContractSortModal({
|
||||
visible,
|
||||
fields,
|
||||
sort,
|
||||
defaultSort,
|
||||
onApply,
|
||||
onClose,
|
||||
}: ContractSortModalProps) {
|
||||
const [draft, setDraft] = useState<SortCriterion[]>(sort);
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) setDraft(sort);
|
||||
}, [sort, visible]);
|
||||
|
||||
const labels = useMemo(
|
||||
() => new Map(fields.map((field) => [field.field, field.label])),
|
||||
[fields],
|
||||
);
|
||||
|
||||
const available = fields.filter(
|
||||
(field) => !draft.some((criterion) => criterion.field === field.field),
|
||||
);
|
||||
|
||||
const add = (field: string) => {
|
||||
setDraft((current) => [...current, { field, direction: "asc" }]);
|
||||
};
|
||||
|
||||
const setDirection = (field: string, direction: SortDirection) => {
|
||||
setDraft((current) =>
|
||||
current.map((criterion) =>
|
||||
criterion.field === field ? { ...criterion, direction } : criterion,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const move = (index: number, offset: -1 | 1) => {
|
||||
setDraft((current) => {
|
||||
const target = index + offset;
|
||||
if (target < 0 || target >= current.length) return current;
|
||||
const next = [...current];
|
||||
[next[index], next[target]] = [next[target], next[index]];
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal visible={visible} animationType="slide" transparent onRequestClose={onClose}>
|
||||
<View style={styles.overlay}>
|
||||
<Pressable style={styles.scrim} onPress={onClose} />
|
||||
<View style={styles.sheet}>
|
||||
<View style={styles.handle} />
|
||||
<View style={styles.header}>
|
||||
<View>
|
||||
<Text style={styles.title}>Sort</Text>
|
||||
<Text style={styles.subtitle}>Earlier rules have higher priority.</Text>
|
||||
</View>
|
||||
<Pressable onPress={onClose} hitSlop={10} style={styles.closeButton}>
|
||||
<Ionicons name="close" size={22} color={Colors.textPrimary} />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
|
||||
{draft.length === 0 ? (
|
||||
<View style={styles.emptyCard}>
|
||||
<Ionicons name="swap-vertical-outline" size={24} color={Colors.primary} />
|
||||
<Text style={styles.emptyTitle}>No sort rules</Text>
|
||||
<Text style={styles.emptyText}>Results will use the backend's natural ordering.</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{draft.map((criterion, index) => (
|
||||
<View key={criterion.field} style={styles.sortCard}>
|
||||
<View style={styles.sortHeader}>
|
||||
<View style={styles.priorityBadge}>
|
||||
<Text style={styles.priorityText}>{index + 1}</Text>
|
||||
</View>
|
||||
<Text style={styles.fieldLabel}>{labels.get(criterion.field) ?? criterion.field}</Text>
|
||||
<View style={styles.rowActions}>
|
||||
<Pressable disabled={index === 0} onPress={() => move(index, -1)} hitSlop={6}>
|
||||
<Ionicons name="chevron-up" size={18} color={index === 0 ? "#CBD5E1" : Colors.textSecondary} />
|
||||
</Pressable>
|
||||
<Pressable disabled={index === draft.length - 1} onPress={() => move(index, 1)} hitSlop={6}>
|
||||
<Ionicons name="chevron-down" size={18} color={index === draft.length - 1 ? "#CBD5E1" : Colors.textSecondary} />
|
||||
</Pressable>
|
||||
<Pressable onPress={() => setDraft((current) => current.filter((item) => item.field !== criterion.field))} hitSlop={6}>
|
||||
<Ionicons name="trash-outline" size={18} color={Colors.error} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.segmented}>
|
||||
{(["asc", "desc"] as const).map((direction) => {
|
||||
const selected = criterion.direction === direction;
|
||||
return (
|
||||
<Pressable
|
||||
key={direction}
|
||||
onPress={() => setDirection(criterion.field, direction)}
|
||||
style={[styles.segment, selected && styles.segmentActive]}
|
||||
>
|
||||
<Ionicons
|
||||
name={direction === "asc" ? "arrow-up-outline" : "arrow-down-outline"}
|
||||
size={15}
|
||||
color={selected ? Colors.primaryDark : Colors.textSecondary}
|
||||
/>
|
||||
<Text style={[styles.segmentText, selected && styles.segmentTextActive]}>
|
||||
{direction === "asc" ? "Ascending" : "Descending"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
|
||||
{available.length > 0 ? (
|
||||
<View style={styles.availableSection}>
|
||||
<Text style={styles.sectionLabel}>Add sort field</Text>
|
||||
<View style={styles.chipWrap}>
|
||||
{available.map((field) => (
|
||||
<Pressable key={field.field} onPress={() => add(field.field)} style={styles.addChip}>
|
||||
<Ionicons name="add" size={15} color={Colors.primaryDark} />
|
||||
<Text style={styles.addChipText}>{field.label}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Pressable onPress={() => setDraft(defaultSort)} style={styles.secondaryButton}>
|
||||
<Text style={styles.secondaryButtonText}>Default</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
onApply(draft);
|
||||
onClose();
|
||||
}}
|
||||
style={styles.primaryButton}
|
||||
>
|
||||
<Text style={styles.primaryButtonText}>Apply sort</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: { flex: 1, justifyContent: "flex-end" },
|
||||
scrim: { ...StyleSheet.absoluteFillObject, backgroundColor: "rgba(15,23,42,0.38)" },
|
||||
sheet: {
|
||||
maxHeight: "82%",
|
||||
minHeight: "48%",
|
||||
backgroundColor: "#F8FAFC",
|
||||
borderTopLeftRadius: moderateScale(24),
|
||||
borderTopRightRadius: moderateScale(24),
|
||||
overflow: "hidden",
|
||||
},
|
||||
handle: { alignSelf: "center", width: 42, height: 4, borderRadius: 2, backgroundColor: "#CBD5E1", marginTop: 9 },
|
||||
header: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "flex-start",
|
||||
paddingHorizontal: moderateScale(20),
|
||||
paddingTop: verticalScale(14),
|
||||
paddingBottom: verticalScale(12),
|
||||
backgroundColor: "#FFFFFF",
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: "#E2E8F0",
|
||||
},
|
||||
title: { fontSize: moderateScale(19), fontWeight: "800", color: Colors.textPrimary },
|
||||
subtitle: { marginTop: 3, fontSize: moderateScale(12), color: Colors.textSecondary },
|
||||
closeButton: { width: 36, height: 36, alignItems: "center", justifyContent: "center" },
|
||||
scrollContent: { padding: moderateScale(20), paddingBottom: verticalScale(18) },
|
||||
emptyCard: { alignItems: "center", padding: 18, borderRadius: 14, borderWidth: 1, borderColor: "#E2E8F0", backgroundColor: "#FFFFFF" },
|
||||
emptyTitle: { marginTop: 8, fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary },
|
||||
emptyText: { marginTop: 4, textAlign: "center", fontSize: moderateScale(12), color: Colors.textSecondary },
|
||||
sortCard: { marginBottom: verticalScale(12), padding: moderateScale(14), borderRadius: 14, borderWidth: 1, borderColor: "#E2E8F0", backgroundColor: "#FFFFFF" },
|
||||
sortHeader: { flexDirection: "row", alignItems: "center", gap: moderateScale(9) },
|
||||
priorityBadge: { width: 26, height: 26, borderRadius: 13, alignItems: "center", justifyContent: "center", backgroundColor: "#E8F5E9" },
|
||||
priorityText: { fontSize: moderateScale(11), fontWeight: "800", color: Colors.primaryDark },
|
||||
fieldLabel: { flex: 1, fontSize: moderateScale(13.5), fontWeight: "800", color: Colors.textPrimary },
|
||||
rowActions: { flexDirection: "row", alignItems: "center", gap: moderateScale(10) },
|
||||
segmented: { marginTop: verticalScale(12), flexDirection: "row", padding: 3, borderRadius: 12, backgroundColor: "#E2E8F0" },
|
||||
segment: { flex: 1, minHeight: 36, flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 5, borderRadius: 10 },
|
||||
segmentActive: { backgroundColor: "#FFFFFF" },
|
||||
segmentText: { fontSize: moderateScale(11.5), fontWeight: "700", color: Colors.textSecondary },
|
||||
segmentTextActive: { color: Colors.primaryDark },
|
||||
availableSection: { marginTop: verticalScale(4) },
|
||||
sectionLabel: { marginBottom: verticalScale(8), fontSize: moderateScale(12), fontWeight: "700", color: Colors.textSecondary },
|
||||
chipWrap: { flexDirection: "row", flexWrap: "wrap", gap: moderateScale(7) },
|
||||
addChip: { flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: moderateScale(10), paddingVertical: verticalScale(7), borderRadius: 999, borderWidth: 1, borderColor: "#A7D7A9", backgroundColor: "#E8F5E9" },
|
||||
addChipText: { fontSize: moderateScale(11.5), fontWeight: "700", color: Colors.primaryDark },
|
||||
footer: { flexDirection: "row", gap: 10, paddingHorizontal: moderateScale(20), paddingTop: verticalScale(12), paddingBottom: verticalScale(16), borderTopWidth: 1, borderTopColor: "#E2E8F0", backgroundColor: "#FFFFFF" },
|
||||
secondaryButton: { minWidth: moderateScale(92), alignItems: "center", justifyContent: "center", paddingHorizontal: 16, paddingVertical: 11, borderRadius: 12, borderWidth: 1, borderColor: "#CBD5E1" },
|
||||
secondaryButtonText: { fontSize: moderateScale(13), fontWeight: "700", color: Colors.textPrimary },
|
||||
primaryButton: { flex: 1, alignItems: "center", justifyContent: "center", paddingHorizontal: 16, paddingVertical: 11, borderRadius: 12, backgroundColor: Colors.primary },
|
||||
primaryButtonText: { fontSize: moderateScale(13), fontWeight: "800", color: "#FFFFFF" },
|
||||
});
|
||||