Compare commits
208 Commits
keycloak2
...
a68f7c7ab5
| Author | SHA1 | Date | |
|---|---|---|---|
| a68f7c7ab5 | |||
| 92dd792121 | |||
| eb6ef2abe1 | |||
| 428cbd9477 | |||
| 0aa16c457a | |||
| 1aeee0bc30 | |||
| fdc2e3e064 | |||
| beeea33842 | |||
| 4ed3924907 | |||
| db38e602aa | |||
| 56f84a003c | |||
| 579ec7547e | |||
| f091ed5b49 | |||
| fc63b9e7b7 | |||
| 07237dece6 | |||
| 7830b92571 | |||
| ddd1728e4e | |||
| 4b44ead3ff | |||
| f1eb0e1ebf | |||
| fb03d548af | |||
| 8af2c8710f | |||
| 3212b52b02 | |||
| f0853409c8 | |||
| e92120654b | |||
|
|
2f22b6c88f | ||
|
|
40b7a98c57 | ||
| cd3d2586f7 | |||
|
|
8794bf998c | ||
| edba074b38 | |||
|
|
6492421c0d | ||
|
|
e6ccb85c34 | ||
|
|
df850cf1b2 | ||
|
|
4afc498cd7 | ||
|
|
4962ba8ec2 | ||
| 4b4a7097ae | |||
|
|
258e18e6a6 | ||
|
|
e3adae69bd | ||
|
|
1fdbaf1bd5 | ||
|
|
63ede85668 | ||
|
|
3dd82902fe | ||
|
|
f47a9e75e2 | ||
|
|
428a1dfb87 | ||
|
|
fee8534fcc | ||
|
|
643e67e2a1 | ||
|
|
5f0ca6bdae | ||
|
|
a52a9bec06 | ||
|
|
9ed52dcf02 | ||
|
|
0c2cfe6d18 | ||
|
|
efa94b3322 | ||
|
|
c6c0fe0a09 | ||
|
|
78221c4267 | ||
|
|
addd3a5dae | ||
| d86495d7f7 | |||
| ffd8cc1b3f | |||
| 71a9ff75c4 | |||
| afdaebc804 | |||
| 47bbeeb155 | |||
| 091144d942 | |||
| e7b484e1d4 | |||
| 81f7a03388 | |||
| c37706f6a9 | |||
| 08b27b022f | |||
| 2bdd54e649 | |||
| 54209553ec | |||
| d99016aa5e | |||
|
|
1b634f9736 | ||
|
|
b96ef47b2d | ||
|
|
cb32ee5339 | ||
|
|
f7f0e5e48f | ||
| a243bd4769 | |||
| 924e89c714 | |||
| be6e3b6960 | |||
| 8a7d88d645 | |||
| 5c4831c5af | |||
| 4302ddb90e | |||
| 64acdfcbbb | |||
| bfadf56173 | |||
| 2019c2c1fc | |||
| ecc8c2b982 | |||
| b729ad9ffa | |||
| 4560d2df1d | |||
| 4ac261fd0d | |||
| e7650e3c32 | |||
| afac628bcf | |||
| 20a497938e | |||
| 7870b8840a | |||
| e5822fd55d | |||
| c51808d899 | |||
| 46774b286e | |||
| 7af6aa438e | |||
| cee37178df | |||
| 000cad7f05 | |||
| 0d08592a9a | |||
| 19631fb2db | |||
| a788e8b587 | |||
| 33a6c92841 | |||
| a229ab4d31 | |||
| eda21b8a99 | |||
| 16b4589330 | |||
| 7e9e1ce3a0 | |||
|
|
14252c3efd | ||
|
|
cbdcc061d5 | ||
|
|
0b7829be8b | ||
|
|
74edc6c679 | ||
| 3525a5ccd2 | |||
| 781a21aef4 | |||
| 74c176912b | |||
|
|
99e62b91a5 | ||
|
|
b31de91daf | ||
|
|
0e7e0b0ed6 | ||
|
|
da6acd8756 | ||
| 745ba874b6 | |||
| e324d6c5d1 | |||
| 6b1f93c317 | |||
| 96f82444a7 | |||
| 0328e518b6 | |||
| 0c764f82e5 | |||
| 4f99e32009 | |||
| e0adc2fb68 | |||
| 76433684e7 | |||
| 8b3e58e833 | |||
| b8a8eab87c | |||
| fa0bbe64fb | |||
| e3cdba6a7c | |||
| 312027b9ed | |||
| 2aad0329f3 | |||
| 229b3d7c27 | |||
| cb11244d79 | |||
| fa9895637d | |||
| 0aea6b80d4 | |||
| be33b892f5 | |||
| 7bc89f7c22 | |||
| 95452de88b | |||
| 9f9508233d | |||
|
|
478eef3681 | ||
| 831e60c3c1 | |||
|
|
86a5931b66 | ||
| 0f16c6552f | |||
| 165d44b13f | |||
| 7d208b41f2 | |||
|
|
ebab0556ba | ||
|
|
514cb3bf7b | ||
| 0281298b0c | |||
| 85c72e777b | |||
|
|
1283094a91 | ||
|
|
ca13e9e30a | ||
| d00449da29 | |||
| c0e9cf5e25 | |||
| fd94320295 | |||
| 596d0e9eee | |||
| 1d641211b6 | |||
| 06154f24bf | |||
| f00899c456 | |||
| c2896d77b0 | |||
| 353e5c3c4b | |||
| 3bdc1cfefc | |||
| 5b91ece1ec | |||
| 0e063cd5dc | |||
| 2c63875806 | |||
| 0081e8948b | |||
| ccdfd5872b | |||
| 321c85bc9c | |||
| aa441d4055 | |||
| c882a24415 | |||
| 077aaee181 | |||
| 57a998d215 | |||
| f01829de96 | |||
| 7815a1c011 | |||
| 96eea95fb9 | |||
| 6495d1c4a3 | |||
| a9612ad992 | |||
| ab2176bc69 | |||
| a89d8d3153 | |||
| 1b29cb222b | |||
| dfcfdb8f97 | |||
| d87d08aaea | |||
| c83694222d | |||
| c08fe26b36 | |||
| d3202a2cb2 | |||
| 2435e6f113 | |||
| 54856b0e45 | |||
| 95e72bb3f8 | |||
| 3d268b6061 | |||
| 5c6280ec42 | |||
| 0de9dcf7e3 | |||
| f3a6fb627c | |||
| c1746c6c20 | |||
| c6f56f6e11 | |||
| a6b246cdf3 | |||
| a705dea9cf | |||
| 8485d2e9a3 | |||
| c356f69656 | |||
| cacd23be40 | |||
| f8765dce49 | |||
| 42bebb6d93 | |||
| 354a0c04ee | |||
| 72bb9a33ef | |||
| 771c28f8ef | |||
|
|
e9497c3d52 | ||
| 70188f297f | |||
| e0940a1600 | |||
| 65eb6c780d | |||
| 6e9cde6b95 | |||
| 3a062eaa9c | |||
| c07acb85a2 | |||
| 1de564b917 | |||
| a2c080914a | |||
|
|
94dd00b9ca |
8
.env
8
.env
@@ -13,7 +13,7 @@ NEXT_PUBLIC_THEME_COLOR="#ffffff"
|
|||||||
NEXT_PUBLIC_THEME_COLOR_DARK="#0a0a0a"
|
NEXT_PUBLIC_THEME_COLOR_DARK="#0a0a0a"
|
||||||
|
|
||||||
# AUTH
|
# AUTH
|
||||||
NEXT_PUBLIC_AUTH_PASSWORD=true
|
NEXT_PUBLIC_AUTH_PASSWORD=false
|
||||||
NEXT_PUBLIC_AUTH_MAGIC_LINK=false
|
NEXT_PUBLIC_AUTH_MAGIC_LINK=false
|
||||||
NEXT_PUBLIC_CAPTCHA_SITE_KEY=
|
NEXT_PUBLIC_CAPTCHA_SITE_KEY=
|
||||||
|
|
||||||
@@ -65,3 +65,9 @@ NEXT_PUBLIC_TEAM_NAVIGATION_STYLE=custom
|
|||||||
NEXT_PUBLIC_USER_NAVIGATION_STYLE=custom
|
NEXT_PUBLIC_USER_NAVIGATION_STYLE=custom
|
||||||
|
|
||||||
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
|
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
|
||||||
|
|
||||||
|
# Configure Medusa password secret for Keycloak users
|
||||||
|
MEDUSA_PASSWORD_SECRET=ODEwMGNiMmUtOGMxYS0xMWYwLWJlZDYtYTM3YzYyMWY0NGEzCg==
|
||||||
|
|
||||||
|
# False by default
|
||||||
|
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=false
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
# SITE
|
# SITE
|
||||||
NEXT_PUBLIC_SITE_URL=http://localhost:3000
|
NEXT_PUBLIC_SITE_URL=http://localhost:3000
|
||||||
|
NEXT_PUBLIC_AUTH_PASSWORD=true
|
||||||
|
|
||||||
# SUPABASE DEVELOPMENT
|
# SUPABASE DEVELOPMENT
|
||||||
|
|
||||||
@@ -25,6 +26,22 @@ EMAIL_PORT=1025 # or 465 for SSL
|
|||||||
EMAIL_TLS=false
|
EMAIL_TLS=false
|
||||||
NODE_TLS_REJECT_UNAUTHORIZED=0
|
NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||||
|
|
||||||
|
# MEDIPOST
|
||||||
|
|
||||||
|
MEDIPOST_URL=https://meditest.medisoft.ee:7443/Medipost/MedipostServlet
|
||||||
|
MEDIPOST_USER=trvurgtst
|
||||||
|
MEDIPOST_PASSWORD=SRB48HZMV
|
||||||
|
MEDIPOST_RECIPIENT=trvurgtst
|
||||||
|
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
||||||
|
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
||||||
|
|
||||||
|
#MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
||||||
|
#MEDIPOST_USER=medreport
|
||||||
|
#MEDIPOST_PASSWORD=
|
||||||
|
#MEDIPOST_RECIPIENT=HTI
|
||||||
|
#MEDIPOST_MESSAGE_SENDER=medreport
|
||||||
|
#MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=false
|
||||||
|
|
||||||
# MEDUSA
|
# MEDUSA
|
||||||
MEDUSA_BACKEND_URL=http://localhost:9000
|
MEDUSA_BACKEND_URL=http://localhost:9000
|
||||||
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
||||||
|
|||||||
@@ -6,10 +6,10 @@
|
|||||||
## PUBLIC KEYS OR CONFIGURATION ARE OKAY TO BE PLACED HERE.
|
## PUBLIC KEYS OR CONFIGURATION ARE OKAY TO BE PLACED HERE.
|
||||||
|
|
||||||
# SUPABASE
|
# SUPABASE
|
||||||
NEXT_PUBLIC_SUPABASE_URL=https://oqsdacktkhmbylmzstjq.supabase.co
|
# NEXT_PUBLIC_SUPABASE_URL=https://oqsdacktkhmbylmzstjq.supabase.co
|
||||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDY1MjgxMjMsImV4cCI6MjA2MjEwNDEyM30.LdHCTWxijFmhXdnT9KVuLRAVbtSwY7OO-oLtpd8GmO0
|
# NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDY1MjgxMjMsImV4cCI6MjA2MjEwNDEyM30.LdHCTWxijFmhXdnT9KVuLRAVbtSwY7OO-oLtpd8GmO0
|
||||||
|
|
||||||
NEXT_PUBLIC_SITE_URL=https://test.medreport.ee
|
# NEXT_PUBLIC_SITE_URL=https://test.medreport.ee
|
||||||
|
|
||||||
# MONTONIO
|
# # MONTONIO
|
||||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
# NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||||
|
|||||||
10
.env.staging
10
.env.staging
@@ -6,10 +6,10 @@
|
|||||||
## PUBLIC KEYS OR CONFIGURATION ARE OKAY TO BE PLACED HERE.
|
## PUBLIC KEYS OR CONFIGURATION ARE OKAY TO BE PLACED HERE.
|
||||||
|
|
||||||
# SUPABASE
|
# SUPABASE
|
||||||
NEXT_PUBLIC_SUPABASE_URL=https://kaldvociniytdbbcxvqk.supabase.co
|
# NEXT_PUBLIC_SUPABASE_URL=https://klocrucggryikaxzvxgc.supabase.co
|
||||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImthbGR2b2Npbml5dGRiYmN4dnFrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTYzNjQ5OTYsImV4cCI6MjA3MTk0MDk5Nn0.eixihH2KGkJZolY9FiQDicJOo2kxvXrSe6gGUCrkLo0
|
# NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imtsb2NydWNnZ3J5aWtheHp2eGdjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTY5ODQ2MjgsImV4cCI6MjA3MjU2MDYyOH0.2XOQngowcymiSUZO_XEEWAWzco2uRIjwG7TAeRRLIdU
|
||||||
|
|
||||||
NEXT_PUBLIC_SITE_URL=https://test.medreport.ee
|
# NEXT_PUBLIC_SITE_URL=https://test.medreport.ee
|
||||||
|
|
||||||
# MONTONIO
|
# # MONTONIO
|
||||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
# NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||||
|
|||||||
1
.npmrc
1
.npmrc
@@ -3,6 +3,7 @@ dedupe-peer-dependents=true
|
|||||||
use-lockfile-v6=true
|
use-lockfile-v6=true
|
||||||
resolution-mode=highest
|
resolution-mode=highest
|
||||||
package-manager-strict=true
|
package-manager-strict=true
|
||||||
|
ignore-workspace-root-check=true
|
||||||
public-hoist-pattern[]=*i18next*
|
public-hoist-pattern[]=*i18next*
|
||||||
public-hoist-pattern[]=*eslint*
|
public-hoist-pattern[]=*eslint*
|
||||||
public-hoist-pattern[]=*prettier*
|
public-hoist-pattern[]=*prettier*
|
||||||
|
|||||||
16
Dockerfile
16
Dockerfile
@@ -22,12 +22,12 @@ COPY . .
|
|||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
RUN set -a \
|
RUN set -a \
|
||||||
&& . .env \
|
&& . .env \
|
||||||
&& . .env.production \
|
&& . .env.production \
|
||||||
&& . .env.staging \
|
&& . .env.staging \
|
||||||
&& set +a \
|
&& set +a \
|
||||||
&& node check-env.js \
|
&& node check-env.js \
|
||||||
&& pnpm build
|
&& pnpm build
|
||||||
|
|
||||||
|
|
||||||
# --- Stage 2: Runtime ---
|
# --- Stage 2: Runtime ---
|
||||||
@@ -41,13 +41,13 @@ COPY --from=builder /app ./
|
|||||||
RUN cp ".env.${APP_ENV}" .env.local
|
RUN cp ".env.${APP_ENV}" .env.local
|
||||||
|
|
||||||
RUN npm install -g pnpm@9 \
|
RUN npm install -g pnpm@9 \
|
||||||
&& pnpm install --prod --frozen-lockfile
|
&& pnpm install --prod --frozen-lockfile
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
# 🔍 Optional: Log key envs for debug
|
# 🔍 Optional: Log key envs for debug
|
||||||
RUN echo "📄 .env contents:" && cat .env.local \
|
RUN echo "📄 .env contents:" && cat .env.local \
|
||||||
&& echo "🔧 Current ENV available to Next.js build:" && printenv | grep -E 'SUPABASE|STRIPE|NEXT|NODE_ENV' || true
|
&& echo "🔧 Current ENV available to Next.js build:" && printenv | grep -E 'SUPABASE|STRIPE|NEXT|NODE_ENV' || true
|
||||||
|
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|||||||
12
README.md
12
README.md
@@ -47,6 +47,18 @@ if you get missing dependency error do `pnpm i --force`
|
|||||||
pnpm add <pacakge-name> -w
|
pnpm add <pacakge-name> -w
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Eslint and prettier
|
||||||
|
|
||||||
|
To clean code run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run lint:fix
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prettier:fix
|
||||||
|
```
|
||||||
|
|
||||||
## Supabase
|
## Supabase
|
||||||
|
|
||||||
Start supabase in docker
|
Start supabase in docker
|
||||||
|
|||||||
44
__mocks__/isikukood.ts
Normal file
44
__mocks__/isikukood.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
// Mock for isikukood library to avoid ES module issues in tests
|
||||||
|
|
||||||
|
export enum Gender {
|
||||||
|
MALE = 'male',
|
||||||
|
FEMALE = 'female',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Isikukood {
|
||||||
|
private code: string;
|
||||||
|
|
||||||
|
constructor(code: string) {
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
static validate(code: string): boolean {
|
||||||
|
return true; // Mock always returns true for tests
|
||||||
|
}
|
||||||
|
|
||||||
|
static generate(options?: { gender?: Gender; century?: number }): string {
|
||||||
|
return '39001010002'; // Mock Estonian ID code
|
||||||
|
}
|
||||||
|
|
||||||
|
isValid(): boolean {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
getGender(): Gender {
|
||||||
|
return Gender.MALE;
|
||||||
|
}
|
||||||
|
|
||||||
|
getBirthDate(): Date {
|
||||||
|
return new Date('1990-01-01');
|
||||||
|
}
|
||||||
|
|
||||||
|
getAge(): number {
|
||||||
|
return 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
getCentury(): number {
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Isikukood };
|
||||||
3
__mocks__/server-only.ts
Normal file
3
__mocks__/server-only.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
// Mock for server-only to avoid Next.js server component issues in tests
|
||||||
|
// This module does nothing in tests - it's just a marker for Next.js
|
||||||
|
export {};
|
||||||
@@ -2,7 +2,6 @@ import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
|
|||||||
@@ -7,17 +7,14 @@ import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace
|
|||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
|
||||||
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
||||||
|
import { featureFlagsConfig, pathsConfig } from '@kit/shared/config';
|
||||||
|
import { useAuthConfig } from '@kit/shared/hooks';
|
||||||
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
|
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
|
||||||
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
|
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { If } from '@kit/ui/if';
|
import { If } from '@kit/ui/if';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { featureFlagsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
|
|
||||||
const ModeToggle = dynamic(() =>
|
const ModeToggle = dynamic(() =>
|
||||||
import('@kit/ui/mode-toggle').then((mod) => ({
|
import('@kit/ui/mode-toggle').then((mod) => ({
|
||||||
default: mod.ModeToggle,
|
default: mod.ModeToggle,
|
||||||
@@ -60,6 +57,8 @@ export function SiteHeaderAccountSection({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function AuthButtons() {
|
function AuthButtons() {
|
||||||
|
const { config } = useAuthConfig();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={'animate-in fade-in flex gap-x-2.5 duration-500'}>
|
<div className={'animate-in fade-in flex gap-x-2.5 duration-500'}>
|
||||||
<div className={'hidden md:flex'}>
|
<div className={'hidden md:flex'}>
|
||||||
@@ -68,19 +67,25 @@ function AuthButtons() {
|
|||||||
</If>
|
</If>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={'flex gap-x-2.5'}>
|
{config && (
|
||||||
<Button className={'block'} asChild variant={'ghost'}>
|
<div className={'flex gap-x-2.5'}>
|
||||||
<Link href={pathsConfig.auth.signIn}>
|
{(config.providers.password || config.providers.oAuth.length > 0) && (
|
||||||
<Trans i18nKey={'auth:signIn'} />
|
<Button className={'block'} asChild variant={'ghost'}>
|
||||||
</Link>
|
<Link href={pathsConfig.auth.signIn}>
|
||||||
</Button>
|
<Trans i18nKey={'auth:signIn'} />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
<Button asChild className="text-xs md:text-sm" variant={'default'}>
|
{config.providers.password && (
|
||||||
<Link href={pathsConfig.auth.signUp}>
|
<Button asChild className="text-xs md:text-sm" variant={'default'}>
|
||||||
<Trans i18nKey={'auth:signUp'} />
|
<Link href={pathsConfig.auth.signUp}>
|
||||||
</Link>
|
<Trans i18nKey={'auth:signUp'} />
|
||||||
</Button>
|
</Link>
|
||||||
</div>
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace';
|
import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace';
|
||||||
|
|
||||||
import { Header } from '@kit/ui/marketing';
|
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
import { Header } from '@kit/ui/marketing';
|
||||||
|
|
||||||
import { SiteHeaderAccountSection } from './site-header-account-section';
|
import { SiteHeaderAccountSection } from './site-header-account-section';
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import { createCmsClient } from '@kit/cms';
|
|||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
import { Post } from '../../blog/_components/post';
|
import { Post } from '../../blog/_components/post';
|
||||||
|
|
||||||
interface BlogPageProps {
|
interface BlogPageProps {
|
||||||
|
|||||||
@@ -11,14 +11,16 @@ const contactEmail = z
|
|||||||
.string({
|
.string({
|
||||||
error:
|
error:
|
||||||
'Contact email is required. Please use the environment variable CONTACT_EMAIL.',
|
'Contact email is required. Please use the environment variable CONTACT_EMAIL.',
|
||||||
}).describe(`The email where you want to receive the contact form submissions.`)
|
})
|
||||||
|
.describe(`The email where you want to receive the contact form submissions.`)
|
||||||
.parse(process.env.CONTACT_EMAIL);
|
.parse(process.env.CONTACT_EMAIL);
|
||||||
|
|
||||||
const emailFrom = z
|
const emailFrom = z
|
||||||
.string({
|
.string({
|
||||||
error:
|
error:
|
||||||
'Sender email is required. Please use the environment variable EMAIL_SENDER.',
|
'Sender email is required. Please use the environment variable EMAIL_SENDER.',
|
||||||
}).describe(`The email sending address.`)
|
})
|
||||||
|
.describe(`The email sending address.`)
|
||||||
.parse(process.env.EMAIL_SENDER);
|
.parse(process.env.EMAIL_SENDER);
|
||||||
|
|
||||||
export const sendContactEmail = enhanceAction(
|
export const sendContactEmail = enhanceAction(
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { ContactForm } from '~/(marketing)/contact/_components/contact-form';
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ import { use } from 'react';
|
|||||||
|
|
||||||
import { SiteFooter } from '~/(marketing)/_components/site-footer';
|
import { SiteFooter } from '~/(marketing)/_components/site-footer';
|
||||||
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
|
||||||
|
|
||||||
import { loadCurrentUserAccounts } from '~/home/(user)/_lib/server/load-accounts';
|
import { loadCurrentUserAccounts } from '~/home/(user)/_lib/server/load-accounts';
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
function SiteLayout(props: React.PropsWithChildren) {
|
function SiteLayout(props: React.PropsWithChildren) {
|
||||||
const accounts = use(loadCurrentUserAccounts());
|
const accounts = use(loadCurrentUserAccounts());
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
|
||||||
import { ArrowRightIcon } from 'lucide-react';
|
import { ArrowRightIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { CtaButton, Hero } from '@kit/ui/marketing';
|
import { CtaButton, Hero } from '@kit/ui/marketing';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
@@ -32,7 +33,7 @@ function MainCallToActionButton() {
|
|||||||
return (
|
return (
|
||||||
<div className={'flex space-x-4'}>
|
<div className={'flex space-x-4'}>
|
||||||
<CtaButton>
|
<CtaButton>
|
||||||
<Link href={'/auth/sign-up'}>
|
<Link href={pathsConfig.auth.signUp}>
|
||||||
<span className={'flex items-center space-x-0.5'}>
|
<span className={'flex items-center space-x-0.5'}>
|
||||||
<span>
|
<span>
|
||||||
<Trans i18nKey={'common:getStarted'} />
|
<Trans i18nKey={'common:getStarted'} />
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
import CompanyOfferForm from './_components/company-offer-form';
|
import CompanyOfferForm from './_components/company-offer-form';
|
||||||
|
|
||||||
function CompanyOffer() {
|
function CompanyOffer() {
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
function SiteLayout(props: React.PropsWithChildren) {
|
function SiteLayout(props: React.PropsWithChildren) {
|
||||||
return (
|
return (
|
||||||
<div className={'flex min-h-[100vh] flex-col justify-center items-center'}>
|
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
||||||
{props.children}
|
{props.children}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
27
app/admin/_components/admin-menu-navigation.tsx
Normal file
27
app/admin/_components/admin-menu-navigation.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
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;
|
||||||
|
}) {
|
||||||
|
const { accounts } = props.workspace;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={'flex w-full flex-1 items-center justify-between gap-3'}>
|
||||||
|
<div className={`flex items-center ${SIDEBAR_WIDTH_PROPERTY}`}>
|
||||||
|
<AppLogo href={'/admin'} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-3">
|
||||||
|
<div>
|
||||||
|
<ProfileAccountDropdownContainer
|
||||||
|
accounts={accounts}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,73 +1,25 @@
|
|||||||
'use client';
|
import { adminNavigationConfig } from '@kit/shared/config';
|
||||||
|
|
||||||
import Link from 'next/link';
|
|
||||||
import { usePathname } from 'next/navigation';
|
|
||||||
|
|
||||||
import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace';
|
|
||||||
import { LayoutDashboard, Users } from 'lucide-react';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Sidebar,
|
Sidebar,
|
||||||
SidebarContent,
|
SidebarContent,
|
||||||
SidebarFooter,
|
|
||||||
SidebarGroup,
|
|
||||||
SidebarGroupContent,
|
|
||||||
SidebarGroupLabel,
|
|
||||||
SidebarHeader,
|
SidebarHeader,
|
||||||
SidebarMenu,
|
SidebarNavigation,
|
||||||
SidebarMenuButton,
|
|
||||||
useSidebar,
|
|
||||||
} from '@kit/ui/shadcn-sidebar';
|
} from '@kit/ui/shadcn-sidebar';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
export function AdminSidebar() {
|
||||||
import { ProfileAccountDropdownContainer } from '@kit/shared/components/personal-account-dropdown-container';
|
const collapsible = adminNavigationConfig.sidebarCollapsedStyle;
|
||||||
|
|
||||||
export function AdminSidebar({
|
|
||||||
accounts,
|
|
||||||
}: {
|
|
||||||
accounts: UserWorkspace['accounts'];
|
|
||||||
}) {
|
|
||||||
const path = usePathname();
|
|
||||||
const { open } = useSidebar();
|
|
||||||
return (
|
return (
|
||||||
<Sidebar collapsible="icon">
|
<Sidebar collapsible={collapsible}>
|
||||||
<SidebarHeader className={'m-2'}>
|
<SidebarHeader className="h-24 justify-center">
|
||||||
<AppLogo href={'/admin'} className="max-w-full" compact={!open} />
|
<div className="mt-24 flex items-center">
|
||||||
|
<h5>Superadmin</h5>
|
||||||
|
</div>
|
||||||
</SidebarHeader>
|
</SidebarHeader>
|
||||||
|
|
||||||
<SidebarContent>
|
<SidebarContent>
|
||||||
<SidebarGroup>
|
<SidebarNavigation config={adminNavigationConfig} />
|
||||||
<SidebarGroupLabel>Super Admin</SidebarGroupLabel>
|
|
||||||
|
|
||||||
<SidebarGroupContent>
|
|
||||||
<SidebarMenu>
|
|
||||||
<SidebarMenuButton isActive={path === '/admin'} asChild>
|
|
||||||
<Link className={'flex gap-2.5'} href={'/admin'}>
|
|
||||||
<LayoutDashboard className={'h-4'} />
|
|
||||||
<span>Dashboard</span>
|
|
||||||
</Link>
|
|
||||||
</SidebarMenuButton>
|
|
||||||
|
|
||||||
<SidebarMenuButton
|
|
||||||
isActive={path.includes('/admin/accounts')}
|
|
||||||
asChild
|
|
||||||
>
|
|
||||||
<Link
|
|
||||||
className={'flex size-full gap-2.5'}
|
|
||||||
href={'/admin/accounts'}
|
|
||||||
>
|
|
||||||
<Users className={'h-4'} />
|
|
||||||
<span>Accounts</span>
|
|
||||||
</Link>
|
|
||||||
</SidebarMenuButton>
|
|
||||||
</SidebarMenu>
|
|
||||||
</SidebarGroupContent>
|
|
||||||
</SidebarGroup>
|
|
||||||
</SidebarContent>
|
</SidebarContent>
|
||||||
|
|
||||||
<SidebarFooter>
|
|
||||||
<ProfileAccountDropdownContainer accounts={accounts} />
|
|
||||||
</SidebarFooter>
|
|
||||||
</Sidebar>
|
</Sidebar>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ import { cache } from 'react';
|
|||||||
|
|
||||||
import { AdminAccountPage } from '@kit/admin/components/admin-account-page';
|
import { AdminAccountPage } from '@kit/admin/components/admin-account-page';
|
||||||
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
||||||
|
|
||||||
import { getAccount } from '~/lib/services/account.service';
|
import { getAccount } from '~/lib/services/account.service';
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
interface Params {
|
interface Params {
|
||||||
params: Promise<{
|
params: Promise<{
|
||||||
@@ -26,6 +28,6 @@ async function AccountPage(props: Params) {
|
|||||||
return <AdminAccountPage account={account} />;
|
return <AdminAccountPage account={account} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AdminGuard(AccountPage);
|
export default withI18n(AdminGuard(AccountPage));
|
||||||
|
|
||||||
const loadAccount = cache(getAccount);
|
const loadAccount = cache(getAccount);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|||||||
import { AppBreadcrumbs } from '@kit/ui/app-breadcrumbs';
|
import { AppBreadcrumbs } from '@kit/ui/app-breadcrumbs';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
interface SearchParams {
|
interface SearchParams {
|
||||||
page?: string;
|
page?: string;
|
||||||
@@ -30,7 +31,7 @@ async function AccountsPage(props: AdminAccountsPageProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader description={<AppBreadcrumbs />}>
|
<PageHeader description={<AppBreadcrumbs />} title="Accounts">
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<AdminCreateUserDialog>
|
<AdminCreateUserDialog>
|
||||||
<Button data-test="admin-create-user-button">
|
<Button data-test="admin-create-user-button">
|
||||||
@@ -84,4 +85,4 @@ async function AccountsPage(props: AdminAccountsPageProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AdminGuard(AccountsPage);
|
export default withI18n(AdminGuard(AccountsPage));
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
|
|||||||
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
||||||
|
|
||||||
import { AdminSidebar } from '~/admin/_components/admin-sidebar';
|
import { AdminSidebar } from '~/admin/_components/admin-sidebar';
|
||||||
|
import { AdminMenuNavigation } from '~/admin/_components/admin-menu-navigation';
|
||||||
import { AdminMobileNavigation } from '~/admin/_components/mobile-navigation';
|
import { AdminMobileNavigation } from '~/admin/_components/mobile-navigation';
|
||||||
|
|
||||||
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
||||||
@@ -21,19 +22,24 @@ export default function AdminLayout(props: React.PropsWithChildren) {
|
|||||||
const workspace = use(loadUserWorkspace());
|
const workspace = use(loadUserWorkspace());
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarProvider defaultOpen={state.open}>
|
<Page style={'header'}>
|
||||||
<Page style={'sidebar'}>
|
<PageNavigation>
|
||||||
<PageNavigation>
|
<AdminMenuNavigation workspace={workspace} />
|
||||||
<AdminSidebar accounts={workspace.accounts} />
|
</PageNavigation>
|
||||||
</PageNavigation>
|
|
||||||
|
|
||||||
<PageMobileNavigation>
|
<PageMobileNavigation>
|
||||||
<AdminMobileNavigation />
|
<AdminMobileNavigation />
|
||||||
</PageMobileNavigation>
|
</PageMobileNavigation>
|
||||||
|
|
||||||
{props.children}
|
<SidebarProvider defaultOpen={state.open}>
|
||||||
</Page>
|
<Page style={'sidebar'}>
|
||||||
</SidebarProvider>
|
<PageNavigation>
|
||||||
|
<AdminSidebar />
|
||||||
|
</PageNavigation>
|
||||||
|
{props.children}
|
||||||
|
</Page>
|
||||||
|
</SidebarProvider>
|
||||||
|
</Page>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { AdminDashboard } from '@kit/admin/components/admin-dashboard';
|
import { AdminDashboard } from '@kit/admin/components/admin-dashboard';
|
||||||
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
function AdminPage() {
|
function AdminPage() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader description={`Super Admin`} />
|
<PageHeader title={`Super Admin`} />
|
||||||
|
|
||||||
<PageBody>
|
<PageBody>
|
||||||
<AdminDashboard />
|
<AdminDashboard />
|
||||||
@@ -14,4 +15,4 @@ function AdminPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AdminGuard(AdminPage);
|
export default withI18n(AdminGuard(AdminPage));
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { getPlanTypesMap } from '@kit/billing';
|
import { getPlanTypesMap } from '@kit/billing';
|
||||||
import { getBillingEventHandlerService } from '@kit/billing-gateway';
|
import { getBillingEventHandlerService } from '@kit/billing-gateway';
|
||||||
import { enhanceRouteHandler } from '@kit/next/routes';
|
import { enhanceRouteHandler } from '@kit/next/routes';
|
||||||
|
import { billingConfig } from '@kit/shared/config';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||||
|
|
||||||
import { billingConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @description Handle the webhooks from Stripe related to checkouts
|
* @description Handle the webhooks from Stripe related to checkouts
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -2,7 +2,11 @@ import { config } from 'dotenv';
|
|||||||
|
|
||||||
export default function loadEnv() {
|
export default function loadEnv() {
|
||||||
config({ path: `.env` });
|
config({ path: `.env` });
|
||||||
if (['local', 'test', 'development', 'production'].includes(process.env.NODE_ENV!)) {
|
if (
|
||||||
|
['local', 'test', 'development', 'production'].includes(
|
||||||
|
process.env.NODE_ENV!,
|
||||||
|
)
|
||||||
|
) {
|
||||||
config({ path: `.env.${process.env.NODE_ENV}` });
|
config({ path: `.env.${process.env.NODE_ENV}` });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
import Medusa from "@medusajs/js-sdk"
|
import { listProductTypes } from '@lib/data/products';
|
||||||
import type { AdminProductCategory } from "@medusajs/types";
|
import Medusa from '@medusajs/js-sdk';
|
||||||
import { listProductTypes } from "@lib/data/products";
|
import type { AdminProductCategory } from '@medusajs/types';
|
||||||
import { getAnalysisElements } from "~/lib/services/analysis-element.service";
|
|
||||||
import { getAnalysisGroups } from "~/lib/services/analysis-group.service";
|
import {
|
||||||
import { createMedusaSyncFailEntry, createMedusaSyncSuccessEntry } from "~/lib/services/analyses.service";
|
createMedusaSyncFailEntry,
|
||||||
|
createMedusaSyncSuccessEntry,
|
||||||
|
} from '~/lib/services/analyses.service';
|
||||||
|
import { getAnalysisElements } from '~/lib/services/analysis-element.service';
|
||||||
|
import { getAnalysisGroups } from '~/lib/services/analysis-group.service';
|
||||||
|
|
||||||
const SYNLAB_SERVICES_CATEGORY_HANDLE = 'synlab-services';
|
const SYNLAB_SERVICES_CATEGORY_HANDLE = 'synlab-services';
|
||||||
const SYNLAB_ANALYSIS_PRODUCT_TYPE_HANDLE = 'synlab-analysis';
|
const SYNLAB_ANALYSIS_PRODUCT_TYPE_HANDLE = 'synlab-analysis';
|
||||||
@@ -12,7 +16,8 @@ const BASE_ANALYSIS_PRODUCT_HANDLE = 'analysis-base';
|
|||||||
|
|
||||||
const getAdminSdk = () => {
|
const getAdminSdk = () => {
|
||||||
const medusaBackendUrl = process.env.MEDUSA_BACKEND_PUBLIC_URL!;
|
const medusaBackendUrl = process.env.MEDUSA_BACKEND_PUBLIC_URL!;
|
||||||
const medusaPublishableApiKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY!;
|
const medusaPublishableApiKey =
|
||||||
|
process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY!;
|
||||||
const key = process.env.MEDUSA_SECRET_API_KEY!;
|
const key = process.env.MEDUSA_SECRET_API_KEY!;
|
||||||
|
|
||||||
if (!medusaBackendUrl || !medusaPublishableApiKey) {
|
if (!medusaBackendUrl || !medusaPublishableApiKey) {
|
||||||
@@ -23,15 +28,14 @@ const getAdminSdk = () => {
|
|||||||
debug: process.env.NODE_ENV === 'development',
|
debug: process.env.NODE_ENV === 'development',
|
||||||
apiKey: key,
|
apiKey: key,
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
async function createProductCategories({
|
async function createProductCategories({ medusa }: { medusa: Medusa }) {
|
||||||
medusa,
|
const { product_categories: existingProductCategories } =
|
||||||
}: {
|
await medusa.admin.productCategory.list();
|
||||||
medusa: Medusa;
|
const parentCategory = existingProductCategories.find(
|
||||||
}) {
|
({ handle }) => handle === SYNLAB_SERVICES_CATEGORY_HANDLE,
|
||||||
const { product_categories: existingProductCategories } = await medusa.admin.productCategory.list();
|
);
|
||||||
const parentCategory = existingProductCategories.find(({ handle }) => handle === SYNLAB_SERVICES_CATEGORY_HANDLE);
|
|
||||||
|
|
||||||
if (!parentCategory) {
|
if (!parentCategory) {
|
||||||
throw new Error('Parent category not found');
|
throw new Error('Parent category not found');
|
||||||
@@ -46,8 +50,12 @@ async function createProductCategories({
|
|||||||
for (const analysisGroup of analysisGroups) {
|
for (const analysisGroup of analysisGroups) {
|
||||||
console.info(`Processing analysis group '${analysisGroup.name}'`);
|
console.info(`Processing analysis group '${analysisGroup.name}'`);
|
||||||
|
|
||||||
const isExisting = existingProductCategories.find(({ name }) => name === analysisGroup.name);
|
const isExisting = existingProductCategories.find(
|
||||||
const isNewlyCreated = createdCategories.find(({ name }) => name === analysisGroup.name);
|
({ name }) => name === analysisGroup.name,
|
||||||
|
);
|
||||||
|
const isNewlyCreated = createdCategories.find(
|
||||||
|
({ name }) => name === analysisGroup.name,
|
||||||
|
);
|
||||||
if (isExisting || isNewlyCreated) {
|
if (isExisting || isNewlyCreated) {
|
||||||
console.info(`Analysis group '${analysisGroup.name}' already exists`);
|
console.info(`Analysis group '${analysisGroup.name}' already exists`);
|
||||||
continue;
|
continue;
|
||||||
@@ -63,18 +71,19 @@ async function createProductCategories({
|
|||||||
analysisGroupId: analysisGroup.id,
|
analysisGroupId: analysisGroup.id,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
console.info(`Successfully created category, id=${createResponse.product_category.id}`);
|
console.info(
|
||||||
|
`Successfully created category, id=${createResponse.product_category.id}`,
|
||||||
|
);
|
||||||
createdCategories.push(createResponse.product_category);
|
createdCategories.push(createResponse.product_category);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getChildProductCategories({
|
async function getChildProductCategories({ medusa }: { medusa: Medusa }) {
|
||||||
medusa,
|
const { product_categories: allCategories } =
|
||||||
}: {
|
await medusa.admin.productCategory.list();
|
||||||
medusa: Medusa;
|
const childCategories = allCategories.filter(
|
||||||
}) {
|
({ parent_category_id }) => parent_category_id !== null,
|
||||||
const { product_categories: allCategories } = await medusa.admin.productCategory.list();
|
);
|
||||||
const childCategories = allCategories.filter(({ parent_category_id }) => parent_category_id !== null);
|
|
||||||
return childCategories;
|
return childCategories;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,34 +102,34 @@ async function deleteProductCategories({
|
|||||||
/**
|
/**
|
||||||
* In case a reset is needed
|
* In case a reset is needed
|
||||||
*/
|
*/
|
||||||
async function deleteProducts({
|
async function deleteProducts({ medusa }: { medusa: Medusa }) {
|
||||||
medusa,
|
|
||||||
}: {
|
|
||||||
medusa: Medusa;
|
|
||||||
}) {
|
|
||||||
const { products: existingProducts } = await medusa.admin.product.list({
|
const { products: existingProducts } = await medusa.admin.product.list({
|
||||||
fields: 'id,collection_id',
|
fields: 'id,collection_id',
|
||||||
limit: 1000,
|
limit: 1000,
|
||||||
});
|
});
|
||||||
|
|
||||||
await Promise.all(existingProducts.filter((a) => !a.collection_id).map(({ id }) => medusa.admin.product.delete(id)));
|
await Promise.all(
|
||||||
|
existingProducts
|
||||||
|
.filter((a) => !a.collection_id)
|
||||||
|
.map(({ id }) => medusa.admin.product.delete(id)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getAnalysisPackagesType() {
|
async function getAnalysisPackagesType() {
|
||||||
const { productTypes } = await listProductTypes();
|
const { productTypes } = await listProductTypes();
|
||||||
const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === SYNLAB_ANALYSIS_PRODUCT_TYPE_HANDLE);
|
const analysisPackagesType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === SYNLAB_ANALYSIS_PRODUCT_TYPE_HANDLE,
|
||||||
|
);
|
||||||
if (!analysisPackagesType) {
|
if (!analysisPackagesType) {
|
||||||
throw new Error('Synlab analysis packages type not found');
|
throw new Error('Synlab analysis packages type not found');
|
||||||
}
|
}
|
||||||
return analysisPackagesType;
|
return analysisPackagesType;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getProductDefaultFields({
|
async function getProductDefaultFields({ medusa }: { medusa: Medusa }) {
|
||||||
medusa,
|
const baseProductsResponse = await medusa.admin.product.list({
|
||||||
}: {
|
handle: BASE_ANALYSIS_PRODUCT_HANDLE,
|
||||||
medusa: Medusa;
|
});
|
||||||
}) {
|
|
||||||
const baseProductsResponse = await medusa.admin.product.list({ handle: BASE_ANALYSIS_PRODUCT_HANDLE })
|
|
||||||
const baseProduct = baseProductsResponse.products[0];
|
const baseProduct = baseProductsResponse.products[0];
|
||||||
if (!baseProduct) {
|
if (!baseProduct) {
|
||||||
throw new Error('Base product not found');
|
throw new Error('Base product not found');
|
||||||
@@ -142,39 +151,36 @@ async function getProductDefaultFields({
|
|||||||
defaultSalesChannels,
|
defaultSalesChannels,
|
||||||
defaultProductOption,
|
defaultProductOption,
|
||||||
defaultProductVariant,
|
defaultProductVariant,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createProducts({
|
async function createProducts({ medusa }: { medusa: Medusa }) {
|
||||||
medusa,
|
const { product_categories: allCategories } =
|
||||||
}: {
|
await medusa.admin.productCategory.list();
|
||||||
medusa: Medusa;
|
|
||||||
}) {
|
|
||||||
const { product_categories: allCategories } = await medusa.admin.productCategory.list();
|
|
||||||
|
|
||||||
const [
|
const [
|
||||||
{ products: existingProducts },
|
{ products: existingProducts },
|
||||||
analysisElements,
|
analysisElements,
|
||||||
analysisPackagesType,
|
analysisPackagesType,
|
||||||
{
|
{ defaultSalesChannels, defaultProductOption, defaultProductVariant },
|
||||||
defaultSalesChannels,
|
|
||||||
defaultProductOption,
|
|
||||||
defaultProductVariant,
|
|
||||||
}
|
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
medusa.admin.product.list({
|
medusa.admin.product.list({
|
||||||
category_id: allCategories.map(({ id }) => id),
|
category_id: allCategories.map(({ id }) => id),
|
||||||
}),
|
}),
|
||||||
getAnalysisElements({}),
|
getAnalysisElements({ getAll: true }),
|
||||||
getAnalysisPackagesType(),
|
getAnalysisPackagesType(),
|
||||||
getProductDefaultFields({ medusa }),
|
getProductDefaultFields({ medusa }),
|
||||||
])
|
]);
|
||||||
|
|
||||||
for (const analysisElement of analysisElements) {
|
for (const analysisElement of analysisElements) {
|
||||||
const { analysis_id_original: originalId } = analysisElement;
|
const { analysis_id_original: originalId } = analysisElement;
|
||||||
const isExisting = existingProducts.find(({ metadata }) => metadata?.analysisIdOriginal === originalId);
|
const isExisting = existingProducts.find(
|
||||||
|
({ metadata }) => metadata?.analysisIdOriginal === originalId,
|
||||||
|
);
|
||||||
if (isExisting) {
|
if (isExisting) {
|
||||||
console.info(`Analysis element '${analysisElement.analysis_name_lab}' already exists`);
|
console.info(
|
||||||
|
`Analysis element '${analysisElement.analysis_name_lab}' already exists`,
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const { analysis_name_lab: name } = analysisElement;
|
const { analysis_name_lab: name } = analysisElement;
|
||||||
@@ -183,7 +189,10 @@ async function createProducts({
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const category = allCategories.find(({ metadata }) => metadata?.analysisGroupId === analysisElement.parent_analysis_group_id);
|
const category = allCategories.find(
|
||||||
|
({ metadata }) =>
|
||||||
|
metadata?.analysisGroupId === analysisElement.parent_analysis_group_id,
|
||||||
|
);
|
||||||
if (!category) {
|
if (!category) {
|
||||||
console.error(`Category not found for analysis element '${name}'`);
|
console.error(`Category not found for analysis element '${name}'`);
|
||||||
continue;
|
continue;
|
||||||
@@ -227,9 +236,9 @@ export default async function syncAnalysisGroupsStore() {
|
|||||||
// await deleteProductCategories({ medusa, categories });
|
// await deleteProductCategories({ medusa, categories });
|
||||||
// await deleteProducts({ medusa });
|
// await deleteProducts({ medusa });
|
||||||
// return;
|
// return;
|
||||||
|
|
||||||
await createProducts({ medusa });
|
await createProducts({ medusa });
|
||||||
|
|
||||||
await createMedusaSyncSuccessEntry();
|
await createMedusaSyncSuccessEntry();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await createMedusaSyncFailEntry(JSON.stringify(e));
|
await createMedusaSyncFailEntry(JSON.stringify(e));
|
||||||
|
|||||||
@@ -1,19 +1,31 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { XMLParser } from 'fast-xml-parser';
|
import { XMLParser } from 'fast-xml-parser';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { createAnalysisGroup, getAnalysisGroups } from '~/lib/services/analysis-group.service';
|
|
||||||
import { IMedipostPublicMessageDataParsed } from '~/lib/services/medipost.types';
|
|
||||||
import { createAnalysis, createNoDataReceivedEntry, createNoNewDataReceivedEntry, createSyncFailEntry, createSyncSuccessEntry } from '~/lib/services/analyses.service';
|
|
||||||
import { getLastCheckedDate } from '~/lib/services/sync-entries.service';
|
|
||||||
import { createAnalysisElement } from '~/lib/services/analysis-element.service';
|
|
||||||
import { createCodes } from '~/lib/services/codes.service';
|
|
||||||
import { getLatestPublicMessageListItem } from '~/lib/services/medipost.service';
|
|
||||||
import type { ICode } from '~/lib/types/code';
|
|
||||||
|
|
||||||
function toArray<T>(input?: T | T[] | null): T[] {
|
import { toArray } from '@kit/shared/utils';
|
||||||
if (!input) return [];
|
|
||||||
return Array.isArray(input) ? input : [input];
|
import {
|
||||||
}
|
createAnalysis,
|
||||||
|
createNoDataReceivedEntry,
|
||||||
|
createNoNewDataReceivedEntry,
|
||||||
|
createSyncFailEntry,
|
||||||
|
createSyncSuccessEntry,
|
||||||
|
getAnalyses,
|
||||||
|
} from '~/lib/services/analyses.service';
|
||||||
|
import {
|
||||||
|
AnalysisElement,
|
||||||
|
createAnalysisElement,
|
||||||
|
getAnalysisElements,
|
||||||
|
} from '~/lib/services/analysis-element.service';
|
||||||
|
import {
|
||||||
|
createAnalysisGroup,
|
||||||
|
getAnalysisGroups,
|
||||||
|
} from '~/lib/services/analysis-group.service';
|
||||||
|
import { createCodes } from '~/lib/services/codes.service';
|
||||||
|
import { IMedipostPublicMessageDataParsed } from '~/lib/services/medipost/medipost.types';
|
||||||
|
import { getLatestPublicMessageListItem } from '~/lib/services/medipost/medipostPublicMessage.service';
|
||||||
|
import { getLastCheckedDate } from '~/lib/services/sync-entries.service';
|
||||||
|
import type { ICode } from '~/lib/types/code';
|
||||||
|
|
||||||
const WRITE_XML_TO_FILE = false as boolean;
|
const WRITE_XML_TO_FILE = false as boolean;
|
||||||
|
|
||||||
@@ -56,7 +68,8 @@ export default async function syncAnalysisGroups() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parser = new XMLParser({ ignoreAttributes: false });
|
const parser = new XMLParser({ ignoreAttributes: false });
|
||||||
const parsed: IMedipostPublicMessageDataParsed = parser.parse(publicMessageData);
|
const parsed: IMedipostPublicMessageDataParsed =
|
||||||
|
parser.parse(publicMessageData);
|
||||||
|
|
||||||
if (parsed.ANSWER?.CODE && parsed.ANSWER?.CODE !== 0) {
|
if (parsed.ANSWER?.CODE && parsed.ANSWER?.CODE !== 0) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -81,43 +94,71 @@ export default async function syncAnalysisGroups() {
|
|||||||
|
|
||||||
const codes: ICode[] = [];
|
const codes: ICode[] = [];
|
||||||
for (const analysisGroup of analysisGroups) {
|
for (const analysisGroup of analysisGroups) {
|
||||||
const existingAnalysisGroup = existingAnalysisGroups?.find(({ original_id }) => original_id === analysisGroup.UuringuGruppId);
|
const existingAnalysisGroup = existingAnalysisGroups?.find(
|
||||||
if (existingAnalysisGroup) {
|
({ original_id }) => original_id === analysisGroup.UuringuGruppId,
|
||||||
console.info(`Analysis group '${analysisGroup.UuringuGruppNimi}' already exists`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// SAVE ANALYSIS GROUP
|
|
||||||
const analysisGroupId = await createAnalysisGroup({
|
|
||||||
id: analysisGroup.UuringuGruppId,
|
|
||||||
name: analysisGroup.UuringuGruppNimi,
|
|
||||||
order: analysisGroup.UuringuGruppJarjekord,
|
|
||||||
});
|
|
||||||
|
|
||||||
const analysisGroupCodes = toArray(analysisGroup.Kood);
|
|
||||||
codes.push(
|
|
||||||
...analysisGroupCodes.map((kood) => ({
|
|
||||||
hk_code: kood.HkKood,
|
|
||||||
hk_code_multiplier: kood.HkKoodiKordaja,
|
|
||||||
coefficient: kood.Koefitsient,
|
|
||||||
price: kood.Hind,
|
|
||||||
analysis_group_id: analysisGroupId,
|
|
||||||
analysis_element_id: null,
|
|
||||||
analysis_id: null,
|
|
||||||
})),
|
|
||||||
);
|
);
|
||||||
|
let groupExistingAnalysisElements: AnalysisElement[] = [];
|
||||||
|
let analysisGroupId: number;
|
||||||
|
if (existingAnalysisGroup) {
|
||||||
|
console.info(
|
||||||
|
`Analysis group '${analysisGroup.UuringuGruppNimi}' already exists, only creating new analysis elements`,
|
||||||
|
);
|
||||||
|
groupExistingAnalysisElements = await getAnalysisElements({
|
||||||
|
analysisGroupId: existingAnalysisGroup.id,
|
||||||
|
});
|
||||||
|
analysisGroupId = existingAnalysisGroup.id;
|
||||||
|
} else {
|
||||||
|
analysisGroupId = await createAnalysisGroup({
|
||||||
|
id: analysisGroup.UuringuGruppId,
|
||||||
|
name: analysisGroup.UuringuGruppNimi,
|
||||||
|
order: analysisGroup.UuringuGruppJarjekord,
|
||||||
|
});
|
||||||
|
|
||||||
|
const analysisGroupCodes = toArray(analysisGroup.Kood);
|
||||||
|
codes.push(
|
||||||
|
...analysisGroupCodes.map((kood) => ({
|
||||||
|
hk_code: kood.HkKood,
|
||||||
|
hk_code_multiplier: kood.HkKoodiKordaja,
|
||||||
|
coefficient: kood.Koefitsient,
|
||||||
|
price: kood.Hind,
|
||||||
|
analysis_group_id: analysisGroupId,
|
||||||
|
analysis_element_id: null,
|
||||||
|
analysis_id: null,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const analysisGroupItems = toArray(analysisGroup.Uuring);
|
const analysisGroupItems = toArray(analysisGroup.Uuring);
|
||||||
|
|
||||||
for (const item of analysisGroupItems) {
|
for (const item of analysisGroupItems) {
|
||||||
const analysisElement = item.UuringuElement;
|
const analysisElement = item.UuringuElement!;
|
||||||
|
const isExistingAnalysisElement = groupExistingAnalysisElements.find(
|
||||||
|
({ analysis_id_original }) =>
|
||||||
|
analysis_id_original === analysisElement.UuringId,
|
||||||
|
);
|
||||||
|
if (isExistingAnalysisElement) {
|
||||||
|
console.info(
|
||||||
|
`Analysis element '${analysisElement.UuringNimi}' already exists`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
const insertedAnalysisElementId = await createAnalysisElement({
|
const insertedAnalysisElementId = await createAnalysisElement({
|
||||||
analysisElement,
|
analysisElement: analysisElement!,
|
||||||
analysisGroupId,
|
analysisGroupId,
|
||||||
materialGroups: toArray(item.MaterjalideGrupp),
|
materialGroups: toArray(item.MaterjalideGrupp),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (Array.isArray(analysisElement.UuringuElement)) {
|
||||||
|
for (const nestedAnalysisElement of analysisElement.UuringuElement) {
|
||||||
|
await createAnalysisElement({
|
||||||
|
analysisElement: nestedAnalysisElement,
|
||||||
|
analysisGroupId,
|
||||||
|
materialGroups: toArray(item.MaterjalideGrupp),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (analysisElement.Kood) {
|
if (analysisElement.Kood) {
|
||||||
const analysisElementCodes = toArray(analysisElement.Kood);
|
const analysisElementCodes = toArray(analysisElement.Kood);
|
||||||
codes.push(
|
codes.push(
|
||||||
@@ -135,8 +176,24 @@ export default async function syncAnalysisGroups() {
|
|||||||
|
|
||||||
const analyses = analysisElement.UuringuElement;
|
const analyses = analysisElement.UuringuElement;
|
||||||
if (analyses?.length) {
|
if (analyses?.length) {
|
||||||
|
const existingAnalyses = await getAnalyses({
|
||||||
|
originalIds: analyses.map(({ UuringId }) => UuringId),
|
||||||
|
});
|
||||||
|
|
||||||
for (const analysis of analyses) {
|
for (const analysis of analyses) {
|
||||||
const insertedAnalysisId = await createAnalysis(analysis, analysisGroupId);
|
const isExistingAnalysis = existingAnalyses.find(
|
||||||
|
({ analysis_id_original }) =>
|
||||||
|
analysis_id_original === analysis.UuringId,
|
||||||
|
);
|
||||||
|
if (isExistingAnalysis) {
|
||||||
|
console.info(`Analysis '${analysis.UuringNimi}' already exists`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertedAnalysisId = await createAnalysis(
|
||||||
|
analysis,
|
||||||
|
analysisGroupId,
|
||||||
|
);
|
||||||
|
|
||||||
if (analysis.Kood) {
|
if (analysis.Kood) {
|
||||||
const analysisCodes = toArray(analysis.Kood);
|
const analysisCodes = toArray(analysis.Kood);
|
||||||
@@ -165,11 +222,17 @@ export default async function syncAnalysisGroups() {
|
|||||||
await createSyncSuccessEntry();
|
await createSyncSuccessEntry();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMessage = e instanceof Error ? e.message : String(e);
|
const errorMessage = e instanceof Error ? e.message : String(e);
|
||||||
await createSyncFailEntry(JSON.stringify({
|
await createSyncFailEntry(
|
||||||
message: errorMessage,
|
JSON.stringify(
|
||||||
stack: e instanceof Error ? e.stack : undefined,
|
{
|
||||||
name: e instanceof Error ? e.name : 'Unknown',
|
message: errorMessage,
|
||||||
}, null, 2));
|
stack: e instanceof Error ? e.stack : undefined,
|
||||||
|
name: e instanceof Error ? e.name : 'Unknown',
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
);
|
||||||
console.error('Sync failed:', e);
|
console.error('Sync failed:', e);
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Failed to sync public message data, error: ${errorMessage}`,
|
`Failed to sync public message data, error: ${errorMessage}`,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { readPrivateMessageResponse } from "~/lib/services/medipost.service";
|
import { readPrivateMessageResponse } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
||||||
|
|
||||||
type ProcessedMessage = {
|
type ProcessedMessage = {
|
||||||
messageId: string;
|
messageId: string;
|
||||||
@@ -6,17 +6,18 @@ type ProcessedMessage = {
|
|||||||
hasPartialAnalysisResponse: boolean;
|
hasPartialAnalysisResponse: boolean;
|
||||||
hasFullAnalysisResponse: boolean;
|
hasFullAnalysisResponse: boolean;
|
||||||
medusaOrderId: string | undefined;
|
medusaOrderId: string | undefined;
|
||||||
|
analysisOrderId: number | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
type GroupedResults = {
|
type GroupedResults = {
|
||||||
processed: Pick<ProcessedMessage, 'messageId' | 'medusaOrderId'>[];
|
processed: Pick<ProcessedMessage, 'messageId' | 'analysisOrderId'>[];
|
||||||
waitingForResults: Pick<ProcessedMessage, 'messageId' | 'medusaOrderId'>[];
|
waitingForResults: Pick<ProcessedMessage, 'messageId' | 'analysisOrderId'>[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function syncAnalysisResults() {
|
export default async function syncAnalysisResults() {
|
||||||
console.info("Syncing analysis results");
|
console.info('Syncing analysis results');
|
||||||
|
|
||||||
let processedMessages: ProcessedMessage[] = [];
|
const processedMessages: ProcessedMessage[] = [];
|
||||||
const excludedMessageIds: string[] = [];
|
const excludedMessageIds: string[] = [];
|
||||||
while (true) {
|
while (true) {
|
||||||
const result = await readPrivateMessageResponse({ excludedMessageIds });
|
const result = await readPrivateMessageResponse({ excludedMessageIds });
|
||||||
@@ -25,7 +26,7 @@ export default async function syncAnalysisResults() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!result.messageId) {
|
if (!result.messageId) {
|
||||||
console.info("No more messages to process");
|
console.info('No more messages to process');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,14 +38,14 @@ export default async function syncAnalysisResults() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const groupedResults = processedMessages.reduce((acc, result) => {
|
const groupedResults = processedMessages.reduce((acc, result) => {
|
||||||
if (result.medusaOrderId) {
|
if (result.analysisOrderId) {
|
||||||
if (result.hasAnalysisResponse) {
|
if (result.hasAnalysisResponse) {
|
||||||
if (!acc.processed) {
|
if (!acc.processed) {
|
||||||
acc.processed = [];
|
acc.processed = [];
|
||||||
}
|
}
|
||||||
acc.processed.push({
|
acc.processed.push({
|
||||||
messageId: result.messageId,
|
messageId: result.messageId,
|
||||||
medusaOrderId: result.medusaOrderId,
|
analysisOrderId: result.analysisOrderId,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
if (!acc.waitingForResults) {
|
if (!acc.waitingForResults) {
|
||||||
@@ -52,11 +53,13 @@ export default async function syncAnalysisResults() {
|
|||||||
}
|
}
|
||||||
acc.waitingForResults.push({
|
acc.waitingForResults.push({
|
||||||
messageId: result.messageId,
|
messageId: result.messageId,
|
||||||
medusaOrderId: result.medusaOrderId,
|
analysisOrderId: result.analysisOrderId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as GroupedResults);
|
}, {} as GroupedResults);
|
||||||
console.info(`Processed ${processedMessages.length} messages, results: ${JSON.stringify(groupedResults)}`);
|
console.info(
|
||||||
|
`Processed ${processedMessages.length} messages, results: ${JSON.stringify(groupedResults)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from 'next/server';
|
||||||
|
|
||||||
export default function validateApiKey(request: NextRequest) {
|
export default function validateApiKey(request: NextRequest) {
|
||||||
const envApiKey = process.env.JOBS_API_TOKEN;
|
const envApiKey = process.env.JOBS_API_TOKEN;
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import loadEnv from "../handler/load-env";
|
|
||||||
import validateApiKey from "../handler/validate-api-key";
|
import { retrieveOrder } from '@lib/data/orders';
|
||||||
import { getOrderedAnalysisElementsIds, sendOrderToMedipost } from "~/lib/services/medipost.service";
|
|
||||||
import { retrieveOrder } from "@lib/data/orders";
|
import { getMedipostDispatchTries } from '~/lib/services/audit.service';
|
||||||
import { getMedipostDispatchTries } from "~/lib/services/audit.service";
|
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
||||||
|
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
||||||
|
|
||||||
|
import loadEnv from '../handler/load-env';
|
||||||
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
|
|
||||||
export const POST = async (request: NextRequest) => {
|
export const POST = async (request: NextRequest) => {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
@@ -18,23 +22,34 @@ export const POST = async (request: NextRequest) => {
|
|||||||
|
|
||||||
const tries = await getMedipostDispatchTries(medusaOrderId);
|
const tries = await getMedipostDispatchTries(medusaOrderId);
|
||||||
if (tries >= 3) {
|
if (tries >= 3) {
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Order has been retried too many times',
|
{
|
||||||
}, { status: 400 });
|
message: 'Order has been retried too many times',
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const medusaOrder = await retrieveOrder(medusaOrderId);
|
const medusaOrder = await retrieveOrder(medusaOrderId);
|
||||||
const orderedAnalysisElements = await getOrderedAnalysisElementsIds({ medusaOrder });
|
const orderedAnalysisElements = await getOrderedAnalysisIds({
|
||||||
|
medusaOrder,
|
||||||
|
});
|
||||||
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
||||||
console.info("Successfully sent order to medipost");
|
console.info('Successfully sent order to medipost');
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Successfully sent order to medipost',
|
{
|
||||||
}, { status: 200 });
|
message: 'Successfully sent order to medipost',
|
||||||
|
},
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error sending order to medipost", e);
|
console.error('Error sending order to medipost', e);
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Failed to send order to medipost',
|
{
|
||||||
}, { status: 500 });
|
message: 'Failed to send order to medipost',
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
NotificationAction,
|
NotificationAction,
|
||||||
createNotificationLog,
|
createNotificationLog,
|
||||||
} from '~/lib/services/audit/notificationEntries.service';
|
} from '~/lib/services/audit/notificationEntries.service';
|
||||||
|
|
||||||
import loadEnv from '../handler/load-env';
|
import loadEnv from '../handler/load-env';
|
||||||
import sendOpenJobsEmails from '../handler/send-open-jobs-emails';
|
import sendOpenJobsEmails from '../handler/send-open-jobs-emails';
|
||||||
import validateApiKey from '../handler/validate-api-key';
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
@@ -23,7 +24,7 @@ export const POST = async (request: NextRequest) => {
|
|||||||
'Successfully sent out open job notification emails to doctors.',
|
'Successfully sent out open job notification emails to doctors.',
|
||||||
);
|
);
|
||||||
await createNotificationLog({
|
await createNotificationLog({
|
||||||
action: NotificationAction.NEW_JOBS_ALERT,
|
action: NotificationAction.DOCTOR_NEW_JOBS,
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
});
|
});
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -39,7 +40,7 @@ export const POST = async (request: NextRequest) => {
|
|||||||
e,
|
e,
|
||||||
);
|
);
|
||||||
await createNotificationLog({
|
await createNotificationLog({
|
||||||
action: NotificationAction.NEW_JOBS_ALERT,
|
action: NotificationAction.DOCTOR_NEW_JOBS,
|
||||||
status: 'FAIL',
|
status: 'FAIL',
|
||||||
comment: e?.message,
|
comment: e?.message,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import loadEnv from "../handler/load-env";
|
|
||||||
import validateApiKey from "../handler/validate-api-key";
|
import loadEnv from '../handler/load-env';
|
||||||
import syncAnalysisGroupsStore from "../handler/sync-analysis-groups-store";
|
import syncAnalysisGroupsStore from '../handler/sync-analysis-groups-store';
|
||||||
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
|
|
||||||
export const POST = async (request: NextRequest) => {
|
export const POST = async (request: NextRequest) => {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
@@ -14,14 +15,20 @@ export const POST = async (request: NextRequest) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await syncAnalysisGroupsStore();
|
await syncAnalysisGroupsStore();
|
||||||
console.info("Successfully synced analysis groups store");
|
console.info('Successfully synced analysis groups store');
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Successfully synced analysis groups store',
|
{
|
||||||
}, { status: 200 });
|
message: 'Successfully synced analysis groups store',
|
||||||
|
},
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error syncing analysis groups store", e);
|
console.error('Error syncing analysis groups store', e);
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Failed to sync analysis groups store',
|
{
|
||||||
}, { status: 500 });
|
message: 'Failed to sync analysis groups store',
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import syncAnalysisGroups from "../handler/sync-analysis-groups";
|
|
||||||
import loadEnv from "../handler/load-env";
|
import loadEnv from '../handler/load-env';
|
||||||
import validateApiKey from "../handler/validate-api-key";
|
import syncAnalysisGroups from '../handler/sync-analysis-groups';
|
||||||
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
|
|
||||||
export const POST = async (request: NextRequest) => {
|
export const POST = async (request: NextRequest) => {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
@@ -14,14 +15,20 @@ export const POST = async (request: NextRequest) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await syncAnalysisGroups();
|
await syncAnalysisGroups();
|
||||||
console.info("Successfully synced analysis groups");
|
console.info('Successfully synced analysis groups');
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Successfully synced analysis groups',
|
{
|
||||||
}, { status: 200 });
|
message: 'Successfully synced analysis groups',
|
||||||
|
},
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error syncing analysis groups", e);
|
console.error('Error syncing analysis groups', e);
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Failed to sync analysis groups',
|
{
|
||||||
}, { status: 500 });
|
message: 'Failed to sync analysis groups',
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import loadEnv from "../handler/load-env";
|
|
||||||
import validateApiKey from "../handler/validate-api-key";
|
import loadEnv from '../handler/load-env';
|
||||||
import syncAnalysisResults from "../handler/sync-analysis-results";
|
import syncAnalysisResults from '../handler/sync-analysis-results';
|
||||||
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
|
|
||||||
export const POST = async (request: NextRequest) => {
|
export const POST = async (request: NextRequest) => {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
@@ -14,14 +15,20 @@ export const POST = async (request: NextRequest) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await syncAnalysisResults();
|
await syncAnalysisResults();
|
||||||
console.info("Successfully synced analysis results");
|
console.info('Successfully synced analysis results');
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Successfully synced analysis results',
|
{
|
||||||
}, { status: 200 });
|
message: 'Successfully synced analysis results',
|
||||||
|
},
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error syncing analysis results", e);
|
console.error('Error syncing analysis results', e);
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Failed to sync analysis results',
|
{
|
||||||
}, { status: 500 });
|
message: 'Failed to sync analysis results',
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import loadEnv from "../handler/load-env";
|
|
||||||
import validateApiKey from "../handler/validate-api-key";
|
import loadEnv from '../handler/load-env';
|
||||||
import syncConnectedOnline from "../handler/sync-connected-online";
|
import syncConnectedOnline from '../handler/sync-connected-online';
|
||||||
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
|
|
||||||
export const POST = async (request: NextRequest) => {
|
export const POST = async (request: NextRequest) => {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
@@ -14,14 +15,20 @@ export const POST = async (request: NextRequest) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await syncConnectedOnline();
|
await syncConnectedOnline();
|
||||||
console.info("Successfully synced connected-online");
|
console.info('Successfully synced connected-online');
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Successfully synced connected-online',
|
{
|
||||||
}, { status: 200 });
|
message: 'Successfully synced connected-online',
|
||||||
|
},
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error syncing connected-online", e);
|
console.error('Error syncing connected-online', e);
|
||||||
return NextResponse.json({
|
return NextResponse.json(
|
||||||
message: 'Failed to sync connected-online',
|
{
|
||||||
}, { status: 500 });
|
message: 'Failed to sync connected-online',
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { getAnalysisOrdersAdmin } from "~/lib/services/order.service";
|
|
||||||
import { composeOrderTestResponseXML, sendPrivateMessageTestResponse } from "~/lib/services/medipostTest.service";
|
import { retrieveOrder } from '@lib/data';
|
||||||
import { retrieveOrder } from "@lib/data";
|
|
||||||
import { getAccountAdmin } from "~/lib/services/account.service";
|
import { getAccountAdmin } from '~/lib/services/account.service';
|
||||||
import { getOrderedAnalysisElementsIds } from "~/lib/services/medipost.service";
|
import {
|
||||||
import loadEnv from "../handler/load-env";
|
composeOrderTestResponseXML,
|
||||||
import validateApiKey from "../handler/validate-api-key";
|
sendPrivateMessageTestResponse,
|
||||||
|
} from '~/lib/services/medipost/medipostTest.service';
|
||||||
|
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
||||||
|
import { getAnalysisOrdersAdmin } from '~/lib/services/order.service';
|
||||||
|
|
||||||
|
import loadEnv from '../handler/load-env';
|
||||||
|
import validateApiKey from '../handler/validate-api-key';
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
loadEnv();
|
loadEnv();
|
||||||
@@ -16,17 +22,27 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const analysisOrders = await getAnalysisOrdersAdmin({ orderStatus: 'PROCESSING' });
|
const analysisOrders = await getAnalysisOrdersAdmin({
|
||||||
|
orderStatus: 'PROCESSING',
|
||||||
|
});
|
||||||
|
|
||||||
console.error(`Sending test responses for ${analysisOrders.length} analysis orders`);
|
console.error(
|
||||||
|
`Sending test responses for ${analysisOrders.length} analysis orders`,
|
||||||
|
);
|
||||||
for (const medreportOrder of analysisOrders) {
|
for (const medreportOrder of analysisOrders) {
|
||||||
const medusaOrderId = medreportOrder.medusa_order_id;
|
const medusaOrderId = medreportOrder.medusa_order_id;
|
||||||
const medusaOrder = await retrieveOrder(medusaOrderId)
|
const medusaOrder = await retrieveOrder(medusaOrderId);
|
||||||
|
|
||||||
const account = await getAccountAdmin({ primaryOwnerUserId: medreportOrder.user_id });
|
const account = await getAccountAdmin({
|
||||||
const orderedAnalysisElementsIds = await getOrderedAnalysisElementsIds({ medusaOrder });
|
primaryOwnerUserId: medreportOrder.user_id,
|
||||||
|
});
|
||||||
|
const orderedAnalysisElementsIds = await getOrderedAnalysisIds({
|
||||||
|
medusaOrder,
|
||||||
|
});
|
||||||
|
|
||||||
console.info(`Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} ordered analysis elements`);
|
console.info(
|
||||||
|
`Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} ordered analysis elements`,
|
||||||
|
);
|
||||||
const idsToSend = orderedAnalysisElementsIds;
|
const idsToSend = orderedAnalysisElementsIds;
|
||||||
const messageXml = await composeOrderTestResponseXML({
|
const messageXml = await composeOrderTestResponseXML({
|
||||||
person: {
|
person: {
|
||||||
@@ -35,16 +51,20 @@ export async function POST(request: NextRequest) {
|
|||||||
lastName: account.last_name ?? '',
|
lastName: account.last_name ?? '',
|
||||||
phone: account.phone ?? '',
|
phone: account.phone ?? '',
|
||||||
},
|
},
|
||||||
orderedAnalysisElementsIds: idsToSend.map(({ analysisElementId }) => analysisElementId),
|
orderedAnalysisElementsIds: idsToSend
|
||||||
orderedAnalysesIds: [],
|
.map(({ analysisElementId }) => analysisElementId)
|
||||||
orderId: medusaOrderId,
|
.filter(Boolean) as number[],
|
||||||
|
orderedAnalysesIds: idsToSend
|
||||||
|
.map(({ analysisId }) => analysisId)
|
||||||
|
.filter(Boolean) as number[],
|
||||||
|
orderId: medreportOrder.id,
|
||||||
orderCreatedAt: new Date(medreportOrder.created_at),
|
orderCreatedAt: new Date(medreportOrder.created_at),
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await sendPrivateMessageTestResponse({ messageXml });
|
await sendPrivateMessageTestResponse({ messageXml });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error sending private message test response: ", error);
|
console.error('Error sending private message test response: ', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -94,4 +95,4 @@ export const POST = enhanceRouteHandler(
|
|||||||
{
|
{
|
||||||
auth: false,
|
auth: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from 'next/server';
|
||||||
import { getOrder } from "~/lib/services/order.service";
|
|
||||||
import { composeOrderTestResponseXML, sendPrivateMessageTestResponse } from "~/lib/services/medipostTest.service";
|
import { retrieveOrder } from '@lib/data';
|
||||||
import { retrieveOrder } from "@lib/data";
|
|
||||||
import { getAccountAdmin } from "~/lib/services/account.service";
|
import { getAccountAdmin } from '~/lib/services/account.service';
|
||||||
import { createMedipostActionLog, getOrderedAnalysisElementsIds } from "~/lib/services/medipost.service";
|
import { upsertMedipostActionLog } from '~/lib/services/medipost/medipostMessageBase.service';
|
||||||
|
import {
|
||||||
|
composeOrderTestResponseXML,
|
||||||
|
sendPrivateMessageTestResponse,
|
||||||
|
} from '~/lib/services/medipost/medipostTest.service';
|
||||||
|
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
||||||
|
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
// const isDev = process.env.NODE_ENV === 'development';
|
// const isDev = process.env.NODE_ENV === 'development';
|
||||||
@@ -11,16 +17,21 @@ export async function POST(request: Request) {
|
|||||||
// return NextResponse.json({ error: 'This endpoint is only available in development mode' }, { status: 403 });
|
// return NextResponse.json({ error: 'This endpoint is only available in development mode' }, { status: 403 });
|
||||||
// }
|
// }
|
||||||
|
|
||||||
const { medusaOrderId, maxItems = null } = await request.json();
|
const { medusaOrderId } = await request.json();
|
||||||
|
|
||||||
const medusaOrder = await retrieveOrder(medusaOrderId)
|
const medusaOrder = await retrieveOrder(medusaOrderId);
|
||||||
const medreportOrder = await getOrder({ medusaOrderId });
|
const analysisOrder = await getAnalysisOrder({ medusaOrderId });
|
||||||
|
|
||||||
const account = await getAccountAdmin({ primaryOwnerUserId: medreportOrder.user_id });
|
const account = await getAccountAdmin({
|
||||||
const orderedAnalysisElementsIds = await getOrderedAnalysisElementsIds({ medusaOrder });
|
primaryOwnerUserId: analysisOrder.user_id,
|
||||||
|
});
|
||||||
|
const orderedAnalysisElementsIds = await getOrderedAnalysisIds({
|
||||||
|
medusaOrder,
|
||||||
|
});
|
||||||
|
|
||||||
console.info(`Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} (${maxItems ?? 'all'}) ordered analysis elements`);
|
console.info(
|
||||||
const idsToSend = typeof maxItems === 'number' ? orderedAnalysisElementsIds.slice(0, maxItems) : orderedAnalysisElementsIds;
|
`Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} ordered analysis elements`,
|
||||||
|
);
|
||||||
const messageXml = await composeOrderTestResponseXML({
|
const messageXml = await composeOrderTestResponseXML({
|
||||||
person: {
|
person: {
|
||||||
idCode: account.personal_code!,
|
idCode: account.personal_code!,
|
||||||
@@ -28,21 +39,25 @@ export async function POST(request: Request) {
|
|||||||
lastName: account.last_name ?? '',
|
lastName: account.last_name ?? '',
|
||||||
phone: account.phone ?? '',
|
phone: account.phone ?? '',
|
||||||
},
|
},
|
||||||
orderedAnalysisElementsIds: idsToSend.map(({ analysisElementId }) => analysisElementId),
|
orderedAnalysisElementsIds: orderedAnalysisElementsIds
|
||||||
orderedAnalysesIds: [],
|
.map(({ analysisElementId }) => analysisElementId)
|
||||||
orderId: medusaOrderId,
|
.filter(Boolean) as number[],
|
||||||
orderCreatedAt: new Date(medreportOrder.created_at),
|
orderedAnalysesIds: orderedAnalysisElementsIds
|
||||||
|
.map(({ analysisId }) => analysisId)
|
||||||
|
.filter(Boolean) as number[],
|
||||||
|
orderId: analysisOrder.id,
|
||||||
|
orderCreatedAt: new Date(analysisOrder.created_at),
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await createMedipostActionLog({
|
await upsertMedipostActionLog({
|
||||||
action: 'send_fake_analysis_results_to_medipost',
|
action: 'send_fake_analysis_results_to_medipost',
|
||||||
xml: messageXml,
|
xml: messageXml,
|
||||||
medusaOrderId,
|
medusaOrderId,
|
||||||
});
|
});
|
||||||
await sendPrivateMessageTestResponse({ messageXml });
|
await sendPrivateMessageTestResponse({ messageXml });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error sending private message test response: ", error);
|
console.error('Error sending private message test response: ', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ success: true });
|
return NextResponse.json({ success: true });
|
||||||
|
|||||||
@@ -3,15 +3,13 @@ import Link from 'next/link';
|
|||||||
import type { AuthError } from '@supabase/supabase-js';
|
import type { AuthError } from '@supabase/supabase-js';
|
||||||
|
|
||||||
import { ResendAuthLinkForm } from '@kit/auth/resend-email-link';
|
import { ResendAuthLinkForm } from '@kit/auth/resend-email-link';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
|
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
interface AuthCallbackErrorPageProps {
|
interface AuthCallbackErrorPageProps {
|
||||||
searchParams: Promise<{
|
searchParams: Promise<{
|
||||||
error: string;
|
error: string;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
|
||||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||||
|
|||||||
@@ -1,19 +1,63 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import type { NextRequest } from 'next/server';
|
import type { NextRequest } from 'next/server';
|
||||||
|
|
||||||
import { createAuthCallbackService } from '@kit/supabase/auth';
|
import { createAccountsApi } from '@/packages/features/accounts/src/server/api';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
|
import {
|
||||||
|
createAuthCallbackService,
|
||||||
|
getErrorURLParameters,
|
||||||
|
} from '@kit/supabase/auth';
|
||||||
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
|
const ERROR_PATH = '/auth/callback/error';
|
||||||
|
|
||||||
|
const redirectOnError = (searchParams?: string) => {
|
||||||
|
return redirect(`${ERROR_PATH}${searchParams ? `?${searchParams}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
|
||||||
|
const error = searchParams.get('error');
|
||||||
|
if (error) {
|
||||||
|
const { searchParams } = getErrorURLParameters({ error });
|
||||||
|
return redirectOnError(searchParams);
|
||||||
|
}
|
||||||
|
|
||||||
|
const authCode = searchParams.get('code');
|
||||||
|
if (!authCode) {
|
||||||
|
return redirectOnError();
|
||||||
|
}
|
||||||
|
|
||||||
|
let redirectPath = searchParams.get('next') || pathsConfig.app.home;
|
||||||
|
// if we have an invite token, we redirect to the join team page
|
||||||
|
// instead of the default next url. This is because the user is trying
|
||||||
|
// to join a team and we want to make sure they are redirected to the
|
||||||
|
// correct page.
|
||||||
|
const inviteToken = searchParams.get('invite_token');
|
||||||
|
if (inviteToken) {
|
||||||
|
const urlParams = new URLSearchParams({
|
||||||
|
invite_token: inviteToken,
|
||||||
|
email: searchParams.get('email') ?? '',
|
||||||
|
});
|
||||||
|
|
||||||
|
redirectPath = `${pathsConfig.app.joinTeam}?${urlParams.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
const service = createAuthCallbackService(getSupabaseServerClient());
|
const service = createAuthCallbackService(getSupabaseServerClient());
|
||||||
|
const oauthResult = await service.exchangeCodeForSession(authCode);
|
||||||
|
if (!('isSuccess' in oauthResult)) {
|
||||||
|
return redirectOnError(oauthResult.searchParams);
|
||||||
|
}
|
||||||
|
|
||||||
const { nextPath } = await service.exchangeCodeForSession(request, {
|
const api = createAccountsApi(getSupabaseServerClient());
|
||||||
joinTeamPath: pathsConfig.app.joinTeam,
|
|
||||||
redirectPath: pathsConfig.app.home,
|
|
||||||
});
|
|
||||||
|
|
||||||
return redirect(nextPath);
|
const account = await api.getPersonalAccountByUserId(oauthResult.user.id);
|
||||||
|
|
||||||
|
if (!account.email || !account.name || !account.last_name) {
|
||||||
|
return redirect(pathsConfig.auth.updateAccount);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect(redirectPath);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
|
||||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { createAuthCallbackService } from '@kit/supabase/auth';
|
import { createAuthCallbackService } from '@kit/supabase/auth';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const service = createAuthCallbackService(getSupabaseServerClient());
|
const service = createAuthCallbackService(getSupabaseServerClient());
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { usePersonalAccountData } from '@kit/accounts/hooks/use-personal-account-data';
|
import { usePersonalAccountData } from '@kit/accounts/hooks/use-personal-account-data';
|
||||||
import { SuccessNotification } from '@kit/notifications/components';
|
import { SuccessNotification } from '@kit/notifications/components';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
|
|
||||||
const MembershipConfirmationNotification: React.FC<{
|
const MembershipConfirmationNotification: React.FC<{
|
||||||
userId: string;
|
userId: string;
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
async function SiteLayout(props: React.PropsWithChildren) {
|
async function SiteLayout(props: React.PropsWithChildren) {
|
||||||
return (
|
return (
|
||||||
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
|
||||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { PasswordResetRequestContainer } from '@kit/auth/password-reset';
|
import { PasswordResetRequestContainer } from '@kit/auth/password-reset';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
|
|||||||
56
app/auth/sign-in/components/PasswordOption.tsx
Normal file
56
app/auth/sign-in/components/PasswordOption.tsx
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
import { Providers, SignInMethodsContainer } from '@kit/auth/sign-in';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { Heading } from '@kit/ui/heading';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
export default function PasswordOption({
|
||||||
|
inviteToken,
|
||||||
|
returnPath,
|
||||||
|
providers,
|
||||||
|
}: {
|
||||||
|
inviteToken?: string;
|
||||||
|
returnPath?: string;
|
||||||
|
providers: Providers;
|
||||||
|
}) {
|
||||||
|
const signUpPath =
|
||||||
|
pathsConfig.auth.signUp +
|
||||||
|
(inviteToken ? `?invite_token=${inviteToken}` : '');
|
||||||
|
|
||||||
|
const paths = {
|
||||||
|
callback: pathsConfig.auth.callback,
|
||||||
|
returnPath: returnPath ?? pathsConfig.app.home,
|
||||||
|
joinTeam: pathsConfig.app.joinTeam,
|
||||||
|
updateAccount: pathsConfig.auth.updateAccount,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className={'flex flex-col items-center gap-1'}>
|
||||||
|
<Heading level={4} className={'tracking-tight'}>
|
||||||
|
<Trans i18nKey={'auth:signInHeading'} />
|
||||||
|
</Heading>
|
||||||
|
|
||||||
|
<p className={'text-muted-foreground text-sm'}>
|
||||||
|
<Trans i18nKey={'auth:signInSubheading'} />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SignInMethodsContainer
|
||||||
|
inviteToken={inviteToken}
|
||||||
|
paths={paths}
|
||||||
|
providers={providers}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className={'flex justify-center'}>
|
||||||
|
<Button asChild variant={'link'} size={'sm'}>
|
||||||
|
<Link href={signUpPath} prefetch={true}>
|
||||||
|
<Trans i18nKey={'auth:doNotHaveAccountYet'} />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
38
app/auth/sign-in/components/SignInPageClientRedirect.tsx
Normal file
38
app/auth/sign-in/components/SignInPageClientRedirect.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
import Loading from '@/app/home/loading';
|
||||||
|
import { getSupabaseBrowserClient } from '@/packages/supabase/src/clients/browser-client';
|
||||||
|
|
||||||
|
export function SignInPageClientRedirect() {
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
async function signIn() {
|
||||||
|
const { data, error } =
|
||||||
|
await getSupabaseBrowserClient().auth.signInWithOAuth({
|
||||||
|
provider: 'keycloak',
|
||||||
|
options: {
|
||||||
|
redirectTo: `${window.location.origin}/auth/callback`,
|
||||||
|
queryParams: {
|
||||||
|
prompt: 'login',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('OAuth error', error);
|
||||||
|
router.push('/');
|
||||||
|
} else if (data.url) {
|
||||||
|
router.push(data.url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
signIn();
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
return <Loading />;
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
|
||||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||||
|
|||||||
@@ -1,15 +1,11 @@
|
|||||||
import Link from 'next/link';
|
import { getServerAuthConfig, pathsConfig } from '@kit/shared/config';
|
||||||
|
|
||||||
|
|
||||||
import { SignInMethodsContainer } from '@kit/auth/sign-in';
|
|
||||||
import { authConfig, pathsConfig } from '@kit/shared/config';
|
|
||||||
import { Button } from '@kit/ui/button';
|
|
||||||
import { Heading } from '@kit/ui/heading';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
import PasswordOption from './components/PasswordOption';
|
||||||
|
import { SignInPageClientRedirect } from './components/SignInPageClientRedirect';
|
||||||
|
|
||||||
interface SignInPageProps {
|
interface SignInPageProps {
|
||||||
searchParams: Promise<{
|
searchParams: Promise<{
|
||||||
invite_token?: string;
|
invite_token?: string;
|
||||||
@@ -26,47 +22,26 @@ export const generateMetadata = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
async function SignInPage({ searchParams }: SignInPageProps) {
|
async function SignInPage({ searchParams }: SignInPageProps) {
|
||||||
const { invite_token: inviteToken, next = pathsConfig.app.home } =
|
const { invite_token: inviteToken, next: returnPath = pathsConfig.app.home } =
|
||||||
await searchParams;
|
await searchParams;
|
||||||
|
|
||||||
const signUpPath =
|
const authConfig = await getServerAuthConfig();
|
||||||
pathsConfig.auth.signUp +
|
|
||||||
(inviteToken ? `?invite_token=${inviteToken}` : '');
|
|
||||||
|
|
||||||
const paths = {
|
if (authConfig.providers.password) {
|
||||||
callback: pathsConfig.auth.callback,
|
return (
|
||||||
returnPath: next ?? pathsConfig.app.home,
|
<PasswordOption
|
||||||
joinTeam: pathsConfig.app.joinTeam,
|
|
||||||
updateAccount: pathsConfig.auth.updateAccount,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div className={'flex flex-col items-center gap-1'}>
|
|
||||||
<Heading level={4} className={'tracking-tight'}>
|
|
||||||
<Trans i18nKey={'auth:signInHeading'} />
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<p className={'text-muted-foreground text-sm'}>
|
|
||||||
<Trans i18nKey={'auth:signInSubheading'} />
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<SignInMethodsContainer
|
|
||||||
inviteToken={inviteToken}
|
inviteToken={inviteToken}
|
||||||
paths={paths}
|
returnPath={returnPath}
|
||||||
providers={authConfig.providers}
|
providers={authConfig.providers}
|
||||||
/>
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
<div className={'flex justify-center'}>
|
if (authConfig.providers.oAuth.includes('keycloak')) {
|
||||||
<Button asChild variant={'link'} size={'sm'}>
|
return <SignInPageClientRedirect />;
|
||||||
<Link href={signUpPath} prefetch={true}>
|
}
|
||||||
<Trans i18nKey={'auth:doNotHaveAccountYet'} />
|
|
||||||
</Link>
|
return null;
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default withI18n(SignInPage);
|
export default withI18n(SignInPage);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
|
||||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import { SignUpMethodsContainer } from '@kit/auth/sign-up';
|
import { SignUpMethodsContainer } from '@kit/auth/sign-up';
|
||||||
import { authConfig, pathsConfig } from '@kit/shared/config';
|
import { getServerAuthConfig, pathsConfig } from '@kit/shared/config';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
@@ -37,6 +37,12 @@ async function SignUpPage({ searchParams }: Props) {
|
|||||||
pathsConfig.auth.signIn +
|
pathsConfig.auth.signIn +
|
||||||
(inviteToken ? `?invite_token=${inviteToken}` : '');
|
(inviteToken ? `?invite_token=${inviteToken}` : '');
|
||||||
|
|
||||||
|
const authConfig = await getServerAuthConfig();
|
||||||
|
|
||||||
|
if (!authConfig.providers.password) {
|
||||||
|
return redirect('/');
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className={'flex flex-col items-center gap-1'}>
|
<div className={'flex flex-col items-center gap-1'}>
|
||||||
@@ -50,8 +56,7 @@ async function SignUpPage({ searchParams }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<SignUpMethodsContainer
|
<SignUpMethodsContainer
|
||||||
providers={authConfig.providers}
|
authConfig={authConfig}
|
||||||
displayTermsCheckbox={authConfig.displayTermsCheckbox}
|
|
||||||
inviteToken={inviteToken}
|
inviteToken={inviteToken}
|
||||||
paths={paths}
|
paths={paths}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { User } from '@supabase/supabase-js';
|
import { pathsConfig } from '@/packages/shared/src/config';
|
||||||
|
|
||||||
import { ExternalLink } from '@/public/assets/external-link';
|
import { ExternalLink } from '@/public/assets/external-link';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Checkbox } from '@kit/ui/checkbox';
|
import { Checkbox } from '@kit/ui/checkbox';
|
||||||
@@ -19,42 +21,97 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@kit/ui/form';
|
} from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
|
import { toast } from '@kit/ui/sonner';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { UpdateAccountSchema } from '../_lib/schemas/update-account.schema';
|
import { UpdateAccountSchemaClient } from '../_lib/schemas/update-account.schema';
|
||||||
import { onUpdateAccount } from '../_lib/server/update-account';
|
import { onUpdateAccount } from '../_lib/server/update-account';
|
||||||
|
|
||||||
export function UpdateAccountForm({ user }: { user: User }) {
|
type UpdateAccountFormValues = z.infer<
|
||||||
|
ReturnType<typeof UpdateAccountSchemaClient>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export function UpdateAccountForm({
|
||||||
|
defaultValues,
|
||||||
|
isEmailUser,
|
||||||
|
}: {
|
||||||
|
defaultValues: UpdateAccountFormValues;
|
||||||
|
isEmailUser: boolean;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const { t } = useTranslation('account');
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
resolver: zodResolver(UpdateAccountSchema),
|
resolver: zodResolver(UpdateAccountSchemaClient({ isEmailUser })),
|
||||||
mode: 'onChange',
|
mode: 'onChange',
|
||||||
defaultValues: {
|
defaultValues,
|
||||||
firstName: '',
|
|
||||||
lastName: '',
|
|
||||||
personalCode: '',
|
|
||||||
email: user.email,
|
|
||||||
phone: '',
|
|
||||||
city: '',
|
|
||||||
weight: 0,
|
|
||||||
height: 0,
|
|
||||||
userConsent: false,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const { firstName, lastName, personalCode, email, userConsent } =
|
||||||
|
defaultValues;
|
||||||
|
|
||||||
|
const defaultValues_weight =
|
||||||
|
'weight' in defaultValues ? defaultValues.weight : null;
|
||||||
|
const defaultValues_height =
|
||||||
|
'height' in defaultValues ? defaultValues.height : null;
|
||||||
|
|
||||||
|
const hasFirstName = !!firstName;
|
||||||
|
const hasLastName = !!lastName;
|
||||||
|
const hasPersonalCode = !!personalCode;
|
||||||
|
const hasEmail = !!email;
|
||||||
|
|
||||||
|
const onUpdateAccountOptions = async (values: UpdateAccountFormValues) => {
|
||||||
|
const loading = toast.loading(t('updateAccount.updateAccountLoading'));
|
||||||
|
try {
|
||||||
|
const response = await onUpdateAccount({
|
||||||
|
firstName: values.firstName || firstName,
|
||||||
|
lastName: values.lastName || lastName,
|
||||||
|
personalCode: values.personalCode || personalCode,
|
||||||
|
email: values.email || email,
|
||||||
|
phone: values.phone,
|
||||||
|
weight: ((('weight' in values && values.weight) ??
|
||||||
|
defaultValues_weight) ||
|
||||||
|
null) as number,
|
||||||
|
height: ((('height' in values && values.height) ??
|
||||||
|
defaultValues_height) ||
|
||||||
|
null) as number,
|
||||||
|
userConsent: values.userConsent ?? userConsent,
|
||||||
|
city: values.city,
|
||||||
|
});
|
||||||
|
if (!response) {
|
||||||
|
throw new Error('Failed to update account');
|
||||||
|
}
|
||||||
|
toast.dismiss(loading);
|
||||||
|
toast.success(t('updateAccount.updateAccountSuccess'));
|
||||||
|
|
||||||
|
if (response.hasUnseenMembershipConfirmation) {
|
||||||
|
router.push(pathsConfig.auth.membershipConfirmation);
|
||||||
|
} else {
|
||||||
|
router.push(pathsConfig.app.selectPackage);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.info('promiseresult error', error);
|
||||||
|
toast.error(t('updateAccount.updateAccountError'));
|
||||||
|
toast.dismiss(loading);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form
|
<form
|
||||||
className="flex flex-col gap-6 px-6 pt-10 text-left"
|
className="flex flex-col gap-6 px-6 pt-10 text-left"
|
||||||
onSubmit={form.handleSubmit(onUpdateAccount)}
|
onSubmit={form.handleSubmit(onUpdateAccountOptions)}
|
||||||
>
|
>
|
||||||
<FormField
|
<FormField
|
||||||
name="firstName"
|
name="firstName"
|
||||||
|
disabled={hasFirstName && !isEmailUser}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
<Trans i18nKey={'common:formField:firstName'} />
|
<Trans i18nKey={'common:formField:firstName'} />
|
||||||
</FormLabel>
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input {...field} />
|
<Input {...field} autoFocus={!hasFirstName} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
@@ -63,13 +120,14 @@ export function UpdateAccountForm({ user }: { user: User }) {
|
|||||||
|
|
||||||
<FormField
|
<FormField
|
||||||
name="lastName"
|
name="lastName"
|
||||||
|
disabled={hasLastName && !isEmailUser}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
<Trans i18nKey={'common:formField:lastName'} />
|
<Trans i18nKey={'common:formField:lastName'} />
|
||||||
</FormLabel>
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input {...field} />
|
<Input {...field} autoFocus={hasFirstName && !hasLastName} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
@@ -78,6 +136,7 @@ export function UpdateAccountForm({ user }: { user: User }) {
|
|||||||
|
|
||||||
<FormField
|
<FormField
|
||||||
name="personalCode"
|
name="personalCode"
|
||||||
|
disabled={hasPersonalCode && !isEmailUser}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
@@ -93,13 +152,14 @@ export function UpdateAccountForm({ user }: { user: User }) {
|
|||||||
|
|
||||||
<FormField
|
<FormField
|
||||||
name="email"
|
name="email"
|
||||||
|
disabled={hasEmail}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
<Trans i18nKey={'common:formField:email'} />
|
<Trans i18nKey={'common:formField:email'} />
|
||||||
</FormLabel>
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input {...field} disabled />
|
<Input {...field} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
@@ -121,72 +181,80 @@ export function UpdateAccountForm({ user }: { user: User }) {
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<FormField
|
{!isEmailUser && (
|
||||||
name="city"
|
<>
|
||||||
render={({ field }) => (
|
<FormField
|
||||||
<FormItem>
|
name="city"
|
||||||
<FormLabel>
|
render={({ field }) => (
|
||||||
<Trans i18nKey={'common:formField:city'} />
|
<FormItem>
|
||||||
</FormLabel>
|
<FormLabel>
|
||||||
<FormControl>
|
<Trans i18nKey={'common:formField:city'} />
|
||||||
<Input {...field} />
|
</FormLabel>
|
||||||
</FormControl>
|
<FormControl>
|
||||||
<FormMessage />
|
<Input {...field} />
|
||||||
</FormItem>
|
</FormControl>
|
||||||
)}
|
<FormMessage />
|
||||||
/>
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="flex flex-row justify-between gap-4">
|
<div className="flex flex-row justify-between gap-4">
|
||||||
<FormField
|
<FormField
|
||||||
name="weight"
|
name="weight"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem className="flex-1 basis-0">
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
<Trans i18nKey={'common:formField:weight'} />
|
<Trans i18nKey={'common:formField:weight'} />
|
||||||
</FormLabel>
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
type="number"
|
type="number"
|
||||||
placeholder="kg"
|
placeholder="kg"
|
||||||
{...field}
|
{...field}
|
||||||
value={field.value ?? ''}
|
value={field.value ?? ''}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
field.onChange(
|
field.onChange(
|
||||||
e.target.value === '' ? null : Number(e.target.value),
|
e.target.value === ''
|
||||||
)
|
? null
|
||||||
}
|
: Number(e.target.value),
|
||||||
/>
|
)
|
||||||
</FormControl>
|
}
|
||||||
<FormMessage />
|
/>
|
||||||
</FormItem>
|
</FormControl>
|
||||||
)}
|
<FormMessage />
|
||||||
/>
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
<FormField
|
<FormField
|
||||||
name="height"
|
name="height"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem className="flex-1 basis-0">
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
<Trans i18nKey={'common:formField:height'} />
|
<Trans i18nKey={'common:formField:height'} />
|
||||||
</FormLabel>
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder="cm"
|
placeholder="cm"
|
||||||
type="number"
|
type="number"
|
||||||
{...field}
|
{...field}
|
||||||
value={field.value ?? ''}
|
value={field.value ?? ''}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
field.onChange(
|
field.onChange(
|
||||||
e.target.value === '' ? null : Number(e.target.value),
|
e.target.value === ''
|
||||||
)
|
? null
|
||||||
}
|
: Number(e.target.value),
|
||||||
/>
|
)
|
||||||
</FormControl>
|
}
|
||||||
<FormMessage />
|
/>
|
||||||
</FormItem>
|
</FormControl>
|
||||||
)}
|
<FormMessage />
|
||||||
/>
|
</FormItem>
|
||||||
</div>
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<FormField
|
<FormField
|
||||||
name="userConsent"
|
name="userConsent"
|
||||||
@@ -205,7 +273,7 @@ export function UpdateAccountForm({ user }: { user: User }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Link
|
<Link
|
||||||
href={''}
|
href={t('account:updateAccount:userConsentUrlPath')}
|
||||||
className="flex flex-row items-center gap-2 text-sm hover:underline"
|
className="flex flex-row items-center gap-2 text-sm hover:underline"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
|
import Isikukood from 'isikukood';
|
||||||
|
import parsePhoneNumber from 'libphonenumber-js/min';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
export const UpdateAccountSchema = z.object({
|
const updateAccountSchema = {
|
||||||
firstName: z
|
firstName: z
|
||||||
.string({
|
.string({
|
||||||
error: 'First name is required',
|
error: 'First name is required',
|
||||||
@@ -10,20 +12,46 @@ export const UpdateAccountSchema = z.object({
|
|||||||
.string({
|
.string({
|
||||||
error: 'Last name is required',
|
error: 'Last name is required',
|
||||||
})
|
})
|
||||||
.nonempty(),
|
.nonempty({
|
||||||
personalCode: z
|
error: 'common:formFieldError.stringNonEmpty',
|
||||||
.string({
|
}),
|
||||||
error: 'Personal code is required',
|
personalCode: z.string().refine(
|
||||||
})
|
(val) => {
|
||||||
.nonempty(),
|
try {
|
||||||
|
return new Isikukood(val).validate();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
message: 'common:formFieldError.invalidPersonalCode',
|
||||||
|
},
|
||||||
|
),
|
||||||
email: z.string().email({
|
email: z.string().email({
|
||||||
message: 'Email is required',
|
message: 'Email is required',
|
||||||
}),
|
}),
|
||||||
phone: z
|
phone: z
|
||||||
.string({
|
.string({
|
||||||
error: 'Phone number is required',
|
error: 'error:invalidPhone',
|
||||||
})
|
})
|
||||||
.nonempty(),
|
.nonempty()
|
||||||
|
.refine(
|
||||||
|
(phone) => {
|
||||||
|
try {
|
||||||
|
const phoneNumber = parsePhoneNumber(phone);
|
||||||
|
return (
|
||||||
|
!!phoneNumber &&
|
||||||
|
phoneNumber.isValid() &&
|
||||||
|
phoneNumber.country === 'EE'
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
message: 'common:formFieldError.invalidPhoneNumber',
|
||||||
|
},
|
||||||
|
),
|
||||||
city: z.string().optional(),
|
city: z.string().optional(),
|
||||||
weight: z
|
weight: z
|
||||||
.number({
|
.number({
|
||||||
@@ -45,4 +73,39 @@ export const UpdateAccountSchema = z.object({
|
|||||||
userConsent: z.boolean().refine((val) => val === true, {
|
userConsent: z.boolean().refine((val) => val === true, {
|
||||||
message: 'Must be true',
|
message: 'Must be true',
|
||||||
}),
|
}),
|
||||||
|
} as const;
|
||||||
|
export const UpdateAccountSchemaServer = z.object({
|
||||||
|
firstName: updateAccountSchema.firstName,
|
||||||
|
lastName: updateAccountSchema.lastName,
|
||||||
|
personalCode: updateAccountSchema.personalCode,
|
||||||
|
email: updateAccountSchema.email,
|
||||||
|
phone: updateAccountSchema.phone,
|
||||||
|
city: updateAccountSchema.city,
|
||||||
|
weight: updateAccountSchema.weight.nullable(),
|
||||||
|
height: updateAccountSchema.height.nullable(),
|
||||||
|
userConsent: updateAccountSchema.userConsent,
|
||||||
});
|
});
|
||||||
|
export const UpdateAccountSchemaClient = ({
|
||||||
|
isEmailUser,
|
||||||
|
}: {
|
||||||
|
isEmailUser: boolean;
|
||||||
|
}) =>
|
||||||
|
z.object({
|
||||||
|
firstName: updateAccountSchema.firstName,
|
||||||
|
lastName: updateAccountSchema.lastName,
|
||||||
|
personalCode: updateAccountSchema.personalCode,
|
||||||
|
email: updateAccountSchema.email,
|
||||||
|
phone: updateAccountSchema.phone,
|
||||||
|
...(isEmailUser
|
||||||
|
? {
|
||||||
|
city: z.string().optional(),
|
||||||
|
weight: z.number().optional(),
|
||||||
|
height: z.number().optional(),
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
city: updateAccountSchema.city,
|
||||||
|
weight: updateAccountSchema.weight,
|
||||||
|
height: updateAccountSchema.height,
|
||||||
|
}),
|
||||||
|
userConsent: updateAccountSchema.userConsent,
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
|
||||||
|
|
||||||
import { updateCustomer } from '@lib/data/customer';
|
import { updateCustomer } from '@lib/data/customer';
|
||||||
|
|
||||||
import { AccountSubmitData, createAuthApi } from '@kit/auth/api';
|
import { AccountSubmitData, createAuthApi } from '@kit/auth/api';
|
||||||
import { enhanceAction } from '@kit/next/actions';
|
import { enhanceAction } from '@kit/next/actions';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { UpdateAccountSchemaServer } from '../schemas/update-account.schema';
|
||||||
|
|
||||||
|
|
||||||
import { UpdateAccountSchema } from '../schemas/update-account.schema';
|
|
||||||
|
|
||||||
export const onUpdateAccount = enhanceAction(
|
export const onUpdateAccount = enhanceAction(
|
||||||
async (params: AccountSubmitData) => {
|
async (params: AccountSubmitData) => {
|
||||||
@@ -28,22 +24,23 @@ export const onUpdateAccount = enhanceAction(
|
|||||||
console.warn('On update account error: ', err);
|
console.warn('On update account error: ', err);
|
||||||
}
|
}
|
||||||
|
|
||||||
await updateCustomer({
|
try {
|
||||||
first_name: params.firstName,
|
await updateCustomer({
|
||||||
last_name: params.lastName,
|
first_name: params.firstName,
|
||||||
phone: params.phone,
|
last_name: params.lastName,
|
||||||
});
|
phone: params.phone,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to update Medusa customer', e);
|
||||||
|
}
|
||||||
|
|
||||||
const hasUnseenMembershipConfirmation =
|
const hasUnseenMembershipConfirmation =
|
||||||
await api.hasUnseenMembershipConfirmation();
|
await api.hasUnseenMembershipConfirmation();
|
||||||
|
return {
|
||||||
if (hasUnseenMembershipConfirmation) {
|
hasUnseenMembershipConfirmation,
|
||||||
redirect(pathsConfig.auth.membershipConfirmation);
|
};
|
||||||
} else {
|
|
||||||
redirect(pathsConfig.app.selectPackage);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
schema: UpdateAccountSchema,
|
schema: UpdateAccountSchemaServer,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
|
||||||
async function SiteLayout(props: React.PropsWithChildren) {
|
async function SiteLayout(props: React.PropsWithChildren) {
|
||||||
return (
|
return (
|
||||||
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
|
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
|
||||||
import { signOutAction } from '@/lib/actions/sign-out';
|
import { signOutAction } from '@/lib/actions/sign-out';
|
||||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
|
||||||
|
|
||||||
import { BackButton } from '@kit/shared/components/back-button';
|
import { BackButton } from '@kit/shared/components/back-button';
|
||||||
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
||||||
@@ -9,23 +9,40 @@ import { pathsConfig } from '@kit/shared/config';
|
|||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
import { toTitleCase } from '~/lib/utils';
|
||||||
|
|
||||||
import { UpdateAccountForm } from './_components/update-account-form';
|
import { UpdateAccountForm } from './_components/update-account-form';
|
||||||
|
|
||||||
async function UpdateAccount() {
|
async function UpdateAccount() {
|
||||||
const client = getSupabaseServerClient();
|
const { account, user } = await loadCurrentUserAccount();
|
||||||
|
|
||||||
const {
|
const isKeycloakUser = user?.app_metadata?.provider === 'keycloak';
|
||||||
data: { user },
|
const isEmailUser = user?.app_metadata?.provider === 'email';
|
||||||
} = await client.auth.getUser();
|
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
redirect(pathsConfig.auth.signIn);
|
redirect(pathsConfig.auth.signIn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const defaultValues = {
|
||||||
|
firstName: account?.name ? toTitleCase(account.name) : '',
|
||||||
|
lastName: account?.last_name ? toTitleCase(account.last_name) : '',
|
||||||
|
personalCode: account?.personal_code ?? '',
|
||||||
|
email: (() => {
|
||||||
|
if (isKeycloakUser) {
|
||||||
|
return account?.email ?? '';
|
||||||
|
}
|
||||||
|
return account?.email ?? user?.email ?? '';
|
||||||
|
})(),
|
||||||
|
phone: account?.phone ?? '+372',
|
||||||
|
city: account?.city ?? '',
|
||||||
|
weight: account?.accountParams?.weight ?? null,
|
||||||
|
height: account?.accountParams?.height ?? null,
|
||||||
|
userConsent: account?.has_consent_personal_data ?? false,
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-border flex max-w-5xl flex-row overflow-hidden rounded-3xl border">
|
<div className="border-border xs:w-3/5 flex w-9/10 flex-row overflow-hidden rounded-3xl border md:w-[988px]">
|
||||||
<div className="relative flex min-w-md flex-col px-12 pt-7 pb-22 text-center md:w-1/2">
|
<div className="xs:px-6 relative flex w-full flex-col pt-7 pb-22 text-center md:w-1/2 md:px-12">
|
||||||
<BackButton onBack={signOutAction} />
|
<BackButton onBack={signOutAction} />
|
||||||
<MedReportLogo />
|
<MedReportLogo />
|
||||||
<h1 className="pt-8">
|
<h1 className="pt-8">
|
||||||
@@ -34,9 +51,12 @@ async function UpdateAccount() {
|
|||||||
<p className="text-muted-foreground pt-1 text-sm">
|
<p className="text-muted-foreground pt-1 text-sm">
|
||||||
<Trans i18nKey={'account:updateAccount:description'} />
|
<Trans i18nKey={'account:updateAccount:description'} />
|
||||||
</p>
|
</p>
|
||||||
<UpdateAccountForm user={user} />
|
<UpdateAccountForm
|
||||||
|
defaultValues={defaultValues}
|
||||||
|
isEmailUser={isEmailUser}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="hidden w-1/2 min-w-[460px] bg-[url(/assets/med-report-logo-big.png)] bg-cover bg-center bg-no-repeat md:block"></div>
|
<div className="hidden w-1/2 bg-[url(/assets/med-report-logo-big.png)] bg-cover bg-center bg-no-repeat md:block"></div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||||
|
|
||||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||||
|
|
||||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import { MultiFactorChallengeContainer } from '@kit/auth/mfa';
|
import { MultiFactorChallengeContainer } from '@kit/auth/mfa';
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { checkRequiresMultiFactorAuthentication } from '@kit/supabase/check-requires-mfa';
|
import { checkRequiresMultiFactorAuthentication } from '@kit/supabase/check-requires-mfa';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
@@ -41,7 +40,8 @@ async function VerifyPage(props: Props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const nextPath = (await props.searchParams).next;
|
const nextPath = (await props.searchParams).next;
|
||||||
const redirectPath = !!nextPath && nextPath.length > 0 ? nextPath : pathsConfig.app.home;
|
const redirectPath =
|
||||||
|
!!nextPath && nextPath.length > 0 ? nextPath : pathsConfig.app.home;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MultiFactorChallengeContainer
|
<MultiFactorChallengeContainer
|
||||||
|
|||||||
149
app/doctor/_components/analysis-doctor.tsx
Normal file
149
app/doctor/_components/analysis-doctor.tsx
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
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';
|
||||||
|
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
import { cn } from '@kit/ui/utils';
|
||||||
|
|
||||||
|
import { AnalysisElement } from '~/lib/services/analysis-element.service';
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
const AnalysisDoctor = ({
|
||||||
|
analysisElement,
|
||||||
|
results,
|
||||||
|
startIcon,
|
||||||
|
endIcon,
|
||||||
|
isCancelled,
|
||||||
|
}: {
|
||||||
|
analysisElement: Pick<AnalysisElement, 'analysis_name_lab'>;
|
||||||
|
results?: AnalysisResultForDisplay;
|
||||||
|
isCancelled?: boolean;
|
||||||
|
startIcon?: ReactElement | null;
|
||||||
|
endIcon?: ReactNode | null;
|
||||||
|
}) => {
|
||||||
|
const name = analysisElement.analysis_name_lab || '';
|
||||||
|
const status = results?.norm_status || AnalysisStatus.NORMAL;
|
||||||
|
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 [showTooltip, setShowTooltip] = useState(false);
|
||||||
|
const analysisResultLevel = useMemo(() => {
|
||||||
|
if (!results) {
|
||||||
|
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;
|
||||||
|
default:
|
||||||
|
return AnalysisResultLevel.NORMAL;
|
||||||
|
}
|
||||||
|
}, [results, value, normLower]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border-border rounded-lg border px-5">
|
||||||
|
<div className="flex flex-col items-center justify-between gap-2 py-3 sm:h-[65px] sm:flex-row sm:gap-0">
|
||||||
|
<div className="flex items-center gap-2 font-semibold">
|
||||||
|
{startIcon || <div className="w-4" />}
|
||||||
|
{name}
|
||||||
|
{results?.response_time && (
|
||||||
|
<div
|
||||||
|
className="group/tooltip relative"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setShowTooltip(!showTooltip);
|
||||||
|
}}
|
||||||
|
onMouseLeave={() => setShowTooltip(false)}
|
||||||
|
>
|
||||||
|
<Info className="hover" />{' '}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'absolute bottom-full left-1/2 z-10 mb-2 hidden -translate-x-1/2 rounded border bg-white p-4 text-sm whitespace-nowrap group-hover/tooltip:block',
|
||||||
|
{ block: showTooltip },
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Trans i18nKey="analysis-results:analysisDate" />
|
||||||
|
{': '}
|
||||||
|
{format(new Date(results.response_time), 'dd.MM.yyyy HH:mm')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{results ? (
|
||||||
|
<>
|
||||||
|
<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}
|
||||||
|
<div>
|
||||||
|
<Trans i18nKey="analysis-results:results.range.normal" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<AnalysisLevelBar
|
||||||
|
results={results}
|
||||||
|
normLowerIncluded={normLowerIncluded}
|
||||||
|
normUpperIncluded={normUpperIncluded}
|
||||||
|
level={analysisResultLevel!}
|
||||||
|
/>
|
||||||
|
{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 />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AnalysisDoctor;
|
||||||
132
app/doctor/_components/analysis-level-bar.tsx
Normal file
132
app/doctor/_components/analysis-level-bar.tsx
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
|
import { ArrowDown } from 'lucide-react';
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
const Level = ({
|
||||||
|
isActive = false,
|
||||||
|
color,
|
||||||
|
isFirst = false,
|
||||||
|
isLast = false,
|
||||||
|
arrowLocation,
|
||||||
|
}: {
|
||||||
|
isActive?: boolean;
|
||||||
|
color: 'destructive' | 'success' | 'warning' | 'gray-200';
|
||||||
|
isFirst?: boolean;
|
||||||
|
isLast?: boolean;
|
||||||
|
arrowLocation?: number;
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(`bg-${color} relative h-3 flex-1`, {
|
||||||
|
'opacity-20': !isActive,
|
||||||
|
'rounded-l-lg': isFirst,
|
||||||
|
'rounded-r-lg': isLast,
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{isActive && (
|
||||||
|
<div
|
||||||
|
className="absolute top-[-14px] left-1/2 -translate-x-1/2 rounded-[10px] bg-white p-[2px]"
|
||||||
|
style={{ left: `${arrowLocation}%` }}
|
||||||
|
>
|
||||||
|
<ArrowDown strokeWidth={2} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
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" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const AnalysisLevelBar = ({
|
||||||
|
normLowerIncluded = true,
|
||||||
|
normUpperIncluded = true,
|
||||||
|
level,
|
||||||
|
results,
|
||||||
|
}: {
|
||||||
|
normLowerIncluded?: boolean;
|
||||||
|
normUpperIncluded?: boolean;
|
||||||
|
level: AnalysisResultLevel;
|
||||||
|
results: AnalysisResultForDisplay;
|
||||||
|
}) => {
|
||||||
|
const {
|
||||||
|
norm_lower: lower,
|
||||||
|
norm_upper: upper,
|
||||||
|
response_value: value,
|
||||||
|
} = results;
|
||||||
|
const arrowLocation = useMemo(() => {
|
||||||
|
if (value < lower!) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normLowerIncluded || normUpperIncluded) {
|
||||||
|
return 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
const calculated = ((value - lower!) / (upper! - lower!)) * 100;
|
||||||
|
|
||||||
|
if (calculated > 100) {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
return calculated;
|
||||||
|
}, [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],
|
||||||
|
);
|
||||||
|
|
||||||
|
const hasAbnormalLevel = isVeryLow || isLow || isHigh || isVeryHigh;
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AnalysisLevelBar;
|
||||||
@@ -23,9 +23,7 @@ import {
|
|||||||
doctorAnalysisFeedbackFormSchema,
|
doctorAnalysisFeedbackFormSchema,
|
||||||
} from '@kit/doctor/schema/doctor-analysis.schema';
|
} from '@kit/doctor/schema/doctor-analysis.schema';
|
||||||
import ConfirmationModal from '@kit/shared/components/confirmation-modal';
|
import ConfirmationModal from '@kit/shared/components/confirmation-modal';
|
||||||
import {
|
import { useCurrentLocaleLanguageNames } from '@kit/shared/hooks';
|
||||||
useCurrentLocaleLanguageNames
|
|
||||||
} from '@kit/shared/hooks';
|
|
||||||
import { getFullName } from '@kit/shared/utils';
|
import { getFullName } from '@kit/shared/utils';
|
||||||
import { useUser } from '@kit/supabase/hooks/use-user';
|
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
} from '@kit/ui/collapsible';
|
} from '@kit/ui/collapsible';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import Analysis from '~/home/(user)/(dashboard)/analysis-results/_components/analysis';
|
import AnalysisDoctor from './analysis-doctor';
|
||||||
|
|
||||||
export default function DoctorAnalysisWrapper({
|
export default function DoctorAnalysisWrapper({
|
||||||
analysisData,
|
analysisData,
|
||||||
@@ -29,7 +29,7 @@ export default function DoctorAnalysisWrapper({
|
|||||||
asChild
|
asChild
|
||||||
>
|
>
|
||||||
<div className="[&[data-state=open]_.caret-icon]:rotate-180">
|
<div className="[&[data-state=open]_.caret-icon]:rotate-180">
|
||||||
<Analysis
|
<AnalysisDoctor
|
||||||
startIcon={
|
startIcon={
|
||||||
analysisData.latestPreviousAnalysis && (
|
analysisData.latestPreviousAnalysis && (
|
||||||
<CaretDownIcon className="caret-icon transition-transform duration-200" />
|
<CaretDownIcon className="caret-icon transition-transform duration-200" />
|
||||||
@@ -65,7 +65,7 @@ export default function DoctorAnalysisWrapper({
|
|||||||
{analysisData.latestPreviousAnalysis && (
|
{analysisData.latestPreviousAnalysis && (
|
||||||
<CollapsibleContent>
|
<CollapsibleContent>
|
||||||
<div className="my-1 flex flex-col">
|
<div className="my-1 flex flex-col">
|
||||||
<Analysis
|
<AnalysisDoctor
|
||||||
endIcon={
|
endIcon={
|
||||||
analysisData.latestPreviousAnalysis.comment && (
|
analysisData.latestPreviousAnalysis.comment && (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
getUserDoneResponsesAction,
|
getUserDoneResponsesAction,
|
||||||
getUserInProgressResponsesAction,
|
getUserInProgressResponsesAction,
|
||||||
} from '@kit/doctor/actions/table-data-fetching-actions';
|
} from '@kit/doctor/actions/table-data-fetching-actions';
|
||||||
|
|
||||||
import ResultsTableWrapper from './results-table-wrapper';
|
import ResultsTableWrapper from './results-table-wrapper';
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
|
||||||
import { isDoctor } from '@kit/doctor/lib/server/utils/is-doctor';
|
import { isDoctor } from '@kit/doctor/lib/server/utils/is-doctor';
|
||||||
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
type LayoutOrPageComponent<Params> = React.ComponentType<Params>;
|
type LayoutOrPageComponent<Params> = React.ComponentType<Params>;
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useTransition } from 'react';
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
|
import { capitalize } from 'lodash';
|
||||||
import { Eye } from 'lucide-react';
|
import { Eye } from 'lucide-react';
|
||||||
|
|
||||||
import { getResultSetName } from '@kit/doctor/lib/helpers';
|
import { getResultSetName } from '@kit/doctor/lib/helpers';
|
||||||
@@ -26,7 +27,6 @@ import {
|
|||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import DoctorJobSelect from './doctor-job-select';
|
import DoctorJobSelect from './doctor-job-select';
|
||||||
import { capitalize } from 'lodash';
|
|
||||||
|
|
||||||
export default function ResultsTable({
|
export default function ResultsTable({
|
||||||
results = [],
|
results = [],
|
||||||
@@ -189,7 +189,9 @@ export default function ResultsTable({
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
{capitalize(
|
{capitalize(
|
||||||
languageNames.of(result?.patient?.preferred_locale ?? 'et'),
|
languageNames.of(
|
||||||
|
result?.patient?.preferred_locale ?? 'et',
|
||||||
|
),
|
||||||
)}
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
|
|||||||
@@ -50,5 +50,3 @@ async function AnalysisPage({
|
|||||||
|
|
||||||
export default DoctorGuard(AnalysisPage);
|
export default DoctorGuard(AnalysisPage);
|
||||||
const loadResult = cache(getAnalysisResultsForDoctor);
|
const loadResult = cache(getAnalysisResultsForDoctor);
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { cookies } from 'next/headers';
|
|||||||
import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
|
import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
|
||||||
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
||||||
|
|
||||||
|
|
||||||
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
||||||
import { DoctorSidebar } from './_components/doctor-sidebar';
|
import { DoctorSidebar } from './_components/doctor-sidebar';
|
||||||
import { DoctorMobileNavigation } from './_components/mobile-navigation';
|
import { DoctorMobileNavigation } from './_components/mobile-navigation';
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ import Link from 'next/link';
|
|||||||
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
import { ArrowLeft, MessageCircle } from 'lucide-react';
|
||||||
|
|
||||||
import { useCaptureException } from '@kit/monitoring/hooks';
|
import { useCaptureException } from '@kit/monitoring/hooks';
|
||||||
|
import { RootProviders } from '@kit/shared/components/root-providers';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
||||||
import { RootProviders } from '@kit/shared/components/root-providers';
|
|
||||||
|
|
||||||
const GlobalErrorPage = ({
|
const GlobalErrorPage = ({
|
||||||
error,
|
error,
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import { ButtonTooltip } from '@kit/shared/components/ui/button-tooltip';
|
import { ButtonTooltip } from '@kit/shared/components/ui/button-tooltip';
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
@@ -22,14 +25,15 @@ export default async function AnalysisResultsPage({
|
|||||||
id: string;
|
id: string;
|
||||||
}>;
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const account = await loadCurrentUserAccount();
|
const { id: analysisOrderId } = await params;
|
||||||
|
|
||||||
const { id: analysisResponseId } = await params;
|
const [{ account }, analysisResponse] = await Promise.all([
|
||||||
|
loadCurrentUserAccount(),
|
||||||
|
loadUserAnalysis(Number(analysisOrderId)),
|
||||||
|
]);
|
||||||
|
|
||||||
const analysisResponse = await loadUserAnalysis(Number(analysisResponseId));
|
if (!account?.id) {
|
||||||
|
return redirect('/');
|
||||||
if (!account?.id || !analysisResponse) {
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await createPageViewLog({
|
await createPageViewLog({
|
||||||
@@ -37,46 +41,62 @@ export default async function AnalysisResultsPage({
|
|||||||
action: PageViewAction.VIEW_ANALYSIS_RESULTS,
|
action: PageViewAction.VIEW_ANALYSIS_RESULTS,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!analysisResponse) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader
|
||||||
|
title={<Trans i18nKey="analysis-results:pageTitle" />}
|
||||||
|
description={<Trans i18nKey="analysis-results:descriptionEmpty" />}
|
||||||
|
/>
|
||||||
|
<PageBody className="gap-4"></PageBody>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderedAnalysisElements = analysisResponse.orderedAnalysisElements;
|
||||||
|
const hasOrderedAnalysisElements = orderedAnalysisElements.length > 0;
|
||||||
|
const isPartialStatus =
|
||||||
|
analysisResponse.order.status === 'PARTIAL_ANALYSIS_RESPONSE';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader />
|
<PageHeader
|
||||||
<PageBody className="gap-4">
|
title={<Trans i18nKey="analysis-results:pageTitle" />}
|
||||||
<div className="mt-8 flex flex-col justify-between gap-4 sm:flex-row sm:items-center sm:gap-0">
|
description={
|
||||||
<div>
|
hasOrderedAnalysisElements ? (
|
||||||
<h4>
|
isPartialStatus ? (
|
||||||
<Trans i18nKey="analysis-results:pageTitle" />
|
<Trans i18nKey="analysis-results:descriptionPartial" />
|
||||||
</h4>
|
) : (
|
||||||
<p className="text-muted-foreground text-sm">
|
<Trans i18nKey="analysis-results:description" />
|
||||||
{analysisResponse?.elements &&
|
)
|
||||||
analysisResponse.elements?.length > 0 ? (
|
) : (
|
||||||
<Trans i18nKey="analysis-results:description" />
|
<Trans i18nKey="analysis-results:descriptionEmpty" />
|
||||||
) : (
|
)
|
||||||
<Trans i18nKey="analysis-results:descriptionEmpty" />
|
}
|
||||||
)}
|
>
|
||||||
</p>
|
<div>
|
||||||
</div>
|
|
||||||
<Button asChild>
|
<Button asChild>
|
||||||
<Link href={pathsConfig.app.orderAnalysisPackage}>
|
<Link href={pathsConfig.app.orderAnalysisPackage}>
|
||||||
<Trans i18nKey="analysis-results:orderNewAnalysis" />
|
<Trans i18nKey="analysis-results:orderNewAnalysis" />
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</PageHeader>
|
||||||
|
<PageBody className="gap-4 pt-4">
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<h4>
|
<h5 className="break-all">
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey="analysis-results:orderTitle"
|
i18nKey="analysis-results:orderTitle"
|
||||||
values={{ orderNumber: analysisResponse.order.medusa_order_id }}
|
values={{ orderNumber: analysisResponse.order.medusaOrderId }}
|
||||||
/>
|
|
||||||
</h4>
|
|
||||||
<h5>
|
|
||||||
<Trans
|
|
||||||
i18nKey={`orders:status.${analysisResponse.order.status}`}
|
|
||||||
/>
|
|
||||||
<ButtonTooltip
|
|
||||||
content={`${analysisResponse.order.created_at ? new Date(analysisResponse?.order?.created_at).toLocaleString() : ''}`}
|
|
||||||
className="ml-6"
|
|
||||||
/>
|
/>
|
||||||
</h5>
|
</h5>
|
||||||
|
<h6>
|
||||||
|
<Trans i18nKey={`orders:status.${analysisResponse.order.status}`} />
|
||||||
|
<ButtonTooltip
|
||||||
|
content={`${analysisResponse.order.createdAt ? new Date(analysisResponse?.order?.createdAt).toLocaleString() : ''}`}
|
||||||
|
className="ml-6"
|
||||||
|
/>
|
||||||
|
</h6>
|
||||||
</div>
|
</div>
|
||||||
{analysisResponse?.summary?.value && (
|
{analysisResponse?.summary?.value && (
|
||||||
<div>
|
<div>
|
||||||
@@ -87,13 +107,20 @@ export default async function AnalysisResultsPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
{analysisResponse.elements ? (
|
{orderedAnalysisElements ? (
|
||||||
analysisResponse.elements.map((element, index) => (
|
orderedAnalysisElements.map((element, index) => (
|
||||||
<Analysis
|
<React.Fragment key={element.analysisIdOriginal}>
|
||||||
key={index}
|
<Analysis element={element} />
|
||||||
analysisElement={{ analysis_name_lab: element.analysis_name }}
|
{element.results?.nestedElements?.map(
|
||||||
results={element}
|
(nestedElement, nestedIndex) => (
|
||||||
/>
|
<Analysis
|
||||||
|
key={`nested-${nestedElement.analysisElementOriginalId}-${nestedIndex}`}
|
||||||
|
nestedElement={nestedElement}
|
||||||
|
isNestedElement
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</React.Fragment>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<div className="text-muted-foreground text-sm">
|
<div className="text-muted-foreground text-sm">
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
|
import type { AnalysisResultDetailsElementResults } from '@/packages/features/user-analyses/src/types/analysis-results';
|
||||||
|
import { AnalysisResultLevel } from '@/packages/features/user-analyses/src/types/analysis-results';
|
||||||
import { ArrowDown } from 'lucide-react';
|
import { ArrowDown } from 'lucide-react';
|
||||||
|
|
||||||
import { cn } from '@kit/ui/utils';
|
import { cn } from '@kit/ui/utils';
|
||||||
import { AnalysisResultForDisplay } from './analysis';
|
|
||||||
|
|
||||||
export enum AnalysisResultLevel {
|
type AnalysisResultLevelBarResults = Pick<
|
||||||
VERY_LOW = 0,
|
AnalysisResultDetailsElementResults,
|
||||||
LOW = 1,
|
'normLower' | 'normUpper' | 'responseValue'
|
||||||
NORMAL = 2,
|
>;
|
||||||
HIGH = 3,
|
|
||||||
VERY_HIGH = 4,
|
|
||||||
}
|
|
||||||
|
|
||||||
const Level = ({
|
const Level = ({
|
||||||
isActive = false,
|
isActive = false,
|
||||||
@@ -19,17 +17,19 @@ const Level = ({
|
|||||||
isFirst = false,
|
isFirst = false,
|
||||||
isLast = false,
|
isLast = false,
|
||||||
arrowLocation,
|
arrowLocation,
|
||||||
|
normRangeText,
|
||||||
}: {
|
}: {
|
||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
color: 'destructive' | 'success' | 'warning' | 'gray-200';
|
color: 'destructive' | 'success' | 'warning' | 'gray-200';
|
||||||
isFirst?: boolean;
|
isFirst?: boolean;
|
||||||
isLast?: boolean;
|
isLast?: boolean;
|
||||||
arrowLocation?: number;
|
arrowLocation?: number;
|
||||||
|
normRangeText?: string | null;
|
||||||
}) => {
|
}) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(`bg-${color} relative h-3 flex-1`, {
|
className={cn(`bg-${color} relative h-3 flex-1`, {
|
||||||
'opacity-20': !isActive,
|
'opacity-60': !isActive,
|
||||||
'rounded-l-lg': isFirst,
|
'rounded-l-lg': isFirst,
|
||||||
'rounded-r-lg': isLast,
|
'rounded-r-lg': isLast,
|
||||||
})}
|
})}
|
||||||
@@ -37,96 +37,171 @@ const Level = ({
|
|||||||
{isActive && (
|
{isActive && (
|
||||||
<div
|
<div
|
||||||
className="absolute top-[-14px] left-1/2 -translate-x-1/2 rounded-[10px] bg-white p-[2px]"
|
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} />
|
<ArrowDown strokeWidth={2} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const AnalysisLevelBarSkeleton = () => {
|
{color === 'success' && typeof normRangeText === 'string' && (
|
||||||
return (
|
<p
|
||||||
<div className="mt-4 flex h-3 w-[35%] max-w-[360px] gap-1 sm:mt-0">
|
className={cn(
|
||||||
<Level color="gray-200" />
|
'text-muted-foreground absolute bottom-[-18px] left-3/8 text-xs font-bold whitespace-nowrap',
|
||||||
|
{
|
||||||
|
'opacity-60': isActive,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{normRangeText}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const AnalysisLevelBar = ({
|
const AnalysisLevelBar = ({
|
||||||
normLowerIncluded = true,
|
|
||||||
normUpperIncluded = true,
|
|
||||||
level,
|
level,
|
||||||
results,
|
results: { normLower: lower, normUpper: upper, responseValue: value },
|
||||||
|
normRangeText,
|
||||||
}: {
|
}: {
|
||||||
normLowerIncluded?: boolean;
|
|
||||||
normUpperIncluded?: boolean;
|
|
||||||
level: AnalysisResultLevel;
|
level: AnalysisResultLevel;
|
||||||
results: AnalysisResultForDisplay;
|
results: AnalysisResultLevelBarResults;
|
||||||
|
normRangeText: string | null;
|
||||||
}) => {
|
}) => {
|
||||||
|
// Calculate arrow position based on value within normal range
|
||||||
const { norm_lower: lower, norm_upper: upper, response_value: value } = results;
|
|
||||||
const arrowLocation = useMemo(() => {
|
const arrowLocation = useMemo(() => {
|
||||||
if (value < lower!) {
|
// If no response value, center the arrow
|
||||||
return 0;
|
if (value === null || value === undefined) {
|
||||||
}
|
|
||||||
|
|
||||||
if (normLowerIncluded || normUpperIncluded) {
|
|
||||||
return 50;
|
return 50;
|
||||||
}
|
}
|
||||||
|
|
||||||
const calculated = ((value - lower!) / (upper! - lower!)) * 100;
|
// If no normal ranges defined, center the arrow
|
||||||
|
if (lower === null && upper === null) {
|
||||||
if (calculated > 100) {
|
return 50;
|
||||||
return 100;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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]);
|
}, [value, upper, lower]);
|
||||||
|
|
||||||
const [isVeryLow, isLow, isHigh, isVeryHigh] = useMemo(() => [
|
// Determine level states based on normStatus
|
||||||
level === AnalysisResultLevel.VERY_LOW,
|
const isNormal = level === AnalysisResultLevel.NORMAL;
|
||||||
level === AnalysisResultLevel.LOW,
|
const isWarning = level === AnalysisResultLevel.WARNING;
|
||||||
level === AnalysisResultLevel.HIGH,
|
const isCritical = level === AnalysisResultLevel.CRITICAL;
|
||||||
level === AnalysisResultLevel.VERY_HIGH,
|
const isPending = level === null;
|
||||||
], [level, value, upper, lower]);
|
|
||||||
|
|
||||||
const hasAbnormalLevel = isVeryLow || isLow || isHigh || isVeryHigh;
|
// 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show appropriate levels based on available norm bounds
|
||||||
|
const hasLowerBound = lower !== null;
|
||||||
|
const hasUpperBound = upper !== null;
|
||||||
|
|
||||||
|
// Determine which section the value falls into
|
||||||
|
const isValueBelowLower = hasLowerBound && value !== null && value < lower!;
|
||||||
|
const isValueAboveUpper = hasUpperBound && value !== null && value > upper!;
|
||||||
|
const isValueInNormalRange = !isValueBelowLower && !isValueAboveUpper;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}, [
|
||||||
|
isValueBelowLower,
|
||||||
|
isValueAboveUpper,
|
||||||
|
isValueInNormalRange,
|
||||||
|
arrowLocation,
|
||||||
|
normRangeText,
|
||||||
|
isNormal,
|
||||||
|
isWarning,
|
||||||
|
isCritical,
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mt-4 flex h-3 w-[35%] max-w-[360px] gap-1 sm:mt-0">
|
<div
|
||||||
{normLowerIncluded && (
|
className={cn(
|
||||||
<>
|
'flex h-3 gap-1',
|
||||||
<Level
|
'mt-4 sm:mt-0',
|
||||||
isActive={isVeryLow}
|
'w-[60%] sm:w-[35%]',
|
||||||
color="destructive"
|
'min-w-[50vw] sm:min-w-auto',
|
||||||
isFirst
|
'max-w-[360px]',
|
||||||
/>
|
|
||||||
<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
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
|
>
|
||||||
|
<Level {...first} />
|
||||||
|
<Level {...second} />
|
||||||
|
<Level {...third} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,93 +1,142 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React, { ReactElement, ReactNode, useMemo, useState } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
|
|
||||||
import { UserAnalysisElement } from '@/packages/features/accounts/src/types/accounts';
|
import type {
|
||||||
|
AnalysisResultDetailsElement,
|
||||||
|
AnalysisResultsDetailsElementNested,
|
||||||
|
} from '@/packages/features/user-analyses/src/types/analysis-results';
|
||||||
|
import { AnalysisResultLevel } from '@/packages/features/user-analyses/src/types/analysis-results';
|
||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
import { Info } from 'lucide-react';
|
import { Info } from 'lucide-react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { cn } from '@kit/ui/utils';
|
import { cn } from '@kit/ui/utils';
|
||||||
|
|
||||||
import { AnalysisElement } from '~/lib/services/analysis-element.service';
|
import AnalysisLevelBar from './analysis-level-bar';
|
||||||
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
const Analysis = ({
|
const Analysis = ({
|
||||||
analysisElement,
|
element: elementOriginal,
|
||||||
results,
|
nestedElement,
|
||||||
startIcon,
|
isNestedElement = false,
|
||||||
endIcon,
|
|
||||||
isCancelled,
|
|
||||||
}: {
|
}: {
|
||||||
analysisElement: Pick<AnalysisElement, 'analysis_name_lab'>;
|
element?: AnalysisResultDetailsElement;
|
||||||
results?: AnalysisResultForDisplay;
|
nestedElement?: AnalysisResultsDetailsElementNested;
|
||||||
isCancelled?: boolean;
|
isNestedElement?: boolean;
|
||||||
startIcon?: ReactElement | null;
|
|
||||||
endIcon?: ReactNode | null;
|
|
||||||
}) => {
|
}) => {
|
||||||
const name = analysisElement.analysis_name_lab || '';
|
const { t } = useTranslation();
|
||||||
const status = results?.norm_status || AnalysisStatus.NORMAL;
|
|
||||||
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 [showTooltip, setShowTooltip] = useState(false);
|
const element = (() => {
|
||||||
const analysisResultLevel = useMemo(() => {
|
if (isNestedElement) {
|
||||||
|
return nestedElement!;
|
||||||
|
}
|
||||||
|
return elementOriginal!;
|
||||||
|
})();
|
||||||
|
const results: AnalysisResultDetailsElement['results'] = useMemo(() => {
|
||||||
|
if (isNestedElement) {
|
||||||
|
const nestedElement = element as AnalysisResultsDetailsElementNested;
|
||||||
|
return {
|
||||||
|
analysisElementOriginalId: nestedElement.analysisElementOriginalId,
|
||||||
|
normLower: nestedElement.normLower,
|
||||||
|
normUpper: nestedElement.normUpper,
|
||||||
|
normStatus: nestedElement.normStatus,
|
||||||
|
responseTime: nestedElement.responseTime,
|
||||||
|
responseValue: nestedElement.responseValue,
|
||||||
|
responseValueIsNegative: nestedElement.responseValueIsNegative,
|
||||||
|
responseValueIsWithinNorm: nestedElement.responseValueIsWithinNorm,
|
||||||
|
normLowerIncluded: nestedElement.normLowerIncluded,
|
||||||
|
normUpperIncluded: nestedElement.normUpperIncluded,
|
||||||
|
unit: nestedElement.unit,
|
||||||
|
status: nestedElement.status,
|
||||||
|
nestedElements: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return (element as AnalysisResultDetailsElement).results;
|
||||||
|
}, [element, isNestedElement]);
|
||||||
|
|
||||||
|
const name = element.analysisName || '';
|
||||||
|
|
||||||
|
const hasIsWithinNorm = results?.responseValueIsWithinNorm !== null;
|
||||||
|
const hasIsNegative = results?.responseValueIsNegative !== null;
|
||||||
|
|
||||||
|
const value = (() => {
|
||||||
if (!results) {
|
if (!results) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isUnderNorm = value < normLower;
|
const {
|
||||||
if (isUnderNorm) {
|
responseValue,
|
||||||
switch (status) {
|
responseValueIsNegative,
|
||||||
case AnalysisStatus.MEDIUM:
|
responseValueIsWithinNorm,
|
||||||
return AnalysisResultLevel.LOW;
|
} = results;
|
||||||
default:
|
if (responseValue === null || responseValue === undefined) {
|
||||||
return AnalysisResultLevel.VERY_LOW;
|
if (hasIsNegative) {
|
||||||
|
if (responseValueIsNegative) {
|
||||||
|
return t('analysis-results:results.value.negative');
|
||||||
|
}
|
||||||
|
return t('analysis-results:results.value.positive');
|
||||||
}
|
}
|
||||||
|
if (hasIsWithinNorm) {
|
||||||
|
if (responseValueIsWithinNorm) {
|
||||||
|
return t('analysis-results:results.value.isWithinNorm');
|
||||||
|
}
|
||||||
|
return t('analysis-results:results.value.isNotWithinNorm');
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
switch (status) {
|
|
||||||
case AnalysisStatus.MEDIUM:
|
return responseValue;
|
||||||
return AnalysisResultLevel.HIGH;
|
})();
|
||||||
case AnalysisStatus.HIGH:
|
const unit = results?.unit || '';
|
||||||
return AnalysisResultLevel.VERY_HIGH;
|
const normLower = results?.normLower ?? null;
|
||||||
|
const normUpper = results?.normUpper ?? null;
|
||||||
|
const normStatus = results?.normStatus ?? null;
|
||||||
|
|
||||||
|
const [showTooltip, setShowTooltip] = useState(false);
|
||||||
|
const analysisResultLevel = useMemo(() => {
|
||||||
|
if (normStatus === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (normStatus) {
|
||||||
|
case 1:
|
||||||
|
return AnalysisResultLevel.WARNING;
|
||||||
|
case 2:
|
||||||
|
return AnalysisResultLevel.CRITICAL;
|
||||||
|
case 0:
|
||||||
default:
|
default:
|
||||||
return AnalysisResultLevel.NORMAL;
|
return AnalysisResultLevel.NORMAL;
|
||||||
}
|
}
|
||||||
}, [results, value, normLower]);
|
}, [normStatus]);
|
||||||
|
|
||||||
|
const isCancelled = Number(results?.status) === 5;
|
||||||
|
const nestedElements = results?.nestedElements ?? null;
|
||||||
|
const hasNestedElements =
|
||||||
|
Array.isArray(nestedElements) && nestedElements.length > 0;
|
||||||
|
|
||||||
|
const normRangeText = (() => {
|
||||||
|
if (normLower === null && normUpper === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return `${normLower ?? '...'} - ${normUpper ?? '...'}`;
|
||||||
|
})();
|
||||||
|
const hasTextualResponse = hasIsNegative || hasIsWithinNorm;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-border rounded-lg border px-5">
|
<div
|
||||||
<div className="flex flex-col items-center justify-between gap-2 py-3 sm:h-[65px] sm:flex-row sm:gap-0">
|
className={cn('border-border rounded-lg border px-5', {
|
||||||
<div className="flex items-center gap-2 font-semibold">
|
'ml-8': isNestedElement,
|
||||||
{startIcon || <div className="w-4" />}
|
})}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col items-center justify-between gap-2 pt-3 pb-6 sm:h-[65px] sm:flex-row sm:gap-0 sm:py-3">
|
||||||
|
<div
|
||||||
|
className={cn('flex items-center gap-2 font-semibold', {
|
||||||
|
'font-bold': isNestedElement,
|
||||||
|
})}
|
||||||
|
>
|
||||||
{name}
|
{name}
|
||||||
{results?.response_time && (
|
{results?.responseTime && (
|
||||||
<div
|
<div
|
||||||
className="group/tooltip relative"
|
className="group/tooltip relative"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
@@ -105,42 +154,55 @@ const Analysis = ({
|
|||||||
>
|
>
|
||||||
<Trans i18nKey="analysis-results:analysisDate" />
|
<Trans i18nKey="analysis-results:analysisDate" />
|
||||||
{': '}
|
{': '}
|
||||||
{format(new Date(results.response_time), 'dd.MM.yyyy HH:mm')}
|
{format(new Date(results.responseTime), 'dd.MM.yyyy HH:mm')}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{results ? (
|
|
||||||
|
{isCancelled && (
|
||||||
|
<div className="text-sm font-semibold text-red-600">
|
||||||
|
<Trans i18nKey="analysis-results:cancelled" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isCancelled || !results || hasNestedElements ? null : (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-3 sm:ml-auto">
|
<div className="flex items-center gap-3 sm:ml-auto">
|
||||||
<div className="font-semibold">{value}</div>
|
<div
|
||||||
|
className={cn('font-semibold', {
|
||||||
|
'text-yellow-600':
|
||||||
|
hasTextualResponse &&
|
||||||
|
analysisResultLevel === AnalysisResultLevel.WARNING,
|
||||||
|
'text-red-600':
|
||||||
|
hasTextualResponse &&
|
||||||
|
analysisResultLevel === AnalysisResultLevel.CRITICAL,
|
||||||
|
'text-green-600':
|
||||||
|
hasTextualResponse &&
|
||||||
|
analysisResultLevel === AnalysisResultLevel.NORMAL,
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</div>
|
||||||
<div className="text-muted-foreground text-sm">{unit}</div>
|
<div className="text-muted-foreground text-sm">{unit}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground mx-8 flex flex-col-reverse gap-2 text-center text-sm sm:block sm:gap-0">
|
{!hasTextualResponse && (
|
||||||
{normLower} - {normUpper}
|
<>
|
||||||
<div>
|
<div className="text-muted-foreground mx-8 flex flex-col-reverse gap-2 text-center text-sm sm:block sm:gap-0">
|
||||||
<Trans i18nKey="analysis-results:results.range.normal" />
|
{normRangeText}
|
||||||
</div>
|
<div>
|
||||||
</div>
|
<Trans i18nKey="analysis-results:results.range.normal" />
|
||||||
<AnalysisLevelBar
|
</div>
|
||||||
results={results}
|
</div>
|
||||||
normLowerIncluded={normLowerIncluded}
|
<AnalysisLevelBar
|
||||||
normUpperIncluded={normUpperIncluded}
|
results={results}
|
||||||
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 />
|
|
||||||
</>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
108
app/home/(user)/(dashboard)/analysis-results/test/page.tsx
Normal file
108
app/home/(user)/(dashboard)/analysis-results/test/page.tsx
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
|
||||||
|
import Modal from '@modules/common/components/modal';
|
||||||
|
|
||||||
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import Analysis from '../_components/analysis';
|
||||||
|
import { analysisResponses } from './test-responses';
|
||||||
|
|
||||||
|
export default function AnalysisResultsPage() {
|
||||||
|
const [openBlocks, setOpenBlocks] = useState<number[]>([]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader />
|
||||||
|
<PageBody className="gap-4">
|
||||||
|
<div className="mt-8 flex flex-col justify-between gap-4 sm:flex-row sm:items-center sm:gap-0">
|
||||||
|
<div>
|
||||||
|
<h2>Analüüsi tulemused demo</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
{analysisResponses.map(({ id, orderedAnalysisElements }, index) => {
|
||||||
|
const isOpen = openBlocks.includes(id);
|
||||||
|
const closeModal = () =>
|
||||||
|
setOpenBlocks(openBlocks.filter((block) => block !== id));
|
||||||
|
return (
|
||||||
|
<div key={index} className="flex flex-col gap-2 py-4">
|
||||||
|
<div className="flex flex-col gap-2 pb-4">
|
||||||
|
<h3>AnalysisOrderId: {id}</h3>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<h5>OrderedAnalysisElements</h5>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
if (isOpen) {
|
||||||
|
closeModal();
|
||||||
|
} else {
|
||||||
|
setOpenBlocks([...openBlocks, id]);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-fit"
|
||||||
|
color={isOpen ? 'orange' : 'grey'}
|
||||||
|
>
|
||||||
|
{isOpen ? 'Close' : 'Open'}
|
||||||
|
</Button>
|
||||||
|
{isOpen && (
|
||||||
|
<Modal isOpen={isOpen} close={closeModal} size="large">
|
||||||
|
<div className="overflow-y-auto">
|
||||||
|
<p>NormiStaatus</p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
0 - testi väärtus jääb normaalväärtuste piirkonda
|
||||||
|
või on määramata,
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
1 - testi väärtus jääb hoiatava (tähelepanu
|
||||||
|
suunava) märkega piirkonda,
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
2 - testi väärtus on normaalväärtuste piirkonnast
|
||||||
|
väljas või kõrgendatud tähelepanu nõudvas
|
||||||
|
piirkonnas.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p>UuringOlek</p>
|
||||||
|
<ul>
|
||||||
|
<li>1 - Järjekorras,</li>
|
||||||
|
<li>2 - Ootel,</li>
|
||||||
|
<li>3 - Töös,</li>
|
||||||
|
<li>4 - Lõpetatud,</li>
|
||||||
|
<li>5 - Tagasi lükatud,</li>
|
||||||
|
<li>6 - Tühistatud,</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<pre className="bg-muted rounded-md p-4 text-sm">
|
||||||
|
{JSON.stringify(orderedAnalysisElements, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{orderedAnalysisElements ? (
|
||||||
|
orderedAnalysisElements.map((element, index) => (
|
||||||
|
<Analysis key={index} element={element} />
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<div className="text-muted-foreground text-sm">
|
||||||
|
<Trans i18nKey="analysis-results:noAnalysisElements" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<hr />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,906 @@
|
|||||||
|
import type { AnalysisResultDetailsMapped } from '@/packages/features/user-analyses/src/types/analysis-results';
|
||||||
|
|
||||||
|
type AnalysisTestResponse = Omit<
|
||||||
|
AnalysisResultDetailsMapped,
|
||||||
|
'order' | 'orderedAnalysisElementIds' | 'summary' | 'elements'
|
||||||
|
>;
|
||||||
|
|
||||||
|
const empty1: AnalysisTestResponse = {
|
||||||
|
id: 1,
|
||||||
|
orderedAnalysisElements: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const big1: AnalysisTestResponse = {
|
||||||
|
id: 2,
|
||||||
|
orderedAnalysisElements: [
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '1744-2',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'ALAT',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'U/l',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 45,
|
||||||
|
normStatus: 2,
|
||||||
|
responseTime: '2024-02-29T10:42:25+00:00',
|
||||||
|
responseValue: 84,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '1744-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '1920-8',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'ASAT',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'U/l',
|
||||||
|
normLower: 15,
|
||||||
|
normUpper: 45,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:20:55+00:00',
|
||||||
|
responseValue: 45,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '1920-8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '1988-5',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'CRP',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mg/l',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 5,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:18:49+00:00',
|
||||||
|
responseValue: 0.79,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '1988-5',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '57747-8',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Erütrotsüüdid',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 5,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: true,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '57747-8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '2276-4',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Ferritiin',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'µg/l',
|
||||||
|
normLower: 28,
|
||||||
|
normUpper: 370,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:46:54+00:00',
|
||||||
|
responseValue: 204.1,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '2276-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '14771-0',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Glükoos',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: 4.1,
|
||||||
|
normUpper: 6,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:06:24+00:00',
|
||||||
|
responseValue: 5.4,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '14771-0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '59156-0',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Glükoos',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 2,
|
||||||
|
normStatus: 2,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: false,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '59156-0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '59156-0',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Glükoos',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 2,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: true,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '59156-0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '13955-0',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'HCV Ab',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: null,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T13:44:48+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: true,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '13955-0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '14646-4',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'HDL kolesterool',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: 1,
|
||||||
|
normUpper: null,
|
||||||
|
normStatus: 1,
|
||||||
|
responseTime: '2024-02-29T10:20:55+00:00',
|
||||||
|
responseValue: 0.8,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '14646-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '2000-8',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Kaltsium',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: 2.1,
|
||||||
|
normUpper: 2.55,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:12:10+00:00',
|
||||||
|
responseValue: 2.49,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '2000-8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '59158-6',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Ketokehad',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 0.5,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: true,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '59158-6',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '14647-2',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Kolesterool',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 5,
|
||||||
|
normStatus: 1,
|
||||||
|
responseTime: '2024-02-29T10:20:34+00:00',
|
||||||
|
responseValue: 5.7,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '14647-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '14682-9',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Kreatiniin',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'µmol/l',
|
||||||
|
normLower: 64,
|
||||||
|
normUpper: 111,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:19:00+00:00',
|
||||||
|
responseValue: 89,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '14682-9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '22748-8',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'LDL kolesterool',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 3,
|
||||||
|
normStatus: 1,
|
||||||
|
responseTime: '2024-02-29T10:21:15+00:00',
|
||||||
|
responseValue: 4.3,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '22748-8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '58805-3',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Leukotsüüdid',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 10,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: true,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '58805-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '2601-3',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Magneesium',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: 0.66,
|
||||||
|
normUpper: 1.07,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:17:26+00:00',
|
||||||
|
responseValue: 0.82,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '2601-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '70204-3',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Mitte-HDL kolesterool',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
labComment: 'Mitte-paastu veri <3,9 mmol/L',
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 3.8,
|
||||||
|
normStatus: 1,
|
||||||
|
responseTime: '2024-02-29T10:20:55+00:00',
|
||||||
|
responseValue: 4.9,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '70204-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '14798-3',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Raud',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'µmol/l',
|
||||||
|
normLower: 11.6,
|
||||||
|
normUpper: 31.3,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:21:16+00:00',
|
||||||
|
responseValue: 16.5,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '14798-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '14927-8',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Triglütseriidid',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
labComment: 'Mitte-paastu veri <2,0 mmol/L',
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 1.7,
|
||||||
|
normStatus: 1,
|
||||||
|
responseTime: '2024-02-29T10:21:16+00:00',
|
||||||
|
responseValue: 1.89,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '14927-8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '3016-3',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'TSH',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mIU/l',
|
||||||
|
normLower: 0.4,
|
||||||
|
normUpper: 4,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:49:02+00:00',
|
||||||
|
responseValue: 1.27,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '3016-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '22664-7',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Uurea',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mmol/l',
|
||||||
|
normLower: 3.2,
|
||||||
|
normUpper: 7.4,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:19:11+00:00',
|
||||||
|
responseValue: 6.4,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '22664-7',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '50561-0',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Valk',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 0.25,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: true,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '50561-0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '60493-4',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Vitamiin D (25-OH)',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
labComment: 'Väärtus >75 nmol/l on D-vitamiini tervislik tase',
|
||||||
|
unit: 'nmol/l',
|
||||||
|
normLower: 75,
|
||||||
|
normUpper: null,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:49:22+00:00',
|
||||||
|
responseValue: 105.5,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '60493-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '60025-4',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Urobilinogeen',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 17,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2024-02-29T10:13:01+00:00',
|
||||||
|
responseValue: null,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: true,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '60025-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const big2: AnalysisTestResponse = {
|
||||||
|
id: 3,
|
||||||
|
orderedAnalysisElements: [
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '1988-5',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'CRP',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
unit: 'mg/L',
|
||||||
|
normLower: null,
|
||||||
|
normUpper: 5,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12T14:02:04+00:00',
|
||||||
|
responseValue: 1,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '1988-5',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '57021-8',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Hemogramm',
|
||||||
|
results: {
|
||||||
|
nestedElements: [
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'g/L',
|
||||||
|
normLower: 134,
|
||||||
|
normUpper: 170,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:03',
|
||||||
|
responseValue: 150,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '718-7',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: '%',
|
||||||
|
normLower: 40,
|
||||||
|
normUpper: 49,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:03',
|
||||||
|
responseValue: 45,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '4544-3',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 4.1,
|
||||||
|
normUpper: 9.7,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:03',
|
||||||
|
responseValue: 5,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '6690-2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E12/L',
|
||||||
|
normLower: 4.5,
|
||||||
|
normUpper: 5.7,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:03',
|
||||||
|
responseValue: 5,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '789-8',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'fL',
|
||||||
|
normLower: 82,
|
||||||
|
normUpper: 95,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 85,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '787-2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'pg',
|
||||||
|
normLower: 28,
|
||||||
|
normUpper: 33,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 30,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '785-6',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'g/L',
|
||||||
|
normLower: 322,
|
||||||
|
normUpper: 356,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 355,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '786-4',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: '%',
|
||||||
|
normLower: 12,
|
||||||
|
normUpper: 15,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 15,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '788-0',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 157,
|
||||||
|
normUpper: 372,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 255,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '777-3',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: '%',
|
||||||
|
normLower: 0.18,
|
||||||
|
normUpper: 0.38,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0.2,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '51637-7',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'fL',
|
||||||
|
normLower: 9.2,
|
||||||
|
normUpper: 12.3,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 10,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '32623-1',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'fL',
|
||||||
|
normLower: 10.1,
|
||||||
|
normUpper: 16.2,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 15,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '32207-3',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 0.01,
|
||||||
|
normUpper: 0.08,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0.05,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '704-7',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 0.02,
|
||||||
|
normUpper: 0.4,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0.05,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '711-2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 1.9,
|
||||||
|
normUpper: 6.7,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 5,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '751-8',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 0.24,
|
||||||
|
normUpper: 0.8,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0.5,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '742-7',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 1.3,
|
||||||
|
normUpper: 3.1,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 1.5,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '731-0',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normLower: 0,
|
||||||
|
normUpper: 0.03,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:03',
|
||||||
|
responseValue: 0,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '51584-1',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: '%',
|
||||||
|
normLower: 0,
|
||||||
|
normUpper: 0.5,
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '38518-7',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: 'E9/L',
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0,
|
||||||
|
normUpper: null,
|
||||||
|
normLower: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '771-6',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 4,
|
||||||
|
unit: '/100WBC',
|
||||||
|
normStatus: 0,
|
||||||
|
responseTime: '2025-09-12 14:02:04',
|
||||||
|
responseValue: 0,
|
||||||
|
normUpper: null,
|
||||||
|
normLower: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
analysisElementOriginalId: '58413-6',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: null,
|
||||||
|
normStatus: null,
|
||||||
|
responseTime: null,
|
||||||
|
responseValue: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: false,
|
||||||
|
responseValueIsWithinNorm: false,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '57021-8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '43583-4',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Lipoproteiin a',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
labComment: 'Kliendi soovil analüüs tühistatud.',
|
||||||
|
unit: null,
|
||||||
|
normLower: null,
|
||||||
|
normUpper: null,
|
||||||
|
normStatus: null,
|
||||||
|
responseTime: null,
|
||||||
|
responseValue: null,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: false,
|
||||||
|
responseValueIsWithinNorm: false,
|
||||||
|
status: 5,
|
||||||
|
analysisElementOriginalId: '43583-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
analysisIdOriginal: '60493-4',
|
||||||
|
isWaitingForResults: false,
|
||||||
|
analysisName: 'Vitamiin D (25-OH)',
|
||||||
|
results: {
|
||||||
|
nestedElements: [],
|
||||||
|
labComment:
|
||||||
|
'Väärtus vahemikus 30-49.9 nmol/L on D-vitamiini ebapiisav tase.',
|
||||||
|
unit: 'nmol/L',
|
||||||
|
normLower: 75,
|
||||||
|
normUpper: null,
|
||||||
|
normStatus: 1,
|
||||||
|
responseTime: '2025-09-12T14:02:04+00:00',
|
||||||
|
responseValue: 30,
|
||||||
|
normLowerIncluded: false,
|
||||||
|
normUpperIncluded: false,
|
||||||
|
responseValueIsNegative: null,
|
||||||
|
responseValueIsWithinNorm: null,
|
||||||
|
status: 4,
|
||||||
|
analysisElementOriginalId: '60493-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
export const analysisResponses: AnalysisTestResponse[] = [empty1, big1, big2];
|
||||||
@@ -28,9 +28,13 @@ function BookingPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<AppBreadcrumbs />
|
<AppBreadcrumbs />
|
||||||
<h3 className="mt-8">
|
<HomeLayoutPageHeader
|
||||||
|
title={<Trans i18nKey={'booking:title'} />}
|
||||||
|
description={<Trans i18nKey={'booking:description'} />}
|
||||||
|
/>
|
||||||
|
<h4 className="mt-8">
|
||||||
<Trans i18nKey="booking:noCategories" />
|
<Trans i18nKey="booking:noCategories" />
|
||||||
</h3>
|
</h4>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,91 +1,15 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
|
import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types';
|
||||||
|
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
|
||||||
|
import { retrieveCart } from '@lib/data/cart';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
import { z } from "zod";
|
|
||||||
import { MontonioOrderToken } from "@/app/home/(user)/_components/cart/types";
|
|
||||||
import { loadCurrentUserAccount } from "@/app/home/(user)/_lib/server/load-user-account";
|
|
||||||
import { listProductTypes } from "@lib/data/products";
|
|
||||||
import { placeOrder, retrieveCart } from "@lib/data/cart";
|
|
||||||
import { createI18nServerInstance } from "~/lib/i18n/i18n.server";
|
|
||||||
import { createOrder } from '~/lib/services/order.service';
|
|
||||||
import { getOrderedAnalysisElementsIds, sendOrderToMedipost } from '~/lib/services/medipost.service';
|
|
||||||
import { createNotificationsApi } from '@kit/notifications/api';
|
|
||||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
|
||||||
import { AccountWithParams } from '@kit/accounts/api';
|
|
||||||
|
|
||||||
const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages';
|
import { handlePlaceOrder } from '../../../_lib/server/cart-actions';
|
||||||
|
|
||||||
const MONTONIO_PAID_STATUS = 'PAID';
|
const MONTONIO_PAID_STATUS = 'PAID';
|
||||||
|
|
||||||
const env = () => z
|
async function decodeOrderToken(orderToken: string) {
|
||||||
.object({
|
|
||||||
emailSender: z
|
|
||||||
.string({
|
|
||||||
error: 'EMAIL_SENDER is required',
|
|
||||||
})
|
|
||||||
.min(1),
|
|
||||||
siteUrl: z
|
|
||||||
.string({
|
|
||||||
error: 'NEXT_PUBLIC_SITE_URL is required',
|
|
||||||
})
|
|
||||||
.min(1),
|
|
||||||
})
|
|
||||||
.parse({
|
|
||||||
emailSender: process.env.EMAIL_SENDER,
|
|
||||||
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
|
|
||||||
});
|
|
||||||
|
|
||||||
const sendEmail = async ({
|
|
||||||
account,
|
|
||||||
email,
|
|
||||||
analysisPackageName,
|
|
||||||
personName,
|
|
||||||
partnerLocationName,
|
|
||||||
language,
|
|
||||||
}: {
|
|
||||||
account: AccountWithParams,
|
|
||||||
email: string,
|
|
||||||
analysisPackageName: string,
|
|
||||||
personName: string,
|
|
||||||
partnerLocationName: string,
|
|
||||||
language: string,
|
|
||||||
}) => {
|
|
||||||
const client = getSupabaseServerAdminClient();
|
|
||||||
try {
|
|
||||||
const { renderSynlabAnalysisPackageEmail } = await import('@kit/email-templates');
|
|
||||||
const { getMailer } = await import('@kit/mailers');
|
|
||||||
|
|
||||||
const mailer = await getMailer();
|
|
||||||
|
|
||||||
const { html, subject } = await renderSynlabAnalysisPackageEmail({
|
|
||||||
analysisPackageName,
|
|
||||||
personName,
|
|
||||||
partnerLocationName,
|
|
||||||
language,
|
|
||||||
});
|
|
||||||
|
|
||||||
await mailer
|
|
||||||
.sendEmail({
|
|
||||||
from: env().emailSender,
|
|
||||||
to: email,
|
|
||||||
subject,
|
|
||||||
html,
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
throw new Error(`Failed to send email, message=${error}`);
|
|
||||||
});
|
|
||||||
await createNotificationsApi(client)
|
|
||||||
.createNotification({
|
|
||||||
account_id: account.id,
|
|
||||||
body: html,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Failed to send email, message=${error}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function processMontonioCallback(orderToken: string) {
|
|
||||||
const { language } = await createI18nServerInstance();
|
|
||||||
|
|
||||||
const secretKey = process.env.MONTONIO_SECRET_KEY as string;
|
const secretKey = process.env.MONTONIO_SECRET_KEY as string;
|
||||||
|
|
||||||
const decoded = jwt.verify(orderToken, secretKey, {
|
const decoded = jwt.verify(orderToken, secretKey, {
|
||||||
@@ -93,61 +17,37 @@ export async function processMontonioCallback(orderToken: string) {
|
|||||||
}) as MontonioOrderToken;
|
}) as MontonioOrderToken;
|
||||||
|
|
||||||
if (decoded.paymentStatus !== MONTONIO_PAID_STATUS) {
|
if (decoded.paymentStatus !== MONTONIO_PAID_STATUS) {
|
||||||
throw new Error("Payment not successful");
|
throw new Error('Payment not successful');
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = await loadCurrentUserAccount();
|
return decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getCartByOrderToken(decoded: MontonioOrderToken) {
|
||||||
|
const [, , cartId] = decoded.merchantReferenceDisplay.split(':');
|
||||||
|
if (!cartId) {
|
||||||
|
throw new Error('Cart ID not found');
|
||||||
|
}
|
||||||
|
const cart = await retrieveCart(cartId);
|
||||||
|
if (!cart) {
|
||||||
|
throw new Error('Cart not found');
|
||||||
|
}
|
||||||
|
return cart;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function processMontonioCallback(orderToken: string) {
|
||||||
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error("Account not found in context");
|
throw new Error('Account not found in context');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [, , cartId] = decoded.merchantReferenceDisplay.split(':');
|
const decoded = await decodeOrderToken(orderToken);
|
||||||
if (!cartId) {
|
const cart = await getCartByOrderToken(decoded);
|
||||||
throw new Error("Cart ID not found");
|
const result = await handlePlaceOrder({ cart });
|
||||||
}
|
return result;
|
||||||
|
|
||||||
const cart = await retrieveCart(cartId);
|
|
||||||
if (!cart) {
|
|
||||||
throw new Error("Cart not found");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const medusaOrder = await placeOrder(cartId, { revalidateCacheTags: false });
|
|
||||||
const orderedAnalysisElements = await getOrderedAnalysisElementsIds({ medusaOrder });
|
|
||||||
const orderId = await createOrder({ medusaOrder, orderedAnalysisElements });
|
|
||||||
|
|
||||||
const { productTypes } = await listProductTypes();
|
|
||||||
const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === ANALYSIS_PACKAGES_TYPE_HANDLE);
|
|
||||||
const analysisPackageOrderItem = medusaOrder.items?.find(({ product_type_id }) => product_type_id === analysisPackagesType?.id);
|
|
||||||
|
|
||||||
const orderResult = {
|
|
||||||
medusaOrderId: medusaOrder.id,
|
|
||||||
email: medusaOrder.email,
|
|
||||||
partnerLocationName: analysisPackageOrderItem?.metadata?.partner_location_name as string ?? '',
|
|
||||||
analysisPackageName: analysisPackageOrderItem?.title ?? '',
|
|
||||||
orderedAnalysisElements,
|
|
||||||
};
|
|
||||||
|
|
||||||
const { medusaOrderId, email, partnerLocationName, analysisPackageName } = orderResult;
|
|
||||||
const personName = account.name;
|
|
||||||
|
|
||||||
if (email && analysisPackageName) {
|
|
||||||
try {
|
|
||||||
await sendEmail({ account, email, analysisPackageName, personName, partnerLocationName, language });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to send email", error);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// @TODO send email for separate analyses
|
|
||||||
console.error("Missing email or analysisPackageName", orderResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
|
||||||
|
|
||||||
return { success: true, orderId };
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to place order", error);
|
console.error('Failed to place order', error);
|
||||||
throw new Error(`Failed to place order, message=${error}`);
|
throw new Error(`Failed to place order, message=${error}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { processMontonioCallback } from './actions';
|
import { processMontonioCallback } from './actions';
|
||||||
|
|
||||||
export default function MontonioCallbackClient({ orderToken, error }: {
|
export default function MontonioCallbackClient({
|
||||||
|
orderToken,
|
||||||
|
error,
|
||||||
|
}: {
|
||||||
orderToken?: string;
|
orderToken?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
}) {
|
}) {
|
||||||
@@ -32,7 +37,7 @@ export default function MontonioCallbackClient({ orderToken, error }: {
|
|||||||
const { orderId } = await processMontonioCallback(orderToken);
|
const { orderId } = await processMontonioCallback(orderToken);
|
||||||
router.push(`/home/order/${orderId}/confirmed`);
|
router.push(`/home/order/${orderId}/confirmed`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to place order", error);
|
console.error('Failed to place order', error);
|
||||||
router.push('/home/cart/montonio-callback/error');
|
router.push('/home/cart/montonio-callback/error');
|
||||||
} finally {
|
} finally {
|
||||||
setIsProcessing(false);
|
setIsProcessing(false);
|
||||||
@@ -43,9 +48,9 @@ export default function MontonioCallbackClient({ orderToken, error }: {
|
|||||||
}, [orderToken, error, router, hasProcessed, isProcessing]);
|
}, [orderToken, error, router, hasProcessed, isProcessing]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex mt-10 justify-center min-h-screen">
|
<div className="mt-10 flex min-h-screen justify-center">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
|
<div className="border-primary mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
|
||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||||
|
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
import { Alert, AlertDescription } from '@kit/ui/shadcn/alert';
|
import { Alert, AlertDescription } from '@kit/ui/shadcn/alert';
|
||||||
import { AlertTitle } from '@kit/ui/shadcn/alert';
|
import { AlertTitle } from '@kit/ui/shadcn/alert';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import MontonioCallbackClient from './client-component';
|
import MontonioCallbackClient from './client-component';
|
||||||
|
|
||||||
export default async function MontonioCallbackPage({ searchParams }: {
|
export default async function MontonioCallbackPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
searchParams: Promise<{
|
searchParams: Promise<{
|
||||||
'order-token'?: string;
|
'order-token'?: string;
|
||||||
}>;
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const orderToken = (await searchParams)['order-token'];
|
const orderToken = (await searchParams)['order-token'];
|
||||||
|
|
||||||
if (!orderToken) {
|
if (!orderToken) {
|
||||||
return <MontonioCallbackClient error="Order token is missing" />;
|
return <MontonioCallbackClient error="Order token is missing" />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||||
|
|
||||||
import { notFound } from 'next/navigation';
|
|
||||||
|
|
||||||
import { retrieveCart } from '@lib/data/cart';
|
import { retrieveCart } from '@lib/data/cart';
|
||||||
import Cart from '../../_components/cart';
|
|
||||||
import { listProductTypes } from '@lib/data/products';
|
import { listProductTypes } from '@lib/data/products';
|
||||||
import CartTimer from '../../_components/cart/cart-timer';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
import Cart from '../../_components/cart';
|
||||||
|
import CartTimer from '../../_components/cart/cart-timer';
|
||||||
|
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||||
|
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
@@ -17,36 +20,67 @@ export async function generateMetadata() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function CartPage() {
|
async function CartPage() {
|
||||||
const cart = await retrieveCart().catch((error) => {
|
const [
|
||||||
console.error(error);
|
cart,
|
||||||
return notFound();
|
{ productTypes },
|
||||||
});
|
{ account },
|
||||||
|
] = await Promise.all([
|
||||||
|
retrieveCart(),
|
||||||
|
listProductTypes(),
|
||||||
|
loadCurrentUserAccount(),
|
||||||
|
]);
|
||||||
|
|
||||||
const { productTypes } = await listProductTypes();
|
if (!account) {
|
||||||
const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages');
|
return null;
|
||||||
const synlabAnalysisType = productTypes.find(({ metadata }) => metadata?.handle === 'synlab-analysis');
|
}
|
||||||
const synlabAnalyses = analysisPackagesType && synlabAnalysisType && cart?.items
|
|
||||||
? cart.items.filter((item) => {
|
|
||||||
const productTypeId = item.product?.type_id;
|
|
||||||
if (!productTypeId) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return [analysisPackagesType.id, synlabAnalysisType.id].includes(productTypeId);
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
const ttoServiceItems = cart?.items?.filter((item) => !synlabAnalyses.some((analysis) => analysis.id === item.id)) ?? [];
|
|
||||||
|
|
||||||
const otherItemsSorted = ttoServiceItems.sort((a, b) => (a.updated_at ?? "") > (b.updated_at ?? "") ? -1 : 1);
|
const balanceSummary = await new AccountBalanceService().getBalanceSummary(account.id);
|
||||||
|
|
||||||
|
const analysisPackagesType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === 'analysis-packages',
|
||||||
|
);
|
||||||
|
const synlabAnalysisType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === 'synlab-analysis',
|
||||||
|
);
|
||||||
|
const synlabAnalyses =
|
||||||
|
analysisPackagesType && synlabAnalysisType && cart?.items
|
||||||
|
? cart.items.filter((item) => {
|
||||||
|
const productTypeId = item.product?.type_id;
|
||||||
|
if (!productTypeId) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return [analysisPackagesType.id, synlabAnalysisType.id].includes(
|
||||||
|
productTypeId,
|
||||||
|
);
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
const ttoServiceItems =
|
||||||
|
cart?.items?.filter(
|
||||||
|
(item) => !synlabAnalyses.some((analysis) => analysis.id === item.id),
|
||||||
|
) ?? [];
|
||||||
|
|
||||||
|
const otherItemsSorted = ttoServiceItems.sort((a, b) =>
|
||||||
|
(a.updated_at ?? '') > (b.updated_at ?? '') ? -1 : 1,
|
||||||
|
);
|
||||||
const item = otherItemsSorted[0];
|
const item = otherItemsSorted[0];
|
||||||
const isTimerShown = ttoServiceItems.length > 0 && !!item && !!item.updated_at;
|
const isTimerShown =
|
||||||
|
ttoServiceItems.length > 0 && !!item && !!item.updated_at;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageBody>
|
<PageBody>
|
||||||
<PageHeader title={<Trans i18nKey="cart:title" />}>
|
<PageHeader title={<Trans i18nKey="cart:title" />}>
|
||||||
{isTimerShown && <CartTimer cartItem={item} />}
|
{isTimerShown && <CartTimer cartItem={item} />}
|
||||||
</PageHeader>
|
</PageHeader>
|
||||||
<Cart cart={cart} synlabAnalyses={synlabAnalyses} ttoServiceItems={ttoServiceItems} />
|
<Cart
|
||||||
|
accountId={account.id}
|
||||||
|
cart={cart}
|
||||||
|
synlabAnalyses={synlabAnalyses}
|
||||||
|
ttoServiceItems={ttoServiceItems}
|
||||||
|
balanceSummary={balanceSummary}
|
||||||
|
/>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default withI18n(CartPage);
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Scale } from 'lucide-react';
|
import { Scale } from 'lucide-react';
|
||||||
|
|
||||||
|
import SelectAnalysisPackages from '@kit/shared/components/select-analysis-packages';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { PageBody } from '@kit/ui/page';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
|
||||||
import SelectAnalysisPackages from '@kit/shared/components/select-analysis-packages';
|
|
||||||
import { PageBody } from '@kit/ui/page';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
|
|
||||||
import ComparePackagesModal from '../../_components/compare-packages-modal';
|
import ComparePackagesModal from '../../_components/compare-packages-modal';
|
||||||
import { loadAnalysisPackages } from '../../_lib/server/load-analysis-packages';
|
import { loadAnalysisPackages } from '../../_lib/server/load-analysis-packages';
|
||||||
|
|
||||||
@@ -21,7 +21,8 @@ export const generateMetadata = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
async function OrderAnalysisPackagePage() {
|
async function OrderAnalysisPackagePage() {
|
||||||
const { analysisPackageElements, analysisPackages, countryCode } = await loadAnalysisPackages();
|
const { analysisPackageElements, analysisPackages, countryCode } =
|
||||||
|
await loadAnalysisPackages();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageBody>
|
<PageBody>
|
||||||
@@ -40,7 +41,10 @@ async function OrderAnalysisPackagePage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<SelectAnalysisPackages analysisPackages={analysisPackages} countryCode={countryCode} />
|
<SelectAnalysisPackages
|
||||||
|
analysisPackages={analysisPackages}
|
||||||
|
countryCode={countryCode}
|
||||||
|
/>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
|
||||||
|
|
||||||
import { PageBody } from '@kit/ui/page';
|
import { PageBody } from '@kit/ui/page';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
import {
|
||||||
|
PageViewAction,
|
||||||
|
createPageViewLog,
|
||||||
|
} from '~/lib/services/audit/pageView.service';
|
||||||
|
|
||||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||||
import { loadAnalyses } from '../../_lib/server/load-analyses';
|
|
||||||
import OrderAnalysesCards from '../../_components/order-analyses-cards';
|
import OrderAnalysesCards from '../../_components/order-analyses-cards';
|
||||||
import { createPageViewLog, PageViewAction } from '~/lib/services/audit/pageView.service';
|
import { loadAnalyses } from '../../_lib/server/load-analyses';
|
||||||
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
@@ -18,13 +22,13 @@ export const generateMetadata = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
async function OrderAnalysisPage() {
|
async function OrderAnalysisPage() {
|
||||||
const account = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error('Account not found');
|
throw new Error('Account not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const { analyses, countryCode } = await loadAnalyses();
|
const { analyses, countryCode } = await loadAnalyses();
|
||||||
|
|
||||||
await createPageViewLog({
|
await createPageViewLog({
|
||||||
accountId: account.id,
|
accountId: account.id,
|
||||||
action: PageViewAction.VIEW_ORDER_ANALYSIS,
|
action: PageViewAction.VIEW_ORDER_ANALYSIS,
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
|
import { PageBody } from '@kit/ui/page';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
import { PageBody } from '@kit/ui/page';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
@@ -21,6 +22,9 @@ async function OrderHealthAnalysisPage() {
|
|||||||
description={<Trans i18nKey={'order-health-analysis:description'} />}
|
description={<Trans i18nKey={'order-health-analysis:description'} />}
|
||||||
/>
|
/>
|
||||||
<PageBody>
|
<PageBody>
|
||||||
|
<h4 className="mt-8">
|
||||||
|
<Trans i18nKey="booking:noCategories" />
|
||||||
|
</h4>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
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 Divider from '@modules/common/components/divider';
|
||||||
|
|
||||||
|
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';
|
||||||
|
|
||||||
|
function OrderConfirmedLoadingWrapper({
|
||||||
|
medusaOrder: initialMedusaOrder,
|
||||||
|
order,
|
||||||
|
}: {
|
||||||
|
medusaOrder: StoreOrder;
|
||||||
|
order: AnalysisOrder;
|
||||||
|
}) {
|
||||||
|
const [medusaOrder, setMedusaOrder] = useState<StoreOrder>(initialMedusaOrder);
|
||||||
|
const fetchingRef = useRef(false);
|
||||||
|
|
||||||
|
const paymentStatus = medusaOrder.payment_status;
|
||||||
|
const medusaOrderId = order.medusa_order_id;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (paymentStatus === 'captured') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const interval = setInterval(async () => {
|
||||||
|
if (fetchingRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchingRef.current = true;
|
||||||
|
const medusaOrder = await retrieveOrder(medusaOrderId, false);
|
||||||
|
fetchingRef.current = false;
|
||||||
|
|
||||||
|
setMedusaOrder(medusaOrder);
|
||||||
|
}, 2_000);
|
||||||
|
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, [paymentStatus, medusaOrderId]);
|
||||||
|
|
||||||
|
const isPaid = paymentStatus === 'captured';
|
||||||
|
|
||||||
|
if (!isPaid) {
|
||||||
|
return (
|
||||||
|
<PageBody>
|
||||||
|
<div className="flex flex-col justify-start items-center h-full pt-[10vh]">
|
||||||
|
<div>
|
||||||
|
<GlobalLoader />
|
||||||
|
</div>
|
||||||
|
<h4 className="text-center">
|
||||||
|
<Trans i18nKey="cart:orderConfirmed.paymentConfirmationLoading" />
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageBody>
|
||||||
|
<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} />
|
||||||
|
<Divider />
|
||||||
|
<OrderItems medusaOrder={medusaOrder} />
|
||||||
|
<CartTotals medusaOrder={medusaOrder} />
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default OrderConfirmedLoadingWrapper;
|
||||||
@@ -1,18 +1,13 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
|
||||||
|
|
||||||
import { getOrder } from '~/lib/services/order.service';
|
|
||||||
import { retrieveOrder } from '@lib/data/orders';
|
import { retrieveOrder } from '@lib/data/orders';
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
|
|
||||||
import Divider from "@modules/common/components/divider"
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';
|
||||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
@@ -27,28 +22,21 @@ async function OrderConfirmedPage(props: {
|
|||||||
}) {
|
}) {
|
||||||
const params = await props.params;
|
const params = await props.params;
|
||||||
|
|
||||||
const order = await getOrder({ orderId: Number(params.orderId) }).catch(() => null);
|
const order = await getAnalysisOrder({
|
||||||
|
analysisOrderId: Number(params.orderId),
|
||||||
|
}).catch(() => null);
|
||||||
if (!order) {
|
if (!order) {
|
||||||
redirect(pathsConfig.app.myOrders);
|
redirect(pathsConfig.app.myOrders);
|
||||||
}
|
}
|
||||||
|
|
||||||
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(() => null);
|
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(
|
||||||
|
() => null,
|
||||||
|
);
|
||||||
if (!medusaOrder) {
|
if (!medusaOrder) {
|
||||||
redirect(pathsConfig.app.myOrders);
|
redirect(pathsConfig.app.myOrders);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return <OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />;
|
||||||
<PageBody>
|
|
||||||
<PageHeader title={<Trans i18nKey="cart:orderConfirmed.title" />} />
|
|
||||||
<Divider />
|
|
||||||
<div className="grid grid-cols-1 small:grid-cols-[1fr_360px] gap-x-40 lg:px-4 gap-y-6">
|
|
||||||
<OrderDetails order={order} />
|
|
||||||
<Divider />
|
|
||||||
<OrderItems medusaOrder={medusaOrder} />
|
|
||||||
<CartTotals medusaOrder={medusaOrder} />
|
|
||||||
</div>
|
|
||||||
</PageBody>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default withI18n(OrderConfirmedPage);
|
export default withI18n(OrderConfirmedPage);
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
|
||||||
|
|
||||||
import { getOrder } from '~/lib/services/order.service';
|
|
||||||
import { retrieveOrder } from '@lib/data/orders';
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
import Divider from "@modules/common/components/divider"
|
|
||||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
|
import { retrieveOrder } from '@lib/data/orders';
|
||||||
|
import Divider from '@modules/common/components/divider';
|
||||||
|
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
@@ -27,12 +27,16 @@ async function OrderConfirmedPage(props: {
|
|||||||
}) {
|
}) {
|
||||||
const params = await props.params;
|
const params = await props.params;
|
||||||
|
|
||||||
const order = await getOrder({ orderId: Number(params.orderId) }).catch(() => null);
|
const order = await getAnalysisOrder({
|
||||||
|
analysisOrderId: Number(params.orderId),
|
||||||
|
}).catch(() => null);
|
||||||
if (!order) {
|
if (!order) {
|
||||||
redirect(pathsConfig.app.myOrders);
|
redirect(pathsConfig.app.myOrders);
|
||||||
}
|
}
|
||||||
|
|
||||||
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(() => null);
|
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(
|
||||||
|
() => null,
|
||||||
|
);
|
||||||
if (!medusaOrder) {
|
if (!medusaOrder) {
|
||||||
redirect(pathsConfig.app.myOrders);
|
redirect(pathsConfig.app.myOrders);
|
||||||
}
|
}
|
||||||
@@ -41,7 +45,7 @@ async function OrderConfirmedPage(props: {
|
|||||||
<PageBody>
|
<PageBody>
|
||||||
<PageHeader title={<Trans i18nKey="cart:order.title" />} />
|
<PageHeader title={<Trans i18nKey="cart:order.title" />} />
|
||||||
<Divider />
|
<Divider />
|
||||||
<div className="grid grid-cols-1 small:grid-cols-[1fr_360px] gap-x-40 lg:px-4 gap-y-6">
|
<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={order} />
|
||||||
<Divider />
|
<Divider />
|
||||||
<OrderItems medusaOrder={medusaOrder} />
|
<OrderItems medusaOrder={medusaOrder} />
|
||||||
|
|||||||
@@ -1,18 +1,23 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import { listOrders } from '~/medusa/lib/data/orders';
|
|
||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
import { listProductTypes } from '@lib/data/products';
|
import { listProductTypes } from '@lib/data/products';
|
||||||
import { PageBody } from '@kit/ui/makerkit/page';
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
|
||||||
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
|
||||||
import { getAnalysisOrders } from '~/lib/services/order.service';
|
|
||||||
import OrderBlock from '../../_components/orders/order-block';
|
|
||||||
import React from 'react';
|
|
||||||
import { Divider } from '@medusajs/ui';
|
import { Divider } from '@medusajs/ui';
|
||||||
|
|
||||||
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
|
import { PageBody } from '@kit/ui/makerkit/page';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
import { getAnalysisOrders } from '~/lib/services/order.service';
|
||||||
|
import { listOrders } from '~/medusa/lib/data/orders';
|
||||||
|
|
||||||
|
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||||
|
import OrderBlock from '../../_components/orders/order-block';
|
||||||
|
|
||||||
|
const ORDERS_LIMIT = 50;
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
@@ -23,15 +28,19 @@ export async function generateMetadata() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function OrdersPage() {
|
async function OrdersPage() {
|
||||||
const medusaOrders = await listOrders();
|
const [medusaOrders, analysisOrders, { productTypes }] = await Promise.all([
|
||||||
const analysisOrders = await getAnalysisOrders();
|
listOrders(ORDERS_LIMIT),
|
||||||
const { productTypes } = await listProductTypes();
|
getAnalysisOrders(),
|
||||||
|
listProductTypes(),
|
||||||
|
]);
|
||||||
|
|
||||||
if (!medusaOrders || !productTypes) {
|
if (!medusaOrders || !productTypes) {
|
||||||
redirect(pathsConfig.auth.signIn);
|
redirect(pathsConfig.auth.signIn);
|
||||||
}
|
}
|
||||||
|
|
||||||
const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages')!;
|
const analysisPackagesType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === 'analysis-packages',
|
||||||
|
)!;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -41,14 +50,20 @@ async function OrdersPage() {
|
|||||||
/>
|
/>
|
||||||
<PageBody>
|
<PageBody>
|
||||||
{analysisOrders.map((analysisOrder) => {
|
{analysisOrders.map((analysisOrder) => {
|
||||||
const medusaOrder = medusaOrders.find(({ id }) => id === analysisOrder.medusa_order_id);
|
const medusaOrder = medusaOrders.find(
|
||||||
|
({ id }) => id === analysisOrder.medusa_order_id,
|
||||||
|
);
|
||||||
if (!medusaOrder) {
|
if (!medusaOrder) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const medusaOrderItems = medusaOrder.items || [];
|
const medusaOrderItems = medusaOrder.items || [];
|
||||||
const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter((item) => item.product_type_id === analysisPackagesType?.id);
|
const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter(
|
||||||
const medusaOrderItemsOther = medusaOrderItems.filter((item) => item.product_type_id !== analysisPackagesType?.id);
|
(item) => item.product_type_id === analysisPackagesType?.id,
|
||||||
|
);
|
||||||
|
const medusaOrderItemsOther = medusaOrderItems.filter(
|
||||||
|
(item) => item.product_type_id !== analysisPackagesType?.id,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<React.Fragment key={analysisOrder.id}>
|
<React.Fragment key={analysisOrder.id}>
|
||||||
@@ -59,8 +74,13 @@ async function OrdersPage() {
|
|||||||
itemsOther={medusaOrderItemsOther}
|
itemsOther={medusaOrderItemsOther}
|
||||||
/>
|
/>
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
)
|
);
|
||||||
})}
|
})}
|
||||||
|
{analysisOrders.length === 0 && (
|
||||||
|
<h5 className="mt-6">
|
||||||
|
<Trans i18nKey="orders:noOrders" />
|
||||||
|
</h5>
|
||||||
|
)}
|
||||||
</PageBody>
|
</PageBody>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,17 +1,21 @@
|
|||||||
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import { toTitleCase } from '@/lib/utils';
|
import { toTitleCase } from '@/lib/utils';
|
||||||
import { createAccountsApi } from '@/packages/features/accounts/src/server/api';
|
|
||||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||||
|
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
import { createUserAnalysesApi } from '@kit/user-analyses/api';
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
import Dashboard from '../_components/dashboard';
|
import Dashboard from '../_components/dashboard';
|
||||||
import DashboardCards from '../_components/dashboard-cards';
|
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';
|
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
@@ -26,8 +30,8 @@ export const generateMetadata = async () => {
|
|||||||
async function UserHomePage() {
|
async function UserHomePage() {
|
||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
|
|
||||||
const account = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
const api = await createAccountsApi(client);
|
const api = createUserAnalysesApi(client);
|
||||||
const bmiThresholds = await api.fetchBmiThresholds();
|
const bmiThresholds = await api.fetchBmiThresholds();
|
||||||
|
|
||||||
if (!account) {
|
if (!account) {
|
||||||
@@ -48,6 +52,17 @@ async function UserHomePage() {
|
|||||||
/>
|
/>
|
||||||
<PageBody>
|
<PageBody>
|
||||||
<Dashboard account={account} bmiThresholds={bmiThresholds} />
|
<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>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</PageBody>
|
</PageBody>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
"use client"
|
'use client';
|
||||||
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { useForm } from "react-hook-form";
|
import { z } from 'zod';
|
||||||
import { z } from "zod";
|
|
||||||
import { StoreCart, StoreCartLineItem } from "@medusajs/types"
|
import { Form } from '@kit/ui/form';
|
||||||
import { Form } from "@kit/ui/form";
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -17,29 +17,39 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@kit/ui/select';
|
} from '@kit/ui/select';
|
||||||
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';
|
||||||
import partnerLocations from './partner-locations.json';
|
import partnerLocations from './partner-locations.json';
|
||||||
|
|
||||||
const AnalysisLocationSchema = z.object({
|
const AnalysisLocationSchema = z.object({
|
||||||
locationId: z.string().min(1),
|
locationId: z.string().min(1),
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function AnalysisLocation({ cart, synlabAnalyses }: { cart: StoreCart, synlabAnalyses: StoreCartLineItem[] }) {
|
export default function AnalysisLocation({
|
||||||
|
cart,
|
||||||
|
synlabAnalyses,
|
||||||
|
}: {
|
||||||
|
cart: StoreCart;
|
||||||
|
synlabAnalyses: StoreCartLineItem[];
|
||||||
|
}) {
|
||||||
const { t } = useTranslation('cart');
|
const { t } = useTranslation('cart');
|
||||||
|
|
||||||
const form = useForm<z.infer<typeof AnalysisLocationSchema>>({
|
const form = useForm<z.infer<typeof AnalysisLocationSchema>>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
locationId: cart.metadata?.partner_location_id as string ?? '',
|
locationId: (cart.metadata?.partner_location_id as string) ?? '',
|
||||||
},
|
},
|
||||||
resolver: zodResolver(AnalysisLocationSchema),
|
resolver: zodResolver(AnalysisLocationSchema),
|
||||||
});
|
});
|
||||||
|
|
||||||
const getLocation = (locationId: string) => partnerLocations.find(({ name }) => name === locationId);
|
const getLocation = (locationId: string) =>
|
||||||
|
partnerLocations.find(({ name }) => name === locationId);
|
||||||
|
|
||||||
const selectedLocation = getLocation(form.watch('locationId'));
|
const selectedLocation = getLocation(form.watch('locationId'));
|
||||||
|
|
||||||
const onSubmit = async ({ locationId }: z.infer<typeof AnalysisLocationSchema>) => {
|
const onSubmit = async ({
|
||||||
|
locationId,
|
||||||
|
}: z.infer<typeof AnalysisLocationSchema>) => {
|
||||||
const promise = updateCartPartnerLocation({
|
const promise = updateCartPartnerLocation({
|
||||||
cartId: cart.id,
|
cartId: cart.id,
|
||||||
lineIds: synlabAnalyses.map(({ id }) => id),
|
lineIds: synlabAnalyses.map(({ id }) => id),
|
||||||
@@ -52,14 +62,18 @@ export default function AnalysisLocation({ cart, synlabAnalyses }: { cart: Store
|
|||||||
loading: t(`cart:items.analysisLocation.loading`),
|
loading: t(`cart:items.analysisLocation.loading`),
|
||||||
error: t(`cart:items.analysisLocation.error`),
|
error: t(`cart:items.analysisLocation.error`),
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full bg-white flex flex-col txt-medium gap-y-2">
|
<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:locations.description'} />
|
||||||
|
</p>
|
||||||
|
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form
|
<form
|
||||||
onSubmit={form.handleSubmit((data) => onSubmit(data))}
|
onSubmit={form.handleSubmit((data) => onSubmit(data))}
|
||||||
className="w-full mb-2 flex gap-x-2"
|
className="mb-2 flex w-full flex-1 gap-x-2"
|
||||||
>
|
>
|
||||||
<Select
|
<Select
|
||||||
value={form.watch('locationId')}
|
value={form.watch('locationId')}
|
||||||
@@ -78,39 +92,38 @@ export default function AnalysisLocation({ cart, synlabAnalyses }: { cart: Store
|
|||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{Object.entries(partnerLocations
|
{Object.entries(
|
||||||
.reduce((acc, curr) => ({
|
partnerLocations.reduce(
|
||||||
...acc,
|
(acc, curr) => ({
|
||||||
[curr.city]: [...((acc[curr.city] as typeof partnerLocations) ?? []), curr],
|
...acc,
|
||||||
}), {} as Record<string, typeof partnerLocations>))
|
[curr.city]: [
|
||||||
.map(([city, locations]) => (
|
...((acc[curr.city] as typeof partnerLocations) ?? []),
|
||||||
<SelectGroup key={city}>
|
curr,
|
||||||
<SelectLabel>{city}</SelectLabel>
|
],
|
||||||
{locations.map((location) => (
|
}),
|
||||||
<SelectItem key={location.name} value={location.name}>{location.name}</SelectItem>
|
{} as Record<string, typeof partnerLocations>,
|
||||||
))}
|
),
|
||||||
</SelectGroup>
|
).map(([city, locations]) => (
|
||||||
))}
|
<SelectGroup key={city}>
|
||||||
|
<SelectLabel>{city}</SelectLabel>
|
||||||
|
{locations.map((location) => (
|
||||||
|
<SelectItem key={location.name} value={location.name}>
|
||||||
|
{location.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectGroup>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</form>
|
</form>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
{selectedLocation && (
|
{selectedLocation && (
|
||||||
<div className="flex flex-col gap-y-2 mb-4">
|
<div className="mb-4 flex flex-col gap-y-2">
|
||||||
<p className="text-sm">
|
<p className="text-sm">{selectedLocation.address}</p>
|
||||||
{selectedLocation.address}
|
<p className="text-sm">{selectedLocation.hours}</p>
|
||||||
</p>
|
|
||||||
<p className="text-sm">
|
|
||||||
{selectedLocation.hours}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
<Trans i18nKey={'cart:locations.description'} />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
"use client";
|
'use client';
|
||||||
|
|
||||||
import { Trash } from "lucide-react";
|
import { useState } from 'react';
|
||||||
import { useState } from "react";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { Spinner } from '@medusajs/icons';
|
||||||
|
import { Trash } from 'lucide-react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
import { Spinner } from "@medusajs/icons";
|
import { handleDeleteCartItem } from '~/lib/services/medusaCart.service';
|
||||||
import { handleDeleteCartItem } from "~/lib/services/medusaCart.service";
|
|
||||||
|
|
||||||
const CartItemDelete = ({
|
const CartItemDelete = ({
|
||||||
id,
|
id,
|
||||||
@@ -33,9 +34,9 @@ const CartItemDelete = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-between text-small-regular">
|
<div className="text-small-regular flex items-center justify-between">
|
||||||
<button
|
<button
|
||||||
className="flex gap-x-1 text-ui-fg-subtle hover:text-ui-fg-base cursor-pointer"
|
className="text-ui-fg-subtle hover:text-ui-fg-base flex cursor-pointer gap-x-1"
|
||||||
onClick={() => handleDelete()}
|
onClick={() => handleDelete()}
|
||||||
>
|
>
|
||||||
{isDeleting ? <Spinner className="animate-spin" /> : <Trash />}
|
{isDeleting ? <Spinner className="animate-spin" /> : <Trash />}
|
||||||
|
|||||||
@@ -1,23 +1,27 @@
|
|||||||
"use client"
|
'use client';
|
||||||
|
|
||||||
import { HttpTypes } from "@medusajs/types"
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
import { useTranslation } from "react-i18next"
|
import { HttpTypes } from '@medusajs/types';
|
||||||
import {
|
import { useTranslation } from 'react-i18next';
|
||||||
TableCell,
|
|
||||||
TableRow,
|
|
||||||
} from '@kit/ui/table';
|
|
||||||
import { formatCurrency } from "@/packages/shared/src/utils"
|
|
||||||
import CartItemDelete from "./cart-item-delete";
|
|
||||||
|
|
||||||
export default function CartItem({ item, currencyCode }: {
|
import { TableCell, TableRow } from '@kit/ui/table';
|
||||||
item: HttpTypes.StoreCartLineItem
|
|
||||||
currencyCode: string
|
import CartItemDelete from './cart-item-delete';
|
||||||
|
|
||||||
|
export default function CartItem({
|
||||||
|
item,
|
||||||
|
currencyCode,
|
||||||
|
}: {
|
||||||
|
item: HttpTypes.StoreCartLineItem;
|
||||||
|
currencyCode: string;
|
||||||
}) {
|
}) {
|
||||||
const { i18n: { language } } = useTranslation();
|
const {
|
||||||
|
i18n: { language },
|
||||||
|
} = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TableRow className="w-full" data-testid="product-row">
|
<TableRow className="w-full" data-testid="product-row">
|
||||||
<TableCell className="text-left w-[100%] px-6">
|
<TableCell className="w-[100%] px-4 text-left sm:px-6">
|
||||||
<p
|
<p
|
||||||
className="txt-medium-plus text-ui-fg-base"
|
className="txt-medium-plus text-ui-fg-base"
|
||||||
data-testid="product-title"
|
data-testid="product-title"
|
||||||
@@ -26,11 +30,9 @@ export default function CartItem({ item, currencyCode }: {
|
|||||||
</p>
|
</p>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|
||||||
<TableCell className="px-6">
|
<TableCell className="px-4 sm:px-6">{item.quantity}</TableCell>
|
||||||
{item.quantity}
|
|
||||||
</TableCell>
|
|
||||||
|
|
||||||
<TableCell className="min-w-[80px] px-6">
|
<TableCell className="min-w-[80px] px-4 sm:px-6">
|
||||||
{formatCurrency({
|
{formatCurrency({
|
||||||
value: item.unit_price,
|
value: item.unit_price,
|
||||||
currencyCode,
|
currencyCode,
|
||||||
@@ -38,7 +40,7 @@ export default function CartItem({ item, currencyCode }: {
|
|||||||
})}
|
})}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|
||||||
<TableCell className="min-w-[80px] px-6">
|
<TableCell className="min-w-[80px] px-4 text-right sm:px-6">
|
||||||
{formatCurrency({
|
{formatCurrency({
|
||||||
value: item.total,
|
value: item.total,
|
||||||
currencyCode,
|
currencyCode,
|
||||||
@@ -46,11 +48,11 @@ export default function CartItem({ item, currencyCode }: {
|
|||||||
})}
|
})}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|
||||||
<TableCell className="text-right px-6">
|
<TableCell className="px-4 text-right sm:px-6">
|
||||||
<span className="flex gap-x-1 justify-end w-[60px]">
|
<span className="flex w-[60px] justify-end gap-x-1">
|
||||||
<CartItemDelete id={item.id} />
|
<CartItemDelete id={item.id} />
|
||||||
</span>
|
</span>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
import { StoreCart, StoreCartLineItem } from "@medusajs/types"
|
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
import CartItem from "./cart-item";
|
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableRow,
|
|
||||||
TableHeader,
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
} from '@kit/ui/table';
|
} from '@kit/ui/table';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
export default function CartItems({ cart, items, productColumnLabelKey }: {
|
import CartItem from './cart-item';
|
||||||
|
|
||||||
|
export default function CartItems({
|
||||||
|
cart,
|
||||||
|
items,
|
||||||
|
productColumnLabelKey,
|
||||||
|
}: {
|
||||||
cart: StoreCart;
|
cart: StoreCart;
|
||||||
items: StoreCartLineItem[];
|
items: StoreCartLineItem[];
|
||||||
productColumnLabelKey: string;
|
productColumnLabelKey: string;
|
||||||
@@ -19,28 +25,29 @@ export default function CartItems({ cart, items, productColumnLabelKey }: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Table className="rounded-lg border border-separate">
|
<Table className="border-separate rounded-lg border">
|
||||||
<TableHeader className="text-ui-fg-subtle txt-medium-plus">
|
<TableHeader className="text-ui-fg-subtle txt-medium-plus">
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableHead className="px-6">
|
<TableHead className="px-4 sm:px-6">
|
||||||
<Trans i18nKey={productColumnLabelKey} />
|
<Trans i18nKey={productColumnLabelKey} />
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="px-6">
|
<TableHead className="px-4 sm:px-6">
|
||||||
<Trans i18nKey="cart:table.quantity" />
|
<Trans i18nKey="cart:table.quantity" />
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="px-6 min-w-[100px]">
|
<TableHead className="min-w-[100px] px-4 sm:px-6">
|
||||||
<Trans i18nKey="cart:table.price" />
|
<Trans i18nKey="cart:table.price" />
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="px-6 min-w-[100px]">
|
<TableHead className="min-w-[100px] px-4 text-right sm:px-6">
|
||||||
<Trans i18nKey="cart:table.total" />
|
<Trans i18nKey="cart:table.total" />
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="px-6">
|
<TableHead className="px-4 sm:px-6"></TableHead>
|
||||||
</TableHead>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{items
|
{items
|
||||||
.sort((a, b) => (a.created_at ?? "") > (b.created_at ?? "") ? -1 : 1)
|
.sort((a, b) =>
|
||||||
|
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||||
|
)
|
||||||
.map((item) => (
|
.map((item) => (
|
||||||
<CartItem
|
<CartItem
|
||||||
key={item.id}
|
key={item.id}
|
||||||
@@ -50,5 +57,5 @@ export default function CartItems({ cart, items, productColumnLabelKey }: {
|
|||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
"use client";
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
import { handleLineItemTimeout } from '@/lib/services/medusaCart.service';
|
||||||
|
import { StoreCartLineItem } from '@medusajs/types';
|
||||||
|
import { Timer } from 'lucide-react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
@@ -8,18 +14,17 @@ import {
|
|||||||
AlertDialogDescription,
|
AlertDialogDescription,
|
||||||
AlertDialogFooter,
|
AlertDialogFooter,
|
||||||
AlertDialogHeader,
|
AlertDialogHeader,
|
||||||
AlertDialogTitle
|
AlertDialogTitle,
|
||||||
} from "@kit/ui/alert-dialog";
|
} from '@kit/ui/alert-dialog';
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
import { Timer } from 'lucide-react';
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
|
||||||
import { StoreCartLineItem } from '@medusajs/types';
|
|
||||||
import { handleLineItemTimeout } from '@/lib/services/medusaCart.service';
|
|
||||||
|
|
||||||
const TIMEOUT_MINUTES = 15;
|
const TIMEOUT_MINUTES = 15;
|
||||||
|
|
||||||
export default function CartTimer({ cartItem }: { cartItem: StoreCartLineItem }) {
|
export default function CartTimer({
|
||||||
|
cartItem,
|
||||||
|
}: {
|
||||||
|
cartItem: StoreCartLineItem;
|
||||||
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [timeLeft, setTimeLeft] = useState<number | null>(null);
|
const [timeLeft, setTimeLeft] = useState<number | null>(null);
|
||||||
const [isDialogOpen, setDialogOpen] = useState(false);
|
const [isDialogOpen, setDialogOpen] = useState(false);
|
||||||
@@ -39,7 +44,9 @@ export default function CartTimer({ cartItem }: { cartItem: StoreCartLineItem })
|
|||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [updatedAt]);
|
}, [updatedAt]);
|
||||||
|
|
||||||
const minutes = timeLeft ? Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60)) : 0;
|
const minutes = timeLeft
|
||||||
|
? Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60))
|
||||||
|
: 0;
|
||||||
const seconds = timeLeft ? Math.floor((timeLeft % (1000 * 60)) / 1000) : 0;
|
const seconds = timeLeft ? Math.floor((timeLeft % (1000 * 60)) / 1000) : 0;
|
||||||
|
|
||||||
const isTimeLeftPositive = timeLeft === null || timeLeft > 0;
|
const isTimeLeftPositive = timeLeft === null || timeLeft > 0;
|
||||||
@@ -53,13 +60,16 @@ export default function CartTimer({ cartItem }: { cartItem: StoreCartLineItem })
|
|||||||
}, [isTimeLeftPositive, cartItem.id]);
|
}, [isTimeLeftPositive, cartItem.id]);
|
||||||
|
|
||||||
if (timeLeft === null) {
|
if (timeLeft === null) {
|
||||||
return <div className='min-h-[40px]' />;
|
return <div className="min-h-[40px]" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="ml-auto">
|
<div className="ml-auto">
|
||||||
<Button variant="outline" className="flex items-center gap-x-2 bg-accent hover:bg-accent px-4 cursor-default">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="bg-accent hover:bg-accent flex cursor-default items-center gap-x-2 px-4"
|
||||||
|
>
|
||||||
<Timer />
|
<Timer />
|
||||||
<span className="text-sm">
|
<span className="text-sm">
|
||||||
{t('cart:checkout.timeLeft', {
|
{t('cart:checkout.timeLeft', {
|
||||||
@@ -76,7 +86,9 @@ export default function CartTimer({ cartItem }: { cartItem: StoreCartLineItem })
|
|||||||
{t('cart:checkout.timeoutTitle')}
|
{t('cart:checkout.timeoutTitle')}
|
||||||
</AlertDialogTitle>
|
</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
{t('cart:checkout.timeoutDescription', { productTitle: cartItem.product?.title })}
|
{t('cart:checkout.timeoutDescription', {
|
||||||
|
productTitle: cartItem.product?.title,
|
||||||
|
})}
|
||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
@@ -87,5 +99,5 @@ export default function CartTimer({ cartItem }: { cartItem: StoreCartLineItem })
|
|||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
</>
|
</>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
29
app/home/(user)/_components/cart/discount-code-actions.ts
Normal file
29
app/home/(user)/_components/cart/discount-code-actions.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import { applyPromotions } from '@lib/data/cart';
|
||||||
|
|
||||||
|
export async function addPromotionCodeAction(code: string) {
|
||||||
|
try {
|
||||||
|
await applyPromotions([code]);
|
||||||
|
return { success: true, message: 'Discount code applied successfully' };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error applying promotion code:', error);
|
||||||
|
return { success: false, message: 'Failed to apply discount code' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removePromotionCodeAction(
|
||||||
|
codeToRemove: string,
|
||||||
|
appliedCodes: string[],
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const updatedCodes = appliedCodes.filter(
|
||||||
|
(appliedCode) => appliedCode !== codeToRemove,
|
||||||
|
);
|
||||||
|
await applyPromotions(updatedCodes);
|
||||||
|
return { success: true, message: 'Discount code removed successfully' };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error removing promotion code:', error);
|
||||||
|
return { success: false, message: 'Failed to remove discount code' };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,56 +1,71 @@
|
|||||||
"use client"
|
'use client';
|
||||||
|
|
||||||
import { Badge, Heading, Text } from "@medusajs/ui"
|
import React from 'react';
|
||||||
import React, { useActionState } from "react";
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { convertToLocale } from '@lib/util/money';
|
||||||
|
import { StoreCart, StorePromotion } from '@medusajs/types';
|
||||||
|
import { Badge, Text } from '@medusajs/ui';
|
||||||
|
import Trash from '@modules/common/icons/trash';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { applyPromotions, submitPromotionForm } from "@lib/data/cart"
|
|
||||||
import { convertToLocale } from "@lib/util/money"
|
|
||||||
import { StoreCart, StorePromotion } from "@medusajs/types"
|
|
||||||
import Trash from "@modules/common/icons/trash"
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Form, FormControl, FormField, FormItem } from "@kit/ui/form";
|
import { Form, 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';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { Input } from "@kit/ui/input";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import {
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
addPromotionCodeAction,
|
||||||
import { useForm } from "react-hook-form";
|
removePromotionCodeAction,
|
||||||
import { z } from "zod";
|
} from './discount-code-actions';
|
||||||
|
|
||||||
const DiscountCodeSchema = z.object({
|
const DiscountCodeSchema = z.object({
|
||||||
code: z.string().min(1),
|
code: z.string().min(1),
|
||||||
})
|
});
|
||||||
|
|
||||||
export default function DiscountCode({ cart }: {
|
export default function DiscountCode({
|
||||||
|
cart,
|
||||||
|
}: {
|
||||||
cart: StoreCart & {
|
cart: StoreCart & {
|
||||||
promotions: StorePromotion[]
|
promotions: StorePromotion[];
|
||||||
}
|
};
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation('cart');
|
const { t } = useTranslation('cart');
|
||||||
|
|
||||||
const { promotions = [] } = cart;
|
const { promotions = [] } = cart;
|
||||||
|
|
||||||
const removePromotionCode = async (code: string) => {
|
const removePromotionCode = async (code: string) => {
|
||||||
const validPromotions = promotions.filter(
|
const appliedCodes = promotions
|
||||||
(promotion) => promotion.code !== code
|
.filter((p) => p.code !== undefined)
|
||||||
)
|
.map((p) => p.code!);
|
||||||
|
|
||||||
await applyPromotions(
|
const loading = toast.loading(t('cart:discountCode.removeLoading'));
|
||||||
validPromotions.filter((p) => p.code === undefined).map((p) => p.code!)
|
|
||||||
)
|
const result = await removePromotionCodeAction(code, appliedCodes);
|
||||||
}
|
|
||||||
|
toast.dismiss(loading);
|
||||||
|
if (result.success) {
|
||||||
|
toast.success(t('cart:discountCode.removeSuccess'));
|
||||||
|
} else {
|
||||||
|
toast.error(t('cart:discountCode.removeError'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const addPromotionCode = async (code: string) => {
|
const addPromotionCode = async (code: string) => {
|
||||||
const codes = promotions
|
const loading = toast.loading(t('cart:discountCode.addLoading'));
|
||||||
.filter((p) => p.code === undefined)
|
const result = await addPromotionCodeAction(code);
|
||||||
.map((p) => p.code!)
|
|
||||||
codes.push(code.toString())
|
|
||||||
|
|
||||||
await applyPromotions(codes)
|
toast.dismiss(loading);
|
||||||
|
if (result.success) {
|
||||||
form.reset()
|
toast.success(t('cart:discountCode.addSuccess'));
|
||||||
}
|
form.reset();
|
||||||
|
} else {
|
||||||
const [message, formAction] = useActionState(submitPromotionForm, null)
|
toast.error(t('cart:discountCode.addError'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const form = useForm<z.infer<typeof DiscountCodeSchema>>({
|
const form = useForm<z.infer<typeof DiscountCodeSchema>>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -60,73 +75,75 @@ export default function DiscountCode({ cart }: {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full bg-white flex flex-col txt-medium">
|
<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 {...form}>
|
||||||
<form
|
<form
|
||||||
onSubmit={form.handleSubmit((data) => addPromotionCode(data.code))}
|
onSubmit={form.handleSubmit((data) => addPromotionCode(data.code))}
|
||||||
className="w-full mb-2 flex gap-x-2"
|
className="mb-2 flex w-full flex-1 flex-col gap-x-2 gap-y-2 sm:flex-row"
|
||||||
>
|
>
|
||||||
<FormField
|
<FormField
|
||||||
name={'code'}
|
name={'code'}
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem className="flex-1">
|
<FormItem className="flex-1">
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input required type="text" {...field} placeholder={t('cart:discountCode.placeholder')} />
|
<Input
|
||||||
|
required
|
||||||
|
type="text"
|
||||||
|
{...field}
|
||||||
|
placeholder={t('cart:discountCode.placeholder')}
|
||||||
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Button
|
<Button type="submit" variant="secondary" className="h-min">
|
||||||
type="submit"
|
|
||||||
variant="secondary"
|
|
||||||
className="h-full"
|
|
||||||
>
|
|
||||||
<Trans i18nKey={'cart:discountCode.apply'} />
|
<Trans i18nKey={'cart:discountCode.apply'} />
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
<Trans i18nKey={'cart:discountCode.subtitle'} />
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{promotions.length > 0 && (
|
{promotions.length > 0 && (
|
||||||
<div className="w-full flex items-center">
|
<div className="mt-4 flex w-full items-center">
|
||||||
<div className="flex flex-col w-full">
|
<div className="flex w-full flex-col gap-y-2">
|
||||||
<Heading className="txt-medium mb-2">
|
<p>
|
||||||
Promotion(s) applied:
|
<Trans i18nKey={'cart:discountCode.appliedCodes'} />
|
||||||
</Heading>
|
</p>
|
||||||
|
|
||||||
{promotions.map((promotion) => {
|
{promotions.map((promotion) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={promotion.id}
|
key={promotion.id}
|
||||||
className="flex items-center justify-between w-full max-w-full mb-2"
|
className="mb-2 flex w-full max-w-full items-center justify-between"
|
||||||
data-testid="discount-row"
|
data-testid="discount-row"
|
||||||
>
|
>
|
||||||
<Text className="flex gap-x-1 items-baseline txt-small-plus w-4/5 pr-1">
|
<Text className="flex w-4/5 items-baseline gap-x-1 pr-1 text-sm">
|
||||||
<span className="truncate" data-testid="discount-code">
|
<span className="truncate" data-testid="discount-code">
|
||||||
<Badge
|
<Badge
|
||||||
color={promotion.is_automatic ? "green" : "grey"}
|
color={promotion.is_automatic ? 'green' : 'grey'}
|
||||||
size="small"
|
size="small"
|
||||||
|
className="px-4 text-sm"
|
||||||
>
|
>
|
||||||
{promotion.code}
|
{promotion.code}
|
||||||
</Badge>{" "}
|
</Badge>{' '}
|
||||||
(
|
(
|
||||||
{promotion.application_method?.value !== undefined &&
|
{promotion.application_method?.value !== undefined &&
|
||||||
promotion.application_method.currency_code !==
|
promotion.application_method.currency_code !==
|
||||||
undefined && (
|
undefined && (
|
||||||
<>
|
<>
|
||||||
{promotion.application_method.type ===
|
{promotion.application_method.type === 'percentage'
|
||||||
"percentage"
|
|
||||||
? `${promotion.application_method.value}%`
|
? `${promotion.application_method.value}%`
|
||||||
: convertToLocale({
|
: convertToLocale({
|
||||||
amount: promotion.application_method.value,
|
amount: Number(
|
||||||
currency_code:
|
promotion.application_method.value,
|
||||||
promotion.application_method
|
),
|
||||||
.currency_code,
|
currency_code:
|
||||||
})}
|
promotion.application_method.currency_code,
|
||||||
|
})}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
)
|
)
|
||||||
@@ -142,25 +159,25 @@ export default function DiscountCode({ cart }: {
|
|||||||
className="flex items-center"
|
className="flex items-center"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!promotion.code) {
|
if (!promotion.code) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
removePromotionCode(promotion.code)
|
removePromotionCode(promotion.code);
|
||||||
}}
|
}}
|
||||||
data-testid="remove-discount-button"
|
data-testid="remove-discount-button"
|
||||||
>
|
>
|
||||||
<Trash size={14} />
|
<Trash size={14} />
|
||||||
<span className="sr-only">
|
<span className="sr-only">
|
||||||
Remove discount code from order
|
<Trans i18nKey={'cart:discountCode.remove'} />
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user