Compare commits
208 Commits
a68f7c7ab5
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| b211cd538a | |||
| d643788919 | |||
| 96fbb71c87 | |||
| bf5546c48b | |||
| 44ca92ac91 | |||
| 1b17dd845a | |||
| 2c0634f444 | |||
| 5757c44e12 | |||
| 487d604e19 | |||
| f7fbbd2352 | |||
| a77e2a7f70 | |||
| b216f7b211 | |||
| 5ef7f58f5d | |||
| 2cb6a0343a | |||
| 8f32fdf08d | |||
|
|
0878b5d1bd | ||
|
|
6ee2e65938 | ||
|
|
633b6db1af | ||
|
|
452440e8db | ||
| 641ee91c90 | |||
|
|
2aa2ce9ce1 | ||
|
|
48381b2c27 | ||
|
|
2972988211 | ||
| ac80460d93 | |||
|
|
58958c8ace | ||
|
|
b76bdf7622 | ||
|
|
c002eeb74b | ||
|
|
5c171fb930 | ||
|
|
99f20cce39 | ||
|
|
3e192c71c5 | ||
|
|
f37d3e19fe | ||
|
|
ac95f7810e | ||
|
|
8bc6089a7f | ||
|
|
b5b01648fc | ||
|
|
38c487b54f | ||
|
|
9a01c15a76 | ||
|
|
a43624e559 | ||
|
|
194934913e | ||
|
|
3ad7afe2be | ||
|
|
bdd740c9ae | ||
|
|
b1435e8e47 | ||
|
|
cd6476821a | ||
|
|
cc1de3e2f3 | ||
|
|
fb44ef577a | ||
|
|
86b2d02a8f | ||
|
|
deee61e3ff | ||
|
|
1a83f1b45d | ||
|
|
76c2382e11 | ||
|
|
4919c4fc12 | ||
|
|
ae5768dbcd | ||
|
|
b94e633742 | ||
|
|
6dcc91a206 | ||
|
|
c6a94fa60f | ||
|
|
766e44e5c3 | ||
|
|
fbdfdaf0c1 | ||
|
|
f74c5a2fc6 | ||
|
|
6aa5149789 | ||
|
|
30e6e47cc7 | ||
|
|
2a3f7248a1 | ||
|
|
e84541339d | ||
|
|
ce01f9a4c9 | ||
|
|
0f962ef59a | ||
|
|
cf147919a6 | ||
|
|
3e60745a92 | ||
|
|
a5ddd790f6 | ||
|
|
963d2c6a01 | ||
|
|
db9d94a59d | ||
|
|
8386e541cb | ||
|
|
3a8d73e742 | ||
|
|
c07b97fb3a | ||
|
|
17e7a98534 | ||
|
|
f614759986 | ||
|
|
a50afea145 | ||
|
|
f00fa95e9e | ||
|
|
ce0416f658 | ||
|
|
57f992a5c3 | ||
|
|
74dac271ef | ||
|
|
258bd62a7f | ||
|
|
85070fcadb | ||
|
|
2f81002e81 | ||
|
|
0e14428518 | ||
|
|
918be18120 | ||
|
|
839882f616 | ||
|
|
5ea0a376c8 | ||
|
|
d2494f3456 | ||
|
|
c66f71b01c | ||
|
|
6704dacc37 | ||
|
|
8958972d78 | ||
|
|
3f08fbc543 | ||
|
|
b3bea06d16 | ||
|
|
98dcb881ac | ||
|
|
6f01f31f22 | ||
|
|
ec99b6ac96 | ||
|
|
975ee20254 | ||
|
|
3f17b82fdb | ||
|
|
e7b7be7562 | ||
|
|
6c9ab76439 | ||
|
|
47e8bd873c | ||
|
|
419bcc11cb | ||
|
|
a5e8d7fecc | ||
|
|
7d90b5b910 | ||
|
|
c47f41fab6 | ||
|
|
eeea6b0d6f | ||
|
|
b9bacd548d | ||
|
|
70c74568be | ||
|
|
449818ed94 | ||
|
|
5cc7c156ae | ||
|
|
98896fe6de | ||
|
|
d8f314cb00 | ||
|
|
ca88387071 | ||
|
|
f73bbf54ad | ||
|
|
0c5d38f274 | ||
|
|
5424032278 | ||
|
|
45f9283e55 | ||
|
|
bac2fba473 | ||
|
|
4cabf81f68 | ||
|
|
96d3880229 | ||
|
|
8493d0e9ec | ||
|
|
8b41653bb5 | ||
| 7f0968a071 | |||
|
|
68672985ec | ||
|
|
b4ab02b4ef | ||
|
|
aec736af3d | ||
| 38e2f34683 | |||
|
|
04d266dacc | ||
|
|
d3442ae724 | ||
|
|
5c09cdcc2f | ||
|
|
b967cecb80 | ||
|
|
94de67f801 | ||
|
|
67c69f6273 | ||
|
|
52eac590a4 | ||
|
|
7931057714 | ||
|
|
2b63d7c529 | ||
|
|
176e1e2a3c | ||
|
|
2af0ad4d15 | ||
|
|
99a530d672 | ||
|
|
72f6f2b716 | ||
|
|
f477bfaa13 | ||
|
|
2868875044 | ||
|
|
bf10741786 | ||
|
|
1e19e0ab8a | ||
|
|
c0c4f5e3db | ||
|
|
45b77f6291 | ||
|
|
02645aa598 | ||
|
|
5d4dc97d19 | ||
| b26ff8819b | |||
| e4fcafa57c | |||
|
|
4003284f3a | ||
|
|
b674640bd8 | ||
| f50f64ebcf | |||
| f794a66147 | |||
| 6bdf5fbf12 | |||
| c6a1400dc7 | |||
|
|
aef772c6b1 | ||
| 2d9e6f8df3 | |||
|
|
c99beea46a | ||
|
|
bfdd1ec62a | ||
| 27689dbbff | |||
|
|
0a61371271 | ||
|
|
1acde486f2 | ||
|
|
0f2bfb74b4 | ||
|
|
2188b73f54 | ||
|
|
85c6621b7a | ||
|
|
c69a1af094 | ||
|
|
cc8c4093ff | ||
|
|
1e02cd99bc | ||
|
|
5d88121e78 | ||
|
|
2e2498577f | ||
|
|
6c3ae1eda6 | ||
|
|
5dc625c903 | ||
|
|
6c6e7a6847 | ||
| d37a99d7cd | |||
|
|
c7298d2b7e | ||
| b4cdc08532 | |||
| d941d82373 | |||
| cf9a51e64f | |||
|
|
41593be44a | ||
|
|
1275f23bb1 | ||
|
|
7817ae0448 | ||
| a520c04a02 | |||
| dc35c3d43e | |||
| 4c003b3cb5 | |||
| 857044793d | |||
|
|
249611886b | ||
|
|
961f726520 | ||
|
|
c50b75ce9b | ||
|
|
b59148630a | ||
| ccbaba291e | |||
|
|
3c272505d6 | ||
|
|
f0fbca832d | ||
|
|
2f470d3531 | ||
|
|
71f3aed875 | ||
|
|
3f3fbad556 | ||
|
|
d85b028bda | ||
|
|
db2ccd0f57 | ||
|
|
4bd88f1b4e | ||
|
|
cd55ddf3f8 | ||
|
|
22f7fa134b | ||
|
|
03ec6eb670 | ||
| 32ce3807e8 | |||
|
|
7c92b787ce | ||
| 90aa6f6fd6 | |||
| be1ba7ef16 | |||
| d3d937dbb2 | |||
| 7baa1d43a2 | |||
|
|
422b0d5856 | ||
| 7a479787c8 | |||
|
|
f7514c698e |
@@ -10,6 +10,10 @@ NEXT_PUBLIC_AUTH_PASSWORD=true
|
||||
## THIS IS FOR DEVELOPMENT ONLY - DO NOT USE IN PRODUCTION
|
||||
SUPABASE_DB_WEBHOOK_SECRET=WEBHOOKSECRET
|
||||
|
||||
# MEDUSA MONTONIO URLS FOR LOCALHOST
|
||||
# Montonio doesn't allow localhost as notification/callback URL
|
||||
DEV_MONTONIO_CALLBACK_URL=http://webhook.site:3000
|
||||
|
||||
# EMAILS
|
||||
|
||||
# CONTACT FORM
|
||||
@@ -34,6 +38,7 @@ MEDIPOST_PASSWORD=SRB48HZMV
|
||||
MEDIPOST_RECIPIENT=trvurgtst
|
||||
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
||||
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
||||
MEDIPOST_ENABLE_DELETE_RESPONSE_PRIVATE_MESSAGE_ON_READ=false
|
||||
|
||||
#MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
||||
#MEDIPOST_USER=medreport
|
||||
@@ -43,6 +48,7 @@ MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
||||
#MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=false
|
||||
|
||||
# MEDUSA
|
||||
COMPANY_BENEFITS_PAYMENT_SECRET_KEY=NzcwMzE2NmEtOThiMS0xMWYwLWI4NjYtMDMwZDQzMjFhMjExCg==
|
||||
MEDUSA_BACKEND_URL=http://localhost:9000
|
||||
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ MEDIPOST_PASSWORD=your-medipost-password
|
||||
MEDIPOST_RECIPIENT=your-medipost-recipient
|
||||
|
||||
CONNECTED_ONLINE_URL=your-connected-online-url
|
||||
CONNECTED_ONLINE_CONFIRMED_URL=your-connected-confirmed-url
|
||||
|
||||
EMAIL_SENDER=
|
||||
EMAIL_USER= # refer to your email provider's documentation
|
||||
@@ -19,6 +20,7 @@ EMAIL_PORT= # or 465 for SSL
|
||||
EMAIL_TLS= # or false for SSL (see provider documentation)
|
||||
|
||||
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
|
||||
MEDUSA_SECRET_API_KEY=
|
||||
|
||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||
MONTONIO_SECRET_KEY=rNZkzwxOiH93mzkdV53AvhSsbGidrgO2Kl5lE/IT7cvo
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
database.types.ts
|
||||
playwright-report
|
||||
*.hbs
|
||||
*.hbs
|
||||
.history
|
||||
node_modules
|
||||
|
||||
@@ -98,13 +98,13 @@ To access admin pages follow these steps:
|
||||
- Register new user
|
||||
- Go to Profile and add Multi-Factor Authentication
|
||||
- Authenticate with mfa (at current time profile page prompts it again)
|
||||
- update your role. look at `supabase/sql/super-admin.sql`
|
||||
- update your `account.application_role` to `super_admin`.
|
||||
- Sign out and Sign in
|
||||
|
||||
## Company User
|
||||
|
||||
- With admin account go to `http://localhost:3000/admin/accounts`
|
||||
- For Create Company Account to work you need to have rows in `medreport.roles` table. For that you can sql in `supabase/sql/super-admin.sql`
|
||||
- For Create Company Account to work you need to have rows in `medreport.roles` table.
|
||||
|
||||
## Start email server
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import { Label } from '@kit/ui/label';
|
||||
import { Spinner } from '@kit/ui/spinner';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { sendCompanyOfferEmail } from '../_lib/server/company-offer-actions';
|
||||
|
||||
const CompanyOfferForm = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
@@ -34,6 +36,16 @@ const CompanyOfferForm = () => {
|
||||
|
||||
const onSubmit = async (data: CompanySubmitData) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await sendCompanyOfferEmail(data, language);
|
||||
router.push('/company-offer/success');
|
||||
} catch (err) {
|
||||
setIsLoading(false);
|
||||
if (err instanceof Error) {
|
||||
console.warn('Could not send company offer email: ' + err.message);
|
||||
}
|
||||
console.warn('Could not send company offer email: ', err);
|
||||
}
|
||||
const formData = new FormData();
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== undefined) formData.append(key, value);
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
'use server';
|
||||
|
||||
import { renderCompanyOfferEmail } from '@/packages/email-templates/src';
|
||||
|
||||
import { sendEmailFromTemplate } from '~/lib/services/mailer.service';
|
||||
import { CompanySubmitData } from '~/lib/types/company';
|
||||
|
||||
export const sendCompanyOfferEmail = async (
|
||||
data: CompanySubmitData,
|
||||
language: string,
|
||||
) => {
|
||||
const formData = new FormData();
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== undefined) formData.append(key, value);
|
||||
});
|
||||
|
||||
sendEmailFromTemplate(
|
||||
renderCompanyOfferEmail,
|
||||
{
|
||||
companyData: data,
|
||||
language,
|
||||
},
|
||||
process.env.CONTACT_EMAIL!,
|
||||
);
|
||||
};
|
||||
@@ -1,12 +1,11 @@
|
||||
import { SIDEBAR_WIDTH_PROPERTY } from '@/packages/ui/src/shadcn/constants';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { ProfileAccountDropdownContainer } from '@kit/shared/components/personal-account-dropdown-container';
|
||||
import { SIDEBAR_WIDTH_PROPERTY } from '@/packages/ui/src/shadcn/constants';
|
||||
|
||||
import type { UserWorkspace } from '../../home/(user)/_lib/server/load-user-workspace';
|
||||
|
||||
export function AdminMenuNavigation(props: {
|
||||
workspace: UserWorkspace;
|
||||
}) {
|
||||
export function AdminMenuNavigation(props: { workspace: UserWorkspace }) {
|
||||
const { accounts } = props.workspace;
|
||||
|
||||
return (
|
||||
@@ -17,9 +16,7 @@ export function AdminMenuNavigation(props: {
|
||||
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<div>
|
||||
<ProfileAccountDropdownContainer
|
||||
accounts={accounts}
|
||||
/>
|
||||
<ProfileAccountDropdownContainer accounts={accounts} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,8 +3,8 @@ import { cache } from 'react';
|
||||
import { AdminAccountPage } from '@kit/admin/components/admin-account-page';
|
||||
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
||||
|
||||
import { getAccount } from '~/lib/services/account.service';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getAccount } from '~/lib/services/account.service';
|
||||
|
||||
interface Params {
|
||||
params: Promise<{
|
||||
|
||||
@@ -8,6 +8,7 @@ import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
import { AppBreadcrumbs } from '@kit/ui/app-breadcrumbs';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
interface SearchParams {
|
||||
|
||||
@@ -5,8 +5,8 @@ import { cookies } from 'next/headers';
|
||||
import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
|
||||
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
||||
|
||||
import { AdminSidebar } from '~/admin/_components/admin-sidebar';
|
||||
import { AdminMenuNavigation } from '~/admin/_components/admin-menu-navigation';
|
||||
import { AdminSidebar } from '~/admin/_components/admin-sidebar';
|
||||
import { AdminMobileNavigation } from '~/admin/_components/mobile-navigation';
|
||||
|
||||
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AdminDashboard } from '@kit/admin/components/admin-dashboard';
|
||||
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
function AdminPage() {
|
||||
|
||||
27
app/api/after-mfa/route.ts
Normal file
27
app/api/after-mfa/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { enhanceRouteHandler } from '@/packages/next/src/routes';
|
||||
import { createAuthCallbackService } from '@/packages/supabase/src/auth-callback.service';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
export const POST = enhanceRouteHandler(
|
||||
async () => {
|
||||
try {
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabaseClient.auth.getUser();
|
||||
const service = createAuthCallbackService(supabaseClient);
|
||||
|
||||
if (user && service.isKeycloakUser(user)) {
|
||||
await service.setupMedusaUserForKeycloak(user);
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 });
|
||||
} catch (err) {
|
||||
console.error('Error on verifying:', { err });
|
||||
return new Response(null, { status: 500 });
|
||||
}
|
||||
},
|
||||
{
|
||||
auth: false,
|
||||
},
|
||||
);
|
||||
@@ -7,11 +7,19 @@ import { sendEmailFromTemplate } from '~/lib/services/mailer.service';
|
||||
export default async function sendOpenJobsEmails() {
|
||||
const analysisResponseIds = await getOpenJobAnalysisResponseIds();
|
||||
|
||||
if (analysisResponseIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const doctorAccounts = await getDoctorAccounts();
|
||||
const doctorEmails: string[] = doctorAccounts
|
||||
const doctorEmails = doctorAccounts
|
||||
.map(({ email }) => email)
|
||||
.filter((email): email is string => !!email);
|
||||
|
||||
if (doctorEmails.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
await sendEmailFromTemplate(
|
||||
renderNewJobsAvailableEmail,
|
||||
{
|
||||
@@ -20,4 +28,6 @@ export default async function sendOpenJobsEmails() {
|
||||
},
|
||||
doctorEmails,
|
||||
);
|
||||
|
||||
return doctorAccounts.filter((email) => !!email).map(({ id }) => id);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ export default async function syncAnalysisGroups() {
|
||||
|
||||
try {
|
||||
console.info('Getting latest public message id');
|
||||
const lastCheckedDate = await getLastCheckedDate();
|
||||
// const lastCheckedDate = await getLastCheckedDate(); never used?
|
||||
|
||||
const latestMessage = await getLatestPublicMessageListItem();
|
||||
if (!latestMessage) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readPrivateMessageResponse } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
||||
import MedipostPrivateMessageSync from '~/lib/services/medipost/medipostPrivateMessageSync.service';
|
||||
|
||||
type ProcessedMessage = {
|
||||
messageId: string;
|
||||
@@ -16,22 +16,22 @@ type GroupedResults = {
|
||||
|
||||
export default async function syncAnalysisResults() {
|
||||
console.info('Syncing analysis results');
|
||||
const sync = new MedipostPrivateMessageSync();
|
||||
|
||||
const processedMessages: ProcessedMessage[] = [];
|
||||
const excludedMessageIds: string[] = [];
|
||||
while (true) {
|
||||
const result = await readPrivateMessageResponse({ excludedMessageIds });
|
||||
if (result.messageId) {
|
||||
processedMessages.push(result as ProcessedMessage);
|
||||
}
|
||||
const result = await sync.handleNextPrivateMessage({ excludedMessageIds });
|
||||
|
||||
if (!result.messageId) {
|
||||
const { messageId } = result;
|
||||
if (!messageId) {
|
||||
console.info('No more messages to process');
|
||||
break;
|
||||
}
|
||||
|
||||
if (!excludedMessageIds.includes(result.messageId)) {
|
||||
excludedMessageIds.push(result.messageId);
|
||||
processedMessages.push(result as ProcessedMessage);
|
||||
if (!excludedMessageIds.includes(messageId)) {
|
||||
excludedMessageIds.push(messageId);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,45 @@ import axios from 'axios';
|
||||
|
||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||
|
||||
import type { ISearchLoadResponse } from '~/lib/types/connected-online';
|
||||
import { logSyncResult } from '~/lib/services/audit.service';
|
||||
import { SyncStatus } from '~/lib/types/audit';
|
||||
import type {
|
||||
ISearchLoadResponse,
|
||||
P_JobTitleTranslation,
|
||||
} from '~/lib/types/connected-online';
|
||||
|
||||
function createTranslationMap(translations: P_JobTitleTranslation[]) {
|
||||
const result: Map<
|
||||
number,
|
||||
Map<number, { textEN: string; textRU: string; textET: string }>
|
||||
> = new Map();
|
||||
|
||||
for (const translation of translations) {
|
||||
const { ClinicID, TextET, TextEN, TextRU, SyncID } = translation;
|
||||
|
||||
if (!result.has(ClinicID)) {
|
||||
result.set(ClinicID, new Map());
|
||||
}
|
||||
|
||||
result.get(ClinicID)!.set(SyncID, {
|
||||
textET: TextET,
|
||||
textEN: TextEN,
|
||||
textRU: TextRU,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function getSpokenLanguages(spokenLanguages?: string) {
|
||||
if (!spokenLanguages || !spokenLanguages.length) return [];
|
||||
return spokenLanguages.split(',');
|
||||
}
|
||||
|
||||
export default async function syncConnectedOnline() {
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
const isProd = !['test', 'localhost'].some((pathString) =>
|
||||
process.env.NEXT_PUBLIC_SITE_URL?.includes(pathString),
|
||||
);
|
||||
|
||||
const baseUrl = process.env.CONNECTED_ONLINE_URL;
|
||||
|
||||
@@ -16,14 +51,19 @@ export default async function syncConnectedOnline() {
|
||||
const supabase = getSupabaseServerAdminClient();
|
||||
|
||||
try {
|
||||
const response = await axios.post<{ d: string }>(`${baseUrl}/Search_Load`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
const searchLoadResponse = await axios.post<{ d: string }>(
|
||||
`${baseUrl}/Search_Load`,
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
param: "{'Value':'|et|-1'}", // get all available services in Estonian
|
||||
},
|
||||
param: "{'Value':'|et|-1'}", // get all available services in Estonian
|
||||
});
|
||||
);
|
||||
|
||||
const responseData: ISearchLoadResponse = JSON.parse(response.data.d);
|
||||
const responseData: ISearchLoadResponse = JSON.parse(
|
||||
searchLoadResponse.data.d,
|
||||
);
|
||||
|
||||
if (responseData?.ErrorCode !== 0) {
|
||||
throw new Error('Failed to get Connected Online data');
|
||||
@@ -41,20 +81,23 @@ export default async function syncConnectedOnline() {
|
||||
});
|
||||
}
|
||||
|
||||
let clinics;
|
||||
let services;
|
||||
// Filter out "Dentas Demo OÜ" in prod or only sync "Dentas Demo OÜ" in any other environment
|
||||
if (isProd) {
|
||||
clinics = responseData.Data.T_Lic.filter((clinic) => clinic.ID !== 2);
|
||||
services = responseData.Data.T_Service.filter(
|
||||
(service) => service.ClinicID !== 2,
|
||||
);
|
||||
} else {
|
||||
clinics = responseData.Data.T_Lic.filter((clinic) => clinic.ID === 2);
|
||||
services = responseData.Data.T_Service.filter(
|
||||
(service) => service.ClinicID === 2,
|
||||
);
|
||||
}
|
||||
const isDemoClinic = (clinicId: number) =>
|
||||
isProd ? clinicId !== 2 : clinicId === 2;
|
||||
const clinics = responseData.Data.T_Lic.filter(({ ID }) =>
|
||||
isDemoClinic(ID),
|
||||
);
|
||||
const services = responseData.Data.T_Service.filter(({ ClinicID }) =>
|
||||
isDemoClinic(ClinicID),
|
||||
);
|
||||
const serviceProviders = responseData.Data.T_Doctor.filter(({ ClinicID }) =>
|
||||
isDemoClinic(ClinicID),
|
||||
);
|
||||
const jobTitleTranslations = createTranslationMap(
|
||||
responseData.Data.P_JobTitleTranslations.filter(({ ClinicID }) =>
|
||||
isDemoClinic(ClinicID),
|
||||
),
|
||||
);
|
||||
|
||||
const mappedClinics = clinics.map((clinic) => {
|
||||
return {
|
||||
@@ -64,6 +107,8 @@ export default async function syncConnectedOnline() {
|
||||
name: clinic.Name,
|
||||
personal_code_required: !!clinic.PersonalCodeRequired,
|
||||
phone_number: clinic.Phone || null,
|
||||
key: clinic.Key,
|
||||
address: clinic.Address,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -71,7 +116,7 @@ export default async function syncConnectedOnline() {
|
||||
return {
|
||||
id: service.ID,
|
||||
clinic_id: service.ClinicID,
|
||||
sync_id: service.SyncID,
|
||||
sync_id: Number(service.SyncID),
|
||||
name: service.Name,
|
||||
description: service.Description || null,
|
||||
price: service.Price,
|
||||
@@ -87,45 +132,133 @@ export default async function syncConnectedOnline() {
|
||||
};
|
||||
});
|
||||
|
||||
const mappedServiceProviders = serviceProviders.map((serviceProvider) => {
|
||||
const jobTitleTranslation = serviceProvider.JobTitleID
|
||||
? jobTitleTranslations
|
||||
.get(serviceProvider.ClinicID)
|
||||
?.get(serviceProvider.JobTitleID)
|
||||
: null;
|
||||
return {
|
||||
id: serviceProvider.ID,
|
||||
prefix: serviceProvider.Prefix,
|
||||
name: serviceProvider.Name,
|
||||
spoken_languages: getSpokenLanguages(serviceProvider.SpokenLanguages),
|
||||
job_title_et: jobTitleTranslation?.textET,
|
||||
job_title_en: jobTitleTranslation?.textEN,
|
||||
job_title_ru: jobTitleTranslation?.textRU,
|
||||
job_title_id: serviceProvider.JobTitleID,
|
||||
is_deleted: !!serviceProvider.Deleted,
|
||||
clinic_id: serviceProvider.ClinicID,
|
||||
};
|
||||
});
|
||||
|
||||
const { error: providersError } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_providers')
|
||||
.upsert(mappedClinics);
|
||||
|
||||
if (providersError) {
|
||||
return logSyncResult({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
comment:
|
||||
'Error saving connected online providers: ' +
|
||||
JSON.stringify(providersError),
|
||||
status: SyncStatus.Fail,
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
}
|
||||
|
||||
const { error: servicesError } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_services')
|
||||
.upsert(mappedServices, { onConflict: 'id', ignoreDuplicates: false });
|
||||
.upsert(mappedServices, {
|
||||
onConflict: 'id',
|
||||
ignoreDuplicates: false,
|
||||
});
|
||||
|
||||
if (providersError || servicesError) {
|
||||
return supabase
|
||||
.schema('audit')
|
||||
.from('sync_entries')
|
||||
.insert({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
comment: providersError
|
||||
? 'Error saving providers: ' + JSON.stringify(providersError)
|
||||
: 'Error saving services: ' + JSON.stringify(servicesError),
|
||||
status: 'FAIL',
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
if (servicesError) {
|
||||
return logSyncResult({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
comment:
|
||||
'Error saving connected online services: ' +
|
||||
JSON.stringify(servicesError),
|
||||
status: SyncStatus.Fail,
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
}
|
||||
|
||||
await supabase.schema('audit').from('sync_entries').insert({
|
||||
const { error: serviceProvidersError } = await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_service_providers')
|
||||
.upsert(mappedServiceProviders, {
|
||||
onConflict: 'id',
|
||||
ignoreDuplicates: false,
|
||||
});
|
||||
|
||||
if (serviceProvidersError) {
|
||||
return logSyncResult({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
comment:
|
||||
'Error saving service providers: ' +
|
||||
JSON.stringify(serviceProvidersError),
|
||||
status: SyncStatus.Fail,
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
}
|
||||
|
||||
for (const mappedClinic of mappedClinics) {
|
||||
const defaultLoadResponse = await axios.post<{ d: string }>(
|
||||
`${baseUrl}/Default_Load`,
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
param: `{'Value':'${mappedClinic.key}|et'}`,
|
||||
},
|
||||
);
|
||||
|
||||
const defaultLoadResponseData = JSON.parse(defaultLoadResponse.data.d);
|
||||
|
||||
if (defaultLoadResponseData?.ErrorCode !== 0) {
|
||||
throw new Error('Failed to get Connected Online location data');
|
||||
}
|
||||
|
||||
const clinicLocations: {
|
||||
SyncID: number;
|
||||
Address: string;
|
||||
Name: string;
|
||||
}[] = defaultLoadResponseData.Data.T_SelectableLocation;
|
||||
|
||||
if (clinicLocations?.length) {
|
||||
const mappedLocations = clinicLocations.map(
|
||||
({ SyncID, Address, Name }) => ({
|
||||
address: Address,
|
||||
clinic_id: mappedClinic.id,
|
||||
sync_id: SyncID,
|
||||
name: Name,
|
||||
}),
|
||||
);
|
||||
|
||||
await supabase
|
||||
.schema('medreport')
|
||||
.from('connected_online_locations')
|
||||
.insert(mappedLocations)
|
||||
.throwOnError();
|
||||
}
|
||||
}
|
||||
|
||||
await logSyncResult({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
status: 'SUCCESS',
|
||||
status: SyncStatus.Success,
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
} catch (e) {
|
||||
await supabase
|
||||
.schema('audit')
|
||||
.from('sync_entries')
|
||||
.insert({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
status: 'FAIL',
|
||||
comment: JSON.stringify(e),
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
await logSyncResult({
|
||||
operation: 'CONNECTED_ONLINE_SYNC',
|
||||
status: SyncStatus.Fail,
|
||||
comment: JSON.stringify(e),
|
||||
changed_by_role: 'service_role',
|
||||
});
|
||||
throw new Error(
|
||||
`Failed to sync Connected Online data, error: ${JSON.stringify(e)}`,
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getLogger } from '@/packages/shared/src/logger';
|
||||
import { retrieveOrder } from '@lib/data/orders';
|
||||
|
||||
import { getMedipostDispatchTries } from '~/lib/services/audit.service';
|
||||
@@ -10,13 +11,17 @@ import loadEnv from '../handler/load-env';
|
||||
import validateApiKey from '../handler/validate-api-key';
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
const logger = await getLogger();
|
||||
const ctx = {
|
||||
api: '/job/medipost-retry-dispatch',
|
||||
};
|
||||
loadEnv();
|
||||
|
||||
const { medusaOrderId } = await request.json();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
@@ -36,15 +41,15 @@ export const POST = async (request: NextRequest) => {
|
||||
medusaOrder,
|
||||
});
|
||||
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
||||
console.info('Successfully sent order to medipost');
|
||||
logger.info(ctx, 'Successfully sent order to medipost');
|
||||
return NextResponse.json(
|
||||
{
|
||||
message: 'Successfully sent order to medipost',
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
} catch (e) {
|
||||
console.error('Error sending order to medipost', e);
|
||||
} catch (error) {
|
||||
logger.error({ ...ctx, error }, 'Error sending order to medipost');
|
||||
return NextResponse.json(
|
||||
{
|
||||
message: 'Failed to send order to medipost',
|
||||
|
||||
@@ -14,18 +14,20 @@ export const POST = async (request: NextRequest) => {
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
try {
|
||||
await sendOpenJobsEmails();
|
||||
const doctors = await sendOpenJobsEmails();
|
||||
const doctorIds = doctors?.join(', ') ?? '-';
|
||||
console.info(
|
||||
'Successfully sent out open job notification emails to doctors.',
|
||||
`Successfully sent out open job notification emails to doctorIds: ${doctorIds}`,
|
||||
);
|
||||
await createNotificationLog({
|
||||
action: NotificationAction.DOCTOR_NEW_JOBS,
|
||||
status: 'SUCCESS',
|
||||
comment: `doctors that received email: ${doctorIds}`,
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
@@ -34,7 +36,7 @@ export const POST = async (request: NextRequest) => {
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
console.error(
|
||||
'Error sending out open job notification emails to doctors.',
|
||||
e,
|
||||
@@ -42,7 +44,7 @@ export const POST = async (request: NextRequest) => {
|
||||
await createNotificationLog({
|
||||
action: NotificationAction.DOCTOR_NEW_JOBS,
|
||||
status: 'FAIL',
|
||||
comment: e?.message,
|
||||
comment: e instanceof Error ? e.message : 'Unknown error',
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ export const POST = async (request: NextRequest) => {
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export const POST = async (request: NextRequest) => {
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export const POST = async (request: NextRequest) => {
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export const POST = async (request: NextRequest) => {
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ export async function POST(request: Request) {
|
||||
action: 'send_fake_analysis_results_to_medipost',
|
||||
xml: messageXml,
|
||||
medusaOrderId,
|
||||
medipostPrivateMessageId: `fake-response-${Date.now()}`,
|
||||
});
|
||||
await sendPrivateMessageTestResponse({ messageXml });
|
||||
} catch (error) {
|
||||
|
||||
@@ -47,6 +47,11 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const service = createAuthCallbackService(getSupabaseServerClient());
|
||||
const oauthResult = await service.exchangeCodeForSession(authCode);
|
||||
|
||||
if (oauthResult.requiresMultiFactorAuthentication) {
|
||||
redirect(pathsConfig.auth.verifyMfa);
|
||||
}
|
||||
|
||||
if (!('isSuccess' in oauthResult)) {
|
||||
return redirectOnError(oauthResult.searchParams);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ const MembershipConfirmationNotification: React.FC<{
|
||||
descriptionKey="account:membershipConfirmation:successDescription"
|
||||
buttonProps={{
|
||||
buttonTitleKey: 'account:membershipConfirmation:successButton',
|
||||
href: pathsConfig.app.home,
|
||||
href: pathsConfig.app.selectPackage,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
async function SiteLayout(props: React.PropsWithChildren) {
|
||||
return (
|
||||
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
||||
|
||||
@@ -181,80 +181,74 @@ export function UpdateAccountForm({
|
||||
)}
|
||||
/>
|
||||
|
||||
{!isEmailUser && (
|
||||
<>
|
||||
<>
|
||||
<FormField
|
||||
name="city"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
<Trans i18nKey={'common:formField:city'} />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex flex-row justify-between gap-4">
|
||||
<FormField
|
||||
name="city"
|
||||
name="weight"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormItem className="flex-1 basis-0">
|
||||
<FormLabel>
|
||||
<Trans i18nKey={'common:formField:city'} />
|
||||
<Trans i18nKey={'common:formField:weight'} />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="kg"
|
||||
{...field}
|
||||
value={field.value ?? ''}
|
||||
onChange={(e) =>
|
||||
field.onChange(
|
||||
e.target.value === '' ? null : Number(e.target.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex flex-row justify-between gap-4">
|
||||
<FormField
|
||||
name="weight"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1 basis-0">
|
||||
<FormLabel>
|
||||
<Trans i18nKey={'common:formField:weight'} />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="kg"
|
||||
{...field}
|
||||
value={field.value ?? ''}
|
||||
onChange={(e) =>
|
||||
field.onChange(
|
||||
e.target.value === ''
|
||||
? null
|
||||
: Number(e.target.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
name="height"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1 basis-0">
|
||||
<FormLabel>
|
||||
<Trans i18nKey={'common:formField:height'} />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="cm"
|
||||
type="number"
|
||||
{...field}
|
||||
value={field.value ?? ''}
|
||||
onChange={(e) =>
|
||||
field.onChange(
|
||||
e.target.value === ''
|
||||
? null
|
||||
: Number(e.target.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<FormField
|
||||
name="height"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1 basis-0">
|
||||
<FormLabel>
|
||||
<Trans i18nKey={'common:formField:height'} />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="cm"
|
||||
type="number"
|
||||
{...field}
|
||||
value={field.value ?? ''}
|
||||
onChange={(e) =>
|
||||
field.onChange(
|
||||
e.target.value === '' ? null : Number(e.target.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
|
||||
<FormField
|
||||
name="userConsent"
|
||||
|
||||
@@ -4,7 +4,6 @@ import { updateCustomer } from '@lib/data/customer';
|
||||
|
||||
import { AccountSubmitData, createAuthApi } from '@kit/auth/api';
|
||||
import { enhanceAction } from '@kit/next/actions';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { UpdateAccountSchemaServer } from '../schemas/update-account.schema';
|
||||
@@ -16,7 +15,6 @@ export const onUpdateAccount = enhanceAction(
|
||||
|
||||
try {
|
||||
await api.updateAccount(params);
|
||||
console.log('SUCCESS', pathsConfig.auth.updateAccountSuccess);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
console.warn('On update account error: ' + err.message);
|
||||
|
||||
@@ -44,12 +44,7 @@ async function VerifyPage(props: Props) {
|
||||
!!nextPath && nextPath.length > 0 ? nextPath : pathsConfig.app.home;
|
||||
|
||||
return (
|
||||
<MultiFactorChallengeContainer
|
||||
userId={user.id}
|
||||
paths={{
|
||||
redirectPath,
|
||||
}}
|
||||
/>
|
||||
<MultiFactorChallengeContainer userId={user.id} paths={{ redirectPath }} />
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import React, { ReactElement, ReactNode, useMemo, useState } from 'react';
|
||||
|
||||
import { UserAnalysisElement } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { format } from 'date-fns';
|
||||
import { Info } from 'lucide-react';
|
||||
|
||||
@@ -10,29 +9,24 @@ import { Trans } from '@kit/ui/trans';
|
||||
import { cn } from '@kit/ui/utils';
|
||||
|
||||
import { AnalysisElement } from '~/lib/services/analysis-element.service';
|
||||
import { NestedAnalysisElement } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
|
||||
import AnalysisLevelBar, {
|
||||
AnalysisLevelBarSkeleton,
|
||||
AnalysisResultLevel,
|
||||
} from './analysis-level-bar';
|
||||
|
||||
export type AnalysisResultForDisplay = Pick<
|
||||
UserAnalysisElement,
|
||||
| 'norm_status'
|
||||
| 'response_value'
|
||||
| 'unit'
|
||||
| 'norm_lower_included'
|
||||
| 'norm_upper_included'
|
||||
| 'norm_lower'
|
||||
| 'norm_upper'
|
||||
| 'response_time'
|
||||
>;
|
||||
|
||||
export enum AnalysisStatus {
|
||||
NORMAL = 0,
|
||||
MEDIUM = 1,
|
||||
HIGH = 2,
|
||||
}
|
||||
export type AnalysisResultForDisplay = {
|
||||
norm_status?: number | null;
|
||||
response_value?: number | null;
|
||||
unit?: string | null;
|
||||
norm_lower_included?: boolean | null;
|
||||
norm_upper_included?: boolean | null;
|
||||
norm_lower?: number | null;
|
||||
norm_upper?: number | null;
|
||||
response_time?: string | null;
|
||||
nestedElements?: NestedAnalysisElement[];
|
||||
};
|
||||
|
||||
const AnalysisDoctor = ({
|
||||
analysisElement,
|
||||
@@ -48,38 +42,41 @@ const AnalysisDoctor = ({
|
||||
endIcon?: ReactNode | null;
|
||||
}) => {
|
||||
const name = analysisElement.analysis_name_lab || '';
|
||||
const status = results?.norm_status || AnalysisStatus.NORMAL;
|
||||
const status = results?.norm_status;
|
||||
const value = results?.response_value || 0;
|
||||
const unit = results?.unit || '';
|
||||
const normLowerIncluded = results?.norm_lower_included || false;
|
||||
const normUpperIncluded = results?.norm_upper_included || false;
|
||||
const normLower = results?.norm_lower || 0;
|
||||
const normUpper = results?.norm_upper || 0;
|
||||
const normLower = results?.norm_lower ?? null;
|
||||
const normUpper = results?.norm_upper ?? null;
|
||||
|
||||
const [showTooltip, setShowTooltip] = useState(false);
|
||||
const analysisResultLevel = useMemo(() => {
|
||||
if (!results) {
|
||||
if (!results || status === null || status === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isUnderNorm = value < normLower;
|
||||
if (isUnderNorm) {
|
||||
switch (status) {
|
||||
case AnalysisStatus.MEDIUM:
|
||||
return AnalysisResultLevel.LOW;
|
||||
default:
|
||||
return AnalysisResultLevel.VERY_LOW;
|
||||
}
|
||||
}
|
||||
switch (status) {
|
||||
case AnalysisStatus.MEDIUM:
|
||||
return AnalysisResultLevel.HIGH;
|
||||
case AnalysisStatus.HIGH:
|
||||
return AnalysisResultLevel.VERY_HIGH;
|
||||
case 1:
|
||||
return AnalysisResultLevel.WARNING;
|
||||
case 2:
|
||||
return AnalysisResultLevel.CRITICAL;
|
||||
case 0:
|
||||
default:
|
||||
return AnalysisResultLevel.NORMAL;
|
||||
}
|
||||
}, [results, value, normLower]);
|
||||
}, [results, status]);
|
||||
|
||||
const normRangeText = useMemo(() => {
|
||||
if (normLower === null && normUpper === null) {
|
||||
return null;
|
||||
}
|
||||
return `${normLower ?? '...'} - ${normUpper ?? '...'}`;
|
||||
}, [normLower, normUpper]);
|
||||
|
||||
const nestedElements = results?.nestedElements ?? null;
|
||||
const hasNestedElements =
|
||||
Array.isArray(nestedElements) && nestedElements.length > 0;
|
||||
|
||||
const isAnalysisLevelBarHidden = isCancelled || !results || hasNestedElements;
|
||||
|
||||
return (
|
||||
<div className="border-border rounded-lg border px-5">
|
||||
@@ -110,37 +107,52 @@ const AnalysisDoctor = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{results ? (
|
||||
{isAnalysisLevelBarHidden ? null : (
|
||||
<>
|
||||
<div className="flex items-center gap-3 sm:ml-auto">
|
||||
<div className="font-semibold">{value}</div>
|
||||
<div className="text-muted-foreground text-sm">{unit}</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground mx-8 flex flex-col-reverse gap-2 text-center text-sm sm:block sm:gap-0">
|
||||
{normLower} - {normUpper}
|
||||
{normRangeText}
|
||||
<div>
|
||||
<Trans i18nKey="analysis-results:results.range.normal" />
|
||||
</div>
|
||||
</div>
|
||||
<AnalysisLevelBar
|
||||
results={results}
|
||||
normLowerIncluded={normLowerIncluded}
|
||||
normUpperIncluded={normUpperIncluded}
|
||||
level={analysisResultLevel!}
|
||||
level={analysisResultLevel}
|
||||
normRangeText={normRangeText}
|
||||
/>
|
||||
{endIcon || <div className="mx-2 w-4" />}
|
||||
</>
|
||||
) : isCancelled ? null : (
|
||||
<>
|
||||
<div className="flex items-center gap-3 sm:ml-auto">
|
||||
<div className="font-semibold">
|
||||
<Trans i18nKey="analysis-results:waitingForResults" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="mx-8 w-[60px]"></div>
|
||||
<AnalysisLevelBarSkeleton />
|
||||
</>
|
||||
)}
|
||||
{(() => {
|
||||
// If parent has nested elements, don't show anything
|
||||
if (hasNestedElements) {
|
||||
return null;
|
||||
}
|
||||
// If we're showing the level bar, don't show waiting
|
||||
if (!isAnalysisLevelBarHidden) {
|
||||
return null;
|
||||
}
|
||||
// If cancelled, don't show waiting
|
||||
if (isCancelled) {
|
||||
return null;
|
||||
}
|
||||
// Otherwise, show waiting for results
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-3 sm:ml-auto">
|
||||
<div className="font-semibold">
|
||||
<Trans i18nKey="analysis-results:waitingForResults" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="mx-8 w-[60px]"></div>
|
||||
<AnalysisLevelBarSkeleton />
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
27
app/doctor/_components/analysis-fallback.tsx
Normal file
27
app/doctor/_components/analysis-fallback.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
'use server';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { Spinner } from '@kit/ui/makerkit/spinner';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Progress } from '@kit/ui/shadcn/progress';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
const AnalysisFallback = ({
|
||||
progress,
|
||||
progressTextKey,
|
||||
}: {
|
||||
progress: number;
|
||||
progressTextKey: string;
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-10">
|
||||
<Trans i18nKey={progressTextKey} />
|
||||
<Spinner />
|
||||
<Progress value={progress} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withI18n(AnalysisFallback);
|
||||
177
app/doctor/_components/analysis-feedback.tsx
Normal file
177
app/doctor/_components/analysis-feedback.tsx
Normal file
@@ -0,0 +1,177 @@
|
||||
import React, { useState } from 'react';
|
||||
|
||||
import { giveFeedbackAction } from '@/packages/features/doctor/src/lib/server/actions/doctor-server-actions';
|
||||
import {
|
||||
DoctorFeedback,
|
||||
Order,
|
||||
Patient,
|
||||
} from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
import {
|
||||
DoctorAnalysisFeedbackForm,
|
||||
doctorAnalysisFeedbackFormSchema,
|
||||
} from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis.schema';
|
||||
import ConfirmationModal from '@/packages/shared/src/components/confirmation-modal';
|
||||
import { useUser } from '@/packages/supabase/src/hooks/use-user';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { Spinner } from '@kit/ui/makerkit/spinner';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormMessage,
|
||||
} from '@kit/ui/shadcn/form';
|
||||
import { toast } from '@kit/ui/shadcn/sonner';
|
||||
import { Textarea } from '@kit/ui/shadcn/textarea';
|
||||
|
||||
const AnalysisFeedback = ({
|
||||
feedback,
|
||||
patient,
|
||||
order,
|
||||
aiDoctorFeedback,
|
||||
timestamp,
|
||||
recommendations,
|
||||
isRecommendationsEdited,
|
||||
}: {
|
||||
feedback?: DoctorFeedback;
|
||||
patient: Patient;
|
||||
order: Order;
|
||||
aiDoctorFeedback?: string;
|
||||
timestamp?: string;
|
||||
recommendations: string[];
|
||||
isRecommendationsEdited: boolean;
|
||||
}) => {
|
||||
const [isDraftSubmitting, setIsDraftSubmitting] = useState(false);
|
||||
const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
const { data: user } = useUser();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(doctorAnalysisFeedbackFormSchema),
|
||||
reValidateMode: 'onChange',
|
||||
defaultValues: {
|
||||
feedbackValue: feedback?.value ?? aiDoctorFeedback ?? '',
|
||||
userId: patient.userId,
|
||||
},
|
||||
});
|
||||
|
||||
const isReadOnly =
|
||||
!!feedback?.doctor_user_id && feedback?.doctor_user_id !== user?.id;
|
||||
|
||||
const handleDraftSubmit = async (e: React.FormEvent) => {
|
||||
setIsDraftSubmitting(true);
|
||||
e.preventDefault();
|
||||
|
||||
form.formState.errors.feedbackValue = undefined;
|
||||
const formData = form.getValues();
|
||||
await onSubmit(formData, 'DRAFT');
|
||||
setIsDraftSubmitting(false);
|
||||
};
|
||||
const handleCompleteSubmit = form.handleSubmit(async () => {
|
||||
setIsConfirmOpen(true);
|
||||
});
|
||||
|
||||
const onSubmit = async (
|
||||
data: DoctorAnalysisFeedbackForm,
|
||||
status: 'DRAFT' | 'COMPLETED',
|
||||
) => {
|
||||
setIsConfirmOpen(false);
|
||||
setIsSubmittingFeedback(true);
|
||||
|
||||
const result = await giveFeedbackAction({
|
||||
...data,
|
||||
analysisOrderId: order.analysisOrderId,
|
||||
status,
|
||||
patientId: patient.userId,
|
||||
timestamp,
|
||||
recommendations,
|
||||
isRecommendationsEdited,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return toast.error(<Trans i18nKey="common:genericServerError" />);
|
||||
}
|
||||
|
||||
setIsSubmittingFeedback(false);
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
});
|
||||
|
||||
return toast.success(<Trans i18nKey={'doctor:updateFeedbackSuccess'} />);
|
||||
};
|
||||
|
||||
const confirmComplete = form.handleSubmit(async (data) => {
|
||||
await onSubmit(data, 'COMPLETED');
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isReadOnly && (
|
||||
<Form {...form}>
|
||||
<form className="space-y-4 lg:w-1/2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="feedbackValue"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="min-h-[200px]"
|
||||
{...field}
|
||||
disabled={isDraftSubmitting || isSubmittingFeedback}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="xs:flex block justify-end gap-2 space-y-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleDraftSubmit}
|
||||
disabled={
|
||||
isReadOnly || isDraftSubmitting || form.formState.isSubmitting
|
||||
}
|
||||
className="xs:w-auto w-full text-xs"
|
||||
>
|
||||
<Trans i18nKey="common:saveAsDraft" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleCompleteSubmit}
|
||||
disabled={
|
||||
isReadOnly || isDraftSubmitting || form.formState.isSubmitting
|
||||
}
|
||||
className="xs:w-1/4 w-full"
|
||||
>
|
||||
{isDraftSubmitting || form.formState.isSubmitting ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Trans i18nKey="common:save" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
)}
|
||||
<ConfirmationModal
|
||||
isOpen={isConfirmOpen}
|
||||
onClose={() => setIsConfirmOpen(false)}
|
||||
onConfirm={confirmComplete}
|
||||
titleKey="doctor:confirmFeedbackModal.title"
|
||||
descriptionKey="doctor:confirmFeedbackModal.description"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AnalysisFeedback;
|
||||
@@ -7,11 +7,9 @@ import { cn } from '@kit/ui/utils';
|
||||
import { AnalysisResultForDisplay } from './analysis-doctor';
|
||||
|
||||
export enum AnalysisResultLevel {
|
||||
VERY_LOW = 0,
|
||||
LOW = 1,
|
||||
NORMAL = 2,
|
||||
HIGH = 3,
|
||||
VERY_HIGH = 4,
|
||||
NORMAL = 'NORMAL',
|
||||
WARNING = 'WARNING',
|
||||
CRITICAL = 'CRITICAL',
|
||||
}
|
||||
|
||||
const Level = ({
|
||||
@@ -20,17 +18,19 @@ const Level = ({
|
||||
isFirst = false,
|
||||
isLast = false,
|
||||
arrowLocation,
|
||||
normRangeText,
|
||||
}: {
|
||||
isActive?: boolean;
|
||||
color: 'destructive' | 'success' | 'warning' | 'gray-200';
|
||||
isFirst?: boolean;
|
||||
isLast?: boolean;
|
||||
arrowLocation?: number;
|
||||
normRangeText?: string | null;
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(`bg-${color} relative h-3 flex-1`, {
|
||||
'opacity-20': !isActive,
|
||||
'opacity-60': !isActive,
|
||||
'rounded-l-lg': isFirst,
|
||||
'rounded-r-lg': isLast,
|
||||
})}
|
||||
@@ -38,11 +38,32 @@ const Level = ({
|
||||
{isActive && (
|
||||
<div
|
||||
className="absolute top-[-14px] left-1/2 -translate-x-1/2 rounded-[10px] bg-white p-[2px]"
|
||||
style={{ left: `${arrowLocation}%` }}
|
||||
{...(arrowLocation
|
||||
? {
|
||||
style: {
|
||||
left: `${arrowLocation}%`,
|
||||
...(arrowLocation > 92.5 && { left: '92.5%' }),
|
||||
...(arrowLocation < 7.5 && { left: '7.5%' }),
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
<ArrowDown strokeWidth={2} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{color === 'success' && typeof normRangeText === 'string' && (
|
||||
<p
|
||||
className={cn(
|
||||
'text-muted-foreground absolute bottom-[-18px] left-3/8 text-xs font-bold whitespace-nowrap',
|
||||
{
|
||||
'opacity-60': isActive,
|
||||
},
|
||||
)}
|
||||
>
|
||||
{normRangeText}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -50,81 +71,148 @@ const Level = ({
|
||||
export const AnalysisLevelBarSkeleton = () => {
|
||||
return (
|
||||
<div className="mt-4 flex h-3 w-[60%] max-w-[360px] gap-1 sm:mt-0 sm:w-[35%]">
|
||||
<Level color="gray-200" />
|
||||
<Level color="gray-200" isFirst isLast />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const AnalysisLevelBar = ({
|
||||
normLowerIncluded = true,
|
||||
normUpperIncluded = true,
|
||||
level,
|
||||
results,
|
||||
normRangeText,
|
||||
}: {
|
||||
normLowerIncluded?: boolean;
|
||||
normUpperIncluded?: boolean;
|
||||
level: AnalysisResultLevel;
|
||||
level: AnalysisResultLevel | null;
|
||||
results: AnalysisResultForDisplay;
|
||||
normRangeText: string | null;
|
||||
}) => {
|
||||
const {
|
||||
norm_lower: lower,
|
||||
norm_upper: upper,
|
||||
response_value: value,
|
||||
} = results;
|
||||
const arrowLocation = useMemo(() => {
|
||||
if (value < lower!) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (normLowerIncluded || normUpperIncluded) {
|
||||
// Calculate arrow position based on value within normal range
|
||||
const arrowLocation = useMemo(() => {
|
||||
// If no response value, center the arrow
|
||||
if (value === null || value === undefined) {
|
||||
return 50;
|
||||
}
|
||||
|
||||
const calculated = ((value - lower!) / (upper! - lower!)) * 100;
|
||||
|
||||
if (calculated > 100) {
|
||||
return 100;
|
||||
// If no normal ranges defined, center the arrow
|
||||
if (lower === null && upper === null) {
|
||||
return 50;
|
||||
}
|
||||
|
||||
return calculated;
|
||||
// If only upper bound exists
|
||||
if (lower === null && upper !== null) {
|
||||
if (value <= upper!) {
|
||||
return Math.min(75, (value / upper!) * 75); // Show in left 75% of normal range
|
||||
}
|
||||
return 100; // Beyond upper bound
|
||||
}
|
||||
|
||||
// If only lower bound exists
|
||||
if (upper === null && lower !== null) {
|
||||
if (value >= lower!) {
|
||||
// Value is in normal range (above lower bound)
|
||||
// Position proportionally in the normal range section
|
||||
const normalizedPosition = Math.min(
|
||||
(value - lower!) / (lower! * 0.5),
|
||||
1,
|
||||
); // Use 50% of lower as scale
|
||||
return normalizedPosition * 100;
|
||||
}
|
||||
// Value is below lower bound - position in the "below normal" section
|
||||
const belowPosition = Math.max(0, Math.min(1, value / lower!));
|
||||
return belowPosition * 100;
|
||||
}
|
||||
|
||||
// Both bounds exist
|
||||
if (lower !== null && upper !== null) {
|
||||
if (value < lower!) {
|
||||
return 0; // Below normal range
|
||||
}
|
||||
if (value > upper!) {
|
||||
return 100; // Above normal range
|
||||
}
|
||||
// Within normal range
|
||||
return ((value - lower!) / (upper! - lower!)) * 100;
|
||||
}
|
||||
|
||||
return 50; // Fallback
|
||||
}, [value, upper, lower]);
|
||||
|
||||
const [isVeryLow, isLow, isHigh, isVeryHigh] = useMemo(
|
||||
() => [
|
||||
level === AnalysisResultLevel.VERY_LOW,
|
||||
level === AnalysisResultLevel.LOW,
|
||||
level === AnalysisResultLevel.HIGH,
|
||||
level === AnalysisResultLevel.VERY_HIGH,
|
||||
],
|
||||
[level, value, upper, lower],
|
||||
);
|
||||
// Determine level states based on normStatus
|
||||
const isNormal = level === AnalysisResultLevel.NORMAL;
|
||||
const isWarning = level === AnalysisResultLevel.WARNING;
|
||||
const isCritical = level === AnalysisResultLevel.CRITICAL;
|
||||
const isPending = level === null;
|
||||
|
||||
const hasAbnormalLevel = isVeryLow || isLow || isHigh || isVeryHigh;
|
||||
// Show appropriate levels based on available norm bounds
|
||||
const hasLowerBound = lower !== null;
|
||||
|
||||
// Calculate level configuration (must be called before any returns)
|
||||
const [first, second, third] = useMemo(() => {
|
||||
const [warning, normal, critical] = [
|
||||
{
|
||||
isActive: isWarning,
|
||||
color: 'warning',
|
||||
...(isWarning ? { arrowLocation } : {}),
|
||||
},
|
||||
{
|
||||
isActive: isNormal,
|
||||
color: 'success',
|
||||
normRangeText,
|
||||
...(isNormal ? { arrowLocation } : {}),
|
||||
},
|
||||
{
|
||||
isActive: isCritical,
|
||||
color: 'destructive',
|
||||
isLast: true,
|
||||
...(isCritical ? { arrowLocation } : {}),
|
||||
},
|
||||
] as const;
|
||||
|
||||
if (!hasLowerBound) {
|
||||
return [{ ...normal, isFirst: true }, warning, critical] as const;
|
||||
}
|
||||
|
||||
return [
|
||||
{ ...warning, isFirst: true },
|
||||
normal,
|
||||
{ ...critical, isLast: true },
|
||||
] as const;
|
||||
}, [
|
||||
arrowLocation,
|
||||
normRangeText,
|
||||
isNormal,
|
||||
isWarning,
|
||||
isCritical,
|
||||
hasLowerBound,
|
||||
]);
|
||||
|
||||
// If pending results, show gray bar
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="w-60% mt-4 flex h-3 max-w-[360px] gap-1 sm:mt-0 sm:w-[35%]">
|
||||
<Level color="gray-200" isFirst isLast />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-4 flex h-3 w-[60%] max-w-[360px] gap-1 sm:mt-0 sm:w-[35%]">
|
||||
{normLowerIncluded && (
|
||||
<>
|
||||
<Level isActive={isVeryLow} color="destructive" isFirst />
|
||||
<Level isActive={isLow} color="warning" />
|
||||
</>
|
||||
)}
|
||||
|
||||
<Level
|
||||
isFirst={!normLowerIncluded}
|
||||
isLast={!normUpperIncluded}
|
||||
{...(hasAbnormalLevel
|
||||
? { color: 'warning', isActive: false }
|
||||
: { color: 'success', isActive: true })}
|
||||
arrowLocation={arrowLocation}
|
||||
/>
|
||||
|
||||
{normUpperIncluded && (
|
||||
<>
|
||||
<Level isActive={isHigh} color="warning" />
|
||||
<Level isActive={isVeryHigh} color="destructive" isLast />
|
||||
</>
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-3 gap-1',
|
||||
'mt-4 sm:mt-0',
|
||||
'w-[60%] sm:w-[35%]',
|
||||
'min-w-[50vw] sm:min-w-auto',
|
||||
'max-w-[360px]',
|
||||
)}
|
||||
>
|
||||
<Level {...first} />
|
||||
<Level {...second} />
|
||||
<Level {...third} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { capitalize } from 'lodash';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { giveFeedbackAction } from '@kit/doctor/actions/doctor-server-actions';
|
||||
import {
|
||||
getDOBWithAgeStringFromPersonalCode,
|
||||
getResultSetName,
|
||||
@@ -18,46 +15,50 @@ import {
|
||||
Order,
|
||||
Patient,
|
||||
} from '@kit/doctor/schema/doctor-analysis-detail-view.schema';
|
||||
import {
|
||||
DoctorAnalysisFeedbackForm,
|
||||
doctorAnalysisFeedbackFormSchema,
|
||||
} from '@kit/doctor/schema/doctor-analysis.schema';
|
||||
import ConfirmationModal from '@kit/shared/components/confirmation-modal';
|
||||
import { useCurrentLocaleLanguageNames } from '@kit/shared/hooks';
|
||||
import { getFullName } from '@kit/shared/utils';
|
||||
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { Textarea } from '@kit/ui/textarea';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { bmiFromMetric } from '~/lib/utils';
|
||||
|
||||
import AnalysisFeedback from './analysis-feedback';
|
||||
import DoctorAnalysisWrapper from './doctor-analysis-wrapper';
|
||||
import DoctorJobSelect from './doctor-job-select';
|
||||
import DoctorRecommendedAnalyses from './doctor-recommended-analyses';
|
||||
|
||||
export default function AnalysisView({
|
||||
patient,
|
||||
order,
|
||||
analyses,
|
||||
feedback,
|
||||
aiDoctorFeedback,
|
||||
recommendations,
|
||||
availableAnalyses,
|
||||
timestamp,
|
||||
}: {
|
||||
patient: Patient;
|
||||
order: Order;
|
||||
analyses: AnalysisResponse[];
|
||||
feedback?: DoctorFeedback;
|
||||
aiDoctorFeedback?: string;
|
||||
recommendations?: string[];
|
||||
availableAnalyses?: string[];
|
||||
timestamp?: string;
|
||||
}) {
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
const [isDraftSubmitting, setIsDraftSubmitting] = useState(false);
|
||||
|
||||
const { data: user } = useUser();
|
||||
const queryClient = useQueryClient();
|
||||
const [recommendedAnalyses, setRecommendedAnalyses] = useState<string[]>(
|
||||
recommendations ?? [],
|
||||
);
|
||||
const isRecommendationsEdited = useMemo(() => {
|
||||
if (recommendedAnalyses.length !== recommendations?.length) return true;
|
||||
const sa = new Set(recommendedAnalyses),
|
||||
sb = new Set(recommendations);
|
||||
if (sa.size !== sb.size) return true;
|
||||
for (const v of sa) if (!sb.has(v)) return true;
|
||||
return false;
|
||||
}, [recommendations, recommendedAnalyses]);
|
||||
|
||||
const languageNames = useCurrentLocaleLanguageNames();
|
||||
|
||||
@@ -68,66 +69,11 @@ export default function AnalysisView({
|
||||
);
|
||||
const isCurrentDoctorJob =
|
||||
!!feedback?.doctor_user_id && feedback?.doctor_user_id === user?.id;
|
||||
const isReadOnly =
|
||||
!isInProgress ||
|
||||
(!!feedback?.doctor_user_id && feedback?.doctor_user_id !== user?.id);
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(doctorAnalysisFeedbackFormSchema),
|
||||
reValidateMode: 'onChange',
|
||||
defaultValues: {
|
||||
feedbackValue: feedback?.value ?? '',
|
||||
userId: patient.userId,
|
||||
},
|
||||
});
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
if (!patient || !order || !analyses) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onSubmit = async (
|
||||
data: DoctorAnalysisFeedbackForm,
|
||||
status: 'DRAFT' | 'COMPLETED',
|
||||
) => {
|
||||
const result = await giveFeedbackAction({
|
||||
...data,
|
||||
analysisOrderId: order.analysisOrderId,
|
||||
status,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return toast.error(<Trans i18nKey="common:genericServerError" />);
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
});
|
||||
|
||||
toast.success(<Trans i18nKey={'doctor:updateFeedbackSuccess'} />);
|
||||
|
||||
return setIsConfirmOpen(false);
|
||||
};
|
||||
|
||||
const handleDraftSubmit = async (e: React.FormEvent) => {
|
||||
setIsDraftSubmitting(true);
|
||||
e.preventDefault();
|
||||
|
||||
form.formState.errors.feedbackValue = undefined;
|
||||
const formData = form.getValues();
|
||||
await onSubmit(formData, 'DRAFT');
|
||||
setIsDraftSubmitting(false);
|
||||
};
|
||||
|
||||
const handleCompleteSubmit = form.handleSubmit(async () => {
|
||||
setIsConfirmOpen(true);
|
||||
});
|
||||
|
||||
const confirmComplete = form.handleSubmit(async (data) => {
|
||||
await onSubmit(data, 'COMPLETED');
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="xs:flex xs:justify-between">
|
||||
@@ -229,59 +175,30 @@ export default function AnalysisView({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<h3>
|
||||
<Trans i18nKey="doctor:feedback" />
|
||||
</h3>
|
||||
<p>{feedback?.value ?? '-'}</p>
|
||||
{!isReadOnly && (
|
||||
<Form {...form}>
|
||||
<form className="space-y-4 lg:w-1/2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="feedbackValue"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<Textarea {...field} disabled={isReadOnly} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
{order.isPackage && (
|
||||
<>
|
||||
<h3>
|
||||
<Trans i18nKey="doctor:feedback" />
|
||||
</h3>
|
||||
<p>{feedback?.value ?? '-'}</p>
|
||||
<div className="flex flex-col gap-4 lg:flex-row">
|
||||
<AnalysisFeedback
|
||||
order={order}
|
||||
patient={patient}
|
||||
feedback={feedback}
|
||||
aiDoctorFeedback={aiDoctorFeedback}
|
||||
timestamp={timestamp}
|
||||
recommendations={recommendedAnalyses}
|
||||
isRecommendationsEdited={isRecommendationsEdited}
|
||||
/>
|
||||
|
||||
<div className="xs:flex block justify-end gap-2 space-y-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleDraftSubmit}
|
||||
disabled={
|
||||
isReadOnly || isDraftSubmitting || form.formState.isSubmitting
|
||||
}
|
||||
className="xs:w-1/4 w-full"
|
||||
>
|
||||
<Trans i18nKey="common:saveAsDraft" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleCompleteSubmit}
|
||||
disabled={
|
||||
isReadOnly || isDraftSubmitting || form.formState.isSubmitting
|
||||
}
|
||||
className="xs:w-1/4 w-full"
|
||||
>
|
||||
<Trans i18nKey="common:save" />
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
<DoctorRecommendedAnalyses
|
||||
recommendedAnalyses={recommendedAnalyses}
|
||||
availableAnalyses={availableAnalyses}
|
||||
setRecommendedAnalyses={setRecommendedAnalyses}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<ConfirmationModal
|
||||
isOpen={isConfirmOpen}
|
||||
onClose={() => setIsConfirmOpen(false)}
|
||||
onConfirm={confirmComplete}
|
||||
titleKey="doctor:confirmFeedbackModal.title"
|
||||
descriptionKey="doctor:confirmFeedbackModal.description"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { CaretDownIcon, QuestionMarkCircledIcon } from '@radix-ui/react-icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
@@ -23,55 +25,25 @@ export default function DoctorAnalysisWrapper({
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Collapsible className="w-full" key={analysisData.id}>
|
||||
<CollapsibleTrigger
|
||||
disabled={!analysisData.latestPreviousAnalysis}
|
||||
asChild
|
||||
>
|
||||
<div className="[&[data-state=open]_.caret-icon]:rotate-180">
|
||||
<AnalysisDoctor
|
||||
startIcon={
|
||||
analysisData.latestPreviousAnalysis && (
|
||||
<CaretDownIcon className="caret-icon transition-transform duration-200" />
|
||||
)
|
||||
}
|
||||
endIcon={
|
||||
analysisData.comment && (
|
||||
<>
|
||||
<div className="xs:flex hidden">
|
||||
<InfoTooltip
|
||||
content={analysisData.comment}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="mx-2 text-blue-800" />
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="xs:hidden">
|
||||
<strong>
|
||||
<Trans i18nKey="doctor:labComment" />:
|
||||
</strong>{' '}
|
||||
{analysisData.comment}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
analysisElement={{
|
||||
analysis_name_lab: analysisData.analysis_name,
|
||||
}}
|
||||
results={analysisData}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
{analysisData.latestPreviousAnalysis && (
|
||||
<CollapsibleContent>
|
||||
<div className="my-1 flex flex-col">
|
||||
<>
|
||||
<Collapsible className="w-full" key={analysisData.id}>
|
||||
<CollapsibleTrigger
|
||||
disabled={!analysisData.latestPreviousAnalysis}
|
||||
asChild
|
||||
>
|
||||
<div className="[&[data-state=open]_.caret-icon]:rotate-180">
|
||||
<AnalysisDoctor
|
||||
startIcon={
|
||||
analysisData.latestPreviousAnalysis && (
|
||||
<CaretDownIcon className="caret-icon transition-transform duration-200" />
|
||||
)
|
||||
}
|
||||
endIcon={
|
||||
analysisData.latestPreviousAnalysis.comment && (
|
||||
analysisData.comment && (
|
||||
<>
|
||||
<div className="xs:flex hidden">
|
||||
<InfoTooltip
|
||||
content={analysisData.latestPreviousAnalysis.comment}
|
||||
content={analysisData.comment}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="mx-2 text-blue-800" />
|
||||
}
|
||||
@@ -79,25 +51,103 @@ export default function DoctorAnalysisWrapper({
|
||||
</div>
|
||||
<p className="xs:hidden">
|
||||
<strong>
|
||||
<Trans i18nKey="doctor:labComment" />:{' '}
|
||||
</strong>
|
||||
{analysisData.latestPreviousAnalysis.comment}
|
||||
<Trans i18nKey="doctor:labComment" />:
|
||||
</strong>{' '}
|
||||
{analysisData.comment}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
analysisElement={{
|
||||
analysis_name_lab: t('doctor:previousResults', {
|
||||
date: formatDate(
|
||||
analysisData.latestPreviousAnalysis.response_time,
|
||||
),
|
||||
}),
|
||||
analysis_name_lab: analysisData.analysis_name,
|
||||
}}
|
||||
results={analysisData.latestPreviousAnalysis}
|
||||
results={analysisData}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
)}
|
||||
</Collapsible>
|
||||
</CollapsibleTrigger>
|
||||
{analysisData.latestPreviousAnalysis && (
|
||||
<CollapsibleContent>
|
||||
<div className="my-1 flex flex-col gap-2">
|
||||
<AnalysisDoctor
|
||||
endIcon={
|
||||
analysisData.latestPreviousAnalysis.comment && (
|
||||
<>
|
||||
<div className="xs:flex hidden">
|
||||
<InfoTooltip
|
||||
content={analysisData.latestPreviousAnalysis.comment}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="mx-2 text-blue-800" />
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="xs:hidden">
|
||||
<strong>
|
||||
<Trans i18nKey="doctor:labComment" />:{' '}
|
||||
</strong>
|
||||
{analysisData.latestPreviousAnalysis.comment}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
analysisElement={{
|
||||
analysis_name_lab: t('doctor:previousResults', {
|
||||
date: formatDate(
|
||||
analysisData.latestPreviousAnalysis.response_time!,
|
||||
),
|
||||
}),
|
||||
}}
|
||||
results={analysisData.latestPreviousAnalysis}
|
||||
/>
|
||||
{analysisData.latestPreviousAnalysis.nestedElements?.map(
|
||||
(nestedElement, nestedIndex) => (
|
||||
<div
|
||||
key={`prev-nested-${nestedElement.analysisElementOriginalId}-${nestedIndex}`}
|
||||
className="ml-8"
|
||||
>
|
||||
<AnalysisDoctor
|
||||
analysisElement={{
|
||||
analysis_name_lab: nestedElement.analysisNameLab ?? '',
|
||||
}}
|
||||
results={{
|
||||
norm_status: nestedElement.normStatus,
|
||||
response_value: nestedElement.responseValue,
|
||||
unit: nestedElement.unit,
|
||||
norm_lower: nestedElement.normLower,
|
||||
norm_upper: nestedElement.normUpper,
|
||||
norm_lower_included: nestedElement.normLowerIncluded,
|
||||
norm_upper_included: nestedElement.normUpperIncluded,
|
||||
response_time: nestedElement.responseTime,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
)}
|
||||
</Collapsible>
|
||||
{analysisData.nestedElements?.map((nestedElement, nestedIndex) => (
|
||||
<div
|
||||
key={`nested-${nestedElement.analysisElementOriginalId}-${nestedIndex}`}
|
||||
className="ml-8"
|
||||
>
|
||||
<AnalysisDoctor
|
||||
analysisElement={{
|
||||
analysis_name_lab: nestedElement.analysisNameLab ?? '',
|
||||
}}
|
||||
results={{
|
||||
norm_status: nestedElement.normStatus,
|
||||
response_value: nestedElement.responseValue,
|
||||
unit: nestedElement.unit,
|
||||
norm_lower: nestedElement.normLower,
|
||||
norm_upper: nestedElement.normUpper,
|
||||
norm_lower_included: nestedElement.normLowerIncluded,
|
||||
norm_upper_included: nestedElement.normUpperIncluded,
|
||||
response_time: nestedElement.responseTime,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
|
||||
import ResultsTableWrapper from './results-table-wrapper';
|
||||
|
||||
export default function Dashboard() {
|
||||
export default function DoctorDashboard() {
|
||||
return (
|
||||
<>
|
||||
<ResultsTableWrapper
|
||||
|
||||
53
app/doctor/_components/doctor-recommended-analyses.tsx
Normal file
53
app/doctor/_components/doctor-recommended-analyses.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
'use client';
|
||||
|
||||
import React, { Dispatch, SetStateAction } from 'react';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
|
||||
const DoctorRecommendedAnalyses = ({
|
||||
recommendedAnalyses,
|
||||
availableAnalyses,
|
||||
setRecommendedAnalyses,
|
||||
}: {
|
||||
recommendedAnalyses?: string[];
|
||||
availableAnalyses?: string[];
|
||||
setRecommendedAnalyses: Dispatch<SetStateAction<string[]>>;
|
||||
}) => {
|
||||
if (availableAnalyses?.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-1/3">
|
||||
<h5>
|
||||
<Trans i18nKey="doctor:recommendedAnalyses" />
|
||||
</h5>
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{availableAnalyses?.map((analysis, index) => {
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
key={`${index}-analysis-feedback-list`}
|
||||
variant={
|
||||
recommendedAnalyses?.includes(analysis) ? 'default' : 'outline'
|
||||
}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setRecommendedAnalyses((prev: string[]) =>
|
||||
prev.includes(analysis)
|
||||
? prev.filter((x) => x !== analysis)
|
||||
: [...prev, analysis],
|
||||
)
|
||||
}
|
||||
>
|
||||
{analysis}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DoctorRecommendedAnalyses;
|
||||
@@ -34,7 +34,7 @@ export function DoctorSidebar({
|
||||
<Sidebar collapsible="icon">
|
||||
<SidebarHeader className={'m-2'}>
|
||||
<AppLogo
|
||||
href={pathsConfig.app.doctor}
|
||||
href={pathsConfig.app.home}
|
||||
className="max-w-full"
|
||||
compact={!open}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
'use server';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { AnalysisResponses } from '@/app/home/(user)/_components/ai/types';
|
||||
import { OrderAnalysisCard } from '@/app/home/(user)/_components/order-analyses-cards';
|
||||
import { loadLifeStyle } from '@/app/home/(user)/_lib/server/load-life-style';
|
||||
import { loadRecommendations } from '@/app/home/(user)/_lib/server/load-recommendations';
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { AnalysisResultDetails } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import {
|
||||
loadDoctorFeedback,
|
||||
prepareFeedback,
|
||||
} from '../_lib/server/load-doctor-feedback';
|
||||
import AnalysisView from './analysis-view';
|
||||
|
||||
async function NewAnalysisRecommendationsLoader({
|
||||
analysisResultDetails,
|
||||
account,
|
||||
analysisResponses,
|
||||
currentAIResponseTimestamp,
|
||||
analyses,
|
||||
patient,
|
||||
}: {
|
||||
currentAIResponseTimestamp: string;
|
||||
account: AccountWithParams | null;
|
||||
analysisResponses: AnalysisResponses;
|
||||
analysisResultDetails: AnalysisResultDetails;
|
||||
analyses: OrderAnalysisCard[];
|
||||
patient: AccountWithParams | null;
|
||||
}) {
|
||||
if (!analysisResultDetails.order.isPackage) {
|
||||
return (
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const [lifeStyle, recommendations, aiFeedback] = await Promise.all([
|
||||
loadLifeStyle({
|
||||
account: patient,
|
||||
analysisResponses,
|
||||
isDoctorView: true,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
}),
|
||||
loadRecommendations({
|
||||
account: patient,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
isDoctorView: true,
|
||||
analyses,
|
||||
}),
|
||||
loadDoctorFeedback(
|
||||
analysisResultDetails.patient,
|
||||
analysisResultDetails.analysisResponse,
|
||||
currentAIResponseTimestamp,
|
||||
),
|
||||
]);
|
||||
|
||||
const feedback = prepareFeedback({
|
||||
aiResponse: aiFeedback,
|
||||
recommendations,
|
||||
lifeStyleSummary: lifeStyle.response.summary,
|
||||
patientName: analysisResultDetails.patient.firstName,
|
||||
doctorName: `${account?.name} ${account?.last_name}`,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
});
|
||||
|
||||
return (
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
aiDoctorFeedback={feedback}
|
||||
availableAnalyses={analyses.map((analysis) => analysis.title)}
|
||||
recommendations={recommendations}
|
||||
timestamp={currentAIResponseTimestamp}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(NewAnalysisRecommendationsLoader);
|
||||
55
app/doctor/_components/prepare-ai-parameters.tsx
Normal file
55
app/doctor/_components/prepare-ai-parameters.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use server';
|
||||
|
||||
import React, { Suspense } from 'react';
|
||||
|
||||
import { loadAnalyses } from '@/app/home/(user)/_lib/server/load-analyses';
|
||||
import {
|
||||
loadCurrentUserAccount,
|
||||
loadUserAccount,
|
||||
} from '@/app/home/(user)/_lib/server/load-user-account';
|
||||
import { AnalysisResultDetails } from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import AnalysisFallback from './analysis-fallback';
|
||||
import NewAnalysisRecommendationsLoader from './new-analysis-recommendations-loader';
|
||||
|
||||
async function PrepareAIParameters({
|
||||
analysisResultDetails,
|
||||
}: {
|
||||
analysisResultDetails: AnalysisResultDetails;
|
||||
}) {
|
||||
const { analyses } = await loadAnalyses();
|
||||
const { account: doctorAccount } = await loadCurrentUserAccount();
|
||||
const patientAccount = await loadUserAccount(
|
||||
analysisResultDetails.patient.userId,
|
||||
);
|
||||
const client = getSupabaseServerClient();
|
||||
const userAnalysesApi = createUserAnalysesApi(client);
|
||||
const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses(
|
||||
patientAccount.id,
|
||||
);
|
||||
const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<AnalysisFallback progress={66} progressTextKey="doctor:loadFeedback" />
|
||||
}
|
||||
>
|
||||
<NewAnalysisRecommendationsLoader
|
||||
account={doctorAccount}
|
||||
currentAIResponseTimestamp={currentAIResponseTimestamp}
|
||||
analysisResponses={analysisResponses}
|
||||
analysisResultDetails={analysisResultDetails}
|
||||
analyses={analyses}
|
||||
patient={patientAccount}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(PrepareAIParameters);
|
||||
@@ -178,7 +178,7 @@ export default function ResultsTable({
|
||||
<TableCell>
|
||||
<Trans
|
||||
i18nKey={
|
||||
resultsReceived === elementsInOrder
|
||||
resultsReceived >= elementsInOrder
|
||||
? 'doctor:resultsTable.responsesReceived'
|
||||
: 'doctor:resultsTable.waitingForNr'
|
||||
}
|
||||
|
||||
98
app/doctor/_lib/server/load-doctor-feedback.ts
Normal file
98
app/doctor/_lib/server/load-doctor-feedback.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { cache } from 'react';
|
||||
|
||||
import { PROMPT_NAME } from '@/app/home/(user)/_components/ai/types';
|
||||
import { generateDoctorFeedback } from '@/app/home/(user)/_lib/server/ai-actions';
|
||||
import {
|
||||
AnalysisResponse,
|
||||
Patient,
|
||||
} from '@/packages/features/doctor/src/lib/server/schema/doctor-analysis-detail-view.schema';
|
||||
import { getLogger } from '@/packages/shared/src/logger';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
export const loadDoctorFeedback = cache(doctorFeedbackLoader);
|
||||
|
||||
const PLACEHOLDER = {
|
||||
ANALYSES: 'SOOVITATUD_ANALYYSID_PLACEHOLDER',
|
||||
LIFE_STYLE_SUMMARY: 'ELUSTIILI_KOKKUVOTTE_PLACEHOLDER',
|
||||
PATIENT_NAME: 'PATSIENDI_NIMI_PLACEHOLDER',
|
||||
DOCTOR_NAME: 'ARSTI_NIMI_PLACEHOLDER',
|
||||
ANALYSES_DATE: 'ANALYYSI_KUUPAEV_PLACEHOLDER',
|
||||
};
|
||||
|
||||
export const prepareFeedback = ({
|
||||
aiResponse,
|
||||
recommendations,
|
||||
lifeStyleSummary,
|
||||
patientName,
|
||||
doctorName,
|
||||
aiResponseTimestamp,
|
||||
}: {
|
||||
aiResponse: string;
|
||||
recommendations?: string[];
|
||||
lifeStyleSummary: string | null;
|
||||
patientName: string;
|
||||
doctorName: string;
|
||||
aiResponseTimestamp: string;
|
||||
}) => {
|
||||
const recommendationsList = recommendations
|
||||
? recommendations.map((analysis) => `${analysis}`).join('\n')
|
||||
: '';
|
||||
const feedback = aiResponse
|
||||
.replace(PLACEHOLDER.ANALYSES, recommendationsList)
|
||||
.replace(PLACEHOLDER.LIFE_STYLE_SUMMARY, lifeStyleSummary ?? '')
|
||||
.replace(PLACEHOLDER.PATIENT_NAME, patientName)
|
||||
.replace(PLACEHOLDER.DOCTOR_NAME, doctorName)
|
||||
.replace(
|
||||
PLACEHOLDER.ANALYSES_DATE,
|
||||
new Date(aiResponseTimestamp).toLocaleString(),
|
||||
);
|
||||
|
||||
return feedback;
|
||||
};
|
||||
|
||||
async function doctorFeedbackLoader(
|
||||
patient: Patient | null,
|
||||
analysisResponses: AnalysisResponse[],
|
||||
aiResponseTimestamp: string,
|
||||
): Promise<string> {
|
||||
const logger = await getLogger();
|
||||
if (!patient?.personalCode) {
|
||||
return '';
|
||||
}
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
|
||||
logger.info(
|
||||
{
|
||||
aiResponseTimestamp,
|
||||
patientId: patient.userId,
|
||||
},
|
||||
'Attempting to receive existing doctor feedback',
|
||||
);
|
||||
|
||||
const { data, error } = await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('ai_responses')
|
||||
.select('*')
|
||||
.eq('account_id', patient.userId)
|
||||
.eq('prompt_name', PROMPT_NAME.FEEDBACK)
|
||||
.eq('latest_data_change', aiResponseTimestamp)
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
|
||||
logger.info({ data: !!data }, 'Existing doctor feedback');
|
||||
|
||||
if (error) {
|
||||
console.error('Error fetching AI response from DB: ', error);
|
||||
return '';
|
||||
}
|
||||
|
||||
if (data?.response) {
|
||||
return data.response as string;
|
||||
} else {
|
||||
return await generateDoctorFeedback({
|
||||
patient,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
import { cache } from 'react';
|
||||
import { Suspense, cache } from 'react';
|
||||
|
||||
import { getAnalysisResultsForDoctor } from '@kit/doctor/services/doctor-analysis.service';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import AnalysisView from '../../_components/analysis-view';
|
||||
import AnalysisFallback from '../../_components/analysis-fallback';
|
||||
import { DoctorGuard } from '../../_components/doctor-guard';
|
||||
import PrepareAiParameters from '../../_components/prepare-ai-parameters';
|
||||
|
||||
async function AnalysisPage({
|
||||
params,
|
||||
@@ -36,17 +38,21 @@ async function AnalysisPage({
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
/>
|
||||
<PageBody className="px-12">
|
||||
<Suspense
|
||||
fallback={
|
||||
<AnalysisFallback
|
||||
progress={33}
|
||||
progressTextKey="doctor:loadParameters"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PrepareAiParameters analysisResultDetails={analysisResultDetails} />
|
||||
</Suspense>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(AnalysisPage);
|
||||
export default DoctorGuard(withI18n(AnalysisPage));
|
||||
const loadResult = cache(getAnalysisResultsForDoctor);
|
||||
|
||||
@@ -17,7 +17,7 @@ async function CompletedJobsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<PageBody className="px-12">
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:completedReviews"
|
||||
action={getUserDoneResponsesAction}
|
||||
|
||||
@@ -17,7 +17,7 @@ async function MyReviewsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<PageBody className="px-12">
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:myReviews"
|
||||
action={getUserInProgressResponsesAction}
|
||||
|
||||
@@ -17,7 +17,7 @@ async function OpenJobsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<PageBody className="px-12">
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:openReviews"
|
||||
action={getOpenResponsesAction}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import Dashboard from './_components/doctor-dashboard';
|
||||
import DoctorDashboard from './_components/doctor-dashboard';
|
||||
import { DoctorGuard } from './_components/doctor-guard';
|
||||
|
||||
async function DoctorPage() {
|
||||
@@ -16,8 +16,8 @@ async function DoctorPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<Dashboard />
|
||||
<PageBody className="px-12">
|
||||
<DoctorDashboard />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
|
||||
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
||||
@@ -20,6 +21,22 @@ const ErrorPage = ({
|
||||
}) => {
|
||||
useCaptureException(error);
|
||||
|
||||
// Ignore next.js internal transient navigation errors that occur during auth state changes
|
||||
const isTransientNavigationError =
|
||||
error?.message?.includes('Error in input stream') ||
|
||||
error?.message?.includes('AbortError') ||
|
||||
(error?.name === 'ChunkLoadError');
|
||||
|
||||
useEffect(() => {
|
||||
if (isTransientNavigationError && typeof window !== 'undefined') {
|
||||
window.location.href = '/';
|
||||
}
|
||||
}, [isTransientNavigationError]);
|
||||
|
||||
if (isTransientNavigationError) {
|
||||
return <div />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={'flex h-screen flex-1 flex-col'}>
|
||||
<SiteHeader />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
|
||||
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
||||
@@ -20,6 +21,22 @@ const GlobalErrorPage = ({
|
||||
reset: () => void;
|
||||
}) => {
|
||||
useCaptureException(error);
|
||||
|
||||
// Ignore next.js internal transient navigation errors that occur during auth state changes
|
||||
const isTransientNavigationError =
|
||||
error?.message?.includes('Error in input stream') ||
|
||||
error?.message?.includes('AbortError') ||
|
||||
(error?.name === 'ChunkLoadError');
|
||||
|
||||
useEffect(() => {
|
||||
if (isTransientNavigationError && typeof window !== 'undefined') {
|
||||
window.location.href = '/';
|
||||
}
|
||||
}, [isTransientNavigationError]);
|
||||
|
||||
if (isTransientNavigationError) {
|
||||
return <div />;
|
||||
}
|
||||
|
||||
return (
|
||||
<html>
|
||||
|
||||
@@ -3,12 +3,17 @@ import React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { createNotificationsApi } from '@/packages/features/notifications/src/server/api';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { ButtonTooltip } from '@kit/shared/components/ui/button-tooltip';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { formatDateAndTime } from '@kit/shared/utils';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { loadCurrentUserAccount } from '~/home/(user)/_lib/server/load-user-account';
|
||||
import { loadUserAnalysis } from '~/home/(user)/_lib/server/load-user-analysis';
|
||||
import {
|
||||
@@ -18,14 +23,16 @@ import {
|
||||
|
||||
import Analysis from '../_components/analysis';
|
||||
|
||||
export default async function AnalysisResultsPage({
|
||||
async function AnalysisResultsPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
}) {
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
const { id: analysisOrderId } = await params;
|
||||
const notificationsApi = createNotificationsApi(supabaseClient);
|
||||
|
||||
const [{ account }, analysisResponse] = await Promise.all([
|
||||
loadCurrentUserAccount(),
|
||||
@@ -41,6 +48,11 @@ export default async function AnalysisResultsPage({
|
||||
action: PageViewAction.VIEW_ANALYSIS_RESULTS,
|
||||
});
|
||||
|
||||
await notificationsApi.dismissNotification(
|
||||
`/home/analysis-results/${analysisOrderId}`,
|
||||
'link',
|
||||
);
|
||||
|
||||
if (!analysisResponse) {
|
||||
return (
|
||||
<>
|
||||
@@ -93,7 +105,14 @@ export default async function AnalysisResultsPage({
|
||||
<h6>
|
||||
<Trans i18nKey={`orders:status.${analysisResponse.order.status}`} />
|
||||
<ButtonTooltip
|
||||
content={`${analysisResponse.order.createdAt ? new Date(analysisResponse?.order?.createdAt).toLocaleString() : ''}`}
|
||||
content={
|
||||
<Trans
|
||||
i18nKey="analysis-results:orderCreatedAt"
|
||||
values={{
|
||||
createdAt: formatDateAndTime(analysisResponse.order.createdAt)
|
||||
}}
|
||||
/>
|
||||
}
|
||||
className="ml-6"
|
||||
/>
|
||||
</h6>
|
||||
@@ -108,7 +127,7 @@ export default async function AnalysisResultsPage({
|
||||
)}
|
||||
<div className="flex flex-col gap-2">
|
||||
{orderedAnalysisElements ? (
|
||||
orderedAnalysisElements.map((element, index) => (
|
||||
orderedAnalysisElements.map((element) => (
|
||||
<React.Fragment key={element.analysisIdOriginal}>
|
||||
<Analysis element={element} />
|
||||
{element.results?.nestedElements?.map(
|
||||
@@ -132,3 +151,5 @@ export default async function AnalysisResultsPage({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(AnalysisResultsPage);
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { HomeLayoutPageHeader } from '@/app/home/(user)/_components/home-page-header';
|
||||
import { loadCategory } from '@/app/home/(user)/_lib/server/load-category';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { AppBreadcrumbs } from '@kit/ui/makerkit/app-breadcrumbs';
|
||||
import { PageBody } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import BookingContainer from '~/home/(user)/_components/booking/booking-container';
|
||||
import { loadCurrentUserAccount } from '~/home/(user)/_lib/server/load-user-account';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import {
|
||||
PageViewAction,
|
||||
createPageViewLog,
|
||||
} from '~/lib/services/audit/pageView.service';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const i18n = await createI18nServerInstance();
|
||||
@@ -17,9 +25,30 @@ export const generateMetadata = async () => {
|
||||
};
|
||||
};
|
||||
|
||||
async function BookingHandlePage({ params }: { params: { handle: string } }) {
|
||||
const handle = await params.handle;
|
||||
async function BookingHandlePage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ handle: string }>;
|
||||
}) {
|
||||
const { handle } = await params;
|
||||
const { category } = await loadCategory({ handle });
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
|
||||
if (!category) {
|
||||
return <div>Category not found</div>;
|
||||
}
|
||||
|
||||
if (!account) {
|
||||
return redirect(pathsConfig.auth.signIn);
|
||||
}
|
||||
|
||||
await createPageViewLog({
|
||||
accountId: account.id,
|
||||
action: PageViewAction.VIEW_TTO_SERVICE_BOOKING,
|
||||
extraData: {
|
||||
handle,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -30,10 +59,10 @@ async function BookingHandlePage({ params }: { params: { handle: string } }) {
|
||||
/>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'booking:title'} />}
|
||||
description={<Trans i18nKey={'booking:description'} />}
|
||||
description=""
|
||||
/>
|
||||
|
||||
<PageBody></PageBody>
|
||||
<BookingContainer category={category} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,8 +34,15 @@ export default function MontonioCallbackClient({
|
||||
setHasProcessed(true);
|
||||
|
||||
try {
|
||||
const { orderId } = await processMontonioCallback(orderToken);
|
||||
router.push(`/home/order/${orderId}/confirmed`);
|
||||
const result = await processMontonioCallback(orderToken);
|
||||
if (result.success) {
|
||||
return router.push(`/home/order/${result.orderId}/confirmed`);
|
||||
}
|
||||
if (result.failedServiceBookings?.length) {
|
||||
router.push(
|
||||
`/home/cart/montonio-callback/error?reasonFailed=${result.failedServiceBookings.map(({ reason }) => reason).join(',')}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to place order', error);
|
||||
router.push('/home/cart/montonio-callback/error');
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
|
||||
import { toArray } from '@kit/shared/utils';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Alert, AlertDescription } from '@kit/ui/shadcn/alert';
|
||||
import { AlertTitle } from '@kit/ui/shadcn/alert';
|
||||
@@ -16,7 +18,15 @@ export async function generateMetadata() {
|
||||
};
|
||||
}
|
||||
|
||||
export default async function MontonioCheckoutCallbackErrorPage() {
|
||||
async function MontonioCheckoutCallbackErrorPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ reasonFailed: string }>;
|
||||
}) {
|
||||
const params = await searchParams;
|
||||
|
||||
const failedBookingData: string[] = toArray(params.reasonFailed?.split(','));
|
||||
|
||||
return (
|
||||
<div className={'flex h-full flex-1 flex-col'}>
|
||||
<PageHeader title={<Trans i18nKey="cart:montonioCallback.title" />} />
|
||||
@@ -28,9 +38,15 @@ export default async function MontonioCheckoutCallbackErrorPage() {
|
||||
</AlertTitle>
|
||||
|
||||
<AlertDescription>
|
||||
<p>
|
||||
{failedBookingData.length ? (
|
||||
failedBookingData.map((failureReason, index) => (
|
||||
<p key={index}>
|
||||
<Trans i18nKey={`checkout.error.${failureReason}`} />
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<Trans i18nKey={'checkout.error.description'} />
|
||||
</p>
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
@@ -46,3 +62,5 @@ export default async function MontonioCheckoutCallbackErrorPage() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(MontonioCheckoutCallbackErrorPage);
|
||||
|
||||
@@ -3,14 +3,17 @@ import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
import { retrieveCart } from '@lib/data/cart';
|
||||
import { listProductTypes } from '@lib/data/products';
|
||||
|
||||
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getCartReservations } from '~/lib/services/reservation.service';
|
||||
import { findProductTypeIdByHandle } from '~/lib/utils';
|
||||
|
||||
import Cart from '../../_components/cart';
|
||||
import CartTimer from '../../_components/cart/cart-timer';
|
||||
import { EnrichedCartItem } from '../../_components/cart/types';
|
||||
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
@@ -21,11 +24,7 @@ export async function generateMetadata() {
|
||||
}
|
||||
|
||||
async function CartPage() {
|
||||
const [
|
||||
cart,
|
||||
{ productTypes },
|
||||
{ account },
|
||||
] = await Promise.all([
|
||||
const [cart, { productTypes }, { account }] = await Promise.all([
|
||||
retrieveCart(),
|
||||
listProductTypes(),
|
||||
loadCurrentUserAccount(),
|
||||
@@ -35,31 +34,36 @@ async function CartPage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const balanceSummary = await new AccountBalanceService().getBalanceSummary(account.id);
|
||||
const balanceSummary = await new AccountBalanceService().getBalanceSummary(
|
||||
account.id,
|
||||
);
|
||||
|
||||
const analysisPackagesType = productTypes.find(
|
||||
({ metadata }) => metadata?.handle === 'analysis-packages',
|
||||
const synlabAnalysisTypeId = findProductTypeIdByHandle(
|
||||
productTypes,
|
||||
'synlab-analysis',
|
||||
);
|
||||
const synlabAnalysisType = productTypes.find(
|
||||
({ metadata }) => metadata?.handle === 'synlab-analysis',
|
||||
const analysisPackagesTypeId = findProductTypeIdByHandle(
|
||||
productTypes,
|
||||
'analysis-packages',
|
||||
);
|
||||
|
||||
const synlabAnalyses =
|
||||
analysisPackagesType && synlabAnalysisType && cart?.items
|
||||
analysisPackagesTypeId && synlabAnalysisTypeId && cart?.items
|
||||
? cart.items.filter((item) => {
|
||||
const productTypeId = item.product?.type_id;
|
||||
if (!productTypeId) {
|
||||
return false;
|
||||
}
|
||||
return [analysisPackagesType.id, synlabAnalysisType.id].includes(
|
||||
return [analysisPackagesTypeId, synlabAnalysisTypeId].includes(
|
||||
productTypeId,
|
||||
);
|
||||
})
|
||||
: [];
|
||||
const ttoServiceItems =
|
||||
cart?.items?.filter(
|
||||
(item) => !synlabAnalyses.some((analysis) => analysis.id === item.id),
|
||||
) ?? [];
|
||||
|
||||
let ttoServiceItems: EnrichedCartItem[] = [];
|
||||
if (cart?.items?.length) {
|
||||
ttoServiceItems = await getCartReservations(cart);
|
||||
}
|
||||
const otherItemsSorted = ttoServiceItems.sort((a, b) =>
|
||||
(a.updated_at ?? '') > (b.updated_at ?? '') ? -1 : 1,
|
||||
);
|
||||
|
||||
77
app/home/(user)/(dashboard)/life-style/page.tsx
Normal file
77
app/home/(user)/(dashboard)/life-style/page.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React from 'react';
|
||||
|
||||
import { createUserAnalysesApi } from '@/packages/features/user-analyses/src/server/api';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { PageBody } from '@kit/ui/makerkit/page';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Skeleton } from '@kit/ui/shadcn/skeleton';
|
||||
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import {
|
||||
PageViewAction,
|
||||
createPageViewLog,
|
||||
} from '~/lib/services/audit/pageView.service';
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||
import { loadLifeStyle } from '../../_lib/server/load-life-style';
|
||||
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('common:lifeStyle.title'),
|
||||
};
|
||||
}
|
||||
|
||||
async function LifeStylePage() {
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
const client = getSupabaseServerClient();
|
||||
const userAnalysesApi = createUserAnalysesApi(client);
|
||||
const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses();
|
||||
const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
const { response } = await loadLifeStyle({
|
||||
account,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
});
|
||||
|
||||
await createPageViewLog({
|
||||
accountId: account.id,
|
||||
action: PageViewAction.VIEW_LIFE_STYLE,
|
||||
});
|
||||
|
||||
if (!response.lifestyle) {
|
||||
return <Skeleton className="mt-10 h-10 w-full" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'common:lifeStyle.title'} />}
|
||||
description=""
|
||||
/>
|
||||
|
||||
<PageBody>
|
||||
<div className="mt-8">
|
||||
{response.lifestyle.map(({ title, description }, index) => (
|
||||
<React.Fragment key={`${index}-${title}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3>{title}</h3>
|
||||
</div>
|
||||
<p className="font-regular py-4">{description}</p>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(LifeStylePage);
|
||||
@@ -28,17 +28,18 @@ async function OrderAnalysisPackagePage() {
|
||||
<PageBody>
|
||||
<div className="space-y-3 text-center">
|
||||
<h3>
|
||||
<Trans i18nKey={'marketing:selectPackage'} />
|
||||
<Trans i18nKey="order-analysis-package:selectPackage" />
|
||||
</h3>
|
||||
<ComparePackagesModal
|
||||
analysisPackages={analysisPackages}
|
||||
analysisPackageElements={analysisPackageElements}
|
||||
triggerElement={
|
||||
<Button variant="secondary" className="gap-2">
|
||||
<Trans i18nKey={'marketing:comparePackages'} />
|
||||
<Trans i18nKey="order-analysis-package:comparePackages" />
|
||||
<Scale className="size-4 stroke-[1.5px]" />
|
||||
</Button>
|
||||
}
|
||||
countryCode={countryCode}
|
||||
/>
|
||||
</div>
|
||||
<SelectAnalysisPackages
|
||||
|
||||
@@ -37,8 +37,8 @@ async function OrderAnalysisPage() {
|
||||
return (
|
||||
<>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'order-analysis:title'} />}
|
||||
description={<Trans i18nKey={'order-analysis:description'} />}
|
||||
title={<Trans i18nKey="order-analysis:title" />}
|
||||
description={<Trans i18nKey="order-analysis:description" />}
|
||||
/>
|
||||
<PageBody>
|
||||
<OrderAnalysesCards analyses={analyses} countryCode={countryCode} />
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||
import { retrieveOrder } from '@lib/data/orders';
|
||||
import { StoreOrder } from '@medusajs/types';
|
||||
import Divider from '@modules/common/components/divider';
|
||||
|
||||
import { GlobalLoader } from '@kit/ui/makerkit/global-loader';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { StoreOrder } from '@medusajs/types';
|
||||
import { AnalysisOrder } from '~/lib/types/analysis-order';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { retrieveOrder } from '@lib/data/orders';
|
||||
import { GlobalLoader } from '@kit/ui/makerkit/global-loader';
|
||||
import { AnalysisOrder } from '~/lib/types/order';
|
||||
|
||||
function OrderConfirmedLoadingWrapper({
|
||||
medusaOrder: initialMedusaOrder,
|
||||
@@ -21,7 +22,8 @@ function OrderConfirmedLoadingWrapper({
|
||||
medusaOrder: StoreOrder;
|
||||
order: AnalysisOrder;
|
||||
}) {
|
||||
const [medusaOrder, setMedusaOrder] = useState<StoreOrder>(initialMedusaOrder);
|
||||
const [medusaOrder, setMedusaOrder] =
|
||||
useState<StoreOrder>(initialMedusaOrder);
|
||||
const fetchingRef = useRef(false);
|
||||
|
||||
const paymentStatus = medusaOrder.payment_status;
|
||||
@@ -52,7 +54,7 @@ function OrderConfirmedLoadingWrapper({
|
||||
if (!isPaid) {
|
||||
return (
|
||||
<PageBody>
|
||||
<div className="flex flex-col justify-start items-center h-full pt-[10vh]">
|
||||
<div className="flex h-full flex-col items-center justify-start pt-[10vh]">
|
||||
<div>
|
||||
<GlobalLoader />
|
||||
</div>
|
||||
@@ -69,7 +71,14 @@ function OrderConfirmedLoadingWrapper({
|
||||
<PageHeader title={<Trans i18nKey="cart:orderConfirmed.title" />} />
|
||||
<Divider />
|
||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 gap-y-6 lg:px-4">
|
||||
<OrderDetails order={order} />
|
||||
<OrderDetails
|
||||
order={{
|
||||
id: order.medusa_order_id,
|
||||
created_at: order.created_at,
|
||||
location: null,
|
||||
serviceProvider: null,
|
||||
}}
|
||||
/>
|
||||
<Divider />
|
||||
<OrderItems medusaOrder={medusaOrder} />
|
||||
<CartTotals medusaOrder={medusaOrder} />
|
||||
|
||||
@@ -7,6 +7,7 @@ import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||
|
||||
import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';
|
||||
|
||||
export async function generateMetadata() {
|
||||
@@ -36,7 +37,9 @@ async function OrderConfirmedPage(props: {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
|
||||
return <OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />;
|
||||
return (
|
||||
<OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(OrderConfirmedPage);
|
||||
|
||||
@@ -4,6 +4,7 @@ import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
import { retrieveOrder } from '@lib/data/orders';
|
||||
import Divider from '@modules/common/components/divider';
|
||||
|
||||
@@ -12,7 +13,6 @@ import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
@@ -25,28 +25,60 @@ export async function generateMetadata() {
|
||||
async function OrderConfirmedPage(props: {
|
||||
params: Promise<{ orderId: string }>;
|
||||
}) {
|
||||
const supabaseClient = getSupabaseServerClient();
|
||||
const params = await props.params;
|
||||
|
||||
const order = await getAnalysisOrder({
|
||||
analysisOrderId: Number(params.orderId),
|
||||
}).catch(() => null);
|
||||
if (!order) {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
|
||||
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(
|
||||
() => null,
|
||||
);
|
||||
const medusaOrder = await retrieveOrder(params.orderId).catch(() => null);
|
||||
if (!medusaOrder) {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
const ttoReservationId =
|
||||
medusaOrder.items &&
|
||||
(medusaOrder.items.find(
|
||||
({ metadata }) => !!metadata?.connectedOnlineReservationId,
|
||||
)?.metadata?.connectedOnlineReservationId as number);
|
||||
|
||||
const [{ data: ttoReservation }] = await Promise.all([
|
||||
ttoReservationId
|
||||
? await supabaseClient
|
||||
.schema('medreport')
|
||||
.from('connected_online_reservation')
|
||||
.select('*')
|
||||
.eq('id', ttoReservationId)
|
||||
.single()
|
||||
: { data: null },
|
||||
]);
|
||||
const [{ data: location }, { data: serviceProvider }] = await Promise.all([
|
||||
ttoReservation
|
||||
? supabaseClient
|
||||
.schema('medreport')
|
||||
.from('connected_online_locations')
|
||||
.select('name,address')
|
||||
.eq('sync_id', ttoReservation.location_sync_id || 0)
|
||||
.single()
|
||||
: { data: null },
|
||||
ttoReservation
|
||||
? supabaseClient
|
||||
.schema('medreport')
|
||||
.from('connected_online_providers')
|
||||
.select('email,phone_number,name')
|
||||
.eq('id', ttoReservation.clinic_id)
|
||||
.single()
|
||||
: { data: null },
|
||||
]);
|
||||
|
||||
return (
|
||||
<PageBody>
|
||||
<PageHeader title={<Trans i18nKey="cart:order.title" />} />
|
||||
<Divider />
|
||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 gap-y-6 lg:px-4">
|
||||
<OrderDetails order={order} />
|
||||
<OrderDetails
|
||||
order={{
|
||||
id: medusaOrder.id,
|
||||
created_at: medusaOrder.created_at,
|
||||
location,
|
||||
serviceProvider,
|
||||
}}
|
||||
/>
|
||||
<Divider />
|
||||
<OrderItems medusaOrder={medusaOrder} />
|
||||
<CartTotals medusaOrder={medusaOrder} />
|
||||
|
||||
@@ -11,7 +11,8 @@ import { PageBody } from '@kit/ui/makerkit/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getAnalysisOrders } from '~/lib/services/order.service';
|
||||
import { getAnalysisOrders, getTtoOrders } from '~/lib/services/order.service';
|
||||
import { findProductTypeIdByHandle } from '~/lib/utils';
|
||||
import { listOrders } from '~/medusa/lib/data/orders';
|
||||
|
||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||
@@ -28,19 +29,26 @@ export async function generateMetadata() {
|
||||
}
|
||||
|
||||
async function OrdersPage() {
|
||||
const [medusaOrders, analysisOrders, { productTypes }] = await Promise.all([
|
||||
listOrders(ORDERS_LIMIT),
|
||||
getAnalysisOrders(),
|
||||
listProductTypes(),
|
||||
]);
|
||||
const [medusaOrders, analysisOrders, ttoOrders, { productTypes }] =
|
||||
await Promise.all([
|
||||
listOrders(ORDERS_LIMIT),
|
||||
getAnalysisOrders(),
|
||||
getTtoOrders(),
|
||||
listProductTypes(),
|
||||
]);
|
||||
|
||||
if (!medusaOrders || !productTypes) {
|
||||
if (!medusaOrders || !productTypes || !ttoOrders) {
|
||||
redirect(pathsConfig.auth.signIn);
|
||||
}
|
||||
|
||||
const analysisPackagesType = productTypes.find(
|
||||
({ metadata }) => metadata?.handle === 'analysis-packages',
|
||||
)!;
|
||||
const analysisPackagesTypeId = findProductTypeIdByHandle(
|
||||
productTypes,
|
||||
'analysis-package',
|
||||
);
|
||||
const ttoServiceTypeId = findProductTypeIdByHandle(
|
||||
productTypes,
|
||||
'tto-service',
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -49,34 +57,64 @@ async function OrdersPage() {
|
||||
description={<Trans i18nKey={'orders:description'} />}
|
||||
/>
|
||||
<PageBody>
|
||||
{analysisOrders.map((analysisOrder) => {
|
||||
const medusaOrder = medusaOrders.find(
|
||||
({ id }) => id === analysisOrder.medusa_order_id,
|
||||
);
|
||||
{medusaOrders.map((medusaOrder) => {
|
||||
if (!medusaOrder) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const medusaOrderItems = medusaOrder.items || [];
|
||||
const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter(
|
||||
(item) => item.product_type_id === analysisPackagesType?.id,
|
||||
);
|
||||
const medusaOrderItemsOther = medusaOrderItems.filter(
|
||||
(item) => item.product_type_id !== analysisPackagesType?.id,
|
||||
const analysisOrder = analysisOrders.find(
|
||||
({ medusa_order_id }) => medusa_order_id === medusaOrder.id,
|
||||
);
|
||||
|
||||
const orderIds = new Set(
|
||||
(medusaOrder?.items ?? [])
|
||||
.map((i) => i?.metadata?.connectedOnlineReservationId)
|
||||
.filter(Boolean)
|
||||
.map(String),
|
||||
);
|
||||
|
||||
const ttoReservation = ttoOrders.find((o) =>
|
||||
orderIds.has(String(o.id)),
|
||||
);
|
||||
|
||||
const medusaOrderItems = medusaOrder.items || [];
|
||||
const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter(
|
||||
(item) => item.product_type_id === analysisPackagesTypeId,
|
||||
);
|
||||
const medusaOrderItemsTtoServices = medusaOrderItems.filter(
|
||||
(item) => item.product_type_id === ttoServiceTypeId,
|
||||
);
|
||||
const medusaOrderItemsOther = medusaOrderItems.filter(
|
||||
(item) =>
|
||||
!item.product_type_id ||
|
||||
![analysisPackagesTypeId, ttoServiceTypeId].includes(
|
||||
item.product_type_id,
|
||||
),
|
||||
);
|
||||
|
||||
if (
|
||||
medusaOrderItemsAnalysisPackages.length === 0 &&
|
||||
medusaOrderItemsOther.length === 0 &&
|
||||
medusaOrderItemsTtoServices.length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<React.Fragment key={analysisOrder.id}>
|
||||
<React.Fragment key={medusaOrder.id}>
|
||||
<Divider className="my-6" />
|
||||
<OrderBlock
|
||||
medusaOrderId={medusaOrder.id}
|
||||
analysisOrder={analysisOrder}
|
||||
ttoReservation={ttoReservation}
|
||||
itemsAnalysisPackage={medusaOrderItemsAnalysisPackages}
|
||||
itemsTtoService={medusaOrderItemsTtoServices}
|
||||
itemsOther={medusaOrderItemsOther}
|
||||
/>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
{analysisOrders.length === 0 && (
|
||||
{analysisOrders.length === 0 && ttoOrders.length === 0 && (
|
||||
<h5 className="mt-6">
|
||||
<Trans i18nKey="orders:noOrders" />
|
||||
</h5>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { Suspense } from 'react';
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { toTitleCase } from '@/lib/utils';
|
||||
@@ -12,10 +10,9 @@ import { createUserAnalysesApi } from '@kit/user-analyses/api';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import AIBlocks from '../_components/ai/ai-blocks';
|
||||
import Dashboard from '../_components/dashboard';
|
||||
import DashboardCards from '../_components/dashboard-cards';
|
||||
import Recommendations from '../_components/recommendations';
|
||||
import RecommendationsSkeleton from '../_components/recommendations-skeleton';
|
||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
@@ -32,7 +29,10 @@ async function UserHomePage() {
|
||||
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
const api = createUserAnalysesApi(client);
|
||||
const userAnalysesApi = createUserAnalysesApi(client);
|
||||
|
||||
const bmiThresholds = await api.fetchBmiThresholds();
|
||||
const analysisResponses = await userAnalysesApi.getAllUserAnalysisResponses();
|
||||
|
||||
if (!account) {
|
||||
redirect('/');
|
||||
@@ -52,17 +52,13 @@ async function UserHomePage() {
|
||||
/>
|
||||
<PageBody>
|
||||
<Dashboard account={account} bmiThresholds={bmiThresholds} />
|
||||
{process.env.OPENAI_API_KEY &&
|
||||
process.env.PROMPT_ID_ANALYSIS_RECOMMENDATIONS && (
|
||||
<>
|
||||
<h4>
|
||||
<Trans i18nKey="dashboard:recommendations.title" />
|
||||
</h4>
|
||||
<Suspense fallback={<RecommendationsSkeleton />}>
|
||||
<Recommendations account={account} />
|
||||
</Suspense>
|
||||
</>
|
||||
)}
|
||||
|
||||
<h4>
|
||||
<Trans i18nKey="dashboard:recommendations.title" />
|
||||
</h4>
|
||||
<div className="mt-4 grid gap-6 sm:grid-cols-3">
|
||||
<AIBlocks account={account} analysisResponses={analysisResponses} />
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
|
||||
52
app/home/(user)/_components/ai/ai-blocks.tsx
Normal file
52
app/home/(user)/_components/ai/ai-blocks.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
'use server';
|
||||
|
||||
import React, { Suspense } from 'react';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
|
||||
import { isValidOpenAiEnv } from '../../_lib/server/is-valid-open-ai-env';
|
||||
import LifeStyleCard from './life-style-card';
|
||||
import OrderAnalysesPackageCard from './order-analyses-package-card';
|
||||
import Recommendations from './recommendations';
|
||||
import RecommendationsSkeleton from './recommendations-skeleton';
|
||||
import { AnalysisResponses } from './types';
|
||||
|
||||
const AIBlocks = async ({
|
||||
account,
|
||||
analysisResponses,
|
||||
}: {
|
||||
account: AccountWithParams;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
}) => {
|
||||
const isOpenAiAvailable = await isValidOpenAiEnv();
|
||||
|
||||
if (!isOpenAiAvailable) {
|
||||
return <OrderAnalysesPackageCard />;
|
||||
}
|
||||
|
||||
if (analysisResponses?.length === 0) {
|
||||
return (
|
||||
<>
|
||||
<OrderAnalysesPackageCard />
|
||||
<Suspense fallback={<RecommendationsSkeleton amount={1} />}>
|
||||
<LifeStyleCard
|
||||
account={account}
|
||||
analysisResponses={analysisResponses}
|
||||
/>
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={<RecommendationsSkeleton />}>
|
||||
<LifeStyleCard account={account} analysisResponses={analysisResponses} />
|
||||
<Recommendations
|
||||
account={account}
|
||||
analysisResponses={analysisResponses}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
export default AIBlocks;
|
||||
56
app/home/(user)/_components/ai/life-style-card.tsx
Normal file
56
app/home/(user)/_components/ai/life-style-card.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
'use server';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import Link from 'next/link';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { pathsConfig } from '@/packages/shared/src/config';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Card, CardHeader } from '@kit/ui/shadcn/card';
|
||||
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import { loadLifeStyle } from '../../_lib/server/load-life-style';
|
||||
import { AnalysisResponses } from './types';
|
||||
|
||||
const LifeStyleCard = async ({
|
||||
account,
|
||||
analysisResponses,
|
||||
}: {
|
||||
account: AccountWithParams;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
}) => {
|
||||
const aiResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
const { response, dateCreated } = await loadLifeStyle({
|
||||
account,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp,
|
||||
});
|
||||
|
||||
return (
|
||||
<Card variant="gradient-success" className="flex flex-col justify-between">
|
||||
<CardHeader className="flex-row justify-between">
|
||||
<div>
|
||||
<span className="text-xs">
|
||||
{new Date(dateCreated).toLocaleString()}
|
||||
</span>
|
||||
<h5 className="flex flex-col">
|
||||
<Trans i18nKey="dashboard:heroCard.lifeStyle.title" />
|
||||
</h5>
|
||||
</div>
|
||||
<Link href={pathsConfig.app.lifeStyle}>
|
||||
<Button size="icon" variant="outline" className="px-2 text-black">
|
||||
<ChevronRight className="size-4 stroke-2" />
|
||||
</Button>
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<span className="text-primary p-4 text-sm">{response.summary}</span>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default LifeStyleCard;
|
||||
@@ -0,0 +1,51 @@
|
||||
import React from 'react';
|
||||
|
||||
import Link from 'next/link';
|
||||
|
||||
import { pathsConfig } from '@/packages/shared/src/config';
|
||||
import { ChevronRight, HeartPulse } from 'lucide-react';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import {
|
||||
Card,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
} from '@kit/ui/shadcn/card';
|
||||
|
||||
const OrderAnalysesPackageCard = () => {
|
||||
return (
|
||||
<Card
|
||||
variant="gradient-success"
|
||||
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
||||
>
|
||||
<CardHeader className="flex-row sm:pb-0">
|
||||
<div
|
||||
className={
|
||||
'bg-primary/10 mb-6 flex size-8 items-center-safe justify-center-safe rounded-full text-white'
|
||||
}
|
||||
>
|
||||
<HeartPulse className="size-4 fill-green-500" />
|
||||
</div>
|
||||
<div className="bg-warning ml-auto flex size-8 items-center-safe justify-center-safe rounded-full text-white">
|
||||
<Link href={pathsConfig.app.orderAnalysisPackage}>
|
||||
<Button size="icon" variant="outline" className="px-2 text-black">
|
||||
<ChevronRight className="size-4 stroke-2" />
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex flex-col items-start gap-2">
|
||||
<h5>
|
||||
<Trans i18nKey="dashboard:heroCard.orderPackage.title" />
|
||||
</h5>
|
||||
<CardDescription className="text-primary">
|
||||
<Trans i18nKey="dashboard:heroCard.orderPackage.description" />
|
||||
</CardDescription>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrderAnalysesPackageCard;
|
||||
67
app/home/(user)/_components/ai/recommendations-skeleton.tsx
Normal file
67
app/home/(user)/_components/ai/recommendations-skeleton.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
|
||||
import { InfoTooltip } from '@/packages/shared/src/components/ui/info-tooltip';
|
||||
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import {
|
||||
Card,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
} from '@kit/ui/shadcn/card';
|
||||
import { Skeleton } from '@kit/ui/skeleton';
|
||||
|
||||
const RecommendationsSkeleton = ({ amount = 2 }: { amount?: number }) => {
|
||||
const emptyData = [
|
||||
{
|
||||
title: '1',
|
||||
description: '',
|
||||
subtitle: '',
|
||||
variant: { id: '' },
|
||||
price: 1,
|
||||
},
|
||||
];
|
||||
return Array.from({ length: amount }, (_, index) => {
|
||||
const { title, description, subtitle } = emptyData[0]!;
|
||||
|
||||
return (
|
||||
<Skeleton key={title + index}>
|
||||
<Card>
|
||||
<CardHeader className="flex-row">
|
||||
<div
|
||||
className={
|
||||
'mb-6 flex size-8 items-center-safe justify-center-safe'
|
||||
}
|
||||
/>
|
||||
<div className="ml-auto flex size-8 items-center-safe justify-center-safe">
|
||||
<Button size="icon" className="px-2" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex">
|
||||
<div className="flex flex-1 flex-col items-start">
|
||||
<h5>
|
||||
{title}
|
||||
{description && (
|
||||
<>
|
||||
{' '}
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="flex flex-col gap-2">
|
||||
<span>{description}</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</h5>
|
||||
{subtitle && <CardDescription>{subtitle}</CardDescription>}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-2 self-end text-sm"></div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Skeleton>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export default RecommendationsSkeleton;
|
||||
41
app/home/(user)/_components/ai/recommendations.tsx
Normal file
41
app/home/(user)/_components/ai/recommendations.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
'use server';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
|
||||
import { getLatestResponseTime } from '~/lib/utils';
|
||||
|
||||
import { loadAnalyses } from '../../_lib/server/load-analyses';
|
||||
import { loadRecommendations } from '../../_lib/server/load-recommendations';
|
||||
import OrderAnalysesCards from '../order-analyses-cards';
|
||||
import { AnalysisResponses } from './types';
|
||||
|
||||
export default async function Recommendations({
|
||||
account,
|
||||
analysisResponses,
|
||||
}: {
|
||||
account: AccountWithParams;
|
||||
analysisResponses?: AnalysisResponses;
|
||||
}) {
|
||||
const { analyses, countryCode } = await loadAnalyses();
|
||||
|
||||
const currentAIResponseTimestamp = getLatestResponseTime(analysisResponses);
|
||||
const analysisRecommendations = await loadRecommendations({
|
||||
account,
|
||||
analyses,
|
||||
analysisResponses,
|
||||
aiResponseTimestamp: currentAIResponseTimestamp,
|
||||
});
|
||||
const orderAnalyses = analyses.filter((analysis) =>
|
||||
analysisRecommendations.includes(analysis.title),
|
||||
);
|
||||
|
||||
if (orderAnalyses.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<OrderAnalysesCards analyses={orderAnalyses} countryCode={countryCode} />
|
||||
);
|
||||
}
|
||||
19
app/home/(user)/_components/ai/types.ts
Normal file
19
app/home/(user)/_components/ai/types.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Database } from '@/packages/supabase/src/database.types';
|
||||
|
||||
export interface ILifeStyleResponse {
|
||||
lifestyle: {
|
||||
title: string;
|
||||
description: string;
|
||||
score: 0 | 1 | 2;
|
||||
}[];
|
||||
summary: string | null;
|
||||
}
|
||||
|
||||
export enum PROMPT_NAME {
|
||||
LIFE_STYLE = 'Life Style',
|
||||
ANALYSIS_RECOMMENDATIONS = 'Analysis Recommendations',
|
||||
FEEDBACK = 'Doctor Feedback',
|
||||
}
|
||||
|
||||
export type AnalysisResponses =
|
||||
Database['medreport']['Functions']['get_latest_analysis_response_elements_for_current_user']['Returns'];
|
||||
40
app/home/(user)/_components/booking/booking-calendar.tsx
Normal file
40
app/home/(user)/_components/booking/booking-calendar.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
'use client';
|
||||
|
||||
import { isBefore, isSameDay } from 'date-fns';
|
||||
import { uniq } from 'lodash';
|
||||
|
||||
import { Calendar } from '@kit/ui/shadcn/calendar';
|
||||
import { Card } from '@kit/ui/shadcn/card';
|
||||
import { cn } from '@kit/ui/utils';
|
||||
|
||||
import { useBooking } from './booking.provider';
|
||||
|
||||
export default function BookingCalendar() {
|
||||
const { selectedDate, setSelectedDate, isLoadingTimeSlots, timeSlots } =
|
||||
useBooking();
|
||||
const availableDates = uniq(timeSlots?.map((timeSlot) => timeSlot.StartTime));
|
||||
|
||||
return (
|
||||
<Card className="mb-4">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selectedDate}
|
||||
onSelect={setSelectedDate}
|
||||
disabled={(date) => {
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return (
|
||||
isBefore(date, today) ||
|
||||
!availableDates.some((dateWithBooking) =>
|
||||
isSameDay(date, dateWithBooking),
|
||||
)
|
||||
);
|
||||
}}
|
||||
className={cn('rounded-md border', {
|
||||
'pointer-events-none rounded-md border opacity-50':
|
||||
isLoadingTimeSlots,
|
||||
})}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
58
app/home/(user)/_components/booking/booking-container.tsx
Normal file
58
app/home/(user)/_components/booking/booking-container.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
import { StoreProduct } from '@medusajs/types';
|
||||
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { EnrichedCartItem } from '../cart/types';
|
||||
import BookingCalendar from './booking-calendar';
|
||||
import { BookingProvider } from './booking.provider';
|
||||
import LocationSelector from './location-selector';
|
||||
import ServiceSelector from './service-selector';
|
||||
import TimeSlots from './time-slots';
|
||||
|
||||
const BookingContainer = ({
|
||||
category,
|
||||
cartItem,
|
||||
onComplete,
|
||||
}: {
|
||||
category: { products: StoreProduct[]; countryCode: string };
|
||||
cartItem?: EnrichedCartItem;
|
||||
onComplete?: () => void;
|
||||
}) => {
|
||||
const products = cartItem?.product ? [cartItem.product] : category.products;
|
||||
|
||||
if (!cartItem || !products?.length) {
|
||||
<p>
|
||||
<Trans i18nKey="booking:noProducts" />
|
||||
</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<BookingProvider category={{ products }} service={cartItem?.product}>
|
||||
<div className="xs:flex-row flex max-h-full flex-col gap-6">
|
||||
<div className="flex flex-col">
|
||||
<ServiceSelector
|
||||
products={products.filter((product) => {
|
||||
if (product.metadata?.serviceIds) {
|
||||
return Array.isArray(
|
||||
JSON.parse(product.metadata.serviceIds as string),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
})}
|
||||
/>
|
||||
<BookingCalendar />
|
||||
<LocationSelector />
|
||||
</div>
|
||||
<TimeSlots
|
||||
countryCode={category.countryCode}
|
||||
cartItem={cartItem}
|
||||
onComplete={onComplete}
|
||||
/>
|
||||
</div>
|
||||
</BookingProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default BookingContainer;
|
||||
113
app/home/(user)/_components/booking/booking-pagination.tsx
Normal file
113
app/home/(user)/_components/booking/booking-pagination.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
import React from 'react';
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { cn } from '@kit/ui/shadcn';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
|
||||
const BookingPagination = ({
|
||||
totalPages,
|
||||
setCurrentPage,
|
||||
currentPage,
|
||||
}: {
|
||||
totalPages: number;
|
||||
setCurrentPage: (page: number) => void;
|
||||
currentPage: number;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const generatePageNumbers = () => {
|
||||
const pages = [];
|
||||
const maxVisiblePages = 5;
|
||||
|
||||
if (totalPages <= maxVisiblePages) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
if (currentPage <= 3) {
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
pages.push('...');
|
||||
pages.push(totalPages);
|
||||
} else if (currentPage >= totalPages - 2) {
|
||||
pages.push(1);
|
||||
pages.push('...');
|
||||
for (let i = totalPages - 3; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
pages.push('...');
|
||||
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
pages.push('...');
|
||||
pages.push(totalPages);
|
||||
}
|
||||
}
|
||||
|
||||
return pages;
|
||||
};
|
||||
|
||||
if (totalPages === 0) {
|
||||
return (
|
||||
<div className="wrap text-muted-foreground flex size-full content-center-safe justify-center-safe">
|
||||
<p>{t('booking:noResults')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
totalPages > 1 && (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t('common:pageOfPages', {
|
||||
page: currentPage,
|
||||
total: totalPages,
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<Trans i18nKey="common:previous" defaultValue="Previous" />
|
||||
</Button>
|
||||
|
||||
{generatePageNumbers().map((page, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant={page === currentPage ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => typeof page === 'number' && setCurrentPage(page)}
|
||||
disabled={page === '...'}
|
||||
className={cn(
|
||||
'min-w-[2rem]',
|
||||
page === '...' && 'cursor-default hover:bg-transparent',
|
||||
)}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(currentPage + 1)}
|
||||
disabled={currentPage === totalPages}
|
||||
>
|
||||
<Trans i18nKey="common:next" defaultValue="Next" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
export default BookingPagination;
|
||||
77
app/home/(user)/_components/booking/booking.context.ts
Normal file
77
app/home/(user)/_components/booking/booking.context.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
import { StoreProduct } from '@medusajs/types';
|
||||
import { noop } from 'lodash';
|
||||
|
||||
import { Tables } from '@kit/supabase/database';
|
||||
|
||||
export type Location = Tables<
|
||||
{ schema: 'medreport' },
|
||||
'connected_online_locations'
|
||||
>;
|
||||
|
||||
export type TimeSlotResponse = {
|
||||
timeSlots: TimeSlot[];
|
||||
locations: Location[];
|
||||
};
|
||||
|
||||
export type TimeSlot = {
|
||||
ClinicID: number;
|
||||
LocationID: number;
|
||||
UserID: number;
|
||||
SyncUserID: number;
|
||||
ServiceID: number;
|
||||
HKServiceID: number;
|
||||
StartTime: Date;
|
||||
EndTime: Date;
|
||||
PayorCode: string;
|
||||
serviceProvider?: ServiceProvider;
|
||||
syncedService?: SyncedService;
|
||||
} & { location?: Location };
|
||||
|
||||
export type ServiceProvider = {
|
||||
name: string;
|
||||
id: number;
|
||||
jobTitleEn: string | null;
|
||||
jobTitleEt: string | null;
|
||||
jobTitleRu: string | null;
|
||||
clinicId: number;
|
||||
};
|
||||
|
||||
export type SyncedService = Tables<
|
||||
{ schema: 'medreport' },
|
||||
'connected_online_services'
|
||||
> & {
|
||||
providerClinic: ProviderClinic;
|
||||
};
|
||||
|
||||
export type ProviderClinic = Tables<
|
||||
{ schema: 'medreport' },
|
||||
'connected_online_providers'
|
||||
> & { locations: Location[] };
|
||||
|
||||
const BookingContext = createContext<{
|
||||
timeSlots: TimeSlot[] | null;
|
||||
selectedService: StoreProduct | null;
|
||||
locations: Location[] | null;
|
||||
selectedLocationId: number | null;
|
||||
selectedDate?: Date;
|
||||
isLoadingTimeSlots?: boolean;
|
||||
setSelectedService: (selectedService: StoreProduct | null) => void;
|
||||
setSelectedLocationId: (selectedLocationId: number | null) => void;
|
||||
updateTimeSlots: (serviceIds: number[]) => Promise<void>;
|
||||
setSelectedDate: (selectedDate?: Date) => void;
|
||||
}>({
|
||||
timeSlots: null,
|
||||
selectedService: null,
|
||||
locations: null,
|
||||
selectedLocationId: null,
|
||||
selectedDate: new Date(),
|
||||
isLoadingTimeSlots: false,
|
||||
setSelectedService: (_) => _,
|
||||
setSelectedLocationId: (_) => _,
|
||||
updateTimeSlots: async (_) => noop(),
|
||||
setSelectedDate: (_) => _,
|
||||
});
|
||||
|
||||
export { BookingContext };
|
||||
79
app/home/(user)/_components/booking/booking.provider.tsx
Normal file
79
app/home/(user)/_components/booking/booking.provider.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import React, { useContext, useEffect, useState } from 'react';
|
||||
|
||||
import { StoreProduct } from '@medusajs/types';
|
||||
|
||||
import { getAvailableTimeSlotsForDisplay } from '~/lib/services/connected-online.service';
|
||||
|
||||
import { BookingContext, Location, TimeSlot } from './booking.context';
|
||||
|
||||
export function useBooking() {
|
||||
const context = useContext(BookingContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useBooking must be used within a BookingProvider.');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
export const BookingProvider: React.FC<{
|
||||
children: React.ReactElement;
|
||||
category: { products: StoreProduct[] };
|
||||
service?: StoreProduct;
|
||||
}> = ({ children, category, service }) => {
|
||||
const [selectedService, setSelectedService] = useState<StoreProduct | null>(
|
||||
(service ?? category?.products?.[0]) || null,
|
||||
);
|
||||
const [selectedLocationId, setSelectedLocationId] = useState<number | null>(
|
||||
null,
|
||||
);
|
||||
const [selectedDate, setSelectedDate] = useState<Date>();
|
||||
const [timeSlots, setTimeSlots] = useState<TimeSlot[] | null>(null);
|
||||
const [locations, setLocations] = useState<Location[] | null>(null);
|
||||
const [isLoadingTimeSlots, setIsLoadingTimeSlots] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const metadataServiceIds = selectedService?.metadata?.serviceIds as string;
|
||||
if (metadataServiceIds) {
|
||||
const json = JSON.parse(metadataServiceIds);
|
||||
if (Array.isArray(json)) {
|
||||
updateTimeSlots(json);
|
||||
}
|
||||
}
|
||||
}, [selectedService, selectedLocationId]);
|
||||
|
||||
const updateTimeSlots = async (serviceIds: number[]) => {
|
||||
setIsLoadingTimeSlots(true);
|
||||
try {
|
||||
const response = await getAvailableTimeSlotsForDisplay(
|
||||
serviceIds,
|
||||
selectedLocationId,
|
||||
);
|
||||
setTimeSlots(response.timeSlots);
|
||||
setLocations(response.locations);
|
||||
} catch {
|
||||
setTimeSlots(null);
|
||||
} finally {
|
||||
setIsLoadingTimeSlots(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BookingContext.Provider
|
||||
value={{
|
||||
timeSlots,
|
||||
locations,
|
||||
selectedService,
|
||||
selectedLocationId,
|
||||
setSelectedLocationId,
|
||||
selectedDate,
|
||||
isLoadingTimeSlots,
|
||||
setSelectedService,
|
||||
updateTimeSlots,
|
||||
setSelectedDate,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</BookingContext.Provider>
|
||||
);
|
||||
};
|
||||
65
app/home/(user)/_components/booking/location-selector.tsx
Normal file
65
app/home/(user)/_components/booking/location-selector.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { Label } from '@medusajs/ui';
|
||||
|
||||
import { RadioGroup, RadioGroupItem } from '@kit/ui/radio-group';
|
||||
import { Card } from '@kit/ui/shadcn/card';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { useBooking } from './booking.provider';
|
||||
|
||||
const LocationSelector = () => {
|
||||
const { selectedLocationId, setSelectedLocationId, locations } = useBooking();
|
||||
|
||||
const onLocationSelect = (locationId: number | string | null) => {
|
||||
if (locationId === 'all') return setSelectedLocationId(null);
|
||||
setSelectedLocationId(Number(locationId));
|
||||
};
|
||||
|
||||
const uniqueLocations = locations?.filter((item, index, self) => {
|
||||
return (
|
||||
index ===
|
||||
self.findIndex(
|
||||
(loc) => loc.sync_id === item.sync_id && loc.name === item.name,
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="mb-4 p-4">
|
||||
<h5 className="text-semibold mb-2">
|
||||
<Trans i18nKey="booking:locations" />
|
||||
</h5>
|
||||
<div className="flex flex-col">
|
||||
<RadioGroup
|
||||
className="mb-2 flex flex-col"
|
||||
onValueChange={(val) => onLocationSelect(val)}
|
||||
>
|
||||
{/* <div className="flex items-center gap-2">
|
||||
<RadioGroupItem
|
||||
value="all"
|
||||
id="all"
|
||||
checked={selectedLocationId === null}
|
||||
/>
|
||||
<Label htmlFor="all">{t('booking:showAllLocations')}</Label>
|
||||
</div> */}
|
||||
{uniqueLocations?.map((location, index) => (
|
||||
<div key={location.sync_id} className="flex items-center gap-2">
|
||||
<RadioGroupItem
|
||||
value={location.sync_id.toString()}
|
||||
id={location.sync_id.toString()}
|
||||
checked={
|
||||
selectedLocationId === location.sync_id ||
|
||||
(index === 0 && selectedLocationId === null)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor={location.sync_id.toString()}>
|
||||
{location.name}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default LocationSelector;
|
||||
85
app/home/(user)/_components/booking/service-selector.tsx
Normal file
85
app/home/(user)/_components/booking/service-selector.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { StoreProduct } from '@medusajs/types';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
import { Card } from '@kit/ui/shadcn/card';
|
||||
import { Label } from '@kit/ui/shadcn/label';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@kit/ui/shadcn/popover';
|
||||
import { RadioGroup, RadioGroupItem } from '@kit/ui/shadcn/radio-group';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { useBooking } from './booking.provider';
|
||||
|
||||
const ServiceSelector = ({ products }: { products: StoreProduct[] }) => {
|
||||
const { selectedService, setSelectedService } = useBooking();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [firstFourProducts] = useState<StoreProduct[]>(products?.slice(0, 4));
|
||||
|
||||
const onServiceSelect = async (productId: StoreProduct['id']) => {
|
||||
const product = products.find((p) => p.id === productId);
|
||||
setSelectedService(product ?? null);
|
||||
setCollapsed(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="mb-4 p-4">
|
||||
<h5 className="text-semibold mb-2">
|
||||
<Trans i18nKey="booking:services" />
|
||||
</h5>
|
||||
<Popover open={collapsed} onOpenChange={setCollapsed}>
|
||||
<div className="flex flex-col">
|
||||
<RadioGroup
|
||||
defaultValue={selectedService?.id || ''}
|
||||
className="mb-2 flex flex-col"
|
||||
onValueChange={onServiceSelect}
|
||||
>
|
||||
{firstFourProducts?.map((product) => (
|
||||
<div key={product.id} className="flex items-center gap-2">
|
||||
<RadioGroupItem
|
||||
value={product.id}
|
||||
id={product.id}
|
||||
checked={selectedService?.id === product.id}
|
||||
/>
|
||||
<Label htmlFor={product.id}>{product.title}</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
{products.length > 4 && (
|
||||
<PopoverTrigger asChild>
|
||||
<div
|
||||
onClick={() => setCollapsed((_) => !_)}
|
||||
className="flex cursor-pointer items-center justify-between border-t py-1"
|
||||
>
|
||||
<span>
|
||||
<Trans i18nKey="booking:showAll" />
|
||||
</span>
|
||||
<ChevronDown />
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
)}
|
||||
</div>
|
||||
<PopoverContent sideOffset={10}>
|
||||
<RadioGroup onValueChange={onServiceSelect}>
|
||||
{products?.map((product) => (
|
||||
<div key={product.id + '-2'} className="flex items-center gap-2">
|
||||
<RadioGroupItem
|
||||
value={product.id}
|
||||
id={product.id + '-2'}
|
||||
checked={selectedService?.id === product.id}
|
||||
/>
|
||||
<Label htmlFor={product.id + '-2'}>{product.title}</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default ServiceSelector;
|
||||
242
app/home/(user)/_components/booking/time-slots.tsx
Normal file
242
app/home/(user)/_components/booking/time-slots.tsx
Normal file
@@ -0,0 +1,242 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { addHours, isAfter, isSameDay } from 'date-fns';
|
||||
import { orderBy } from 'lodash';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { formatDateAndTime } from '@kit/shared/utils';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Card } from '@kit/ui/shadcn/card';
|
||||
import { Skeleton } from '@kit/ui/shadcn/skeleton';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { cn } from '@kit/ui/utils';
|
||||
|
||||
import { updateReservationTime } from '~/lib/services/reservation.service';
|
||||
|
||||
import { createInitialReservationAction } from '../../_lib/server/actions';
|
||||
import { EnrichedCartItem } from '../cart/types';
|
||||
import BookingPagination from './booking-pagination';
|
||||
import { ServiceProvider, TimeSlot } from './booking.context';
|
||||
import { useBooking } from './booking.provider';
|
||||
|
||||
const getServiceProviderTitle = (
|
||||
currentLocale: string,
|
||||
serviceProvider?: ServiceProvider,
|
||||
) => {
|
||||
if (!serviceProvider) return null;
|
||||
if (currentLocale === 'en') return serviceProvider.jobTitleEn;
|
||||
if (currentLocale === 'ru') return serviceProvider.jobTitleRu;
|
||||
|
||||
return serviceProvider.jobTitleEt;
|
||||
};
|
||||
|
||||
const PAGE_SIZE = 7;
|
||||
|
||||
const TimeSlots = ({
|
||||
countryCode,
|
||||
cartItem,
|
||||
onComplete,
|
||||
}: {
|
||||
countryCode: string;
|
||||
cartItem?: EnrichedCartItem;
|
||||
onComplete?: () => void;
|
||||
}) => {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
const {
|
||||
t,
|
||||
i18n: { language: currentLocale },
|
||||
} = useTranslation();
|
||||
|
||||
const booking = useBooking();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const selectedDate = booking.selectedDate ?? new Date();
|
||||
|
||||
const filteredBookings = useMemo(
|
||||
() =>
|
||||
orderBy(
|
||||
booking?.timeSlots?.filter(({ StartTime }) => {
|
||||
const firstAvailableTimeToSelect = isSameDay(selectedDate, new Date())
|
||||
? addHours(new Date(), 0.5)
|
||||
: selectedDate;
|
||||
return isAfter(StartTime, firstAvailableTimeToSelect);
|
||||
}) ?? [],
|
||||
'StartTime',
|
||||
'asc',
|
||||
).filter(({ StartTime }) => isSameDay(StartTime, selectedDate)),
|
||||
[booking.timeSlots, selectedDate],
|
||||
);
|
||||
|
||||
const paginatedBookings = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * PAGE_SIZE;
|
||||
const endIndex = startIndex + PAGE_SIZE;
|
||||
return filteredBookings.slice(startIndex, endIndex);
|
||||
}, [filteredBookings, currentPage, PAGE_SIZE]);
|
||||
|
||||
if (!booking?.timeSlots?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleBookTime = async (timeSlot: TimeSlot, comments?: string) => {
|
||||
const selectedService = booking.selectedService;
|
||||
|
||||
const selectedVariant = selectedService?.variants?.[0];
|
||||
|
||||
const syncedService = timeSlot.syncedService;
|
||||
if (!syncedService || !selectedVariant) {
|
||||
return toast.error(t('booking:serviceNotFound'));
|
||||
}
|
||||
|
||||
const bookTimePromise = createInitialReservationAction(
|
||||
selectedVariant,
|
||||
countryCode,
|
||||
Number(syncedService.id),
|
||||
syncedService?.clinic_id,
|
||||
timeSlot.UserID,
|
||||
timeSlot.SyncUserID,
|
||||
timeSlot.StartTime,
|
||||
booking.selectedLocationId ? booking.selectedLocationId : null,
|
||||
comments,
|
||||
)
|
||||
.then(() => {
|
||||
if (onComplete) {
|
||||
onComplete();
|
||||
}
|
||||
router.push(pathsConfig.app.cart);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Booking error: ', error);
|
||||
throw error;
|
||||
});
|
||||
|
||||
toast.promise(() => bookTimePromise, {
|
||||
success: <Trans i18nKey={'booking:bookTimeSuccess'} />,
|
||||
error: <Trans i18nKey={'booking:bookTimeError'} />,
|
||||
loading: <Trans i18nKey={'booking:bookTimeLoading'} />,
|
||||
});
|
||||
};
|
||||
|
||||
const handleChangeTime = async (
|
||||
timeSlot: TimeSlot,
|
||||
reservationId: number,
|
||||
cartId: string,
|
||||
) => {
|
||||
const syncedService = timeSlot.syncedService;
|
||||
if (!syncedService) {
|
||||
return toast.error(t('booking:serviceNotFound'));
|
||||
}
|
||||
|
||||
const bookTimePromise = updateReservationTime({
|
||||
reservationId,
|
||||
newStartTime: timeSlot.StartTime,
|
||||
newServiceId: Number(syncedService.id),
|
||||
newAppointmentUserId: timeSlot.UserID,
|
||||
newSyncUserId: timeSlot.SyncUserID,
|
||||
newLocationId: booking.selectedLocationId
|
||||
? booking.selectedLocationId
|
||||
: null,
|
||||
cartId,
|
||||
});
|
||||
|
||||
toast.promise(() => bookTimePromise, {
|
||||
success: <Trans i18nKey={'booking:bookTimeSuccess'} />,
|
||||
error: <Trans i18nKey={'booking:bookTimeError'} />,
|
||||
loading: <Trans i18nKey={'booking:bookTimeLoading'} />,
|
||||
});
|
||||
|
||||
if (onComplete) {
|
||||
onComplete();
|
||||
}
|
||||
};
|
||||
|
||||
const handleTimeSelect = async (timeSlot: TimeSlot) => {
|
||||
if (cartItem?.reservation.id) {
|
||||
return handleChangeTime(
|
||||
timeSlot,
|
||||
cartItem.reservation.id,
|
||||
cartItem.cart_id,
|
||||
);
|
||||
}
|
||||
|
||||
return handleBookTime(timeSlot);
|
||||
};
|
||||
|
||||
return (
|
||||
<Skeleton
|
||||
isLoading={booking.isLoadingTimeSlots}
|
||||
className="flex w-full flex-col gap-4"
|
||||
>
|
||||
<div className="flex h-full w-full flex-col gap-2 overflow-auto">
|
||||
{paginatedBookings.map((timeSlot, index) => {
|
||||
const isHaigeKassa = timeSlot.HKServiceID > 0;
|
||||
const serviceProviderTitle = getServiceProviderTitle(
|
||||
currentLocale,
|
||||
timeSlot.serviceProvider,
|
||||
);
|
||||
const price =
|
||||
booking.selectedService?.variants?.[0]?.calculated_price
|
||||
?.calculated_amount ?? cartItem?.unit_price;
|
||||
|
||||
return (
|
||||
<Card
|
||||
className="xs:flex xs:justify-between w-full justify-center-safe gap-3 p-4"
|
||||
key={index}
|
||||
>
|
||||
<div>
|
||||
<span>{formatDateAndTime(timeSlot.StartTime.toString())}</span>
|
||||
<div className="flex">
|
||||
<h5
|
||||
className={cn(
|
||||
(serviceProviderTitle || isHaigeKassa) &&
|
||||
"after:mx-2 after:content-['·']",
|
||||
)}
|
||||
>
|
||||
{timeSlot.serviceProvider?.name}
|
||||
</h5>
|
||||
{serviceProviderTitle && (
|
||||
<span
|
||||
className={cn(
|
||||
isHaigeKassa && "after:mx-2 after:content-['·']",
|
||||
)}
|
||||
>
|
||||
{serviceProviderTitle}
|
||||
</span>
|
||||
)}
|
||||
{isHaigeKassa && <span>{t('booking:ehifBooking')}</span>}
|
||||
</div>
|
||||
<div className="flex text-xs">{timeSlot.location?.address}</div>
|
||||
</div>
|
||||
<div className="flex-end not-last:xs:justify-center flex items-center justify-between gap-2">
|
||||
<span className="text-sm font-semibold">
|
||||
{formatCurrency({
|
||||
currencyCode: 'EUR',
|
||||
locale: 'et-EE',
|
||||
value: price ?? '',
|
||||
})}
|
||||
</span>
|
||||
<Button onClick={() => handleTimeSelect(timeSlot)} size="sm">
|
||||
<Trans i18nKey="common:book" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<BookingPagination
|
||||
totalPages={Math.ceil(filteredBookings.length / PAGE_SIZE)}
|
||||
setCurrentPage={setCurrentPage}
|
||||
currentPage={currentPage}
|
||||
/>
|
||||
</Skeleton>
|
||||
);
|
||||
};
|
||||
|
||||
export default TimeSlots;
|
||||
@@ -1,13 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { Form } from '@kit/ui/form';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -22,10 +19,6 @@ import { Trans } from '@kit/ui/trans';
|
||||
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';
|
||||
import partnerLocations from './partner-locations.json';
|
||||
|
||||
const AnalysisLocationSchema = z.object({
|
||||
locationId: z.string().min(1),
|
||||
});
|
||||
|
||||
export default function AnalysisLocation({
|
||||
cart,
|
||||
synlabAnalyses,
|
||||
@@ -35,21 +28,15 @@ export default function AnalysisLocation({
|
||||
}) {
|
||||
const { t } = useTranslation('cart');
|
||||
|
||||
const form = useForm<z.infer<typeof AnalysisLocationSchema>>({
|
||||
defaultValues: {
|
||||
locationId: (cart.metadata?.partner_location_id as string) ?? '',
|
||||
},
|
||||
resolver: zodResolver(AnalysisLocationSchema),
|
||||
});
|
||||
const { watch, setValue } = useFormContext();
|
||||
const currentValue = watch('locationId');
|
||||
|
||||
const getLocation = (locationId: string) =>
|
||||
partnerLocations.find(({ name }) => name === locationId);
|
||||
|
||||
const selectedLocation = getLocation(form.watch('locationId'));
|
||||
const selectedLocation = getLocation(currentValue);
|
||||
|
||||
const onSubmit = async ({
|
||||
locationId,
|
||||
}: z.infer<typeof AnalysisLocationSchema>) => {
|
||||
const handleUpdateCartPartnerLocation = async (locationId: string) => {
|
||||
const promise = updateCartPartnerLocation({
|
||||
cartId: cart.id,
|
||||
lineIds: synlabAnalyses.map(({ id }) => id),
|
||||
@@ -70,53 +57,48 @@ export default function AnalysisLocation({
|
||||
<Trans i18nKey={'cart:locations.description'} />
|
||||
</p>
|
||||
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit((data) => onSubmit(data))}
|
||||
className="mb-2 flex w-full flex-1 gap-x-2"
|
||||
<div className="mb-2 flex w-full flex-1 gap-x-2">
|
||||
<Select
|
||||
value={currentValue}
|
||||
onValueChange={(value) => {
|
||||
setValue('locationId', value, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
|
||||
return handleUpdateCartPartnerLocation(value);
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
value={form.watch('locationId')}
|
||||
onValueChange={(value) => {
|
||||
form.setValue('locationId', value, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('cart:locations.locationSelect')} />
|
||||
</SelectTrigger>
|
||||
|
||||
return onSubmit(form.getValues());
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('cart:locations.locationSelect')} />
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
{Object.entries(
|
||||
partnerLocations.reduce(
|
||||
(acc, curr) => ({
|
||||
...acc,
|
||||
[curr.city]: [
|
||||
...((acc[curr.city] as typeof partnerLocations) ?? []),
|
||||
curr,
|
||||
],
|
||||
}),
|
||||
{} as Record<string, typeof partnerLocations>,
|
||||
),
|
||||
).map(([city, locations]) => (
|
||||
<SelectGroup key={city}>
|
||||
<SelectLabel>{city}</SelectLabel>
|
||||
{locations.map((location) => (
|
||||
<SelectItem key={location.name} value={location.name}>
|
||||
{location.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</form>
|
||||
</Form>
|
||||
<SelectContent>
|
||||
{Object.entries(
|
||||
partnerLocations.reduce(
|
||||
(acc, curr) => ({
|
||||
...acc,
|
||||
[curr.city]: [
|
||||
...((acc[curr.city] as typeof partnerLocations) ?? []),
|
||||
curr,
|
||||
],
|
||||
}),
|
||||
{} as Record<string, typeof partnerLocations>,
|
||||
),
|
||||
).map(([city, locations]) => (
|
||||
<SelectGroup key={city}>
|
||||
<SelectLabel>{city}</SelectLabel>
|
||||
{locations.map((location) => (
|
||||
<SelectItem key={location.name} value={location.name}>
|
||||
{location.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedLocation && (
|
||||
<div className="mb-4 flex flex-col gap-y-2">
|
||||
|
||||
219
app/home/(user)/_components/cart/cart-form-content.tsx
Normal file
219
app/home/(user)/_components/cart/cart-form-content.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
'use client';
|
||||
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import {
|
||||
StoreCart,
|
||||
StoreCartLineItem,
|
||||
StoreCartPromotion,
|
||||
} from '@medusajs/types';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Card, CardContent, CardHeader } from '@kit/ui/card';
|
||||
import { Checkbox } from '@kit/ui/checkbox';
|
||||
import { FormControl, FormField, FormItem, FormLabel } from '@kit/ui/form';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { cn } from '~/lib/utils';
|
||||
|
||||
import AnalysisLocation from './analysis-location';
|
||||
import CartItems from './cart-items';
|
||||
import CartServiceItems from './cart-service-items';
|
||||
import DiscountCode from './discount-code';
|
||||
import { EnrichedCartItem, GetBalanceSummarySelection } from './types';
|
||||
|
||||
const IS_DISCOUNT_SHOWN = true as boolean;
|
||||
|
||||
export default function CartFormContent({
|
||||
cart,
|
||||
synlabAnalyses,
|
||||
ttoServiceItems,
|
||||
unavailableLineItemIds,
|
||||
isInitiatingSession,
|
||||
getBalanceSummarySelection,
|
||||
}: {
|
||||
cart: StoreCart & {
|
||||
promotions: StoreCartPromotion[];
|
||||
};
|
||||
synlabAnalyses: StoreCartLineItem[];
|
||||
ttoServiceItems: EnrichedCartItem[];
|
||||
unavailableLineItemIds?: string[];
|
||||
isInitiatingSession: boolean;
|
||||
getBalanceSummarySelection: GetBalanceSummarySelection;
|
||||
}) {
|
||||
const {
|
||||
i18n: { language },
|
||||
} = useTranslation();
|
||||
const { watch } = useFormContext();
|
||||
|
||||
const items = cart?.items ?? [];
|
||||
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
||||
|
||||
const isLocationsShown = synlabAnalyses.length > 0;
|
||||
|
||||
const useCompanyBenefits = watch('useCompanyBenefits');
|
||||
const balanceSummary = getBalanceSummarySelection({ useCompanyBenefits });
|
||||
|
||||
const { benefitsAmount, benefitsAmountTotal, montonioAmount } =
|
||||
balanceSummary;
|
||||
|
||||
const hasBenefitsApplied = benefitsAmountTotal > 0 && !!useCompanyBenefits;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-y-6 bg-white">
|
||||
<CartItems
|
||||
cart={cart}
|
||||
items={synlabAnalyses}
|
||||
productColumnLabelKey="cart:items.synlabAnalyses.productColumnLabel"
|
||||
/>
|
||||
<CartServiceItems
|
||||
cart={cart}
|
||||
items={ttoServiceItems}
|
||||
productColumnLabelKey="cart:items.ttoServices.productColumnLabel"
|
||||
unavailableLineItemIds={unavailableLineItemIds}
|
||||
/>
|
||||
</div>
|
||||
{hasCartItems && (
|
||||
<>
|
||||
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.subtotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: cart.subtotal,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4',
|
||||
{
|
||||
'py-2 sm:py-4': !hasBenefitsApplied,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.promotionsTotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: cart.discount_total,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{hasBenefitsApplied && (
|
||||
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.companyBenefitsTotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: benefitsAmount,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.total" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: montonioAmount,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{benefitsAmountTotal > 0 && (
|
||||
<FormField
|
||||
name="useCompanyBenefits"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-8">
|
||||
<div className="flex flex-row items-center gap-2 pb-1">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel>
|
||||
<Trans i18nKey={'cart:companyBenefits.label'} />
|
||||
</FormLabel>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
|
||||
{IS_DISCOUNT_SHOWN && (
|
||||
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
||||
<CardHeader className="pb-4">
|
||||
<h5>
|
||||
<Trans i18nKey="cart:discountCode.title" />
|
||||
</h5>
|
||||
</CardHeader>
|
||||
<CardContent className="h-full">
|
||||
<DiscountCode cart={{ ...cart }} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{isLocationsShown && (
|
||||
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
||||
<CardHeader className="pb-4">
|
||||
<h5>
|
||||
<Trans i18nKey="cart:locations.title" />
|
||||
</h5>
|
||||
</CardHeader>
|
||||
<CardContent className="h-full">
|
||||
<AnalysisLocation
|
||||
cart={{ ...cart }}
|
||||
synlabAnalyses={synlabAnalyses}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button className="h-10" type="submit" disabled={isInitiatingSession}>
|
||||
{isInitiatingSession && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
<Trans i18nKey="cart:checkout.goToCheckout" />
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
49
app/home/(user)/_components/cart/cart-form.tsx
Normal file
49
app/home/(user)/_components/cart/cart-form.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import type { StoreCart } from '@medusajs/types';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { Form } from '@kit/ui/form';
|
||||
|
||||
const CartFormSchema = z.object({
|
||||
code: z.string().optional(),
|
||||
locationId: z.string().optional(),
|
||||
useCompanyBenefits: z.boolean(),
|
||||
});
|
||||
|
||||
export type CartFormOnSubmit = (
|
||||
data: z.infer<typeof CartFormSchema>,
|
||||
) => Promise<void>;
|
||||
|
||||
export default function CartForm({
|
||||
children,
|
||||
cart,
|
||||
onSubmit,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
cart: StoreCart;
|
||||
onSubmit: CartFormOnSubmit;
|
||||
}) {
|
||||
const form = useForm<z.infer<typeof CartFormSchema>>({
|
||||
defaultValues: {
|
||||
code: '',
|
||||
locationId: (cart.metadata?.partner_location_id as string) ?? '',
|
||||
useCompanyBenefits: true,
|
||||
},
|
||||
resolver: zodResolver(CartFormSchema),
|
||||
});
|
||||
|
||||
const handleSubmit: CartFormOnSubmit = async (data) => {
|
||||
await onSubmit(data);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit((data) => handleSubmit(data))}>
|
||||
{children}
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -38,6 +38,7 @@ const CartItemDelete = ({
|
||||
<button
|
||||
className="text-ui-fg-subtle hover:text-ui-fg-base flex cursor-pointer gap-x-1"
|
||||
onClick={() => handleDelete()}
|
||||
type="button"
|
||||
>
|
||||
{isDeleting ? <Spinner className="animate-spin" /> : <Trash />}
|
||||
<span>{children}</span>
|
||||
|
||||
@@ -20,7 +20,7 @@ export default function CartItem({
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<TableRow className="w-full" data-testid="product-row">
|
||||
<TableRow className="sm:w-full" data-testid="product-row">
|
||||
<TableCell className="w-[100%] px-4 text-left sm:px-6">
|
||||
<p
|
||||
className="txt-medium-plus text-ui-fg-base"
|
||||
@@ -41,11 +41,12 @@ export default function CartItem({
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="min-w-[80px] px-4 text-right sm:px-6">
|
||||
{formatCurrency({
|
||||
value: item.total,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})}
|
||||
{item.total &&
|
||||
formatCurrency({
|
||||
value: item.total,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="px-4 text-right sm:px-6">
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import CartItem from './cart-item';
|
||||
import MobileCartItems from './mobile-cart-items';
|
||||
|
||||
export default function CartItems({
|
||||
cart,
|
||||
@@ -25,37 +26,54 @@ export default function CartItems({
|
||||
}
|
||||
|
||||
return (
|
||||
<Table className="border-separate rounded-lg border">
|
||||
<TableHeader className="text-ui-fg-subtle txt-medium-plus">
|
||||
<TableRow>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey={productColumnLabelKey} />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.quantity" />
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[100px] px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.price" />
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[100px] px-4 text-right sm:px-6">
|
||||
<Trans i18nKey="cart:table.total" />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<>
|
||||
<Table className="hidden border-separate rounded-lg border sm:block">
|
||||
<TableHeader className="text-ui-fg-subtle txt-medium-plus">
|
||||
<TableRow>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey={productColumnLabelKey} />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.quantity" />
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[100px] px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.price" />
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[100px] px-4 text-right sm:px-6">
|
||||
<Trans i18nKey="cart:table.total" />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{items
|
||||
.sort((a, b) =>
|
||||
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||
)
|
||||
.map((item) => (
|
||||
<CartItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
currencyCode={cart.currency_code}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div className="sm:hidden">
|
||||
{items
|
||||
.sort((a, b) =>
|
||||
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||
)
|
||||
.map((item) => (
|
||||
<CartItem
|
||||
<MobileCartItems
|
||||
key={item.id}
|
||||
item={item}
|
||||
currencyCode={cart.currency_code}
|
||||
productColumnLabelKey={productColumnLabelKey}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
97
app/home/(user)/_components/cart/cart-service-item.tsx
Normal file
97
app/home/(user)/_components/cart/cart-service-item.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
'use client';
|
||||
|
||||
import { formatCurrency, formatDateAndTime } from '@/packages/shared/src/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { TableCell, TableRow } from '@kit/ui/table';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import CartItemDelete from './cart-item-delete';
|
||||
import { EnrichedCartItem } from './types';
|
||||
|
||||
export default function CartServiceItem({
|
||||
item,
|
||||
currencyCode,
|
||||
isUnavailable,
|
||||
setEditingItem,
|
||||
}: {
|
||||
item: EnrichedCartItem;
|
||||
currencyCode: string;
|
||||
isUnavailable?: boolean;
|
||||
setEditingItem: (item: EnrichedCartItem | null) => void;
|
||||
}) {
|
||||
const {
|
||||
i18n: { language },
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<>
|
||||
<TableRow className="w-full" data-testid="product-row">
|
||||
<TableCell className="w-[100%] px-4 text-left sm:px-6">
|
||||
<p
|
||||
className="txt-medium-plus text-ui-fg-base"
|
||||
data-testid="product-title"
|
||||
>
|
||||
{item.product_title}
|
||||
</p>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="px-4 sm:px-6">
|
||||
{formatDateAndTime(item.reservation.startTime.toString())}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="px-4 sm:px-6">
|
||||
{item.reservation.location?.address ?? '-'}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="px-4 sm:px-6">{item.quantity}</TableCell>
|
||||
|
||||
<TableCell className="min-w-[80px] px-4 sm:px-6">
|
||||
{formatCurrency({
|
||||
value: item.unit_price,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="min-w-[80px] px-4 text-right sm:px-6">
|
||||
{item.total &&
|
||||
formatCurrency({
|
||||
value: item.total,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})}
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="px-4 text-right sm:px-6">
|
||||
<span className="flex justify-end gap-x-1">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={() => setEditingItem(item)}
|
||||
>
|
||||
<Trans i18nKey="common:change" />
|
||||
</Button>
|
||||
</span>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="px-4 text-right sm:px-6">
|
||||
<span className="flex w-[60px] justify-end gap-x-1">
|
||||
<CartItemDelete id={item.id} />
|
||||
</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{isUnavailable && (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={8}
|
||||
className="text-destructive px-4 text-left sm:px-6"
|
||||
>
|
||||
<Trans i18nKey="booking:timeSlotUnavailable" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
149
app/home/(user)/_components/cart/cart-service-items.tsx
Normal file
149
app/home/(user)/_components/cart/cart-service-items.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { StoreCart } from '@medusajs/types';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@kit/ui/shadcn/dialog';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@kit/ui/table';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import BookingContainer from '../booking/booking-container';
|
||||
import CartServiceItem from './cart-service-item';
|
||||
import MobileCartServiceItems from './mobile-cart-service-items';
|
||||
import { EnrichedCartItem } from './types';
|
||||
|
||||
const EditCartServiceItemModal = ({
|
||||
item,
|
||||
onComplete,
|
||||
}: {
|
||||
item: EnrichedCartItem | null;
|
||||
onComplete: () => void;
|
||||
}) => {
|
||||
if (!item) return null;
|
||||
|
||||
return (
|
||||
<Dialog defaultOpen>
|
||||
<DialogContent className="xs:max-w-[90vw] flex max-h-screen max-w-full flex-col items-center gap-4 space-y-4 overflow-y-scroll">
|
||||
<DialogHeader className="items-center text-center">
|
||||
<DialogTitle>
|
||||
<Trans i18nKey="cart:editServiceItem.title" />
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
<Trans i18nKey="cart:editServiceItem.description" />
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div>
|
||||
{item.product && item.reservation.countryCode ? (
|
||||
<BookingContainer
|
||||
category={{
|
||||
products: [item.product],
|
||||
countryCode: item.reservation.countryCode,
|
||||
}}
|
||||
cartItem={item}
|
||||
onComplete={onComplete}
|
||||
/>
|
||||
) : (
|
||||
<p>
|
||||
<Trans i18nKey="booking:noProducts" />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default function CartServiceItems({
|
||||
cart,
|
||||
items,
|
||||
productColumnLabelKey,
|
||||
unavailableLineItemIds,
|
||||
}: {
|
||||
cart: StoreCart;
|
||||
items: EnrichedCartItem[];
|
||||
productColumnLabelKey: string;
|
||||
unavailableLineItemIds?: string[];
|
||||
}) {
|
||||
const [editingItem, setEditingItem] = useState<EnrichedCartItem | null>(null);
|
||||
if (!items || items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table className="hidden border-separate rounded-lg border sm:block">
|
||||
<TableHeader className="text-ui-fg-subtle txt-medium-plus">
|
||||
<TableRow>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey={productColumnLabelKey} />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.time" />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.location" />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.quantity" />
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[100px] px-4 sm:px-6">
|
||||
<Trans i18nKey="cart:table.price" />
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[100px] px-4 text-right sm:px-6">
|
||||
<Trans i18nKey="cart:table.total" />
|
||||
</TableHead>
|
||||
<TableHead className="px-4 sm:px-6"></TableHead>
|
||||
<TableHead className="px-4 sm:px-6"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{items
|
||||
.sort((a, b) =>
|
||||
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||
)
|
||||
.map((item) => (
|
||||
<CartServiceItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
currencyCode={cart.currency_code}
|
||||
isUnavailable={unavailableLineItemIds?.includes(item.id)}
|
||||
setEditingItem={setEditingItem}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className="sm:hidden">
|
||||
{items
|
||||
.sort((a, b) =>
|
||||
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||
)
|
||||
.map((item) => (
|
||||
<MobileCartServiceItems
|
||||
key={item.id}
|
||||
item={item}
|
||||
currencyCode={cart.currency_code}
|
||||
isUnavailable={unavailableLineItemIds?.includes(item.id)}
|
||||
productColumnLabelKey={productColumnLabelKey}
|
||||
setEditingItem={setEditingItem}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<EditCartServiceItemModal
|
||||
item={editingItem}
|
||||
onComplete={() => setEditingItem(null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { convertToLocale } from '@lib/util/money';
|
||||
import { StoreCart, StorePromotion } from '@medusajs/types';
|
||||
import { StoreCart, StoreCartPromotion } from '@medusajs/types';
|
||||
import { Badge, Text } from '@medusajs/ui';
|
||||
import Trash from '@modules/common/icons/trash';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Form, FormControl, FormField, FormItem } from '@kit/ui/form';
|
||||
import { FormControl, FormField, FormItem } from '@kit/ui/form';
|
||||
import { Input } from '@kit/ui/input';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
@@ -22,21 +20,22 @@ import {
|
||||
removePromotionCodeAction,
|
||||
} from './discount-code-actions';
|
||||
|
||||
const DiscountCodeSchema = z.object({
|
||||
code: z.string().min(1),
|
||||
});
|
||||
|
||||
export default function DiscountCode({
|
||||
cart,
|
||||
}: {
|
||||
cart: StoreCart & {
|
||||
promotions: StorePromotion[];
|
||||
promotions: StoreCartPromotion[];
|
||||
};
|
||||
}) {
|
||||
const { t } = useTranslation('cart');
|
||||
|
||||
const { setValue, watch } = useFormContext();
|
||||
const currentValue = watch('code');
|
||||
|
||||
const { promotions = [] } = cart;
|
||||
|
||||
const [isAddingPromotionCode, setIsAddingPromotionCode] = useState(false);
|
||||
|
||||
const removePromotionCode = async (code: string) => {
|
||||
const appliedCodes = promotions
|
||||
.filter((p) => p.code !== undefined)
|
||||
@@ -55,57 +54,56 @@ export default function DiscountCode({
|
||||
};
|
||||
|
||||
const addPromotionCode = async (code: string) => {
|
||||
if (!code || code.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsAddingPromotionCode(true);
|
||||
const loading = toast.loading(t('cart:discountCode.addLoading'));
|
||||
const result = await addPromotionCodeAction(code);
|
||||
|
||||
toast.dismiss(loading);
|
||||
if (result.success) {
|
||||
toast.success(t('cart:discountCode.addSuccess'));
|
||||
form.reset();
|
||||
setValue('code', '');
|
||||
} else {
|
||||
toast.error(t('cart:discountCode.addError'));
|
||||
}
|
||||
setIsAddingPromotionCode(false);
|
||||
};
|
||||
|
||||
const form = useForm<z.infer<typeof DiscountCodeSchema>>({
|
||||
defaultValues: {
|
||||
code: '',
|
||||
},
|
||||
resolver: zodResolver(DiscountCodeSchema),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="txt-medium flex h-full w-full flex-col gap-y-4 bg-white">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
<Trans i18nKey={'cart:discountCode.subtitle'} />
|
||||
</p>
|
||||
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit((data) => addPromotionCode(data.code))}
|
||||
className="mb-2 flex w-full flex-1 flex-col gap-x-2 gap-y-2 sm:flex-row"
|
||||
>
|
||||
<FormField
|
||||
name={'code'}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormControl>
|
||||
<Input
|
||||
required
|
||||
type="text"
|
||||
{...field}
|
||||
placeholder={t('cart:discountCode.placeholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="mb-2 flex w-full flex-1 flex-col gap-x-2 gap-y-2 sm:flex-row">
|
||||
<FormField
|
||||
name={'code'}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormControl>
|
||||
<Input
|
||||
type="text"
|
||||
{...field}
|
||||
placeholder={t('cart:discountCode.placeholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" variant="secondary" className="h-min">
|
||||
<Trans i18nKey={'cart:discountCode.apply'} />
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-min"
|
||||
onClick={() => addPromotionCode(currentValue)}
|
||||
disabled={isAddingPromotionCode}
|
||||
>
|
||||
<Trans i18nKey={'cart:discountCode.apply'} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{promotions.length > 0 && (
|
||||
<div className="mt-4 flex w-full items-center">
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import {
|
||||
StoreCart,
|
||||
StoreCartLineItem,
|
||||
StoreCartPromotion,
|
||||
} from '@medusajs/types';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Card, CardContent, CardHeader } from '@kit/ui/card';
|
||||
import { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import AnalysisLocation from './analysis-location';
|
||||
import CartItems from './cart-items';
|
||||
import DiscountCode from './discount-code';
|
||||
import { initiatePayment } from '../../_lib/server/cart-actions';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
||||
|
||||
const IS_DISCOUNT_SHOWN = true as boolean;
|
||||
import CartForm, { CartFormOnSubmit } from './cart-form';
|
||||
import CartFormContent from './cart-form-content';
|
||||
import { EnrichedCartItem } from './types';
|
||||
|
||||
export default function Cart({
|
||||
accountId,
|
||||
@@ -28,9 +27,13 @@ export default function Cart({
|
||||
balanceSummary,
|
||||
}: {
|
||||
accountId: string;
|
||||
cart: StoreCart | null;
|
||||
cart:
|
||||
| (StoreCart & {
|
||||
promotions: StoreCartPromotion[];
|
||||
})
|
||||
| null;
|
||||
synlabAnalyses: StoreCartLineItem[];
|
||||
ttoServiceItems: StoreCartLineItem[];
|
||||
ttoServiceItems: EnrichedCartItem[];
|
||||
balanceSummary: AccountBalanceSummary | null;
|
||||
}) {
|
||||
const {
|
||||
@@ -39,6 +42,50 @@ export default function Cart({
|
||||
|
||||
const [isInitiatingSession, setIsInitiatingSession] = useState(false);
|
||||
const router = useRouter();
|
||||
const [unavailableLineItemIds, setUnavailableLineItemIds] =
|
||||
useState<string[]>();
|
||||
|
||||
const getBalanceSummarySelection = useCallback(
|
||||
({
|
||||
useCompanyBenefits,
|
||||
}: {
|
||||
useCompanyBenefits: boolean;
|
||||
}): {
|
||||
benefitsAmount: number;
|
||||
benefitsAmountTotal: number;
|
||||
montonioAmount: number;
|
||||
} => {
|
||||
if (!cart) {
|
||||
return {
|
||||
benefitsAmount: 0,
|
||||
benefitsAmountTotal: 0,
|
||||
montonioAmount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const benefitsAmountTotal = balanceSummary?.totalBalance ?? 0;
|
||||
const cartTotal = cart.total;
|
||||
if (!useCompanyBenefits) {
|
||||
return {
|
||||
benefitsAmount: 0,
|
||||
benefitsAmountTotal,
|
||||
montonioAmount: cartTotal,
|
||||
};
|
||||
}
|
||||
|
||||
const benefitsAmount =
|
||||
benefitsAmountTotal > cartTotal ? cartTotal : benefitsAmountTotal;
|
||||
const montonioAmount =
|
||||
benefitsAmount > 0 ? cartTotal - benefitsAmount : cartTotal;
|
||||
return {
|
||||
benefitsAmount,
|
||||
benefitsAmountTotal,
|
||||
montonioAmount,
|
||||
};
|
||||
},
|
||||
[balanceSummary, cart],
|
||||
);
|
||||
|
||||
const items = cart?.items ?? [];
|
||||
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
||||
|
||||
@@ -62,16 +109,23 @@ export default function Cart({
|
||||
);
|
||||
}
|
||||
|
||||
async function initiateSession() {
|
||||
const initiateSession: CartFormOnSubmit = async ({ useCompanyBenefits }) => {
|
||||
setIsInitiatingSession(true);
|
||||
|
||||
try {
|
||||
const { url, isFullyPaidByBenefits, orderId } = await initiatePayment({
|
||||
accountId,
|
||||
balanceSummary: balanceSummary!,
|
||||
cart: cart!,
|
||||
language,
|
||||
const { benefitsAmount } = getBalanceSummarySelection({
|
||||
useCompanyBenefits,
|
||||
});
|
||||
const { url, isFullyPaidByBenefits, orderId, unavailableLineItemIds } =
|
||||
await initiatePayment({
|
||||
accountId,
|
||||
benefitsAmount,
|
||||
cart: cart!,
|
||||
language,
|
||||
});
|
||||
if (unavailableLineItemIds) {
|
||||
setUnavailableLineItemIds(unavailableLineItemIds);
|
||||
}
|
||||
if (url) {
|
||||
window.location.href = url;
|
||||
} else if (isFullyPaidByBenefits) {
|
||||
@@ -84,141 +138,20 @@ export default function Cart({
|
||||
console.error('Failed to initiate payment', error);
|
||||
setIsInitiatingSession(false);
|
||||
}
|
||||
}
|
||||
|
||||
const isLocationsShown = synlabAnalyses.length > 0;
|
||||
|
||||
const companyBenefitsTotal = balanceSummary?.totalBalance ?? 0;
|
||||
const montonioTotal = cart && companyBenefitsTotal > 0 ? cart.total - companyBenefitsTotal : cart.total;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 lg:px-4">
|
||||
<div className="flex flex-col gap-y-6 bg-white">
|
||||
<CartItems
|
||||
<CartForm cart={cart} onSubmit={initiateSession}>
|
||||
<CartFormContent
|
||||
cart={cart}
|
||||
items={synlabAnalyses}
|
||||
productColumnLabelKey="cart:items.synlabAnalyses.productColumnLabel"
|
||||
synlabAnalyses={synlabAnalyses}
|
||||
ttoServiceItems={ttoServiceItems}
|
||||
unavailableLineItemIds={unavailableLineItemIds}
|
||||
isInitiatingSession={isInitiatingSession}
|
||||
getBalanceSummarySelection={getBalanceSummarySelection}
|
||||
/>
|
||||
<CartItems
|
||||
cart={cart}
|
||||
items={ttoServiceItems}
|
||||
productColumnLabelKey="cart:items.ttoServices.productColumnLabel"
|
||||
/>
|
||||
</div>
|
||||
{hasCartItems && (
|
||||
<>
|
||||
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.subtotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: cart.subtotal,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.promotionsTotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: cart.discount_total,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{companyBenefitsTotal > 0 && (
|
||||
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.companyBenefitsTotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: (companyBenefitsTotal > cart.total ? cart.total : companyBenefitsTotal),
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.total" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: montonioTotal < 0 ? 0 : montonioTotal,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
|
||||
{IS_DISCOUNT_SHOWN && (
|
||||
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
||||
<CardHeader className="pb-4">
|
||||
<h5>
|
||||
<Trans i18nKey="cart:discountCode.title" />
|
||||
</h5>
|
||||
</CardHeader>
|
||||
<CardContent className="h-full">
|
||||
<DiscountCode cart={{ ...cart }} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{isLocationsShown && (
|
||||
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
||||
<CardHeader className="pb-4">
|
||||
<h5>
|
||||
<Trans i18nKey="cart:locations.title" />
|
||||
</h5>
|
||||
</CardHeader>
|
||||
<CardContent className="h-full">
|
||||
<AnalysisLocation
|
||||
cart={{ ...cart }}
|
||||
synlabAnalyses={synlabAnalyses}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button
|
||||
className="h-10"
|
||||
onClick={initiateSession}
|
||||
disabled={isInitiatingSession}
|
||||
>
|
||||
{isInitiatingSession && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
<Trans i18nKey="cart:checkout.goToCheckout" />
|
||||
</Button>
|
||||
</div>
|
||||
</CartForm>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
56
app/home/(user)/_components/cart/mobile-cart-items.tsx
Normal file
56
app/home/(user)/_components/cart/mobile-cart-items.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { StoreCartLineItem } from '@medusajs/types';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Table, TableBody } from '@kit/ui/shadcn/table';
|
||||
|
||||
import MobileTableRow from './mobile-table-row';
|
||||
|
||||
const MobileCartItems = ({
|
||||
item,
|
||||
currencyCode,
|
||||
productColumnLabelKey,
|
||||
}: {
|
||||
item: StoreCartLineItem;
|
||||
currencyCode: string;
|
||||
productColumnLabelKey: string;
|
||||
}) => {
|
||||
const {
|
||||
i18n: { language, t },
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<Table className="border-separate rounded-lg border p-2">
|
||||
<TableBody>
|
||||
<MobileTableRow
|
||||
title={t(productColumnLabelKey)}
|
||||
value={item.product_title}
|
||||
/>
|
||||
<MobileTableRow title={t('cart:table.time')} value={item.quantity} />
|
||||
<MobileTableRow
|
||||
title={t('cart:table.price')}
|
||||
value={formatCurrency({
|
||||
value: item.unit_price,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.total')}
|
||||
value={
|
||||
item.total &&
|
||||
formatCurrency({
|
||||
value: item.total,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
};
|
||||
|
||||
export default MobileCartItems;
|
||||
@@ -0,0 +1,94 @@
|
||||
import React from 'react';
|
||||
|
||||
import { formatCurrency, formatDateAndTime } from '@/packages/shared/src/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Table, TableBody, TableCell, TableRow } from '@kit/ui/shadcn/table';
|
||||
|
||||
import CartItemDelete from './cart-item-delete';
|
||||
import MobileTableRow from './mobile-table-row';
|
||||
import { EnrichedCartItem } from './types';
|
||||
|
||||
const MobileCartServiceItems = ({
|
||||
item,
|
||||
currencyCode,
|
||||
isUnavailable,
|
||||
productColumnLabelKey,
|
||||
setEditingItem,
|
||||
}: {
|
||||
item: EnrichedCartItem;
|
||||
currencyCode: string;
|
||||
isUnavailable?: boolean;
|
||||
productColumnLabelKey: string;
|
||||
setEditingItem: (item: EnrichedCartItem | null) => void;
|
||||
}) => {
|
||||
const {
|
||||
i18n: { language, t },
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<Table className="border-separate rounded-lg border p-2">
|
||||
<TableBody>
|
||||
<MobileTableRow
|
||||
title={t(productColumnLabelKey)}
|
||||
value={item.product_title}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.time')}
|
||||
value={formatDateAndTime(item.reservation.startTime.toString())}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.location')}
|
||||
value={item.reservation.location?.address ?? '-'}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.quantity')}
|
||||
value={item.quantity}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.price')}
|
||||
value={formatCurrency({
|
||||
value: item.unit_price,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})}
|
||||
/>
|
||||
<MobileTableRow
|
||||
title={t('cart:table.total')}
|
||||
value={
|
||||
item.total &&
|
||||
formatCurrency({
|
||||
value: item.total,
|
||||
currencyCode,
|
||||
locale: language,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<TableRow>
|
||||
<TableCell />
|
||||
<TableCell className="flex w-full items-center justify-end gap-4 p-0 pt-2">
|
||||
<CartItemDelete id={item.id} />
|
||||
<Button type="button" onClick={() => setEditingItem(item)}>
|
||||
<Trans i18nKey="common:change" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
{isUnavailable && (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={8}
|
||||
className="text-destructive px-4 text-left sm:px-6"
|
||||
>
|
||||
<Trans i18nKey="booking:timeSlotUnavailable" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
};
|
||||
|
||||
export default MobileCartServiceItems;
|
||||
21
app/home/(user)/_components/cart/mobile-table-row.tsx
Normal file
21
app/home/(user)/_components/cart/mobile-table-row.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
|
||||
import { TableCell, TableHead, TableRow } from '@kit/ui/shadcn/table';
|
||||
|
||||
const MobleTableRow = ({
|
||||
title,
|
||||
value,
|
||||
}: {
|
||||
title?: string;
|
||||
value?: string | number;
|
||||
}) => (
|
||||
<TableRow>
|
||||
<TableHead className="h-2 font-bold">{title}</TableHead>
|
||||
|
||||
<TableCell className="p-0 text-right">
|
||||
<p className="txt-medium-plus text-ui-fg-base">{value}</p>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
export default MobleTableRow;
|
||||
@@ -1,3 +1,7 @@
|
||||
import { StoreCartLineItem } from '@medusajs/types';
|
||||
|
||||
import { Reservation } from '~/lib/types/reservation';
|
||||
|
||||
export interface MontonioOrderToken {
|
||||
uuid: string;
|
||||
accessKey: string;
|
||||
@@ -20,3 +24,20 @@ export interface MontonioOrderToken {
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
export enum CartItemType {
|
||||
analysisOrders = 'analysisOrders',
|
||||
ttoServices = 'ttoServices',
|
||||
}
|
||||
|
||||
export type EnrichedCartItem = StoreCartLineItem & { reservation: Reservation };
|
||||
|
||||
export type GetBalanceSummarySelection = ({
|
||||
useCompanyBenefits,
|
||||
}: {
|
||||
useCompanyBenefits: boolean;
|
||||
}) => {
|
||||
benefitsAmount: number;
|
||||
benefitsAmountTotal: number;
|
||||
montonioAmount: number;
|
||||
};
|
||||
|
||||
11
app/home/(user)/_components/check-with-background.tsx
Normal file
11
app/home/(user)/_components/check-with-background.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { Check } from 'lucide-react';
|
||||
|
||||
export const CheckWithBackground = () => {
|
||||
return (
|
||||
<div className="bg-primary w-min rounded-full p-1 text-white">
|
||||
<Check className="size-3 stroke-2" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { AnalysisPackageWithVariant } from '@/packages/shared/src/components/select-analysis-package';
|
||||
import { pathsConfig } from '@/packages/shared/src/config';
|
||||
|
||||
import { Spinner } from '@kit/ui/makerkit/spinner';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { toast } from '@kit/ui/shadcn/sonner';
|
||||
import { Table, TableBody, TableCell, TableRow } from '@kit/ui/shadcn/table';
|
||||
|
||||
import { handleAddToCart } from '~/lib/services/medusaCart.service';
|
||||
import { cn } from '~/lib/utils';
|
||||
|
||||
const AddToCartButton = ({
|
||||
onClick,
|
||||
disabled,
|
||||
isLoading,
|
||||
}: {
|
||||
onClick: () => void;
|
||||
disabled: boolean;
|
||||
isLoading: boolean;
|
||||
}) => {
|
||||
return (
|
||||
<TableCell align="center" className="xs:px-2 px-1 py-6">
|
||||
<Button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className="xs:p-6 xs:text-sm relative p-2 text-[10px]"
|
||||
>
|
||||
{isLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={cn({
|
||||
invisible: isLoading,
|
||||
})}
|
||||
>
|
||||
<Trans i18nKey="compare-packages-modal:selectThisPackage" />
|
||||
</div>
|
||||
</Button>
|
||||
</TableCell>
|
||||
);
|
||||
};
|
||||
|
||||
const ComparePackagesAddToCartButtons = ({
|
||||
countryCode,
|
||||
standardPackage,
|
||||
standardPlusPackage,
|
||||
premiumPackage,
|
||||
}: {
|
||||
countryCode: string;
|
||||
standardPackage: AnalysisPackageWithVariant;
|
||||
standardPlusPackage: AnalysisPackageWithVariant;
|
||||
premiumPackage: AnalysisPackageWithVariant;
|
||||
}) => {
|
||||
const [addedPackage, setAddedPackage] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const handleSelect = async ({ variantId }: AnalysisPackageWithVariant) => {
|
||||
setAddedPackage(variantId);
|
||||
try {
|
||||
await handleAddToCart({
|
||||
selectedVariant: { id: variantId },
|
||||
countryCode,
|
||||
});
|
||||
setAddedPackage(null);
|
||||
toast.success(
|
||||
<Trans i18nKey={'order-analysis-package:analysisPackageAddedToCart'} />,
|
||||
);
|
||||
router.push(pathsConfig.app.cart);
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
<Trans
|
||||
i18nKey={'order-analysis-package:analysisPackageAddToCartError'}
|
||||
/>,
|
||||
);
|
||||
setAddedPackage(null);
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell className="w-[30vw] py-6" />
|
||||
<AddToCartButton
|
||||
onClick={() => handleSelect(standardPackage)}
|
||||
disabled={!!addedPackage}
|
||||
isLoading={addedPackage === standardPackage.variantId}
|
||||
/>
|
||||
<AddToCartButton
|
||||
onClick={() => handleSelect(standardPlusPackage)}
|
||||
disabled={!!addedPackage}
|
||||
isLoading={addedPackage === standardPlusPackage.variantId}
|
||||
/>
|
||||
<AddToCartButton
|
||||
onClick={() => handleSelect(premiumPackage)}
|
||||
disabled={!!addedPackage}
|
||||
isLoading={addedPackage === premiumPackage.variantId}
|
||||
/>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
};
|
||||
|
||||
export default ComparePackagesAddToCartButtons;
|
||||
@@ -3,7 +3,7 @@ import { JSX } from 'react';
|
||||
import { StoreProduct } from '@medusajs/types';
|
||||
import { QuestionMarkCircledIcon } from '@radix-ui/react-icons';
|
||||
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
|
||||
import { Check, X } from 'lucide-react';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
import { PackageHeader } from '@kit/shared/components/package-header';
|
||||
import { AnalysisPackageWithVariant } from '@kit/shared/components/select-analysis-package';
|
||||
@@ -26,6 +26,10 @@ import {
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import { CheckWithBackground } from './check-with-background';
|
||||
import ComparePackagesAddToCartButtons from './compare-packages-add-to-cart-buttons';
|
||||
import DefaultPackageFeaturesRows from './default-package-features-rows';
|
||||
|
||||
export type AnalysisPackageElement = Pick<
|
||||
StoreProduct,
|
||||
'title' | 'id' | 'description'
|
||||
@@ -35,14 +39,6 @@ export type AnalysisPackageElement = Pick<
|
||||
isIncludedInPremium: boolean;
|
||||
};
|
||||
|
||||
const CheckWithBackground = () => {
|
||||
return (
|
||||
<div className="bg-primary w-min rounded-full p-1 text-white">
|
||||
<Check className="size-3 stroke-2" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const PackageTableHead = async ({
|
||||
product,
|
||||
}: {
|
||||
@@ -53,7 +49,7 @@ const PackageTableHead = async ({
|
||||
const { title, price, nrOfAnalyses } = product;
|
||||
|
||||
return (
|
||||
<TableHead className="py-2">
|
||||
<TableHead className="xs:content-normal content-start py-2">
|
||||
<PackageHeader
|
||||
title={t(title)}
|
||||
tagColor="bg-cyan"
|
||||
@@ -69,10 +65,12 @@ const ComparePackagesModal = async ({
|
||||
analysisPackages,
|
||||
analysisPackageElements,
|
||||
triggerElement,
|
||||
countryCode,
|
||||
}: {
|
||||
analysisPackages: AnalysisPackageWithVariant[];
|
||||
analysisPackageElements: AnalysisPackageElement[];
|
||||
triggerElement: JSX.Element;
|
||||
countryCode: string;
|
||||
}) => {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
@@ -92,7 +90,7 @@ const ComparePackagesModal = async ({
|
||||
<DialogContent
|
||||
className="min-h-screen max-w-fit min-w-screen"
|
||||
customClose={
|
||||
<div className="inline-flex place-items-center-safe gap-1 align-middle">
|
||||
<div className="absolute top-6 right-0 flex place-items-center-safe sm:top-0">
|
||||
<p className="text-sm font-medium text-black">
|
||||
{t('common:close')}
|
||||
</p>
|
||||
@@ -106,11 +104,13 @@ const ComparePackagesModal = async ({
|
||||
</VisuallyHidden>
|
||||
<div className="m-auto">
|
||||
<div className="space-y-6 text-center">
|
||||
<h3>{t('product:healthPackageComparison.label')}</h3>
|
||||
<p className="text-muted-foreground mx-auto w-3/5 text-sm">
|
||||
<h3 className="sm:text-xxl text-lg">
|
||||
{t('product:healthPackageComparison.label')}
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm sm:mx-auto sm:w-3/5">
|
||||
{t('product:healthPackageComparison.description')}
|
||||
</p>
|
||||
<div className="max-h-[80vh] overflow-y-auto rounded-md border">
|
||||
<div className="max-h-[50vh] overflow-y-auto rounded-md border sm:max-h-[70vh]">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
@@ -121,6 +121,8 @@ const ComparePackagesModal = async ({
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<DefaultPackageFeaturesRows />
|
||||
|
||||
{analysisPackageElements.map(
|
||||
({
|
||||
title,
|
||||
@@ -136,12 +138,14 @@ const ComparePackagesModal = async ({
|
||||
|
||||
return (
|
||||
<TableRow key={id}>
|
||||
<TableCell className="py-6 sm:max-w-[30vw]">
|
||||
<TableCell className="relative py-6 sm:w-[30vw]">
|
||||
{title}{' '}
|
||||
{description && (
|
||||
<InfoTooltip
|
||||
content={description}
|
||||
icon={<QuestionMarkCircledIcon />}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="absolute top-2 right-0 size-5 sm:static sm:ml-2 sm:size-4" />
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
@@ -164,6 +168,12 @@ const ComparePackagesModal = async ({
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
<ComparePackagesAddToCartButtons
|
||||
countryCode={countryCode}
|
||||
standardPackage={standardPackage}
|
||||
premiumPackage={premiumPackage}
|
||||
standardPlusPackage={standardPlusPackage}
|
||||
/>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { ChevronRight, HeartPulse } from 'lucide-react';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
@@ -11,25 +13,27 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@kit/ui/card';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { cn } from '@kit/ui/lib/utils';
|
||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { getAccountBalanceSummary } from '../_lib/server/balance-actions';
|
||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||
|
||||
export default async function DashboardCards() {
|
||||
const { language } = await createI18nServerInstance();
|
||||
|
||||
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
const balanceSummary = account ? await getAccountBalanceSummary(account.id) : null;
|
||||
const balanceSummary = account
|
||||
? await getAccountBalanceSummary(account.id)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'grid grid-cols-1 gap-4',
|
||||
'md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
|
||||
)}>
|
||||
)}
|
||||
>
|
||||
<Card
|
||||
variant="gradient-success"
|
||||
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
||||
@@ -79,7 +83,7 @@ export default async function DashboardCards() {
|
||||
<Trans
|
||||
i18nKey="dashboard:heroCard.benefits.validUntil"
|
||||
values={{ date: '31.12.2025' }}
|
||||
/>
|
||||
/>
|
||||
</CardDescription>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -14,7 +14,10 @@ import {
|
||||
User,
|
||||
} from 'lucide-react';
|
||||
|
||||
import type { AccountWithParams, BmiThresholds } from '@kit/accounts/types/accounts';
|
||||
import type {
|
||||
AccountWithParams,
|
||||
BmiThresholds,
|
||||
} from '@kit/accounts/types/accounts';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { InfoTooltip } from '@/packages/shared/src/components/ui/info-tooltip';
|
||||
import { QuestionMarkCircledIcon } from '@radix-ui/react-icons';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { TableCell, TableRow } from '@kit/ui/shadcn/table';
|
||||
|
||||
import { CheckWithBackground } from './check-with-background';
|
||||
|
||||
const DefaultPackageFeaturesRows = () => {
|
||||
return (
|
||||
<>
|
||||
<TableRow key="digital-doctor-feedback">
|
||||
<TableCell className="relative max-w-[30vw] py-6">
|
||||
<Trans i18nKey="order-analysis-package:digitalDoctorFeedback" />
|
||||
<InfoTooltip
|
||||
content={
|
||||
<Trans i18nKey="order-analysis-package:digitalDoctorFeedbackInfo" />
|
||||
}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="absolute top-2 right-0 size-5 sm:static sm:ml-2 sm:size-4" />
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="center" className="py-6">
|
||||
<CheckWithBackground />
|
||||
</TableCell>
|
||||
<TableCell align="center" className="py-6">
|
||||
<CheckWithBackground />
|
||||
</TableCell>
|
||||
<TableCell align="center" className="py-6">
|
||||
<CheckWithBackground />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<TableRow key="give-analyses">
|
||||
<TableCell className="py-6 sm:max-w-[30vw]">
|
||||
<Trans i18nKey="order-analysis-package:giveAnalyses" />
|
||||
</TableCell>
|
||||
<TableCell align="center" className="py-6">
|
||||
<CheckWithBackground />
|
||||
</TableCell>
|
||||
<TableCell align="center" className="py-6">
|
||||
<CheckWithBackground />
|
||||
</TableCell>
|
||||
<TableCell align="center" className="py-6">
|
||||
<CheckWithBackground />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default DefaultPackageFeaturesRows;
|
||||
@@ -9,12 +9,12 @@ import { ShoppingCart } from 'lucide-react';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { ProfileAccountDropdownContainer } from '@kit/shared/components/personal-account-dropdown-container';
|
||||
import { Search } from '@kit/shared/components/ui/search';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Card } from '@kit/ui/shadcn/card';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { UserNotifications } from '../_components/user-notifications';
|
||||
import { getAccountBalanceSummary } from '../_lib/server/balance-actions';
|
||||
import { type UserWorkspace } from '../_lib/server/load-user-workspace';
|
||||
|
||||
export async function HomeMenuNavigation(props: {
|
||||
@@ -23,13 +23,9 @@ export async function HomeMenuNavigation(props: {
|
||||
}) {
|
||||
const { language } = await createI18nServerInstance();
|
||||
const { workspace, user, accounts } = props.workspace;
|
||||
const totalValue = props.cart?.total
|
||||
? formatCurrency({
|
||||
currencyCode: props.cart.currency_code,
|
||||
locale: language,
|
||||
value: props.cart.total,
|
||||
})
|
||||
: 0;
|
||||
const balanceSummary = workspace?.id
|
||||
? await getAccountBalanceSummary(workspace.id)
|
||||
: null;
|
||||
|
||||
const cartQuantityTotal =
|
||||
props.cart?.items?.reduce((acc, item) => acc + item.quantity, 0) ?? 0;
|
||||
@@ -47,29 +43,32 @@ export async function HomeMenuNavigation(props: {
|
||||
/> */}
|
||||
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
{/* TODO: add wallet functionality
|
||||
<Card className="px-6 py-2">
|
||||
<span>€ {Number(0).toFixed(2).replace('.', ',')}</span>
|
||||
<span>
|
||||
{formatCurrency({
|
||||
value: balanceSummary?.totalBalance || 0,
|
||||
locale: language,
|
||||
currencyCode: 'EUR',
|
||||
})}
|
||||
</span>
|
||||
</Card>
|
||||
*/}
|
||||
{hasCartItems && (
|
||||
<Button
|
||||
className="relative mr-0 h-10 cursor-pointer border-1 px-4 py-2"
|
||||
variant="ghost"
|
||||
>
|
||||
<span className="flex items-center text-nowrap">{totalValue}</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Link href={pathsConfig.app.cart}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="relative mr-0 h-10 cursor-pointer border-1 px-4 py-2"
|
||||
>
|
||||
<ShoppingCart className="stroke-[1.5px]" />
|
||||
<Trans
|
||||
i18nKey="common:shoppingCartCount"
|
||||
values={{ count: cartQuantityTotal }}
|
||||
/>
|
||||
<Trans i18nKey="common:shoppingCart" />{' '}
|
||||
{hasCartItems && (
|
||||
<>
|
||||
(
|
||||
<span className="text-success font-bold">
|
||||
{cartQuantityTotal}
|
||||
</span>
|
||||
)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</Link>
|
||||
<UserNotifications userId={user.id} />
|
||||
|
||||
@@ -25,16 +25,22 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@kit/ui/dropdown-menu';
|
||||
import { If } from '@kit/ui/if';
|
||||
import { cn } from '@kit/ui/shadcn';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@kit/ui/shadcn/avatar';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
// home imports
|
||||
import type { UserWorkspace } from '../_lib/server/load-user-workspace';
|
||||
import { UserNotifications } from './user-notifications';
|
||||
|
||||
const PERSONAL_ACCOUNT_SLUG = 'personal';
|
||||
|
||||
export function HomeMobileNavigation(props: {
|
||||
workspace: UserWorkspace;
|
||||
cart: StoreCart | null;
|
||||
}) {
|
||||
const user = props.workspace.user;
|
||||
const { user, accounts } = props.workspace;
|
||||
|
||||
const signOut = useSignOut();
|
||||
const { data: personalAccountData } = usePersonalAccountData(user.id);
|
||||
@@ -76,8 +82,8 @@ export function HomeMobileNavigation(props: {
|
||||
const hasDoctorRole =
|
||||
personalAccountData?.application_role === ApplicationRoleEnum.Doctor;
|
||||
|
||||
return hasDoctorRole && hasTotpFactor;
|
||||
}, [user, personalAccountData, hasTotpFactor]);
|
||||
return hasDoctorRole;
|
||||
}, [personalAccountData]);
|
||||
|
||||
const cartQuantityTotal =
|
||||
props.cart?.items?.reduce((acc, item) => acc + item.quantity, 0) ?? 0;
|
||||
@@ -85,10 +91,31 @@ export function HomeMobileNavigation(props: {
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger>
|
||||
<Menu className={'h-9'} />
|
||||
</DropdownMenuTrigger>
|
||||
<div className="flex justify-between gap-3">
|
||||
<Link href={pathsConfig.app.cart}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="relative mr-0 h-10 cursor-pointer border-1 px-4 py-2"
|
||||
>
|
||||
<ShoppingCart className="stroke-[1.5px]" />
|
||||
{hasCartItems && (
|
||||
<>
|
||||
(
|
||||
<span className="text-success font-bold">
|
||||
{cartQuantityTotal}
|
||||
</span>
|
||||
)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</Link>
|
||||
|
||||
<UserNotifications userId={user.id} />
|
||||
|
||||
<DropdownMenuTrigger>
|
||||
<Menu className="h-6 w-6" />
|
||||
</DropdownMenuTrigger>
|
||||
</div>
|
||||
<DropdownMenuContent sideOffset={10} className={'w-screen rounded-none'}>
|
||||
<If condition={props.cart && hasCartItems}>
|
||||
<DropdownMenuGroup>
|
||||
@@ -148,6 +175,46 @@ export function HomeMobileNavigation(props: {
|
||||
</If>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<If condition={accounts.length > 0}>
|
||||
<span className="text-muted-foreground px-2 text-xs">
|
||||
<Trans
|
||||
i18nKey={'teams:yourTeams'}
|
||||
values={{ teamsCount: accounts.length }}
|
||||
/>
|
||||
</span>
|
||||
|
||||
{accounts.map((account) => (
|
||||
<DropdownMenuItem key={account.value} asChild>
|
||||
<Link
|
||||
className={'s-full flex cursor-pointer items-center space-x-2'}
|
||||
href={`${pathsConfig.app.home}/${account.value}`}
|
||||
>
|
||||
<div className={'flex items-center'}>
|
||||
<Avatar className={'h-5 w-5 rounded-xs ' + account.image}>
|
||||
<AvatarImage
|
||||
{...(account.image && { src: account.image })}
|
||||
/>
|
||||
|
||||
<AvatarFallback
|
||||
className={cn('rounded-md', {
|
||||
['bg-background']:
|
||||
PERSONAL_ACCOUNT_SLUG === account.value,
|
||||
['group-hover:bg-background']:
|
||||
PERSONAL_ACCOUNT_SLUG !== account.value,
|
||||
})}
|
||||
>
|
||||
{account.label ? account.label[0] : ''}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<span className={'pl-3'}>{account.label}</span>
|
||||
</div>
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
</If>
|
||||
|
||||
<SignOutDropdownItem onSignOut={() => signOut.mutateAsync()} />
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -57,73 +57,64 @@ export default function OrderAnalysesCards({
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="xs:grid-cols-3 mt-4 grid gap-6">
|
||||
{analyses.map(({ title, variant, description, subtitle, price }) => {
|
||||
const formattedPrice =
|
||||
typeof price === 'number'
|
||||
? formatCurrency({
|
||||
currencyCode: 'eur',
|
||||
locale: language,
|
||||
value: price,
|
||||
})
|
||||
: null;
|
||||
return (
|
||||
<Card
|
||||
key={title}
|
||||
variant="gradient-success"
|
||||
className="flex flex-col justify-between"
|
||||
>
|
||||
<CardHeader className="flex-row">
|
||||
<div
|
||||
className={
|
||||
'bg-primary/10 mb-6 flex size-8 items-center-safe justify-center-safe rounded-full text-white'
|
||||
}
|
||||
>
|
||||
<HeartPulse className="size-4 fill-green-500" />
|
||||
</div>
|
||||
<div className="bg-warning ml-auto flex size-8 items-center-safe justify-center-safe rounded-full text-white">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
className="px-2 text-black"
|
||||
onClick={() => handleSelect(variant.id)}
|
||||
>
|
||||
{variantAddingToCart === variant.id ? (
|
||||
<Loader2 className="size-4 animate-spin stroke-2" />
|
||||
) : (
|
||||
<ShoppingCart className="size-4 stroke-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex gap-2">
|
||||
<div className="flex flex-1 flex-col items-start gap-2">
|
||||
<h5>
|
||||
{title}
|
||||
{description && (
|
||||
<>
|
||||
{' '}
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="flex flex-col gap-2">
|
||||
<span>{formattedPrice}</span>
|
||||
<span>{description}</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</h5>
|
||||
{subtitle && <CardDescription>{subtitle}</CardDescription>}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-2 self-end text-sm">
|
||||
<span>{formattedPrice}</span>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
return analyses.map(({ title, variant, description, subtitle, price }) => {
|
||||
const formattedPrice =
|
||||
typeof price === 'number'
|
||||
? formatCurrency({
|
||||
currencyCode: 'eur',
|
||||
locale: language,
|
||||
value: price,
|
||||
})
|
||||
: null;
|
||||
return (
|
||||
<Card
|
||||
key={title}
|
||||
variant="gradient-success"
|
||||
className="flex flex-col justify-between"
|
||||
>
|
||||
<CardHeader className="flex-row">
|
||||
<div className="bg-primary/10 mb-6 flex size-8 items-center-safe justify-center-safe rounded-full text-white">
|
||||
<HeartPulse className="size-4 fill-green-500" />
|
||||
</div>
|
||||
<div className="bg-warning ml-auto flex size-8 items-center-safe justify-center-safe rounded-full text-white">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
className="px-2 text-black"
|
||||
onClick={() => handleSelect(variant.id)}
|
||||
>
|
||||
{variantAddingToCart === variant.id ? (
|
||||
<Loader2 className="size-4 animate-spin stroke-2" />
|
||||
) : (
|
||||
<ShoppingCart className="size-4 stroke-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardFooter className="flex gap-2">
|
||||
<div className="flex flex-1 flex-col items-start gap-2">
|
||||
<h5>
|
||||
{title}
|
||||
{description && (
|
||||
<>
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="flex flex-col gap-2">
|
||||
<span>{formattedPrice}</span>
|
||||
<span>{description}</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</h5>
|
||||
{subtitle && <CardDescription>{subtitle}</CardDescription>}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-2 self-end text-sm">
|
||||
<span>{formattedPrice}</span>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user