Compare commits
1 Commits
keycloak
...
feature/ME
| Author | SHA1 | Date | |
|---|---|---|---|
| ab0834149d |
40
.env
40
.env
@@ -5,6 +5,7 @@
|
||||
# TO OVERRIDE THESE VARIABLES IN A SPECIFIC ENVIRONMENT, PLEASE ADD THEM TO THE SPECIFIC ENVIRONMENT FILE (e.g. .env.development, .env.production)
|
||||
|
||||
# SITE
|
||||
NEXT_PUBLIC_SITE_URL=https://localhost:3000
|
||||
NEXT_PUBLIC_PRODUCT_NAME=MedReport
|
||||
NEXT_PUBLIC_SITE_TITLE="MedReport"
|
||||
NEXT_PUBLIC_SITE_DESCRIPTION="MedReport."
|
||||
@@ -13,12 +14,12 @@ NEXT_PUBLIC_THEME_COLOR="#ffffff"
|
||||
NEXT_PUBLIC_THEME_COLOR_DARK="#0a0a0a"
|
||||
|
||||
# AUTH
|
||||
NEXT_PUBLIC_AUTH_PASSWORD=false
|
||||
NEXT_PUBLIC_AUTH_PASSWORD=true
|
||||
NEXT_PUBLIC_AUTH_MAGIC_LINK=false
|
||||
NEXT_PUBLIC_CAPTCHA_SITE_KEY=
|
||||
|
||||
# BILLING
|
||||
NEXT_PUBLIC_BILLING_PROVIDER=montonio
|
||||
NEXT_PUBLIC_BILLING_PROVIDER=stripe
|
||||
|
||||
# CMS
|
||||
CMS_CLIENT=keystatic
|
||||
@@ -34,25 +35,13 @@ NEXT_PUBLIC_ENABLE_THEME_TOGGLE=true
|
||||
NEXT_PUBLIC_ENABLE_PERSONAL_ACCOUNT_DELETION=true
|
||||
NEXT_PUBLIC_ENABLE_PERSONAL_ACCOUNT_BILLING=false
|
||||
NEXT_PUBLIC_ENABLE_TEAM_ACCOUNTS_DELETION=false
|
||||
NEXT_PUBLIC_ENABLE_TEAM_ACCOUNTS_BILLING=true
|
||||
NEXT_PUBLIC_ENABLE_TEAM_ACCOUNTS_BILLING=false
|
||||
NEXT_PUBLIC_ENABLE_TEAM_ACCOUNTS=true
|
||||
NEXT_PUBLIC_ENABLE_TEAM_ACCOUNTS_CREATION=true
|
||||
NEXT_PUBLIC_LANGUAGE_PRIORITY=application
|
||||
NEXT_PUBLIC_ENABLE_NOTIFICATIONS=true
|
||||
NEXT_PUBLIC_REALTIME_NOTIFICATIONS=true
|
||||
|
||||
WEBHOOK_SENDER_PROVIDER=postgres
|
||||
|
||||
# MAILER DEV
|
||||
CONTACT_EMAIL=info@medreport.ee
|
||||
MAILER_PROVIDER=nodemailer
|
||||
EMAIL_SENDER=info@medreport.ee
|
||||
EMAIL_USER= # refer to your email provider's documentation
|
||||
EMAIL_PASSWORD= # refer to your email provider's documentation
|
||||
EMAIL_HOST=localhost # refer to your email provider's documentation
|
||||
EMAIL_PORT=1025 # or 465 for SSL
|
||||
EMAIL_TLS=true
|
||||
NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||
|
||||
# NEXTJS
|
||||
NEXT_TELEMETRY_DISABLED=1
|
||||
@@ -64,4 +53,23 @@ NEXT_PUBLIC_DEFAULT_LOCALE=et
|
||||
NEXT_PUBLIC_TEAM_NAVIGATION_STYLE=custom
|
||||
NEXT_PUBLIC_USER_NAVIGATION_STYLE=custom
|
||||
|
||||
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
|
||||
#### MEDUSA
|
||||
#NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_0ec86252438b38ce18d5601f7877e4395d7e0a6afa8687dfea8d37af33015633
|
||||
#MEDUSA_BACKEND_URL=http://5.181.51.38:9000
|
||||
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_e23a820689a07d55aa0a0ad187268559f5d6288ecb0768ff4520516285bdef84
|
||||
MEDUSA_BACKEND_URL=http://localhost:9000
|
||||
# NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_068d930c33fea53608a410d84a51935f6ce2ccec5bef8e0ecf75eaee602ac486
|
||||
# MEDUSA_BACKEND_URL=https://backoffice-test.medreport.ee:443
|
||||
|
||||
#### MONTONIO
|
||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||
MONTONIO_SECRET_KEY=rNZkzwxOiH93mzkdV53AvhSsbGidrgO2Kl5lE/IT7cvo
|
||||
MONTONIO_API_URL=https://sandbox-stargate.montonio.com
|
||||
|
||||
#### SUPABASE
|
||||
# NEXT_PUBLIC_SUPABASE_URL=https://oqsdacktkhmbylmzstjq.supabase.co
|
||||
# NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDY1MjgxMjMsImV4cCI6MjA2MjEwNDEyM30.LdHCTWxijFmhXdnT9KVuLRAVbtSwY7OO-oLtpd8GmO0
|
||||
# SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc0NjUyODEyMywiZXhwIjoyMDYyMTA0MTIzfQ.KVcnkZ21Pd0XkJho23dZqFHawVTLQqfvF7l2RxsELLk
|
||||
NEXT_PUBLIC_SUPABASE_URL=http://5.181.51.38:54321
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# This file is used to define environment variables for the development environment.
|
||||
# These values are only used when running the app in development mode.
|
||||
|
||||
# SITE
|
||||
NEXT_PUBLIC_SITE_URL=http://localhost:3000
|
||||
|
||||
# SUPABASE DEVELOPMENT
|
||||
# SUPABASE
|
||||
NEXT_PUBLIC_SUPABASE_URL=http://5.181.51.38:54321
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
|
||||
|
||||
## THIS IS FOR DEVELOPMENT ONLY - DO NOT USE IN PRODUCTION
|
||||
SUPABASE_DB_WEBHOOK_SECRET=WEBHOOKSECRET
|
||||
@@ -14,79 +14,14 @@ SUPABASE_DB_WEBHOOK_SECRET=WEBHOOKSECRET
|
||||
# CONTACT FORM
|
||||
CONTACT_EMAIL=test@makerkit.dev
|
||||
|
||||
# STRIPE
|
||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
||||
|
||||
# MAILER
|
||||
MAILER_PROVIDER=nodemailer
|
||||
EMAIL_SENDER=info@medreport.ee
|
||||
EMAIL_USER= # refer to your email provider's documentation
|
||||
EMAIL_PASSWORD= # refer to your email provider's documentation
|
||||
EMAIL_HOST=localhost # refer to your email provider's documentation
|
||||
EMAIL_PORT=1025 # or 465 for SSL
|
||||
EMAIL_TLS=false
|
||||
NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||
|
||||
# MEDUSA
|
||||
MEDUSA_BACKEND_URL=http://localhost:9000
|
||||
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
||||
|
||||
# MONTONIO
|
||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||
MONTONIO_SECRET_KEY=rNZkzwxOiH93mzkdV53AvhSsbGidrgO2Kl5lE/IT7cvo
|
||||
MONTONIO_API_URL=https://sandbox-stargate.montonio.com
|
||||
|
||||
# JOBS
|
||||
JOBS_API_TOKEN=73ce073c-6dd4-11f0-8e75-8fee89786197
|
||||
|
||||
# MEDIPOST
|
||||
|
||||
MEDIPOST_URL=https://meditest.medisoft.ee:7443/Medipost/MedipostServlet
|
||||
MEDIPOST_USER=trvurgtst
|
||||
MEDIPOST_PASSWORD=SRB48HZMV
|
||||
MEDIPOST_RECIPIENT=trvurgtst
|
||||
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
||||
|
||||
MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
||||
MEDIPOST_USER=medreport
|
||||
MEDIPOST_PASSWORD=85MXFFDB7
|
||||
MEDIPOST_RECIPIENT=HTI
|
||||
MEDIPOST_MESSAGE_SENDER=medreport
|
||||
|
||||
### TEST.MEDREPORT.ee ###
|
||||
|
||||
DB_PASSWORD=T#u-$M7%RjbA@L@
|
||||
|
||||
#### MEDUSA
|
||||
MEDUSA_BACKEND_URL=https://backoffice-test.medreport.ee
|
||||
MEDUSA_BACKEND_PUBLIC_URL=https://backoffice-test.medreport.ee
|
||||
MEDUSA_SECRET_API_KEY=sk_fdb1808fbabf62979cc46316aa997378ffbb87882883e8f5c3ee47cee39dcac5
|
||||
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_827a2ab863021cb67993f1d81078f81bfce4b4e0da642d8c0f5398ded9d8fd32
|
||||
|
||||
#### SUPABASE
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://oqsdacktkhmbylmzstjq.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDY1MjgxMjMsImV4cCI6MjA2MjEwNDEyM30.LdHCTWxijFmhXdnT9KVuLRAVbtSwY7OO-oLtpd8GmO0
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc0NjUyODEyMywiZXhwIjoyMDYyMTA0MTIzfQ.KVcnkZ21Pd0XkJho23dZqFHawVTLQqfvF7l2RxsELLk
|
||||
|
||||
#######
|
||||
|
||||
### LOCAL ###
|
||||
|
||||
#### MEDUSA
|
||||
MEDUSA_BACKEND_URL=http://localhost:9000
|
||||
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
||||
#MEDUSA_BACKEND_URL=http://5.181.51.38:9000
|
||||
#MEDUSA_BACKEND_PUBLIC_URL=http://5.181.51.38:9000
|
||||
MEDUSA_SECRET_API_KEY=sk_b332d525212ab4078ef73fb2b8232c3beebccc4a460e2c7abf6e187a458d60cf
|
||||
NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_e23a820689a07d55aa0a0ad187268559f5d6288ecb0768ff4520516285bdef84
|
||||
#NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_0ec86252438b38ce18d5601f7877e4395d7e0a6afa8687dfea8d37af33015633
|
||||
|
||||
#### SUPABASE
|
||||
NEXT_PUBLIC_SUPABASE_URL=http://5.181.51.38:54321
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
|
||||
|
||||
#######
|
||||
|
||||
SUPABASE_AUTH_CLIENT_ID=supabase
|
||||
SUPABASE_AUTH_KEYCLOAK_SECRET=Gl394GjizClhQl06KFeoFyZ7ZbPamG5I
|
||||
SUPABASE_AUTH_KEYCLOAK_URL=http://localhost:8585/realms/medreport-sandbox
|
||||
SUPABASE_AUTH_KEYCLOAK_CALLBACK_URL=http://localhost:3000/auth/callback
|
||||
# EMAIL_SENDER=
|
||||
# EMAIL_USER= # refer to your email provider's documentation
|
||||
# EMAIL_PASSWORD= # refer to your email provider's documentation
|
||||
# EMAIL_HOST= # refer to your email provider's documentation
|
||||
# EMAIL_PORT= # or 465 for SSL
|
||||
# EMAIL_TLS= # or false for SSL (see provider documentation)
|
||||
@@ -2,7 +2,7 @@
|
||||
# https://app.supabase.com/project/_/settings/api
|
||||
NEXT_PUBLIC_SUPABASE_URL=your-project-url
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
|
||||
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
|
||||
NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
|
||||
|
||||
MEDIPOST_URL=your-medipost-url
|
||||
MEDIPOST_USER=your-medipost-user
|
||||
@@ -23,5 +23,3 @@ NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
|
||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||
MONTONIO_SECRET_KEY=rNZkzwxOiH93mzkdV53AvhSsbGidrgO2Kl5lE/IT7cvo
|
||||
MONTONIO_API_URL=https://sandbox-stargate.montonio.com
|
||||
|
||||
JOBS_API_TOKEN=73ce073c-6dd4-11f0-8e75-8fee89786197
|
||||
|
||||
@@ -6,10 +6,7 @@
|
||||
## PUBLIC KEYS OR CONFIGURATION ARE OKAY TO BE PLACED HERE.
|
||||
|
||||
# SUPABASE
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://oqsdacktkhmbylmzstjq.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9xc2RhY2t0a2htYnlsbXpzdGpxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDY1MjgxMjMsImV4cCI6MjA2MjEwNDEyM30.LdHCTWxijFmhXdnT9KVuLRAVbtSwY7OO-oLtpd8GmO0
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
|
||||
NEXT_PUBLIC_SITE_URL=https://test.medreport.ee
|
||||
|
||||
# MONTONIO
|
||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||
# STRIPE
|
||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
|
||||
|
||||
15
.env.staging
15
.env.staging
@@ -1,15 +0,0 @@
|
||||
# PRODUCTION ENVIRONMENT VARIABLES
|
||||
|
||||
## DO NOT ADD VARS HERE UNLESS THEY ARE PUBLIC OR NOT SENSITIVE
|
||||
## THIS ENV IS USED FOR PRODUCTION AND IS COMMITED TO THE REPO
|
||||
## AVOID PLACING SENSITIVE DATA IN THIS FILE.
|
||||
## PUBLIC KEYS OR CONFIGURATION ARE OKAY TO BE PLACED HERE.
|
||||
|
||||
# SUPABASE
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://kaldvociniytdbbcxvqk.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImthbGR2b2Npbml5dGRiYmN4dnFrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTYzNjQ5OTYsImV4cCI6MjA3MTk0MDk5Nn0.eixihH2KGkJZolY9FiQDicJOo2kxvXrSe6gGUCrkLo0
|
||||
|
||||
NEXT_PUBLIC_SITE_URL=https://test.medreport.ee
|
||||
|
||||
# MONTONIO
|
||||
NEXT_PUBLIC_MONTONIO_ACCESS_KEY=7da5d7fa-3383-4997-9435-46aa818f4ead
|
||||
@@ -19,6 +19,4 @@ EMAIL_PASSWORD=password
|
||||
# STRIPE
|
||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51K9cWKI1i3VnbZTq2HGstY2S8wt3peF1MOqPXFO4LR8ln2QgS7GxL8XyKaKLvn7iFHeqAnvdDw0o48qN7rrwwcHU00jOtKhjsf
|
||||
|
||||
CONTACT_EMAIL=test@makerkit.dev
|
||||
|
||||
SUPABASE_AUTH_KEYCLOAK_URL=https://keycloak.medreport.ee/realms/medreport-prod
|
||||
CONTACT_EMAIL=test@makerkit.dev
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -43,4 +43,3 @@ yarn-error.log*
|
||||
next-env.d.ts
|
||||
|
||||
dump.sql
|
||||
data.sql
|
||||
44
Dockerfile
44
Dockerfile
@@ -1,55 +1,17 @@
|
||||
# --- Stage 1: Build ---
|
||||
FROM node:20-alpine as builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN npm install -g pnpm@9
|
||||
RUN npm install -g dotenv-cli
|
||||
|
||||
# Copy necessary files for workspace resolution
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
COPY packages packages
|
||||
COPY tooling tooling
|
||||
COPY .env .env
|
||||
COPY .env.production .env.production
|
||||
COPY .env.staging .env.staging
|
||||
|
||||
# Load env file and echo a specific variable
|
||||
# RUN dotenv -e .env -- printenv | grep 'SUPABASE' || true
|
||||
# Install all dependencies
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
RUN set -a \
|
||||
&& . .env \
|
||||
&& . .env.production \
|
||||
&& . .env.staging \
|
||||
&& set +a \
|
||||
&& node check-env.js \
|
||||
&& pnpm build
|
||||
|
||||
|
||||
# --- Stage 2: Runtime ---
|
||||
FROM node:20-alpine
|
||||
ARG APP_ENV=production
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /app ./
|
||||
|
||||
RUN cp ".env.${APP_ENV}" .env.local
|
||||
|
||||
RUN npm install -g pnpm@9 \
|
||||
&& pnpm install --prod --frozen-lockfile
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# 🔍 Optional: Log key envs for debug
|
||||
RUN echo "📄 .env contents:" && cat .env.local \
|
||||
&& echo "🔧 Current ENV available to Next.js build:" && printenv | grep -E 'SUPABASE|STRIPE|NEXT|NODE_ENV' || true
|
||||
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["pnpm", "start"]
|
||||
RUN pnpm build
|
||||
55
README.md
55
README.md
@@ -85,58 +85,5 @@ To access admin pages follow these steps:
|
||||
|
||||
- Register new user
|
||||
- Go to Profile and add Multi-Factor Authentication
|
||||
- Authenticate with mfa (at current time profile page prompts it again)
|
||||
- update your role. look at `supabase/sql/super-admin.sql`
|
||||
- Sign out and Sign in
|
||||
|
||||
## Company User
|
||||
|
||||
- With admin account go to `http://localhost:3000/admin/accounts`
|
||||
- For Create Company Account to work you need to have rows in `medreport.roles` table. For that you can sql in `supabase/sql/super-admin.sql`
|
||||
|
||||
## Start email server
|
||||
|
||||
`docker run -p 1080:1080 -p 1025:1025 maildev/maildev`
|
||||
|
||||
- [View emails](http://localhost:1080/#/)
|
||||
- Mail server is running on `localhost:1025` without password
|
||||
|
||||
## Medipost flow
|
||||
|
||||
1. Customer adds analysis to cart in **B2B** storefront
|
||||
2. Customer checks out from cart and is redirected to **Montonio**
|
||||
3. Customer pays and is redirected back to **B2B** `GET B2B/home/cart/montonio-callback?order-token=$JWT`
|
||||
|
||||
- **Medusa** order is created and cart is emptied
|
||||
- email is sent to customer
|
||||
- B2B sends order XML as private message to Medipost.
|
||||
|
||||
When **Montonio** has confirmed payment, it will call **Medusa** webhook endpoint and **Medusa** will mark order payment as captured.
|
||||
|
||||
In background a job will call `POST B2B/api/job/sync-analysis-results` every n minutes and sync private messages with responses from **Medipost**.
|
||||
|
||||
In local dev environment, you can create a private message with analysis responses in **Medipost** system for a submitted order:
|
||||
`POST B2B/api/order/medipost-test-response body={medusaOrderId:'input here'}`
|
||||
After that run `POST /api/job/sync-analysis-results` and analysis results should be synced.
|
||||
|
||||
In local dev environment, you can import products from B2B to Medusa with this API:
|
||||
|
||||
- `POST /api/job/sync-analysis-groups-store`
|
||||
- Syncs required data of `analyses`, `analysis_elements` data from **B2B** to **Medusa** and creates relevant products and categories.
|
||||
If product or category already exists, then it is not recreated. Old entries are not deleted either currently.
|
||||
|
||||
## Jobs
|
||||
|
||||
Required headers:
|
||||
|
||||
- `x-jobs-api-key` in UUID format
|
||||
|
||||
Endpoints:
|
||||
|
||||
- `POST /api/job/sync-analysis-groups`
|
||||
- Queries **Medipost** for public messages list and takes analysis info from the latest event.
|
||||
Updates `analyses` and `analysis_elements` lists in **B2B**.
|
||||
- `POST /api/job/sync-analysis-results`
|
||||
- Queries **Medipost** for latest private message that has a response and updates order analysis results from lab results data.
|
||||
- `POST /api/job/sync-connected-online`
|
||||
- TODO
|
||||
- Authenticate with mfa (at current time profile page prompts it again)
|
||||
|
||||
@@ -2,7 +2,6 @@ import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { appConfig } from '@kit/shared/config';
|
||||
import { Footer } from '@kit/ui/marketing';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
import appConfig from '~/config/app.config';
|
||||
|
||||
export function SiteFooter() {
|
||||
return (
|
||||
<Footer
|
||||
logo={<AppLogo className="w-[85px] md:w-[95px]" />}
|
||||
description=""
|
||||
description={<Trans i18nKey="marketing:footerDescription" />}
|
||||
copyright={
|
||||
<Trans
|
||||
i18nKey="marketing:copyright"
|
||||
@@ -18,6 +19,22 @@ export function SiteFooter() {
|
||||
/>
|
||||
}
|
||||
sections={[
|
||||
{
|
||||
heading: <Trans i18nKey="marketing:about" />,
|
||||
links: [
|
||||
{ href: '/blog', label: <Trans i18nKey="marketing:blog" /> },
|
||||
{ href: '/contact', label: <Trans i18nKey="marketing:contact" /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
heading: <Trans i18nKey="marketing:product" />,
|
||||
links: [
|
||||
{
|
||||
href: '/docs',
|
||||
label: <Trans i18nKey="marketing:documentation" />,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
heading: <Trans i18nKey="marketing:legal" />,
|
||||
links: [
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import dynamic from 'next/dynamic';
|
||||
import Link from 'next/link';
|
||||
|
||||
import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
|
||||
@@ -13,10 +12,8 @@ import { Button } from '@kit/ui/button';
|
||||
import { If } from '@kit/ui/if';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { featureFlagsConfig } from '@kit/shared/config';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import featuresFlagConfig from '~/config/feature-flags.config';
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
|
||||
const ModeToggle = dynamic(() =>
|
||||
import('@kit/ui/mode-toggle').then((mod) => ({
|
||||
@@ -26,20 +23,13 @@ const ModeToggle = dynamic(() =>
|
||||
|
||||
const paths = {
|
||||
home: pathsConfig.app.home,
|
||||
admin: pathsConfig.app.admin,
|
||||
doctor: pathsConfig.app.doctor,
|
||||
personalAccountSettings: pathsConfig.app.personalAccountSettings,
|
||||
};
|
||||
|
||||
const features = {
|
||||
enableThemeToggle: featureFlagsConfig.enableThemeToggle,
|
||||
enableThemeToggle: featuresFlagConfig.enableThemeToggle,
|
||||
};
|
||||
|
||||
export function SiteHeaderAccountSection({
|
||||
accounts,
|
||||
}: {
|
||||
accounts: UserWorkspace['accounts'];
|
||||
}) {
|
||||
export function SiteHeaderAccountSection() {
|
||||
const session = useSession();
|
||||
const signOut = useSignOut();
|
||||
|
||||
@@ -51,7 +41,6 @@ export function SiteHeaderAccountSection({
|
||||
features={features}
|
||||
user={session.data.user}
|
||||
signOutRequested={() => signOut.mutateAsync()}
|
||||
accounts={accounts}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -69,7 +58,7 @@ function AuthButtons() {
|
||||
</div>
|
||||
|
||||
<div className={'flex gap-x-2.5'}>
|
||||
<Button className={'block'} asChild variant={'ghost'}>
|
||||
<Button className={'hidden md:block'} asChild variant={'ghost'}>
|
||||
<Link href={pathsConfig.auth.signIn}>
|
||||
<Trans i18nKey={'auth:signIn'} />
|
||||
</Link>
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
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 '~/components/app-logo';
|
||||
|
||||
import { SiteHeaderAccountSection } from './site-header-account-section';
|
||||
import { SiteNavigation } from './site-navigation';
|
||||
|
||||
export function SiteHeader({
|
||||
accounts,
|
||||
}: {
|
||||
accounts: UserWorkspace['accounts'];
|
||||
}) {
|
||||
export function SiteHeader() {
|
||||
return (
|
||||
<Header
|
||||
logo={<AppLogo />}
|
||||
actions={<SiteHeaderAccountSection accounts={accounts} />}
|
||||
navigation={<SiteNavigation />}
|
||||
actions={<SiteHeaderAccountSection />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ const links = {
|
||||
label: 'marketing:documentation',
|
||||
path: '/docs',
|
||||
},
|
||||
Pricing: {
|
||||
label: 'marketing:pricing',
|
||||
path: '/pricing',
|
||||
},
|
||||
FAQ: {
|
||||
label: 'marketing:faq',
|
||||
path: '/faq',
|
||||
|
||||
@@ -8,7 +8,6 @@ import { createCmsClient } from '@kit/cms';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
import { Post } from '../../blog/_components/post';
|
||||
|
||||
interface BlogPageProps {
|
||||
|
||||
@@ -6,7 +6,6 @@ import { ContactForm } from '~/(marketing)/contact/_components/contact-form';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
import { use } from 'react';
|
||||
|
||||
import { SiteFooter } from '~/(marketing)/_components/site-footer';
|
||||
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import { loadCurrentUserAccounts } from '~/home/(user)/_lib/server/load-accounts';
|
||||
|
||||
function SiteLayout(props: React.PropsWithChildren) {
|
||||
const accounts = use(loadCurrentUserAccounts());
|
||||
return (
|
||||
<div className={'flex min-h-[100vh] flex-col'}>
|
||||
<SiteHeader accounts={accounts} />
|
||||
<SiteHeader />
|
||||
|
||||
{props.children}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
||||
import { MedReportLogo } from '@/components/med-report-logo';
|
||||
import { ArrowRightIcon } from 'lucide-react';
|
||||
|
||||
import { CtaButton, Hero } from '@kit/ui/marketing';
|
||||
@@ -49,8 +49,8 @@ function MainCallToActionButton() {
|
||||
</CtaButton>
|
||||
|
||||
<CtaButton variant={'link'}>
|
||||
<Link href="/company-offer">
|
||||
<Trans i18nKey="account:createCompanyAccount" />
|
||||
<Link href={'/company-offer'}>
|
||||
<Trans i18nKey={'account:createCompanyAccount'} />
|
||||
</Link>
|
||||
</CtaButton>
|
||||
</div>
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { sendEmailFromTemplate } from '@/lib/services/mailer.service';
|
||||
import { SubmitButton } from '@/components/ui/submit-button';
|
||||
import { sendCompanyOfferEmail } from '@/lib/services/mailer.service';
|
||||
import { CompanySubmitData } from '@/lib/types/company';
|
||||
import { companyOfferSchema } from '@/lib/validations/company-offer.schema';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { renderCompanyOfferEmail } from '@kit/email-templates';
|
||||
import { SubmitButton } from '@kit/shared/components/ui/submit-button';
|
||||
import { FormItem } from '@kit/ui/form';
|
||||
import { Input } from '@kit/ui/input';
|
||||
import { Label } from '@kit/ui/label';
|
||||
import { Spinner } from '@kit/ui/spinner';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
const CompanyOfferForm = () => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const language = useTranslation().i18n.language;
|
||||
const {
|
||||
@@ -33,29 +28,16 @@ const CompanyOfferForm = () => {
|
||||
});
|
||||
|
||||
const onSubmit = async (data: CompanySubmitData) => {
|
||||
setIsLoading(true);
|
||||
const formData = new FormData();
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
if (value !== undefined) formData.append(key, value);
|
||||
});
|
||||
|
||||
try {
|
||||
sendEmailFromTemplate(
|
||||
renderCompanyOfferEmail,
|
||||
{
|
||||
companyData: data,
|
||||
language,
|
||||
},
|
||||
process.env.CONTACT_EMAIL!,
|
||||
)
|
||||
sendCompanyOfferEmail(data, language)
|
||||
.then(() => router.push('/company-offer/success'))
|
||||
.catch((error) => {
|
||||
setIsLoading(false);
|
||||
alert('Could not send email at this time');
|
||||
console.warn('error: ' + error);
|
||||
});
|
||||
.catch((error) => alert('error: ' + error));
|
||||
} catch (err: unknown) {
|
||||
setIsLoading(false);
|
||||
if (err instanceof Error) {
|
||||
console.warn('Server validation error: ' + err.message);
|
||||
}
|
||||
@@ -94,15 +76,11 @@ const CompanyOfferForm = () => {
|
||||
<Input type="tel" {...register('phone')} />
|
||||
</FormItem>
|
||||
<SubmitButton
|
||||
disabled={isLoading || !isValid || isSubmitting}
|
||||
disabled={!isValid || isSubmitting}
|
||||
pendingText="Saatmine..."
|
||||
type="submit"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Trans i18nKey={'account:requestCompanyAccount:button'} />
|
||||
)}
|
||||
<Trans i18nKey={'account:requestCompanyAccount:button'} />
|
||||
</SubmitButton>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React from 'react';
|
||||
|
||||
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { MedReportLogo } from '@/components/med-report-logo';
|
||||
import { withI18n } from '@/lib/i18n/with-i18n';
|
||||
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import CompanyOfferForm from './_components/company-offer-form';
|
||||
@@ -9,7 +10,7 @@ import CompanyOfferForm from './_components/company-offer-form';
|
||||
function CompanyOffer() {
|
||||
return (
|
||||
<div className="border-border flex max-w-5xl flex-row overflow-hidden rounded-3xl border">
|
||||
<div className="flex flex-col px-12 py-14 text-center md:w-1/2">
|
||||
<div className="flex w-1/2 flex-col px-12 py-14 text-center">
|
||||
<MedReportLogo />
|
||||
<h1 className="pt-8">
|
||||
<Trans i18nKey={'account:requestCompanyAccount:title'} />
|
||||
@@ -19,7 +20,7 @@ function CompanyOffer() {
|
||||
</p>
|
||||
<CompanyOfferForm />
|
||||
</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="w-1/2 min-w-[460px] bg-[url(/assets/med-report-logo-big.png)] bg-cover bg-center bg-no-repeat"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
function SiteLayout(props: React.PropsWithChildren) {
|
||||
return (
|
||||
<div className={'flex min-h-[100vh] flex-col justify-center items-center'}>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
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 {
|
||||
@@ -19,16 +18,13 @@ import {
|
||||
useSidebar,
|
||||
} from '@kit/ui/shadcn-sidebar';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { ProfileAccountDropdownContainer } from '@kit/shared/components/personal-account-dropdown-container';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
import { ProfileAccountDropdownContainer } from '~/components/personal-account-dropdown-container';
|
||||
|
||||
export function AdminSidebar({
|
||||
accounts,
|
||||
}: {
|
||||
accounts: UserWorkspace['accounts'];
|
||||
}) {
|
||||
export function AdminSidebar() {
|
||||
const path = usePathname();
|
||||
const { open } = useSidebar();
|
||||
|
||||
return (
|
||||
<Sidebar collapsible="icon">
|
||||
<SidebarHeader className={'m-2'}>
|
||||
@@ -66,8 +62,8 @@ export function AdminSidebar({
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
<ProfileAccountDropdownContainer accounts={accounts} />
|
||||
<ProfileAccountDropdownContainer />
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { cache } from 'react';
|
||||
|
||||
import { AdminAccountPage } from '@kit/admin/components/admin-account-page';
|
||||
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
||||
import { getAccount } from '~/lib/services/account.service';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
interface Params {
|
||||
params: Promise<{
|
||||
@@ -28,4 +28,21 @@ async function AccountPage(props: Params) {
|
||||
|
||||
export default AdminGuard(AccountPage);
|
||||
|
||||
const loadAccount = cache(getAccount);
|
||||
const loadAccount = cache(accountLoader);
|
||||
|
||||
async function accountLoader(id: string) {
|
||||
const client = getSupabaseServerClient();
|
||||
|
||||
const { data, error } = await client
|
||||
.schema('medreport')
|
||||
.from('accounts')
|
||||
.select('*, memberships: accounts_memberships (*)')
|
||||
.eq('id', id)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ServerDataLoader } from '@makerkit/data-loader-supabase-nextjs';
|
||||
|
||||
import { AdminAccountsTable } from '@kit/admin/components/admin-accounts-table';
|
||||
import { AdminCreateCompanyDialog } from '@kit/admin/components/admin-create-company-dialog';
|
||||
import { AdminCreateUserDialog } from '@kit/admin/components/admin-create-user-dialog';
|
||||
import { AdminCreateCompanyDialog } from '@kit/admin/components/admin-create-company-dialog';
|
||||
import { AdminGuard } from '@kit/admin/components/admin-guard';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
import { AppBreadcrumbs } from '@kit/ui/app-breadcrumbs';
|
||||
@@ -24,7 +24,7 @@ export const metadata = {
|
||||
};
|
||||
|
||||
async function AccountsPage(props: AdminAccountsPageProps) {
|
||||
const client = getSupabaseServerClient().schema('medreport');
|
||||
const client = getSupabaseServerClient();
|
||||
const searchParams = await props.searchParams;
|
||||
const page = searchParams.page ? parseInt(searchParams.page) : 1;
|
||||
|
||||
@@ -33,19 +33,18 @@ async function AccountsPage(props: AdminAccountsPageProps) {
|
||||
<PageHeader description={<AppBreadcrumbs />}>
|
||||
<div className="flex justify-end gap-2">
|
||||
<AdminCreateUserDialog>
|
||||
<Button data-test="admin-create-user-button">
|
||||
Create Personal Account
|
||||
</Button>
|
||||
<Button data-test="admin-create-user-button">Create Personal Account</Button>
|
||||
</AdminCreateUserDialog>
|
||||
<AdminCreateCompanyDialog>
|
||||
<Button>Create Company Account</Button>
|
||||
</AdminCreateCompanyDialog>
|
||||
|
||||
</div>
|
||||
</PageHeader>
|
||||
|
||||
<PageBody>
|
||||
<ServerDataLoader
|
||||
table="accounts"
|
||||
table={'accounts'}
|
||||
client={client}
|
||||
page={page}
|
||||
where={(queryBuilder) => {
|
||||
@@ -56,9 +55,7 @@ async function AccountsPage(props: AdminAccountsPageProps) {
|
||||
}
|
||||
|
||||
if (query) {
|
||||
queryBuilder.or(
|
||||
`name.ilike.%${query}%,email.ilike.%${query}%,personal_code.ilike.%${query}%`,
|
||||
);
|
||||
queryBuilder.or(`name.ilike.%${query}%,email.ilike.%${query}%,personal_code.ilike.%${query}%`);
|
||||
}
|
||||
|
||||
return queryBuilder;
|
||||
|
||||
@@ -8,8 +8,6 @@ import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
||||
import { AdminSidebar } from '~/admin/_components/admin-sidebar';
|
||||
import { AdminMobileNavigation } from '~/admin/_components/mobile-navigation';
|
||||
|
||||
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
||||
|
||||
export const metadata = {
|
||||
title: `Super Admin`,
|
||||
};
|
||||
@@ -18,13 +16,12 @@ export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function AdminLayout(props: React.PropsWithChildren) {
|
||||
const state = use(getLayoutState());
|
||||
const workspace = use(loadUserWorkspace());
|
||||
|
||||
return (
|
||||
<SidebarProvider defaultOpen={state.open}>
|
||||
<Page style={'sidebar'}>
|
||||
<PageNavigation>
|
||||
<AdminSidebar accounts={workspace.accounts} />
|
||||
<AdminSidebar />
|
||||
</PageNavigation>
|
||||
|
||||
<PageMobileNavigation>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { enhanceRouteHandler } from '@kit/next/routes';
|
||||
import { getLogger } from '@kit/shared/logger';
|
||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||
|
||||
import { billingConfig } from '@kit/shared/config';
|
||||
import billingConfig from '~/config/billing.config';
|
||||
|
||||
/**
|
||||
* @description Handle the webhooks from Stripe related to checkouts
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { config } from 'dotenv';
|
||||
|
||||
export default function loadEnv() {
|
||||
config({ path: `.env` });
|
||||
if (['local', 'test', 'development', 'production'].includes(process.env.NODE_ENV!)) {
|
||||
config({ path: `.env.${process.env.NODE_ENV}` });
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { renderNewJobsAvailableEmail } from '@kit/email-templates';
|
||||
|
||||
import { getDoctorAccounts } from '~/lib/services/account.service';
|
||||
import { getOpenJobAnalysisResponseIds } from '~/lib/services/doctor-jobs.service';
|
||||
import { sendEmailFromTemplate } from '~/lib/services/mailer.service';
|
||||
|
||||
export default async function sendOpenJobsEmails() {
|
||||
const analysisResponseIds = await getOpenJobAnalysisResponseIds();
|
||||
|
||||
const doctorAccounts = await getDoctorAccounts();
|
||||
const doctorEmails: string[] = doctorAccounts
|
||||
.map(({ email }) => email)
|
||||
.filter((email): email is string => !!email);
|
||||
|
||||
await sendEmailFromTemplate(
|
||||
renderNewJobsAvailableEmail,
|
||||
{
|
||||
language: 'et',
|
||||
analysisResponseIds,
|
||||
},
|
||||
doctorEmails,
|
||||
);
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
import Medusa from "@medusajs/js-sdk"
|
||||
import type { AdminProductCategory } from "@medusajs/types";
|
||||
import { listProductTypes } from "@lib/data/products";
|
||||
import { getAnalysisElements } from "~/lib/services/analysis-element.service";
|
||||
import { getAnalysisGroups } from "~/lib/services/analysis-group.service";
|
||||
import { createMedusaSyncFailEntry, createMedusaSyncSuccessEntry } from "~/lib/services/analyses.service";
|
||||
|
||||
const SYNLAB_SERVICES_CATEGORY_HANDLE = 'synlab-services';
|
||||
const SYNLAB_ANALYSIS_PRODUCT_TYPE_HANDLE = 'synlab-analysis';
|
||||
|
||||
const BASE_ANALYSIS_PRODUCT_HANDLE = 'analysis-base';
|
||||
|
||||
const getAdminSdk = () => {
|
||||
const medusaBackendUrl = process.env.MEDUSA_BACKEND_PUBLIC_URL!;
|
||||
const medusaPublishableApiKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY!;
|
||||
const key = process.env.MEDUSA_SECRET_API_KEY!;
|
||||
|
||||
if (!medusaBackendUrl || !medusaPublishableApiKey) {
|
||||
throw new Error('Medusa environment variables not set');
|
||||
}
|
||||
return new Medusa({
|
||||
baseUrl: medusaBackendUrl,
|
||||
debug: process.env.NODE_ENV === 'development',
|
||||
apiKey: key,
|
||||
});
|
||||
}
|
||||
|
||||
async function createProductCategories({
|
||||
medusa,
|
||||
}: {
|
||||
medusa: Medusa;
|
||||
}) {
|
||||
const { product_categories: existingProductCategories } = await medusa.admin.productCategory.list();
|
||||
const parentCategory = existingProductCategories.find(({ handle }) => handle === SYNLAB_SERVICES_CATEGORY_HANDLE);
|
||||
|
||||
if (!parentCategory) {
|
||||
throw new Error('Parent category not found');
|
||||
}
|
||||
|
||||
const analysisGroups = await getAnalysisGroups();
|
||||
if (!analysisGroups) {
|
||||
throw new Error('Analysis groups not found');
|
||||
}
|
||||
|
||||
const createdCategories: AdminProductCategory[] = [];
|
||||
for (const analysisGroup of analysisGroups) {
|
||||
console.info(`Processing analysis group '${analysisGroup.name}'`);
|
||||
|
||||
const isExisting = existingProductCategories.find(({ name }) => name === analysisGroup.name);
|
||||
const isNewlyCreated = createdCategories.find(({ name }) => name === analysisGroup.name);
|
||||
if (isExisting || isNewlyCreated) {
|
||||
console.info(`Analysis group '${analysisGroup.name}' already exists`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const createResponse = await medusa.admin.productCategory.create({
|
||||
name: analysisGroup.name,
|
||||
handle: analysisGroup.name,
|
||||
parent_category_id: parentCategory.id,
|
||||
is_active: true,
|
||||
metadata: {
|
||||
analysisGroupOriginalId: analysisGroup.original_id,
|
||||
analysisGroupId: analysisGroup.id,
|
||||
},
|
||||
});
|
||||
console.info(`Successfully created category, id=${createResponse.product_category.id}`);
|
||||
createdCategories.push(createResponse.product_category);
|
||||
}
|
||||
}
|
||||
|
||||
async function getChildProductCategories({
|
||||
medusa,
|
||||
}: {
|
||||
medusa: Medusa;
|
||||
}) {
|
||||
const { product_categories: allCategories } = await medusa.admin.productCategory.list();
|
||||
const childCategories = allCategories.filter(({ parent_category_id }) => parent_category_id !== null);
|
||||
return childCategories;
|
||||
}
|
||||
|
||||
async function deleteProductCategories({
|
||||
medusa,
|
||||
categories,
|
||||
}: {
|
||||
medusa: Medusa;
|
||||
categories: AdminProductCategory[];
|
||||
}) {
|
||||
for (const category of categories) {
|
||||
await medusa.admin.productCategory.delete(category.id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In case a reset is needed
|
||||
*/
|
||||
async function deleteProducts({
|
||||
medusa,
|
||||
}: {
|
||||
medusa: Medusa;
|
||||
}) {
|
||||
const { products: existingProducts } = await medusa.admin.product.list({
|
||||
fields: 'id,collection_id',
|
||||
limit: 1000,
|
||||
});
|
||||
|
||||
await Promise.all(existingProducts.filter((a) => !a.collection_id).map(({ id }) => medusa.admin.product.delete(id)));
|
||||
}
|
||||
|
||||
async function getAnalysisPackagesType() {
|
||||
const { productTypes } = await listProductTypes();
|
||||
const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === SYNLAB_ANALYSIS_PRODUCT_TYPE_HANDLE);
|
||||
if (!analysisPackagesType) {
|
||||
throw new Error('Synlab analysis packages type not found');
|
||||
}
|
||||
return analysisPackagesType;
|
||||
}
|
||||
|
||||
async function getProductDefaultFields({
|
||||
medusa,
|
||||
}: {
|
||||
medusa: Medusa;
|
||||
}) {
|
||||
const baseProductsResponse = await medusa.admin.product.list({ handle: BASE_ANALYSIS_PRODUCT_HANDLE })
|
||||
const baseProduct = baseProductsResponse.products[0];
|
||||
if (!baseProduct) {
|
||||
throw new Error('Base product not found');
|
||||
}
|
||||
const defaultSalesChannels = baseProduct.sales_channels;
|
||||
if (!Array.isArray(defaultSalesChannels)) {
|
||||
throw new Error('Base analysis product has no required sales channels');
|
||||
}
|
||||
const defaultProductOption = baseProduct.options;
|
||||
if (!Array.isArray(defaultProductOption)) {
|
||||
throw new Error('Base analysis product has no required options');
|
||||
}
|
||||
const defaultProductVariant = baseProduct.variants?.[0];
|
||||
if (!defaultProductVariant) {
|
||||
throw new Error('Base analysis product has no required variant');
|
||||
}
|
||||
|
||||
return {
|
||||
defaultSalesChannels,
|
||||
defaultProductOption,
|
||||
defaultProductVariant,
|
||||
}
|
||||
}
|
||||
|
||||
async function createProducts({
|
||||
medusa,
|
||||
}: {
|
||||
medusa: Medusa;
|
||||
}) {
|
||||
const { product_categories: allCategories } = await medusa.admin.productCategory.list();
|
||||
|
||||
const [
|
||||
{ products: existingProducts },
|
||||
analysisElements,
|
||||
analysisPackagesType,
|
||||
{
|
||||
defaultSalesChannels,
|
||||
defaultProductOption,
|
||||
defaultProductVariant,
|
||||
}
|
||||
] = await Promise.all([
|
||||
medusa.admin.product.list({
|
||||
category_id: allCategories.map(({ id }) => id),
|
||||
}),
|
||||
getAnalysisElements({}),
|
||||
getAnalysisPackagesType(),
|
||||
getProductDefaultFields({ medusa }),
|
||||
])
|
||||
|
||||
for (const analysisElement of analysisElements) {
|
||||
const { analysis_id_original: originalId } = analysisElement;
|
||||
const isExisting = existingProducts.find(({ metadata }) => metadata?.analysisIdOriginal === originalId);
|
||||
if (isExisting) {
|
||||
console.info(`Analysis element '${analysisElement.analysis_name_lab}' already exists`);
|
||||
continue;
|
||||
}
|
||||
const { analysis_name_lab: name } = analysisElement;
|
||||
if (!name) {
|
||||
console.error(`Analysis element '${originalId}' has no name`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const category = allCategories.find(({ metadata }) => metadata?.analysisGroupId === analysisElement.parent_analysis_group_id);
|
||||
if (!category) {
|
||||
console.error(`Category not found for analysis element '${name}'`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await medusa.admin.product.create({
|
||||
title: name,
|
||||
handle: `analysis-element-${analysisElement.id}`,
|
||||
categories: [{ id: category.id }],
|
||||
options: defaultProductOption.map(({ id, title, values }) => ({
|
||||
id,
|
||||
title,
|
||||
values: values?.map(({ value }) => value) ?? [],
|
||||
})),
|
||||
metadata: {
|
||||
analysisIdOriginal: originalId,
|
||||
},
|
||||
is_giftcard: false,
|
||||
discountable: false,
|
||||
status: 'published',
|
||||
sales_channels: defaultSalesChannels.map(({ id }) => ({ id })),
|
||||
variants: [
|
||||
{
|
||||
title: defaultProductVariant.title!,
|
||||
prices: defaultProductVariant.prices!,
|
||||
manage_inventory: false,
|
||||
},
|
||||
],
|
||||
type_id: analysisPackagesType.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default async function syncAnalysisGroupsStore() {
|
||||
const medusa = getAdminSdk();
|
||||
|
||||
try {
|
||||
await createProductCategories({ medusa });
|
||||
|
||||
// const categories = await getChildProductCategories({ medusa });
|
||||
// await deleteProductCategories({ medusa, categories });
|
||||
// await deleteProducts({ medusa });
|
||||
// return;
|
||||
|
||||
await createProducts({ medusa });
|
||||
|
||||
await createMedusaSyncSuccessEntry();
|
||||
} catch (e) {
|
||||
await createMedusaSyncFailEntry(JSON.stringify(e));
|
||||
console.error(e);
|
||||
throw new Error(
|
||||
`Failed to sync analyses to Medusa, error: ${JSON.stringify(e)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
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[] {
|
||||
if (!input) return [];
|
||||
return Array.isArray(input) ? input : [input];
|
||||
}
|
||||
|
||||
const WRITE_XML_TO_FILE = false as boolean;
|
||||
|
||||
export default async function syncAnalysisGroups() {
|
||||
const baseUrl = process.env.MEDIPOST_URL;
|
||||
const user = process.env.MEDIPOST_USER;
|
||||
const password = process.env.MEDIPOST_PASSWORD;
|
||||
const sender = process.env.MEDIPOST_MESSAGE_SENDER;
|
||||
|
||||
if (!baseUrl || !user || !password || !sender) {
|
||||
throw new Error('Could not access all necessary environment variables');
|
||||
}
|
||||
|
||||
try {
|
||||
console.info('Getting latest public message id');
|
||||
const lastCheckedDate = await getLastCheckedDate();
|
||||
|
||||
const latestMessage = await getLatestPublicMessageListItem();
|
||||
if (!latestMessage) {
|
||||
console.info('No new data received');
|
||||
await createNoNewDataReceivedEntry();
|
||||
return;
|
||||
}
|
||||
console.info('Getting public message with id: ', latestMessage.messageId);
|
||||
|
||||
const { data: publicMessageData } = await axios.get(baseUrl, {
|
||||
params: {
|
||||
Action: 'GetPublicMessage',
|
||||
User: user,
|
||||
Password: password,
|
||||
MessageId: latestMessage.messageId,
|
||||
},
|
||||
headers: {
|
||||
Accept: 'application/xml',
|
||||
},
|
||||
});
|
||||
|
||||
if (WRITE_XML_TO_FILE) {
|
||||
fs.writeFileSync('public-messages-list-response.xml', publicMessageData);
|
||||
}
|
||||
|
||||
const parser = new XMLParser({ ignoreAttributes: false });
|
||||
const parsed: IMedipostPublicMessageDataParsed = parser.parse(publicMessageData);
|
||||
|
||||
if (parsed.ANSWER?.CODE && parsed.ANSWER?.CODE !== 0) {
|
||||
throw new Error(
|
||||
`Failed to get public message (id: ${latestMessage.messageId})`,
|
||||
);
|
||||
}
|
||||
|
||||
const existingAnalysisGroups = await getAnalysisGroups();
|
||||
|
||||
// SAVE PUBLIC MESSAGE DATA
|
||||
|
||||
const providers = toArray(parsed?.Saadetis?.Teenused.Teostaja);
|
||||
const analysisGroups = providers.flatMap((provider) =>
|
||||
toArray(provider.UuringuGrupp),
|
||||
);
|
||||
|
||||
if (!parsed || !analysisGroups.length) {
|
||||
console.info('No analysis groups data received');
|
||||
await createNoDataReceivedEntry();
|
||||
return;
|
||||
}
|
||||
|
||||
const codes: ICode[] = [];
|
||||
for (const analysisGroup of analysisGroups) {
|
||||
const existingAnalysisGroup = existingAnalysisGroups?.find(({ original_id }) => original_id === analysisGroup.UuringuGruppId);
|
||||
if (existingAnalysisGroup) {
|
||||
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,
|
||||
})),
|
||||
);
|
||||
|
||||
const analysisGroupItems = toArray(analysisGroup.Uuring);
|
||||
|
||||
for (const item of analysisGroupItems) {
|
||||
const analysisElement = item.UuringuElement;
|
||||
|
||||
const insertedAnalysisElementId = await createAnalysisElement({
|
||||
analysisElement,
|
||||
analysisGroupId,
|
||||
materialGroups: toArray(item.MaterjalideGrupp),
|
||||
});
|
||||
|
||||
if (analysisElement.Kood) {
|
||||
const analysisElementCodes = toArray(analysisElement.Kood);
|
||||
codes.push(
|
||||
...analysisElementCodes.map((kood) => ({
|
||||
hk_code: kood.HkKood,
|
||||
hk_code_multiplier: kood.HkKoodiKordaja,
|
||||
coefficient: kood.Koefitsient,
|
||||
price: kood.Hind,
|
||||
analysis_group_id: null,
|
||||
analysis_element_id: insertedAnalysisElementId,
|
||||
analysis_id: null,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const analyses = analysisElement.UuringuElement;
|
||||
if (analyses?.length) {
|
||||
for (const analysis of analyses) {
|
||||
const insertedAnalysisId = await createAnalysis(analysis, analysisGroupId);
|
||||
|
||||
if (analysis.Kood) {
|
||||
const analysisCodes = toArray(analysis.Kood);
|
||||
|
||||
codes.push(
|
||||
...analysisCodes.map((kood) => ({
|
||||
hk_code: kood.HkKood,
|
||||
hk_code_multiplier: kood.HkKoodiKordaja,
|
||||
coefficient: kood.Koefitsient,
|
||||
price: kood.Hind,
|
||||
analysis_group_id: null,
|
||||
analysis_element_id: null,
|
||||
analysis_id: insertedAnalysisId,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.info('Inserting codes');
|
||||
await createCodes(codes);
|
||||
|
||||
console.info('Inserting sync entry');
|
||||
await createSyncSuccessEntry();
|
||||
} catch (e) {
|
||||
const errorMessage = e instanceof Error ? e.message : String(e);
|
||||
await createSyncFailEntry(JSON.stringify({
|
||||
message: errorMessage,
|
||||
stack: e instanceof Error ? e.stack : undefined,
|
||||
name: e instanceof Error ? e.name : 'Unknown',
|
||||
}, null, 2));
|
||||
console.error('Sync failed:', e);
|
||||
throw new Error(
|
||||
`Failed to sync public message data, error: ${errorMessage}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { readPrivateMessageResponse } from "~/lib/services/medipost.service";
|
||||
|
||||
type ProcessedMessage = {
|
||||
messageId: string;
|
||||
hasAnalysisResponse: boolean;
|
||||
hasPartialAnalysisResponse: boolean;
|
||||
hasFullAnalysisResponse: boolean;
|
||||
medusaOrderId: string | undefined;
|
||||
};
|
||||
|
||||
type GroupedResults = {
|
||||
processed: Pick<ProcessedMessage, 'messageId' | 'medusaOrderId'>[];
|
||||
waitingForResults: Pick<ProcessedMessage, 'messageId' | 'medusaOrderId'>[];
|
||||
};
|
||||
|
||||
export default async function syncAnalysisResults() {
|
||||
console.info("Syncing analysis results");
|
||||
|
||||
let processedMessages: ProcessedMessage[] = [];
|
||||
const excludedMessageIds: string[] = [];
|
||||
while (true) {
|
||||
const result = await readPrivateMessageResponse({ excludedMessageIds });
|
||||
if (result.messageId) {
|
||||
processedMessages.push(result as ProcessedMessage);
|
||||
}
|
||||
|
||||
if (!result.messageId) {
|
||||
console.info("No more messages to process");
|
||||
break;
|
||||
}
|
||||
|
||||
if (!excludedMessageIds.includes(result.messageId)) {
|
||||
excludedMessageIds.push(result.messageId);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const groupedResults = processedMessages.reduce((acc, result) => {
|
||||
if (result.medusaOrderId) {
|
||||
if (result.hasAnalysisResponse) {
|
||||
if (!acc.processed) {
|
||||
acc.processed = [];
|
||||
}
|
||||
acc.processed.push({
|
||||
messageId: result.messageId,
|
||||
medusaOrderId: result.medusaOrderId,
|
||||
});
|
||||
} else {
|
||||
if (!acc.waitingForResults) {
|
||||
acc.waitingForResults = [];
|
||||
}
|
||||
acc.waitingForResults.push({
|
||||
messageId: result.messageId,
|
||||
medusaOrderId: result.medusaOrderId,
|
||||
});
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}, {} as GroupedResults);
|
||||
console.info(`Processed ${processedMessages.length} messages, results: ${JSON.stringify(groupedResults)}`);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
export default function validateApiKey(request: NextRequest) {
|
||||
const envApiKey = process.env.JOBS_API_TOKEN;
|
||||
const requestApiKey = request.headers.get('x-jobs-api-key');
|
||||
if (requestApiKey !== envApiKey) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import loadEnv from "../handler/load-env";
|
||||
import validateApiKey from "../handler/validate-api-key";
|
||||
import { getOrderedAnalysisElementsIds, sendOrderToMedipost } from "~/lib/services/medipost.service";
|
||||
import { retrieveOrder } from "@lib/data/orders";
|
||||
import { getMedipostDispatchTries } from "~/lib/services/audit.service";
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
loadEnv();
|
||||
|
||||
const { medusaOrderId } = await request.json();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
const tries = await getMedipostDispatchTries(medusaOrderId);
|
||||
if (tries >= 3) {
|
||||
return NextResponse.json({
|
||||
message: 'Order has been retried too many times',
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const medusaOrder = await retrieveOrder(medusaOrderId);
|
||||
const orderedAnalysisElements = await getOrderedAnalysisElementsIds({ medusaOrder });
|
||||
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
||||
console.info("Successfully sent order to medipost");
|
||||
return NextResponse.json({
|
||||
message: 'Successfully sent order to medipost',
|
||||
}, { status: 200 });
|
||||
} catch (e) {
|
||||
console.error("Error sending order to medipost", e);
|
||||
return NextResponse.json({
|
||||
message: 'Failed to send order to medipost',
|
||||
}, { status: 500 });
|
||||
}
|
||||
};
|
||||
@@ -1,53 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import {
|
||||
NotificationAction,
|
||||
createNotificationLog,
|
||||
} from '~/lib/services/audit/notificationEntries.service';
|
||||
import loadEnv from '../handler/load-env';
|
||||
import sendOpenJobsEmails from '../handler/send-open-jobs-emails';
|
||||
import validateApiKey from '../handler/validate-api-key';
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
loadEnv();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
try {
|
||||
await sendOpenJobsEmails();
|
||||
console.info(
|
||||
'Successfully sent out open job notification emails to doctors.',
|
||||
);
|
||||
await createNotificationLog({
|
||||
action: NotificationAction.NEW_JOBS_ALERT,
|
||||
status: 'SUCCESS',
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
message:
|
||||
'Successfully sent out open job notification emails to doctors.',
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
} catch (e: any) {
|
||||
console.error(
|
||||
'Error sending out open job notification emails to doctors.',
|
||||
e,
|
||||
);
|
||||
await createNotificationLog({
|
||||
action: NotificationAction.NEW_JOBS_ALERT,
|
||||
status: 'FAIL',
|
||||
comment: e?.message,
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
message: 'Failed to send out open job notification emails to doctors.',
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import loadEnv from "../handler/load-env";
|
||||
import validateApiKey from "../handler/validate-api-key";
|
||||
import syncAnalysisGroupsStore from "../handler/sync-analysis-groups-store";
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
loadEnv();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
try {
|
||||
await syncAnalysisGroupsStore();
|
||||
console.info("Successfully synced analysis groups store");
|
||||
return NextResponse.json({
|
||||
message: 'Successfully synced analysis groups store',
|
||||
}, { status: 200 });
|
||||
} catch (e) {
|
||||
console.error("Error syncing analysis groups store", e);
|
||||
return NextResponse.json({
|
||||
message: 'Failed to sync analysis groups store',
|
||||
}, { status: 500 });
|
||||
}
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import syncAnalysisGroups from "../handler/sync-analysis-groups";
|
||||
import loadEnv from "../handler/load-env";
|
||||
import validateApiKey from "../handler/validate-api-key";
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
loadEnv();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
try {
|
||||
await syncAnalysisGroups();
|
||||
console.info("Successfully synced analysis groups");
|
||||
return NextResponse.json({
|
||||
message: 'Successfully synced analysis groups',
|
||||
}, { status: 200 });
|
||||
} catch (e) {
|
||||
console.error("Error syncing analysis groups", e);
|
||||
return NextResponse.json({
|
||||
message: 'Failed to sync analysis groups',
|
||||
}, { status: 500 });
|
||||
}
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import loadEnv from "../handler/load-env";
|
||||
import validateApiKey from "../handler/validate-api-key";
|
||||
import syncAnalysisResults from "../handler/sync-analysis-results";
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
loadEnv();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
try {
|
||||
await syncAnalysisResults();
|
||||
console.info("Successfully synced analysis results");
|
||||
return NextResponse.json({
|
||||
message: 'Successfully synced analysis results',
|
||||
}, { status: 200 });
|
||||
} catch (e) {
|
||||
console.error("Error syncing analysis results", e);
|
||||
return NextResponse.json({
|
||||
message: 'Failed to sync analysis results',
|
||||
}, { status: 500 });
|
||||
}
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import loadEnv from "../handler/load-env";
|
||||
import validateApiKey from "../handler/validate-api-key";
|
||||
import syncConnectedOnline from "../handler/sync-connected-online";
|
||||
|
||||
export const POST = async (request: NextRequest) => {
|
||||
loadEnv();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
try {
|
||||
await syncConnectedOnline();
|
||||
console.info("Successfully synced connected-online");
|
||||
return NextResponse.json({
|
||||
message: 'Successfully synced connected-online',
|
||||
}, { status: 200 });
|
||||
} catch (e) {
|
||||
console.error("Error syncing connected-online", e);
|
||||
return NextResponse.json({
|
||||
message: 'Failed to sync connected-online',
|
||||
}, { status: 500 });
|
||||
}
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
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 { getAccountAdmin } from "~/lib/services/account.service";
|
||||
import { getOrderedAnalysisElementsIds } from "~/lib/services/medipost.service";
|
||||
import loadEnv from "../handler/load-env";
|
||||
import validateApiKey from "../handler/validate-api-key";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
loadEnv();
|
||||
|
||||
try {
|
||||
validateApiKey(request);
|
||||
} catch (e) {
|
||||
return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
|
||||
}
|
||||
|
||||
const analysisOrders = await getAnalysisOrdersAdmin({ orderStatus: 'PROCESSING' });
|
||||
|
||||
console.error(`Sending test responses for ${analysisOrders.length} analysis orders`);
|
||||
for (const medreportOrder of analysisOrders) {
|
||||
const medusaOrderId = medreportOrder.medusa_order_id;
|
||||
const medusaOrder = await retrieveOrder(medusaOrderId)
|
||||
|
||||
const account = await getAccountAdmin({ primaryOwnerUserId: medreportOrder.user_id });
|
||||
const orderedAnalysisElementsIds = await getOrderedAnalysisElementsIds({ medusaOrder });
|
||||
|
||||
console.info(`Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} ordered analysis elements`);
|
||||
const idsToSend = orderedAnalysisElementsIds;
|
||||
const messageXml = await composeOrderTestResponseXML({
|
||||
person: {
|
||||
idCode: account.personal_code!,
|
||||
firstName: account.name ?? '',
|
||||
lastName: account.last_name ?? '',
|
||||
phone: account.phone ?? '',
|
||||
},
|
||||
orderedAnalysisElementsIds: idsToSend.map(({ analysisElementId }) => analysisElementId),
|
||||
orderedAnalysesIds: [],
|
||||
orderId: medusaOrderId,
|
||||
orderCreatedAt: new Date(medreportOrder.created_at),
|
||||
});
|
||||
|
||||
try {
|
||||
await sendPrivateMessageTestResponse({ messageXml });
|
||||
} catch (error) {
|
||||
console.error("Error sending private message test response: ", error);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
@@ -38,6 +38,9 @@ export const POST = enhanceRouteHandler(
|
||||
const body = await request.json();
|
||||
const namespace = 'montonio.verify-token';
|
||||
|
||||
const activeCartId = request.cookies.get('_medusa_cart_id')?.value;
|
||||
console.info('cart id', activeCartId);
|
||||
|
||||
try {
|
||||
const { token } = BodySchema.parse(body);
|
||||
|
||||
@@ -58,6 +61,12 @@ export const POST = enhanceRouteHandler(
|
||||
algorithms: ['HS256'],
|
||||
}) as MontonioOrderToken;
|
||||
|
||||
const [, cartId] = decoded.merchantReferenceDisplay.split(':');
|
||||
console.info('active cart id parsed', {cartId, activeCartId, decoded:decoded.merchantReferenceDisplay});
|
||||
if (cartId !== activeCartId) {
|
||||
throw new Error('Invalid cart id');
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
name: namespace,
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
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 { getAccountAdmin } from "~/lib/services/account.service";
|
||||
import { createMedipostActionLog, getOrderedAnalysisElementsIds } from "~/lib/services/medipost.service";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// const isDev = process.env.NODE_ENV === 'development';
|
||||
// if (!isDev) {
|
||||
// return NextResponse.json({ error: 'This endpoint is only available in development mode' }, { status: 403 });
|
||||
// }
|
||||
|
||||
const { medusaOrderId, maxItems = null } = await request.json();
|
||||
|
||||
const medusaOrder = await retrieveOrder(medusaOrderId)
|
||||
const medreportOrder = await getOrder({ medusaOrderId });
|
||||
|
||||
const account = await getAccountAdmin({ primaryOwnerUserId: medreportOrder.user_id });
|
||||
const orderedAnalysisElementsIds = await getOrderedAnalysisElementsIds({ medusaOrder });
|
||||
|
||||
console.info(`Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} (${maxItems ?? 'all'}) ordered analysis elements`);
|
||||
const idsToSend = typeof maxItems === 'number' ? orderedAnalysisElementsIds.slice(0, maxItems) : orderedAnalysisElementsIds;
|
||||
const messageXml = await composeOrderTestResponseXML({
|
||||
person: {
|
||||
idCode: account.personal_code!,
|
||||
firstName: account.name ?? '',
|
||||
lastName: account.last_name ?? '',
|
||||
phone: account.phone ?? '',
|
||||
},
|
||||
orderedAnalysisElementsIds: idsToSend.map(({ analysisElementId }) => analysisElementId),
|
||||
orderedAnalysesIds: [],
|
||||
orderId: medusaOrderId,
|
||||
orderCreatedAt: new Date(medreportOrder.created_at),
|
||||
});
|
||||
|
||||
try {
|
||||
await createMedipostActionLog({
|
||||
action: 'send_fake_analysis_results_to_medipost',
|
||||
xml: messageXml,
|
||||
medusaOrderId,
|
||||
});
|
||||
await sendPrivateMessageTestResponse({ messageXml });
|
||||
} catch (error) {
|
||||
console.error("Error sending private message test response: ", error);
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
@@ -7,11 +7,9 @@ import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
interface AuthCallbackErrorPageProps {
|
||||
searchParams: Promise<{
|
||||
error: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
|
||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||
return <AuthLayoutShell Logo={AppLogo}>{children}</AuthLayoutShell>;
|
||||
|
||||
@@ -4,8 +4,7 @@ import type { NextRequest } from 'next/server';
|
||||
import { createAuthCallbackService } from '@kit/supabase/auth';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const service = createAuthCallbackService(getSupabaseServerClient());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
|
||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||
return <AuthLayoutShell Logo={AppLogo}>{children}</AuthLayoutShell>;
|
||||
|
||||
@@ -3,8 +3,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createAuthCallbackService } from '@kit/supabase/auth';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const service = createAuthCallbackService(getSupabaseServerClient());
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import pathsConfig from '@/config/paths.config';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { usePersonalAccountData } from '@kit/accounts/hooks/use-personal-account-data';
|
||||
@@ -25,7 +25,7 @@ const MembershipConfirmationNotification: React.FC<{
|
||||
descriptionKey="account:membershipConfirmation:successDescription"
|
||||
buttonProps={{
|
||||
buttonTitleKey: 'account:membershipConfirmation:successButton',
|
||||
href: pathsConfig.app.home,
|
||||
href: pathsConfig.app.selectPackage,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
async function SiteLayout(props: React.PropsWithChildren) {
|
||||
return (
|
||||
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import pathsConfig from '@/config/paths.config';
|
||||
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import {
|
||||
PageViewAction,
|
||||
createPageViewLog,
|
||||
} from '~/lib/services/audit/pageView.service';
|
||||
|
||||
import MembershipConfirmationNotification from './_components/membership-confirmation-notification';
|
||||
|
||||
async function MembershipConfirmation() {
|
||||
async function UpdateAccountSuccess() {
|
||||
const client = getSupabaseServerClient();
|
||||
|
||||
const {
|
||||
@@ -21,12 +18,8 @@ async function MembershipConfirmation() {
|
||||
if (!user?.id) {
|
||||
redirect(pathsConfig.app.home);
|
||||
}
|
||||
await createPageViewLog({
|
||||
accountId: user.id,
|
||||
action: PageViewAction.REGISTRATION_SUCCESS,
|
||||
});
|
||||
|
||||
return <MembershipConfirmationNotification userId={user.id} />;
|
||||
}
|
||||
|
||||
export default withI18n(MembershipConfirmation);
|
||||
export default withI18n(UpdateAccountSuccess);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
|
||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||
return <AuthLayoutShell Logo={AppLogo}>{children}</AuthLayoutShell>;
|
||||
|
||||
@@ -5,12 +5,10 @@ import { Button } from '@kit/ui/button';
|
||||
import { Heading } from '@kit/ui/heading';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
|
||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||
return <AuthLayoutShell Logo={AppLogo}>{children}</AuthLayoutShell>;
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { register } from 'module';
|
||||
|
||||
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 authConfig from '~/config/auth.config';
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
|
||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||
return <AuthLayoutShell Logo={AppLogo}>{children}</AuthLayoutShell>;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { SignUpMethodsContainer } from '@kit/auth/sign-up';
|
||||
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 authConfig from '~/config/auth.config';
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
|
||||
async function SiteLayout(props: React.PropsWithChildren) {
|
||||
return (
|
||||
<div className={'flex min-h-[100vh] flex-col items-center justify-center'}>
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { BackButton } from '@/components/back-button';
|
||||
import { MedReportLogo } from '@/components/med-report-logo';
|
||||
import pathsConfig from '@/config/paths.config';
|
||||
import { signOutAction } from '@/lib/actions/sign-out';
|
||||
import { UpdateAccountForm } from '@/packages/features/auth/src/components/update-account-form';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { BackButton } from '@kit/shared/components/back-button';
|
||||
import { MedReportLogo } from '@kit/shared/components/med-report-logo';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import { UpdateAccountForm } from './_components/update-account-form';
|
||||
|
||||
async function UpdateAccount() {
|
||||
const client = getSupabaseServerClient();
|
||||
|
||||
@@ -25,7 +24,7 @@ async function UpdateAccount() {
|
||||
|
||||
return (
|
||||
<div className="border-border flex max-w-5xl flex-row overflow-hidden rounded-3xl border">
|
||||
<div className="relative flex min-w-md flex-col px-12 pt-7 pb-22 text-center md:w-1/2">
|
||||
<div className="relative flex w-1/2 min-w-md flex-col px-12 pt-7 pb-22 text-center">
|
||||
<BackButton onBack={signOutAction} />
|
||||
<MedReportLogo />
|
||||
<h1 className="pt-8">
|
||||
@@ -36,7 +35,7 @@ async function UpdateAccount() {
|
||||
</p>
|
||||
<UpdateAccountForm user={user} />
|
||||
</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="w-1/2 min-w-[460px] bg-[url(/assets/med-report-logo-big.png)] bg-cover bg-center bg-no-repeat"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AuthLayoutShell } from '@kit/auth/shared';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
|
||||
function AuthLayout({ children }: React.PropsWithChildren) {
|
||||
return <AuthLayoutShell Logo={AppLogo}>{children}</AuthLayoutShell>;
|
||||
|
||||
@@ -4,8 +4,7 @@ import { MultiFactorChallengeContainer } from '@kit/auth/mfa';
|
||||
import { checkRequiresMultiFactorAuthentication } from '@kit/supabase/check-requires-mfa';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import pathsConfig from '~/config/paths.config';
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
@@ -41,7 +40,7 @@ async function VerifyPage(props: Props) {
|
||||
}
|
||||
|
||||
const nextPath = (await props.searchParams).next;
|
||||
const redirectPath = !!nextPath && nextPath.length > 0 ? nextPath : pathsConfig.app.home;
|
||||
const redirectPath = nextPath ?? pathsConfig.app.home;
|
||||
|
||||
return (
|
||||
<MultiFactorChallengeContainer
|
||||
|
||||
@@ -1,289 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { capitalize } from 'lodash';
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
import { giveFeedbackAction } from '@kit/doctor/actions/doctor-server-actions';
|
||||
import {
|
||||
getDOBWithAgeStringFromPersonalCode,
|
||||
getResultSetName,
|
||||
} from '@kit/doctor/lib/helpers';
|
||||
import {
|
||||
AnalysisResponse,
|
||||
DoctorFeedback,
|
||||
Order,
|
||||
Patient,
|
||||
} from '@kit/doctor/schema/doctor-analysis-detail-view.schema';
|
||||
import {
|
||||
DoctorAnalysisFeedbackForm,
|
||||
doctorAnalysisFeedbackFormSchema,
|
||||
} from '@kit/doctor/schema/doctor-analysis.schema';
|
||||
import ConfirmationModal from '@kit/shared/components/confirmation-modal';
|
||||
import {
|
||||
useCurrentLocaleLanguageNames
|
||||
} from '@kit/shared/hooks';
|
||||
import { getFullName } from '@kit/shared/utils';
|
||||
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormMessage,
|
||||
} from '@kit/ui/form';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { Textarea } from '@kit/ui/textarea';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { bmiFromMetric } from '~/lib/utils';
|
||||
|
||||
import DoctorAnalysisWrapper from './doctor-analysis-wrapper';
|
||||
import DoctorJobSelect from './doctor-job-select';
|
||||
|
||||
export default function AnalysisView({
|
||||
patient,
|
||||
order,
|
||||
analyses,
|
||||
feedback,
|
||||
}: {
|
||||
patient: Patient;
|
||||
order: Order;
|
||||
analyses: AnalysisResponse[];
|
||||
feedback?: DoctorFeedback;
|
||||
}) {
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
const [isDraftSubmitting, setIsDraftSubmitting] = useState(false);
|
||||
|
||||
const { data: user } = useUser();
|
||||
|
||||
const languageNames = useCurrentLocaleLanguageNames();
|
||||
|
||||
const isInProgress = !!(
|
||||
!!feedback?.status &&
|
||||
feedback?.doctor_user_id &&
|
||||
feedback?.status !== 'COMPLETED'
|
||||
);
|
||||
const isCurrentDoctorJob =
|
||||
!!feedback?.doctor_user_id && feedback?.doctor_user_id === user?.id;
|
||||
const isReadOnly =
|
||||
!isInProgress ||
|
||||
(!!feedback?.doctor_user_id && feedback?.doctor_user_id !== user?.id);
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(doctorAnalysisFeedbackFormSchema),
|
||||
reValidateMode: 'onChange',
|
||||
defaultValues: {
|
||||
feedbackValue: feedback?.value ?? '',
|
||||
userId: patient.userId,
|
||||
},
|
||||
});
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
if (!patient || !order || !analyses) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onSubmit = async (
|
||||
data: DoctorAnalysisFeedbackForm,
|
||||
status: 'DRAFT' | 'COMPLETED',
|
||||
) => {
|
||||
const result = await giveFeedbackAction({
|
||||
...data,
|
||||
analysisOrderId: order.analysisOrderId,
|
||||
status,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return toast.error(<Trans i18nKey="common:genericServerError" />);
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
});
|
||||
|
||||
toast.success(<Trans i18nKey={'doctor:updateFeedbackSuccess'} />);
|
||||
|
||||
return setIsConfirmOpen(false);
|
||||
};
|
||||
|
||||
const handleDraftSubmit = async (e: React.FormEvent) => {
|
||||
setIsDraftSubmitting(true);
|
||||
e.preventDefault();
|
||||
|
||||
form.formState.errors.feedbackValue = undefined;
|
||||
const formData = form.getValues();
|
||||
await onSubmit(formData, 'DRAFT');
|
||||
setIsDraftSubmitting(false);
|
||||
};
|
||||
|
||||
const handleCompleteSubmit = form.handleSubmit(async () => {
|
||||
setIsConfirmOpen(true);
|
||||
});
|
||||
|
||||
const confirmComplete = form.handleSubmit(async (data) => {
|
||||
await onSubmit(data, 'COMPLETED');
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="xs:flex xs:justify-between">
|
||||
<h3>
|
||||
<Trans
|
||||
i18nKey={getResultSetName(
|
||||
order.title,
|
||||
order.isPackage,
|
||||
Object.keys(analyses)?.length,
|
||||
)}
|
||||
/>
|
||||
</h3>
|
||||
<div className="xs:flex hidden">
|
||||
<DoctorJobSelect
|
||||
analysisOrderId={order.analysisOrderId}
|
||||
userId={patient.userId}
|
||||
doctorUserId={feedback?.doctor_user_id}
|
||||
isRemovable={isCurrentDoctorJob && isInProgress}
|
||||
onJobUpdate={() =>
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="xs:grid-cols-2 grid">
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:name" />
|
||||
</div>
|
||||
<div>{getFullName(patient.firstName, patient.lastName)}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:personalCode" />
|
||||
</div>
|
||||
<div>{patient.personalCode ?? ''}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:dobAndAge" />
|
||||
</div>
|
||||
<div>{getDOBWithAgeStringFromPersonalCode(patient.personalCode)}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:height" />
|
||||
</div>
|
||||
<div>{patient.height}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:weight" />
|
||||
</div>
|
||||
<div>{patient.weight}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:bmi" />
|
||||
</div>
|
||||
<div>
|
||||
{patient?.weight && patient?.height
|
||||
? bmiFromMetric(patient.weight, patient.height)
|
||||
: '-'}
|
||||
</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:smoking" />
|
||||
</div>
|
||||
<div>-</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:phone" />
|
||||
</div>
|
||||
<div>{patient.phone}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="doctor:email" />
|
||||
</div>
|
||||
<div>{patient.email}</div>
|
||||
<div className="font-bold">
|
||||
<Trans i18nKey="common:language" />
|
||||
</div>
|
||||
<div>
|
||||
{capitalize(languageNames.of(patient.preferred_locale ?? 'et'))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="xs:hidden block">
|
||||
<DoctorJobSelect
|
||||
className="w-full"
|
||||
analysisOrderId={order.analysisOrderId}
|
||||
userId={patient.userId}
|
||||
doctorUserId={feedback?.doctor_user_id}
|
||||
isRemovable={isCurrentDoctorJob && isInProgress}
|
||||
onJobUpdate={() =>
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<h3>
|
||||
<Trans i18nKey="doctor:results" />
|
||||
</h3>
|
||||
<div className="flex flex-col gap-2">
|
||||
{analyses.map((analysisData) => {
|
||||
return (
|
||||
<DoctorAnalysisWrapper
|
||||
key={analysisData.id}
|
||||
analysisData={analysisData}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<h3>
|
||||
<Trans i18nKey="doctor:feedback" />
|
||||
</h3>
|
||||
<p>{feedback?.value ?? '-'}</p>
|
||||
{!isReadOnly && (
|
||||
<Form {...form}>
|
||||
<form className="space-y-4 lg:w-1/2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="feedbackValue"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<Textarea {...field} disabled={isReadOnly} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="xs:flex block justify-end gap-2 space-y-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleDraftSubmit}
|
||||
disabled={
|
||||
isReadOnly || isDraftSubmitting || form.formState.isSubmitting
|
||||
}
|
||||
className="xs:w-1/4 w-full"
|
||||
>
|
||||
<Trans i18nKey="common:saveAsDraft" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleCompleteSubmit}
|
||||
disabled={
|
||||
isReadOnly || isDraftSubmitting || form.formState.isSubmitting
|
||||
}
|
||||
className="xs:w-1/4 w-full"
|
||||
>
|
||||
<Trans i18nKey="common:save" />
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
)}
|
||||
<ConfirmationModal
|
||||
isOpen={isConfirmOpen}
|
||||
onClose={() => setIsConfirmOpen(false)}
|
||||
onConfirm={confirmComplete}
|
||||
titleKey="doctor:confirmFeedbackModal.title"
|
||||
descriptionKey="doctor:confirmFeedbackModal.description"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { CaretDownIcon, QuestionMarkCircledIcon } from '@radix-ui/react-icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { AnalysisResponse } from '@kit/doctor/schema/doctor-analysis-detail-view.schema';
|
||||
import { InfoTooltip } from '@kit/shared/components/ui/info-tooltip';
|
||||
import { formatDate } from '@kit/shared/utils';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@kit/ui/collapsible';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import Analysis from '~/home/(user)/(dashboard)/analysis-results/_components/analysis';
|
||||
|
||||
export default function DoctorAnalysisWrapper({
|
||||
analysisData,
|
||||
}: {
|
||||
analysisData: AnalysisResponse;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Collapsible className="w-full" key={analysisData.id}>
|
||||
<CollapsibleTrigger
|
||||
disabled={!analysisData.latestPreviousAnalysis}
|
||||
asChild
|
||||
>
|
||||
<div className="[&[data-state=open]_.caret-icon]:rotate-180">
|
||||
<Analysis
|
||||
startIcon={
|
||||
analysisData.latestPreviousAnalysis && (
|
||||
<CaretDownIcon className="caret-icon transition-transform duration-200" />
|
||||
)
|
||||
}
|
||||
endIcon={
|
||||
analysisData.comment && (
|
||||
<>
|
||||
<div className="xs:flex hidden">
|
||||
<InfoTooltip
|
||||
content={analysisData.comment}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="mx-2 text-blue-800" />
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="xs:hidden">
|
||||
<strong>
|
||||
<Trans i18nKey="doctor:labComment" />:
|
||||
</strong>{' '}
|
||||
{analysisData.comment}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
analysisElement={{
|
||||
analysis_name_lab: analysisData.analysis_name,
|
||||
}}
|
||||
results={analysisData}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
{analysisData.latestPreviousAnalysis && (
|
||||
<CollapsibleContent>
|
||||
<div className="my-1 flex flex-col">
|
||||
<Analysis
|
||||
endIcon={
|
||||
analysisData.latestPreviousAnalysis.comment && (
|
||||
<>
|
||||
<div className="xs:flex hidden">
|
||||
<InfoTooltip
|
||||
content={analysisData.latestPreviousAnalysis.comment}
|
||||
icon={
|
||||
<QuestionMarkCircledIcon className="mx-2 text-blue-800" />
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="xs:hidden">
|
||||
<strong>
|
||||
<Trans i18nKey="doctor:labComment" />:{' '}
|
||||
</strong>
|
||||
{analysisData.latestPreviousAnalysis.comment}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
analysisElement={{
|
||||
analysis_name_lab: t('doctor:previousResults', {
|
||||
date: formatDate(
|
||||
analysisData.latestPreviousAnalysis.response_time,
|
||||
),
|
||||
}),
|
||||
}}
|
||||
results={analysisData.latestPreviousAnalysis}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
)}
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getOpenResponsesAction,
|
||||
getOtherResponsesAction,
|
||||
getUserDoneResponsesAction,
|
||||
getUserInProgressResponsesAction,
|
||||
} from '@kit/doctor/actions/table-data-fetching-actions';
|
||||
import ResultsTableWrapper from './results-table-wrapper';
|
||||
|
||||
export default function Dashboard() {
|
||||
return (
|
||||
<>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:openReviews"
|
||||
action={getOpenResponsesAction}
|
||||
queryKey="doctor-open-jobs"
|
||||
/>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:myReviews"
|
||||
action={getUserInProgressResponsesAction}
|
||||
queryKey="doctor-in-progress-jobs"
|
||||
/>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:completedReviews"
|
||||
action={getUserDoneResponsesAction}
|
||||
queryKey="doctor-done-jobs"
|
||||
/>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:otherReviews"
|
||||
action={getOtherResponsesAction}
|
||||
queryKey="doctor-other-jobs"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
import { isDoctor } from '@kit/doctor/lib/server/utils/is-doctor';
|
||||
|
||||
|
||||
type LayoutOrPageComponent<Params> = React.ComponentType<Params>;
|
||||
|
||||
/**
|
||||
* DoctorGuard is a server component wrapper that checks if the user is a doctor before rendering the component.
|
||||
* If the user is not a doctor, we redirect to a 404.
|
||||
* @param Component - The Page or Layout component to wrap
|
||||
*/
|
||||
export function DoctorGuard<Params extends object>(
|
||||
Component: LayoutOrPageComponent<Params>,
|
||||
) {
|
||||
return async function DoctorGuardServerComponentWrapper(params: Params) {
|
||||
const client = getSupabaseServerClient();
|
||||
const isUserDoctor = await isDoctor(client);
|
||||
|
||||
// if the user is not a super-admin, we redirect to a 404
|
||||
if (!isUserDoctor) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return <Component {...params} />;
|
||||
};
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useTransition } from 'react';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
|
||||
import {
|
||||
selectJobAction,
|
||||
unselectJobAction,
|
||||
} from '@kit/doctor/actions/doctor-server-actions';
|
||||
import { ErrorReason } from '@kit/doctor/schema/error.type';
|
||||
import { Button, ButtonProps } from '@kit/ui/button';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { cn } from '@kit/ui/utils';
|
||||
|
||||
export default function DoctorJobSelect({
|
||||
className,
|
||||
size = 'sm',
|
||||
doctorUserId,
|
||||
doctorName,
|
||||
analysisOrderId,
|
||||
userId,
|
||||
isRemovable,
|
||||
onJobUpdate,
|
||||
linkTo,
|
||||
}: {
|
||||
className?: string;
|
||||
size?: ButtonProps['size'];
|
||||
doctorUserId?: string | null;
|
||||
doctorName?: string;
|
||||
analysisOrderId: number;
|
||||
userId: string;
|
||||
isRemovable?: boolean;
|
||||
linkTo?: string;
|
||||
onJobUpdate: () => void;
|
||||
}) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const router = useRouter();
|
||||
|
||||
const handleSelectJob = () => {
|
||||
startTransition(async () => {
|
||||
const result = await selectJobAction({
|
||||
analysisOrderId,
|
||||
userId,
|
||||
});
|
||||
|
||||
if (result?.success) {
|
||||
onJobUpdate();
|
||||
linkTo && router.push(linkTo);
|
||||
} else {
|
||||
toast.error(
|
||||
<Trans
|
||||
i18nKey={`doctor:error.${result.reason ?? ErrorReason.UNKNOWN}`}
|
||||
/>,
|
||||
);
|
||||
if (result.reason === ErrorReason.JOB_ASSIGNED) {
|
||||
onJobUpdate();
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleUnselectJob = () => {
|
||||
startTransition(async () => {
|
||||
const result = await unselectJobAction({
|
||||
analysisOrderId,
|
||||
});
|
||||
|
||||
if (result?.success) {
|
||||
onJobUpdate();
|
||||
} else {
|
||||
toast.error(
|
||||
<Trans
|
||||
i18nKey={`doctor:error.${result.reason ?? ErrorReason.UNKNOWN}`}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (isRemovable) {
|
||||
return (
|
||||
<Button
|
||||
className={cn('w-16', className)}
|
||||
size={size}
|
||||
variant="destructive"
|
||||
onClick={handleUnselectJob}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? (
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trans i18nKey="doctor:unselectJob" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (!doctorUserId) {
|
||||
return (
|
||||
<Button
|
||||
className={cn('w-16', className)}
|
||||
size={size}
|
||||
onClick={handleSelectJob}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? (
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trans i18nKey="doctor:selectJob" />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{doctorName}</>;
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace';
|
||||
import { LayoutDashboard } from 'lucide-react';
|
||||
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import { ProfileAccountDropdownContainer } from '@kit/shared/components/personal-account-dropdown-container';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
useSidebar,
|
||||
} from '@kit/ui/shadcn-sidebar';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
export function DoctorSidebar({
|
||||
accounts,
|
||||
}: {
|
||||
accounts: UserWorkspace['accounts'];
|
||||
}) {
|
||||
const path = usePathname();
|
||||
const { open } = useSidebar();
|
||||
return (
|
||||
<Sidebar collapsible="icon">
|
||||
<SidebarHeader className={'m-2'}>
|
||||
<AppLogo
|
||||
href={pathsConfig.app.doctor}
|
||||
className="max-w-full"
|
||||
compact={!open}
|
||||
/>
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>
|
||||
<Trans i18nKey="common:doctor" />
|
||||
</SidebarGroupLabel>
|
||||
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuButton
|
||||
isActive={path === pathsConfig.app.doctor}
|
||||
asChild
|
||||
>
|
||||
<Link className={'flex gap-2.5'} href={pathsConfig.app.doctor}>
|
||||
<LayoutDashboard className={'h-4'} />
|
||||
<Trans i18nKey={'doctor:sidebar.dashboard'} />
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuButton
|
||||
isActive={path === pathsConfig.app.openJobs}
|
||||
asChild
|
||||
>
|
||||
<Link
|
||||
className={'flex gap-2.5'}
|
||||
href={pathsConfig.app.openJobs}
|
||||
>
|
||||
<LayoutDashboard className={'h-4'} />
|
||||
<Trans i18nKey={'doctor:sidebar.openReviews'} />
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuButton
|
||||
isActive={path === pathsConfig.app.myJobs}
|
||||
asChild
|
||||
>
|
||||
<Link className={'flex gap-2.5'} href={pathsConfig.app.myJobs}>
|
||||
<LayoutDashboard className={'h-4'} />
|
||||
<Trans i18nKey={'doctor:sidebar.myReviews'} />
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuButton
|
||||
isActive={path === pathsConfig.app.completedJobs}
|
||||
asChild
|
||||
>
|
||||
<Link
|
||||
className={'flex gap-2.5'}
|
||||
href={pathsConfig.app.completedJobs}
|
||||
>
|
||||
<LayoutDashboard className={'h-4'} />
|
||||
<Trans i18nKey={'doctor:sidebar.completedReviews'} />
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
<ProfileAccountDropdownContainer accounts={accounts} />
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { Menu } from 'lucide-react';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@kit/ui/dropdown-menu';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
export function DoctorMobileNavigation() {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger>
|
||||
<Menu className={'h-8 w-8'} />
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>
|
||||
<Link href={pathsConfig.app.home}>
|
||||
<Trans i18nKey={'common:routes.home'} />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Link href={pathsConfig.app.doctor}>
|
||||
<Trans i18nKey={'doctor:sidebar.dashboard'} />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Link href={pathsConfig.app.openJobs}>
|
||||
<Trans i18nKey={'doctor:sidebar.openReviews'} />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Link href={pathsConfig.app.myJobs}>
|
||||
<Trans i18nKey={'doctor:sidebar.myReviews'} />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Link href={pathsConfig.app.completedJobs}>
|
||||
<Trans i18nKey={'doctor:sidebar.completedReviews'} />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import {
|
||||
PaginatedData,
|
||||
ResponseTable,
|
||||
ServerActionResponse,
|
||||
} from '@kit/doctor/schema/doctor-analysis.schema';
|
||||
import TableSkeleton from '@kit/shared/components/table-skeleton';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { cn } from '@kit/ui/utils';
|
||||
|
||||
import ResultsTable from './results-table';
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
export default function ResultsTableWrapper({
|
||||
titleKey,
|
||||
action,
|
||||
queryKey,
|
||||
}: {
|
||||
titleKey: string;
|
||||
action: ({
|
||||
page,
|
||||
pageSize,
|
||||
}: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}) => Promise<ServerActionResponse<PaginatedData<ResponseTable>>>;
|
||||
queryKey: string;
|
||||
}) {
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const {
|
||||
data: jobs,
|
||||
isLoading,
|
||||
isError,
|
||||
isFetching,
|
||||
} = useQuery({
|
||||
queryKey: [queryKey, 'doctor-jobs', page],
|
||||
queryFn: async () => await action({ page: page, pageSize: PAGE_SIZE }),
|
||||
placeholderData: (previousData) => previousData,
|
||||
});
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const onJobUpdate = () => {
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => query.queryKey.includes('doctor-jobs'),
|
||||
});
|
||||
};
|
||||
|
||||
const createPageChangeHandler = (setPage: (page: number) => void) => {
|
||||
return async ({ page }: { page: number; pageSize: number }) => {
|
||||
setPage(page);
|
||||
return { success: true, data: null };
|
||||
};
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<>
|
||||
<h3>
|
||||
<Trans i18nKey={titleKey} />
|
||||
</h3>
|
||||
|
||||
<div className="relative">
|
||||
<div
|
||||
className={`transition-opacity duration-200 ${
|
||||
isFetching ? 'opacity-50' : 'opacity-100'
|
||||
}`}
|
||||
>
|
||||
<TableSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<>
|
||||
<h3>
|
||||
<Trans i18nKey={titleKey} />
|
||||
</h3>
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<div className="text-lg text-red-600">
|
||||
<Trans i18nKey="common:genericServerError" />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3>
|
||||
<Trans i18nKey={titleKey} />
|
||||
</h3>
|
||||
|
||||
<div className="relative">
|
||||
<div
|
||||
className={cn('opacity-100 transition-opacity duration-200', {
|
||||
'opacity-50': isFetching,
|
||||
})}
|
||||
>
|
||||
<ResultsTable
|
||||
results={jobs?.data?.data || []}
|
||||
pagination={jobs?.data?.pagination}
|
||||
fetchAction={createPageChangeHandler(setPage)}
|
||||
onJobUpdate={onJobUpdate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useTransition } from 'react';
|
||||
|
||||
import Link from 'next/link';
|
||||
|
||||
import { format } from 'date-fns';
|
||||
import { Eye } from 'lucide-react';
|
||||
|
||||
import { getResultSetName } from '@kit/doctor/lib/helpers';
|
||||
import { ResponseTable } from '@kit/doctor/schema/doctor-analysis.schema';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { useCurrentLocaleLanguageNames } from '@kit/shared/hooks';
|
||||
import { getFullName } from '@kit/shared/utils';
|
||||
import { useUser } from '@kit/supabase/hooks/use-user';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { toast } from '@kit/ui/sonner';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@kit/ui/table';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import DoctorJobSelect from './doctor-job-select';
|
||||
import { capitalize } from 'lodash';
|
||||
|
||||
export default function ResultsTable({
|
||||
results = [],
|
||||
pagination = {
|
||||
currentPage: 1,
|
||||
totalPages: 1,
|
||||
totalCount: 0,
|
||||
pageSize: 10,
|
||||
},
|
||||
fetchAction,
|
||||
onJobUpdate,
|
||||
}: {
|
||||
results: ResponseTable[] | null;
|
||||
pagination?: {
|
||||
currentPage: number;
|
||||
totalPages: number;
|
||||
totalCount: number;
|
||||
pageSize: number;
|
||||
};
|
||||
fetchAction: ({
|
||||
page,
|
||||
pageSize,
|
||||
}: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}) => Promise<{
|
||||
success: boolean;
|
||||
data: null;
|
||||
}>;
|
||||
onJobUpdate: () => void;
|
||||
}) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const { data: currentUser } = useUser();
|
||||
|
||||
const languageNames = useCurrentLocaleLanguageNames();
|
||||
|
||||
const fetchPage = async (page: number) => {
|
||||
startTransition(async () => {
|
||||
const result = await fetchAction({
|
||||
page,
|
||||
pageSize: pagination.pageSize,
|
||||
});
|
||||
if (!result.success) {
|
||||
toast.error('common.genericServerError');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleNextPage = () => {
|
||||
if (pagination.currentPage < pagination.totalPages) {
|
||||
fetchPage(pagination.currentPage + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrevPage = () => {
|
||||
if (pagination.currentPage > 1) {
|
||||
fetchPage(pagination.currentPage - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleJobUpdate = () => {
|
||||
onJobUpdate();
|
||||
fetchPage(pagination.currentPage);
|
||||
};
|
||||
|
||||
if (!results?.length) {
|
||||
return (
|
||||
<p>
|
||||
<Trans i18nKey="common:noData" />.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table className="border-separate rounded-lg border">
|
||||
<TableHeader className="text-ui-fg-subtle txt-medium-plus">
|
||||
<TableRow>
|
||||
<TableHead className="w-6"></TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.patientName" />
|
||||
</TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.serviceName" />
|
||||
</TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.orderNr" />
|
||||
</TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.time" />
|
||||
</TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.resultsStatus" />
|
||||
</TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.language" />
|
||||
</TableHead>
|
||||
<TableHead className="w-20">
|
||||
<Trans i18nKey="doctor:resultsTable.assignedTo" />
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{results
|
||||
?.sort((a, b) =>
|
||||
(a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
|
||||
)
|
||||
.map((result) => {
|
||||
const isCompleted = result.feedback?.status === 'COMPLETED';
|
||||
const isCurrentDoctorJob =
|
||||
!!result.doctor?.primary_owner_user_id &&
|
||||
result.doctor?.primary_owner_user_id === currentUser?.id;
|
||||
|
||||
const resultsReceived = result.elements.length || 0;
|
||||
const elementsInOrder = Array.from(
|
||||
new Set(result.analysis_order_id.analysis_element_ids),
|
||||
)?.length;
|
||||
|
||||
return (
|
||||
<TableRow key={result.order_number}>
|
||||
<TableCell className="text-center">
|
||||
<Link
|
||||
href={`/${pathsConfig.app.analysisDetails}/${result.id}`}
|
||||
>
|
||||
<Eye />
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{getFullName(
|
||||
result.patient?.name,
|
||||
result.patient?.last_name,
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Trans
|
||||
i18nKey={getResultSetName(
|
||||
result.order?.title ?? '-',
|
||||
result.order?.isPackage,
|
||||
result.elements?.length || 0,
|
||||
)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>{result.order_number}</TableCell>
|
||||
<TableCell>
|
||||
{result.firstSampleGivenAt
|
||||
? format(result.firstSampleGivenAt, 'dd.MM.yyyy HH:mm')
|
||||
: '-'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Trans
|
||||
i18nKey={
|
||||
resultsReceived === elementsInOrder
|
||||
? 'doctor:resultsTable.responsesReceived'
|
||||
: 'doctor:resultsTable.waitingForNr'
|
||||
}
|
||||
values={{
|
||||
nr: elementsInOrder - resultsReceived,
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{capitalize(
|
||||
languageNames.of(result?.patient?.preferred_locale ?? 'et'),
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DoctorJobSelect
|
||||
doctorUserId={result.doctor?.primary_owner_user_id}
|
||||
doctorName={getFullName(
|
||||
result.doctor?.name,
|
||||
result.doctor?.last_name,
|
||||
)}
|
||||
analysisOrderId={result.analysis_order_id?.id}
|
||||
userId={result.patient?.id}
|
||||
isRemovable={!isCompleted && isCurrentDoctorJob}
|
||||
onJobUpdate={handleJobUpdate}
|
||||
linkTo={`/${pathsConfig.app.analysisDetails}/${result.id}`}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<Button
|
||||
onClick={handlePrevPage}
|
||||
disabled={pagination.currentPage === 1 || isPending}
|
||||
variant="outline"
|
||||
>
|
||||
<Trans i18nKey="common:previous" />
|
||||
</Button>
|
||||
<span className="text-sm text-gray-600">
|
||||
<Trans
|
||||
i18nKey={'common:pageOfPages'}
|
||||
values={{
|
||||
page: pagination.currentPage,
|
||||
total: pagination.totalPages,
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
<Button
|
||||
onClick={handleNextPage}
|
||||
disabled={
|
||||
pagination.currentPage === pagination.totalPages || isPending
|
||||
}
|
||||
variant="outline"
|
||||
>
|
||||
<Trans i18nKey="common:next" />
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { cache } from 'react';
|
||||
|
||||
import { getAnalysisResultsForDoctor } from '@kit/doctor/services/doctor-analysis.service';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import AnalysisView from '../../_components/analysis-view';
|
||||
import { DoctorGuard } from '../../_components/doctor-guard';
|
||||
|
||||
async function AnalysisPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
}) {
|
||||
const { id: analysisOrderId } = await params;
|
||||
const analysisResultDetails = await loadResult(Number(analysisOrderId));
|
||||
|
||||
if (!analysisResultDetails) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (analysisResultDetails) {
|
||||
await createDoctorPageViewLog({
|
||||
action: DoctorPageViewAction.VIEW_ANALYSIS_RESULTS,
|
||||
recordKey: analysisOrderId,
|
||||
dataOwnerUserId: analysisResultDetails.patient.userId,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<AnalysisView
|
||||
patient={analysisResultDetails.patient}
|
||||
order={analysisResultDetails.order}
|
||||
analyses={analysisResultDetails.analysisResponse}
|
||||
feedback={analysisResultDetails.doctorFeedback}
|
||||
/>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(AnalysisPage);
|
||||
const loadResult = cache(getAnalysisResultsForDoctor);
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { getUserDoneResponsesAction } from '@kit/doctor/actions/table-data-fetching-actions';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import { DoctorGuard } from '../_components/doctor-guard';
|
||||
import ResultsTableWrapper from '../_components/results-table-wrapper';
|
||||
|
||||
async function CompletedJobsPage() {
|
||||
await createDoctorPageViewLog({
|
||||
action: DoctorPageViewAction.VIEW_DONE_JOBS,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:completedReviews"
|
||||
action={getUserDoneResponsesAction}
|
||||
queryKey="doctor-done-jobs"
|
||||
/>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(CompletedJobsPage);
|
||||
@@ -1,47 +0,0 @@
|
||||
import { use } from 'react';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
|
||||
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
||||
|
||||
|
||||
import { loadUserWorkspace } from '../home/(user)/_lib/server/load-user-workspace';
|
||||
import { DoctorSidebar } from './_components/doctor-sidebar';
|
||||
import { DoctorMobileNavigation } from './_components/mobile-navigation';
|
||||
|
||||
export const metadata = {
|
||||
title: `Doctor`,
|
||||
};
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function DoctorLayout(props: React.PropsWithChildren) {
|
||||
const state = use(getLayoutState());
|
||||
const workspace = use(loadUserWorkspace());
|
||||
|
||||
return (
|
||||
<SidebarProvider defaultOpen={state.open}>
|
||||
<Page style={'sidebar'}>
|
||||
<PageNavigation>
|
||||
<DoctorSidebar accounts={workspace.accounts} />
|
||||
</PageNavigation>
|
||||
|
||||
<PageMobileNavigation>
|
||||
<DoctorMobileNavigation />
|
||||
</PageMobileNavigation>
|
||||
|
||||
{props.children}
|
||||
</Page>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
|
||||
async function getLayoutState() {
|
||||
const cookieStore = await cookies();
|
||||
const sidebarOpenCookie = cookieStore.get('sidebar:state');
|
||||
|
||||
return {
|
||||
open: sidebarOpenCookie?.value !== 'true',
|
||||
};
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import { GlobalLoader } from '@kit/ui/global-loader';
|
||||
|
||||
export default GlobalLoader;
|
||||
@@ -1,31 +0,0 @@
|
||||
import { getUserInProgressResponsesAction } from '@kit/doctor/actions/table-data-fetching-actions';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import { DoctorGuard } from '../_components/doctor-guard';
|
||||
import ResultsTableWrapper from '../_components/results-table-wrapper';
|
||||
|
||||
async function MyReviewsPage() {
|
||||
await createDoctorPageViewLog({
|
||||
action: DoctorPageViewAction.VIEW_OWN_JOBS,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:myReviews"
|
||||
action={getUserInProgressResponsesAction}
|
||||
queryKey="doctor-in-progress-jobs"
|
||||
/>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(MyReviewsPage);
|
||||
@@ -1,31 +0,0 @@
|
||||
import { getOpenResponsesAction } from '@kit/doctor/actions/table-data-fetching-actions';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import { DoctorGuard } from '../_components/doctor-guard';
|
||||
import ResultsTableWrapper from '../_components/results-table-wrapper';
|
||||
|
||||
async function OpenJobsPage() {
|
||||
await createDoctorPageViewLog({
|
||||
action: DoctorPageViewAction.VIEW_OPEN_JOBS,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<ResultsTableWrapper
|
||||
titleKey="doctor:openReviews"
|
||||
action={getOpenResponsesAction}
|
||||
queryKey="doctor-open-jobs"
|
||||
/>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(OpenJobsPage);
|
||||
@@ -1,26 +0,0 @@
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
import {
|
||||
DoctorPageViewAction,
|
||||
createDoctorPageViewLog,
|
||||
} from '~/lib/services/audit/doctorPageView.service';
|
||||
|
||||
import Dashboard from './_components/doctor-dashboard';
|
||||
import { DoctorGuard } from './_components/doctor-guard';
|
||||
|
||||
async function DoctorPage() {
|
||||
await createDoctorPageViewLog({
|
||||
action: DoctorPageViewAction.VIEW_DASHBOARD,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader />
|
||||
<PageBody>
|
||||
<Dashboard />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DoctorGuard(DoctorPage);
|
||||
@@ -10,7 +10,7 @@ import { Heading } from '@kit/ui/heading';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { SiteHeader } from '~/(marketing)/_components/site-header';
|
||||
import { RootProviders } from '@kit/shared/components/root-providers';
|
||||
import { RootProviders } from '~/components/root-providers';
|
||||
|
||||
const GlobalErrorPage = ({
|
||||
error,
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
const HealthPage = () => {
|
||||
const commit = process.env.NEXT_PUBLIC_COMMIT_HASH;
|
||||
|
||||
return <div>{commit}</div>;
|
||||
};
|
||||
|
||||
export default HealthPage;
|
||||
@@ -1,107 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { ButtonTooltip } from '@kit/shared/components/ui/button-tooltip';
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { loadCurrentUserAccount } from '~/home/(user)/_lib/server/load-user-account';
|
||||
import { loadUserAnalysis } from '~/home/(user)/_lib/server/load-user-analysis';
|
||||
import {
|
||||
PageViewAction,
|
||||
createPageViewLog,
|
||||
} from '~/lib/services/audit/pageView.service';
|
||||
|
||||
import Analysis from '../_components/analysis';
|
||||
|
||||
export default async function AnalysisResultsPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
}) {
|
||||
const account = await loadCurrentUserAccount();
|
||||
|
||||
const { id: analysisResponseId } = await params;
|
||||
|
||||
const analysisResponse = await loadUserAnalysis(Number(analysisResponseId));
|
||||
|
||||
if (!account?.id || !analysisResponse) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await createPageViewLog({
|
||||
accountId: account.id,
|
||||
action: PageViewAction.VIEW_ANALYSIS_RESULTS,
|
||||
});
|
||||
|
||||
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>
|
||||
<h4>
|
||||
<Trans i18nKey="analysis-results:pageTitle" />
|
||||
</h4>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{analysisResponse?.elements &&
|
||||
analysisResponse.elements?.length > 0 ? (
|
||||
<Trans i18nKey="analysis-results:description" />
|
||||
) : (
|
||||
<Trans i18nKey="analysis-results:descriptionEmpty" />
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link href={pathsConfig.app.orderAnalysisPackage}>
|
||||
<Trans i18nKey="analysis-results:orderNewAnalysis" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<h4>
|
||||
<Trans
|
||||
i18nKey="analysis-results:orderTitle"
|
||||
values={{ orderNumber: analysisResponse.order.medusa_order_id }}
|
||||
/>
|
||||
</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>
|
||||
</div>
|
||||
{analysisResponse?.summary?.value && (
|
||||
<div>
|
||||
<strong>
|
||||
<Trans i18nKey="account:doctorAnalysisSummary" />
|
||||
</strong>
|
||||
<p>{analysisResponse.summary.value}</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-2">
|
||||
{analysisResponse.elements ? (
|
||||
analysisResponse.elements.map((element, index) => (
|
||||
<Analysis
|
||||
key={index}
|
||||
analysisElement={{ analysis_name_lab: element.analysis_name }}
|
||||
results={element}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<div className="text-muted-foreground text-sm">
|
||||
<Trans i18nKey="analysis-results:noAnalysisElements" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { ArrowDown } from 'lucide-react';
|
||||
|
||||
import { cn } from '@kit/ui/utils';
|
||||
import { AnalysisResultForDisplay } from './analysis';
|
||||
|
||||
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-[35%] max-w-[360px] gap-1 sm:mt-0">
|
||||
<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-[35%] max-w-[360px] gap-1 sm:mt-0">
|
||||
{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;
|
||||
@@ -1,149 +0,0 @@
|
||||
'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 Analysis = ({
|
||||
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 Analysis;
|
||||
@@ -1,41 +0,0 @@
|
||||
import { HomeLayoutPageHeader } from '@/app/home/(user)/_components/home-page-header';
|
||||
import { loadCategory } from '@/app/home/(user)/_lib/server/load-category';
|
||||
|
||||
import { AppBreadcrumbs } from '@kit/ui/makerkit/app-breadcrumbs';
|
||||
import { PageBody } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const i18n = await createI18nServerInstance();
|
||||
const title = i18n.t('booking:title');
|
||||
|
||||
return {
|
||||
title,
|
||||
};
|
||||
};
|
||||
|
||||
async function BookingHandlePage({ params }: { params: { handle: string } }) {
|
||||
const handle = await params.handle;
|
||||
const { category } = await loadCategory({ handle });
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppBreadcrumbs
|
||||
values={{
|
||||
[handle]: category?.name || handle,
|
||||
}}
|
||||
/>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'booking:title'} />}
|
||||
description={<Trans i18nKey={'booking:description'} />}
|
||||
/>
|
||||
|
||||
<PageBody></PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(BookingHandlePage);
|
||||
@@ -1,6 +1,3 @@
|
||||
import { use } from 'react';
|
||||
|
||||
import { AppBreadcrumbs } from '@kit/ui/makerkit/app-breadcrumbs';
|
||||
import { PageBody } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
@@ -9,8 +6,6 @@ import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||
import OrderCards from '../../_components/order-cards';
|
||||
import ServiceCategories from '../../_components/service-categories';
|
||||
import { loadTtoServices } from '../../_lib/server/load-tto-services';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const i18n = await createI18nServerInstance();
|
||||
@@ -22,30 +17,15 @@ export const generateMetadata = async () => {
|
||||
};
|
||||
|
||||
function BookingPage() {
|
||||
const { heroCategories, ttoCategories } = use(loadTtoServices());
|
||||
|
||||
if (!heroCategories.length && !ttoCategories.length) {
|
||||
return (
|
||||
<>
|
||||
<AppBreadcrumbs />
|
||||
<h3 className="mt-8">
|
||||
<Trans i18nKey="booking:noCategories" />
|
||||
</h3>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppBreadcrumbs />
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'booking:title'} />}
|
||||
description={<Trans i18nKey={'booking:description'} />}
|
||||
/>
|
||||
|
||||
<PageBody className="space-y-2">
|
||||
<OrderCards heroCategories={heroCategories} />
|
||||
<ServiceCategories categories={ttoCategories} />
|
||||
<PageBody>
|
||||
<OrderCards />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
import { MontonioCheckoutCallback } from '../../../../_components/cart/montonio-checkout-callback';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('cart:montonioCallback.title'),
|
||||
};
|
||||
}
|
||||
|
||||
export default async function MontonioCheckoutCallbackPage() {
|
||||
return (
|
||||
<div className={'flex h-full flex-1 flex-col'}>
|
||||
<PageHeader title={<Trans i18nKey="cart:montonioCallback.title" />} />
|
||||
<PageBody>
|
||||
<MontonioCheckoutCallback />
|
||||
</PageBody>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
'use server';
|
||||
|
||||
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';
|
||||
const MONTONIO_PAID_STATUS = 'PAID';
|
||||
|
||||
const env = () => z
|
||||
.object({
|
||||
emailSender: z
|
||||
.string({
|
||||
required_error: 'EMAIL_SENDER is required',
|
||||
})
|
||||
.min(1),
|
||||
siteUrl: z
|
||||
.string({
|
||||
required_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 decoded = jwt.verify(orderToken, secretKey, {
|
||||
algorithms: ['HS256'],
|
||||
}) as MontonioOrderToken;
|
||||
|
||||
if (decoded.paymentStatus !== MONTONIO_PAID_STATUS) {
|
||||
throw new Error("Payment not successful");
|
||||
}
|
||||
|
||||
const account = await loadCurrentUserAccount();
|
||||
if (!account) {
|
||||
throw new Error("Account not found in context");
|
||||
}
|
||||
|
||||
try {
|
||||
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");
|
||||
}
|
||||
|
||||
|
||||
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) {
|
||||
console.error("Failed to place order", error);
|
||||
throw new Error(`Failed to place order, message=${error}`);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { processMontonioCallback } from './actions';
|
||||
|
||||
export default function MontonioCallbackClient({ orderToken, error }: {
|
||||
orderToken?: string;
|
||||
error?: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [hasProcessed, setHasProcessed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (error) {
|
||||
console.error(error);
|
||||
router.push('/home/cart/montonio-callback/error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!orderToken || hasProcessed || isProcessing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const processOrder = async () => {
|
||||
setIsProcessing(true);
|
||||
setHasProcessed(true);
|
||||
|
||||
try {
|
||||
const { orderId } = await processMontonioCallback(orderToken);
|
||||
router.push(`/home/order/${orderId}/confirmed`);
|
||||
} catch (error) {
|
||||
console.error("Failed to place order", error);
|
||||
router.push('/home/cart/montonio-callback/error');
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
processOrder();
|
||||
}, [orderToken, error, router, hasProcessed, isProcessing]);
|
||||
|
||||
return (
|
||||
<div className="flex mt-10 justify-center min-h-screen">
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { Alert, AlertDescription } from '@kit/ui/shadcn/alert';
|
||||
import { AlertTitle } from '@kit/ui/shadcn/alert';
|
||||
import { Button } from '@kit/ui/button';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('cart:montonioCallback.title'),
|
||||
};
|
||||
}
|
||||
|
||||
export default async function MontonioCheckoutCallbackErrorPage() {
|
||||
return (
|
||||
<div className={'flex h-full flex-1 flex-col'}>
|
||||
<PageHeader title={<Trans i18nKey="cart:montonioCallback.title" />} />
|
||||
<PageBody>
|
||||
<div className={'flex flex-col space-y-4'}>
|
||||
<Alert variant={'destructive'}>
|
||||
<AlertTitle>
|
||||
<Trans i18nKey={'checkout.error.title'} />
|
||||
</AlertTitle>
|
||||
|
||||
<AlertDescription>
|
||||
<p>
|
||||
<Trans i18nKey={'checkout.error.description'} />
|
||||
</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className={'flex'}>
|
||||
<Button asChild>
|
||||
<Link href={'/home'}>
|
||||
<Trans i18nKey={'checkout.goToDashboard'} />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import MontonioCallbackClient from './client-component';
|
||||
|
||||
export default async function MontonioCallbackPage({ searchParams }: {
|
||||
searchParams: Promise<{
|
||||
'order-token'?: string;
|
||||
}>;
|
||||
}) {
|
||||
const orderToken = (await searchParams)['order-token'];
|
||||
|
||||
if (!orderToken) {
|
||||
return <MontonioCallbackClient error="Order token is missing" />;
|
||||
}
|
||||
|
||||
return <MontonioCallbackClient orderToken={orderToken} />;
|
||||
}
|
||||
@@ -3,9 +3,9 @@ import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { retrieveCart } from '@lib/data/cart';
|
||||
import { retrieveCart } from '~/medusa/lib/data/cart';
|
||||
import Cart from '../../_components/cart';
|
||||
import { listProductTypes } from '@lib/data/products';
|
||||
import { listCollections } from '@lib/data';
|
||||
import CartTimer from '../../_components/cart/cart-timer';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
@@ -23,30 +23,25 @@ export default async function CartPage() {
|
||||
return notFound();
|
||||
});
|
||||
|
||||
const { productTypes } = await listProductTypes();
|
||||
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 { collections } = await listCollections({
|
||||
limit: "100",
|
||||
});
|
||||
|
||||
const otherItemsSorted = ttoServiceItems.sort((a, b) => (a.updated_at ?? "") > (b.updated_at ?? "") ? -1 : 1);
|
||||
const analysisPackagesCollection = collections.find(({ handle }) => handle === 'analysis-packages');
|
||||
const analysisPackages = analysisPackagesCollection && cart?.items
|
||||
? cart.items.filter((item) => item.product?.collection_id === analysisPackagesCollection.id)
|
||||
: [];
|
||||
const otherItems = cart?.items?.filter((item) => item.product?.collection_id !== analysisPackagesCollection?.id) ?? [];
|
||||
|
||||
const otherItemsSorted = otherItems.sort((a, b) => (a.updated_at ?? "") > (b.updated_at ?? "") ? -1 : 1);
|
||||
const item = otherItemsSorted[0];
|
||||
const isTimerShown = ttoServiceItems.length > 0 && !!item && !!item.updated_at;
|
||||
|
||||
return (
|
||||
<PageBody>
|
||||
<PageHeader title={<Trans i18nKey="cart:title" />}>
|
||||
{isTimerShown && <CartTimer cartItem={item} />}
|
||||
{item && item.updated_at && <CartTimer cartItem={item} />}
|
||||
</PageHeader>
|
||||
<Cart cart={cart} synlabAnalyses={synlabAnalyses} ttoServiceItems={ttoServiceItems} />
|
||||
<Cart cart={cart} analysisPackages={analysisPackages} otherItems={otherItems} />
|
||||
</PageBody>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,19 +2,14 @@ import { use } from 'react';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
import { retrieveCart } from '@lib/data/cart';
|
||||
import { StoreCart } from '@medusajs/types';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { UserWorkspaceContextProvider } from '@kit/accounts/components';
|
||||
import { AppLogo } from '@kit/shared/components/app-logo';
|
||||
import {
|
||||
pathsConfig,
|
||||
personalAccountNavigationConfig,
|
||||
} from '@kit/shared/config';
|
||||
import { Page, PageMobileNavigation, PageNavigation } from '@kit/ui/page';
|
||||
import { SidebarProvider } from '@kit/ui/shadcn-sidebar';
|
||||
|
||||
import { AppLogo } from '~/components/app-logo';
|
||||
import { personalAccountNavigationConfig } from '~/config/personal-account-navigation.config';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
// home imports
|
||||
@@ -22,6 +17,7 @@ import { HomeMenuNavigation } from '../_components/home-menu-navigation';
|
||||
import { HomeMobileNavigation } from '../_components/home-mobile-navigation';
|
||||
import { HomeSidebar } from '../_components/home-sidebar';
|
||||
import { loadUserWorkspace } from '../_lib/server/load-user-workspace';
|
||||
import { retrieveCart } from '@lib/data';
|
||||
|
||||
function UserHomeLayout({ children }: React.PropsWithChildren) {
|
||||
const state = use(getLayoutState());
|
||||
@@ -48,7 +44,7 @@ function SidebarLayout({ children }: React.PropsWithChildren) {
|
||||
</PageNavigation>
|
||||
|
||||
<PageMobileNavigation className={'flex items-center justify-between'}>
|
||||
<MobileNavigation workspace={workspace} cart={null} />
|
||||
<MobileNavigation workspace={workspace} />
|
||||
</PageMobileNavigation>
|
||||
|
||||
{children}
|
||||
@@ -70,7 +66,7 @@ function HeaderLayout({ children }: React.PropsWithChildren) {
|
||||
</PageNavigation>
|
||||
|
||||
<PageMobileNavigation className={'flex items-center justify-between'}>
|
||||
<MobileNavigation workspace={workspace} cart={cart} />
|
||||
<MobileNavigation workspace={workspace} />
|
||||
</PageMobileNavigation>
|
||||
|
||||
<SidebarProvider defaultOpen>
|
||||
@@ -88,16 +84,14 @@ function HeaderLayout({ children }: React.PropsWithChildren) {
|
||||
|
||||
function MobileNavigation({
|
||||
workspace,
|
||||
cart,
|
||||
}: {
|
||||
workspace: Awaited<ReturnType<typeof loadUserWorkspace>>;
|
||||
cart: StoreCart | null;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<AppLogo href={pathsConfig.app.home} />
|
||||
<AppLogo />
|
||||
|
||||
<HomeMobileNavigation workspace={workspace} cart={cart} />
|
||||
<HomeMobileNavigation workspace={workspace} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,8 @@ import { Scale } from 'lucide-react';
|
||||
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import { Button } from '@kit/ui/button';
|
||||
import SelectAnalysisPackages from '@kit/shared/components/select-analysis-packages';
|
||||
import SelectAnalysisPackages from '@/components/select-analysis-packages';
|
||||
import { PageBody } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
@@ -21,7 +20,7 @@ export const generateMetadata = async () => {
|
||||
};
|
||||
|
||||
async function OrderAnalysisPackagePage() {
|
||||
const { analysisPackageElements, analysisPackages, countryCode } = await loadAnalysisPackages();
|
||||
const { analysisPackages, countryCode } = await loadAnalysisPackages();
|
||||
|
||||
return (
|
||||
<PageBody>
|
||||
@@ -31,7 +30,6 @@ async function OrderAnalysisPackagePage() {
|
||||
</h3>
|
||||
<ComparePackagesModal
|
||||
analysisPackages={analysisPackages}
|
||||
analysisPackageElements={analysisPackageElements}
|
||||
triggerElement={
|
||||
<Button variant="secondary" className="gap-2">
|
||||
<Trans i18nKey={'marketing:comparePackages'} />
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
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 { loadAnalyses } from '../../_lib/server/load-analyses';
|
||||
import OrderAnalysesCards from '../../_components/order-analyses-cards';
|
||||
import { createPageViewLog, PageViewAction } from '~/lib/services/audit/pageView.service';
|
||||
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('order-analysis:title'),
|
||||
};
|
||||
};
|
||||
|
||||
async function OrderAnalysisPage() {
|
||||
const account = await loadCurrentUserAccount();
|
||||
if (!account) {
|
||||
throw new Error('Account not found');
|
||||
}
|
||||
|
||||
const { analyses, countryCode } = await loadAnalyses();
|
||||
|
||||
await createPageViewLog({
|
||||
accountId: account.id,
|
||||
action: PageViewAction.VIEW_ORDER_ANALYSIS,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'order-analysis:title'} />}
|
||||
description={<Trans i18nKey={'order-analysis:description'} />}
|
||||
/>
|
||||
<PageBody>
|
||||
<OrderAnalysesCards analyses={analyses} countryCode={countryCode} />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(OrderAnalysisPage);
|
||||
@@ -1,29 +0,0 @@
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
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';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('order-health-analysis:title'),
|
||||
};
|
||||
};
|
||||
|
||||
async function OrderHealthAnalysisPage() {
|
||||
return (
|
||||
<>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'order-health-analysis:title'} />}
|
||||
description={<Trans i18nKey={'order-health-analysis:description'} />}
|
||||
/>
|
||||
<PageBody>
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(OrderHealthAnalysisPage);
|
||||
@@ -1,18 +1,12 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { retrieveOrder } from '~/medusa/lib/data/orders';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import OrderCompleted from '@/app/home/(user)/_components/order/order-completed';
|
||||
|
||||
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 OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
type Props = {
|
||||
params: Promise<{ orderId: string }>;
|
||||
};
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
@@ -22,33 +16,13 @@ export async function generateMetadata() {
|
||||
};
|
||||
}
|
||||
|
||||
async function OrderConfirmedPage(props: {
|
||||
params: Promise<{ orderId: string }>;
|
||||
}) {
|
||||
export default async function OrderConfirmedPage(props: Props) {
|
||||
const params = await props.params;
|
||||
const order = await retrieveOrder(params.orderId).catch(() => null);
|
||||
|
||||
const order = await getOrder({ orderId: Number(params.orderId) }).catch(() => null);
|
||||
if (!order) {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
return notFound();
|
||||
}
|
||||
|
||||
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(() => null);
|
||||
if (!medusaOrder) {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
return <OrderCompleted order={order} />;
|
||||
}
|
||||
|
||||
export default withI18n(OrderConfirmedPage);
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
|
||||
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 { pathsConfig } from '@kit/shared/config';
|
||||
|
||||
import Divider from "@modules/common/components/divider"
|
||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('cart:order.title'),
|
||||
};
|
||||
}
|
||||
|
||||
async function OrderConfirmedPage(props: {
|
||||
params: Promise<{ orderId: string }>;
|
||||
}) {
|
||||
const params = await props.params;
|
||||
|
||||
const order = await getOrder({ orderId: Number(params.orderId) }).catch(() => null);
|
||||
if (!order) {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
|
||||
const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(() => null);
|
||||
if (!medusaOrder) {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageBody>
|
||||
<PageHeader title={<Trans i18nKey="cart:order.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);
|
||||
@@ -1,69 +0,0 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { listOrders } from '~/medusa/lib/data/orders';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
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 { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('orders:title'),
|
||||
};
|
||||
}
|
||||
|
||||
async function OrdersPage() {
|
||||
const medusaOrders = await listOrders();
|
||||
const analysisOrders = await getAnalysisOrders();
|
||||
const { productTypes } = await listProductTypes();
|
||||
|
||||
if (!medusaOrders || !productTypes) {
|
||||
redirect(pathsConfig.auth.signIn);
|
||||
}
|
||||
|
||||
const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages')!;
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeLayoutPageHeader
|
||||
title={<Trans i18nKey={'orders:title'} />}
|
||||
description={<Trans i18nKey={'orders:description'} />}
|
||||
/>
|
||||
<PageBody>
|
||||
{analysisOrders.map((analysisOrder) => {
|
||||
const medusaOrder = medusaOrders.find(({ id }) => id === analysisOrder.medusa_order_id);
|
||||
if (!medusaOrder) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const medusaOrderItems = medusaOrder.items || [];
|
||||
const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter((item) => item.product_type_id === analysisPackagesType?.id);
|
||||
const medusaOrderItemsOther = medusaOrderItems.filter((item) => item.product_type_id !== analysisPackagesType?.id);
|
||||
|
||||
return (
|
||||
<React.Fragment key={analysisOrder.id}>
|
||||
<Divider className="my-6" />
|
||||
<OrderBlock
|
||||
analysisOrder={analysisOrder}
|
||||
itemsAnalysisPackage={medusaOrderItemsAnalysisPackages}
|
||||
itemsOther={medusaOrderItemsOther}
|
||||
/>
|
||||
</React.Fragment>
|
||||
)
|
||||
})}
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default withI18n(OrdersPage);
|
||||
@@ -1,17 +1,12 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { toTitleCase } from '@/lib/utils';
|
||||
import { createAccountsApi } from '@/packages/features/accounts/src/server/api';
|
||||
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { toTitleCase } from '@/lib/utils';
|
||||
|
||||
import Dashboard from '../_components/dashboard';
|
||||
import DashboardCards from '../_components/dashboard-cards';
|
||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||
|
||||
export const generateMetadata = async () => {
|
||||
@@ -24,30 +19,25 @@ export const generateMetadata = async () => {
|
||||
};
|
||||
|
||||
async function UserHomePage() {
|
||||
const client = getSupabaseServerClient();
|
||||
|
||||
const account = await loadCurrentUserAccount();
|
||||
const api = await createAccountsApi(client);
|
||||
const bmiThresholds = await api.fetchBmiThresholds();
|
||||
|
||||
if (!account) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardCards />
|
||||
<PageHeader
|
||||
title={
|
||||
<>
|
||||
<Trans i18nKey={'common:welcome'} />
|
||||
{account.name ? `, ${toTitleCase(account.name)}` : ''}
|
||||
</>
|
||||
<PageHeader title={
|
||||
<>
|
||||
<Trans i18nKey={'common:welcome'} />
|
||||
{account.name ? `, ${toTitleCase(account.name)}` : ''}
|
||||
</>
|
||||
}
|
||||
description={
|
||||
<Trans i18nKey={'dashboard:recentlyCheckedDescription'} />
|
||||
}
|
||||
description={<Trans i18nKey={'dashboard:recentlyCheckedDescription'} />}
|
||||
/>
|
||||
<PageBody>
|
||||
<Dashboard account={account} bmiThresholds={bmiThresholds} />
|
||||
<Dashboard />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { toast } from 'sonner';
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { StoreCart, StoreCartLineItem } from "@medusajs/types"
|
||||
import { Form } from "@kit/ui/form";
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@kit/ui/select';
|
||||
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';
|
||||
|
||||
import partnerLocations from './partner-locations.json';
|
||||
|
||||
const AnalysisLocationSchema = z.object({
|
||||
locationId: z.string().min(1),
|
||||
});
|
||||
|
||||
export default function AnalysisLocation({ cart, synlabAnalyses }: { cart: StoreCart, synlabAnalyses: StoreCartLineItem[] }) {
|
||||
const { t } = useTranslation('cart');
|
||||
|
||||
const form = useForm<z.infer<typeof AnalysisLocationSchema>>({
|
||||
defaultValues: {
|
||||
locationId: cart.metadata?.partner_location_id as string ?? '',
|
||||
},
|
||||
resolver: zodResolver(AnalysisLocationSchema),
|
||||
});
|
||||
|
||||
const getLocation = (locationId: string) => partnerLocations.find(({ name }) => name === locationId);
|
||||
|
||||
const selectedLocation = getLocation(form.watch('locationId'));
|
||||
|
||||
const onSubmit = async ({ locationId }: z.infer<typeof AnalysisLocationSchema>) => {
|
||||
const promise = updateCartPartnerLocation({
|
||||
cartId: cart.id,
|
||||
lineIds: synlabAnalyses.map(({ id }) => id),
|
||||
partnerLocationId: locationId,
|
||||
partnerLocationName: getLocation(locationId)?.name ?? '',
|
||||
});
|
||||
|
||||
toast.promise(promise, {
|
||||
success: t(`cart:items.analysisLocation.success`),
|
||||
loading: t(`cart:items.analysisLocation.loading`),
|
||||
error: t(`cart:items.analysisLocation.error`),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full bg-white flex flex-col txt-medium gap-y-2">
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit((data) => onSubmit(data))}
|
||||
className="w-full mb-2 flex gap-x-2"
|
||||
>
|
||||
<Select
|
||||
value={form.watch('locationId')}
|
||||
onValueChange={(value) => {
|
||||
form.setValue('locationId', value, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
|
||||
return onSubmit(form.getValues());
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('cart:locations.locationSelect')} />
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
{Object.entries(partnerLocations
|
||||
.reduce((acc, curr) => ({
|
||||
...acc,
|
||||
[curr.city]: [...((acc[curr.city] as typeof partnerLocations) ?? []), curr],
|
||||
}), {} as Record<string, typeof partnerLocations>))
|
||||
.map(([city, locations]) => (
|
||||
<SelectGroup key={city}>
|
||||
<SelectLabel>{city}</SelectLabel>
|
||||
{locations.map((location) => (
|
||||
<SelectItem key={location.name} value={location.name}>{location.name}</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
{selectedLocation && (
|
||||
<div className="flex flex-col gap-y-2 mb-4">
|
||||
<p className="text-sm">
|
||||
{selectedLocation.address}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{selectedLocation.hours}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<Trans i18nKey={'cart:locations.description'} />
|
||||
</p>
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,8 +5,8 @@ import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { deleteLineItem } from "@lib/data/cart";
|
||||
import { Spinner } from "@medusajs/icons";
|
||||
import { handleDeleteCartItem } from "~/lib/services/medusaCart.service";
|
||||
|
||||
const CartItemDelete = ({
|
||||
id,
|
||||
@@ -22,7 +22,7 @@ const CartItemDelete = ({
|
||||
setIsDeleting(true);
|
||||
|
||||
const promise = async () => {
|
||||
await handleDeleteCartItem({ lineId: id });
|
||||
await deleteLineItem(id);
|
||||
};
|
||||
|
||||
toast.promise(promise, {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user