Merge branch 'develop' into MED-102
This commit is contained in:
@@ -34,6 +34,7 @@ MEDIPOST_PASSWORD=SRB48HZMV
|
|||||||
MEDIPOST_RECIPIENT=trvurgtst
|
MEDIPOST_RECIPIENT=trvurgtst
|
||||||
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
||||||
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
||||||
|
MEDIPOST_ENABLE_DELETE_RESPONSE_PRIVATE_MESSAGE_ON_READ=false
|
||||||
|
|
||||||
#MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
#MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
||||||
#MEDIPOST_USER=medreport
|
#MEDIPOST_USER=medreport
|
||||||
@@ -43,6 +44,7 @@ MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
|||||||
#MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=false
|
#MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=false
|
||||||
|
|
||||||
# MEDUSA
|
# MEDUSA
|
||||||
|
COMPANY_BENEFITS_PAYMENT_SECRET_KEY=NzcwMzE2NmEtOThiMS0xMWYwLWI4NjYtMDMwZDQzMjFhMjExCg==
|
||||||
MEDUSA_BACKEND_URL=http://localhost:9000
|
MEDUSA_BACKEND_URL=http://localhost:9000
|
||||||
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
MEDUSA_BACKEND_PUBLIC_URL=http://localhost:9000
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,9 @@ function getSpokenLanguages(spokenLanguages?: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default async function syncConnectedOnline() {
|
export default async function syncConnectedOnline() {
|
||||||
const isProd = process.env.NODE_ENV === 'production';
|
const isProd = !['test', 'localhost'].some((pathString) =>
|
||||||
|
process.env.NEXT_PUBLIC_SITE_URL?.includes(pathString),
|
||||||
|
);
|
||||||
|
|
||||||
const baseUrl = process.env.CONNECTED_ONLINE_URL;
|
const baseUrl = process.env.CONNECTED_ONLINE_URL;
|
||||||
|
|
||||||
@@ -84,34 +86,20 @@ export default async function syncConnectedOnline() {
|
|||||||
let serviceProviders;
|
let serviceProviders;
|
||||||
let jobTitleTranslations;
|
let jobTitleTranslations;
|
||||||
// Filter out "Dentas Demo OÜ" in prod or only sync "Dentas Demo OÜ" in any other environment
|
// Filter out "Dentas Demo OÜ" in prod or only sync "Dentas Demo OÜ" in any other environment
|
||||||
const isDemoClinic = (clinicId: number) => clinicId === 2;
|
const isDemoClinic = (clinicId: number) =>
|
||||||
if (isProd) {
|
isProd ? clinicId !== 2 : clinicId === 2;
|
||||||
clinics = responseData.Data.T_Lic.filter(({ ID }) => !isDemoClinic(ID));
|
clinics = responseData.Data.T_Lic.filter(({ ID }) => isDemoClinic(ID));
|
||||||
services = responseData.Data.T_Service.filter(
|
services = responseData.Data.T_Service.filter(({ ClinicID }) =>
|
||||||
({ ClinicID }) => !isDemoClinic(ClinicID),
|
isDemoClinic(ClinicID),
|
||||||
);
|
);
|
||||||
serviceProviders = responseData.Data.T_Doctor.filter(
|
serviceProviders = responseData.Data.T_Doctor.filter(({ ClinicID }) =>
|
||||||
({ ClinicID }) => !isDemoClinic(ClinicID),
|
isDemoClinic(ClinicID),
|
||||||
);
|
);
|
||||||
jobTitleTranslations = createTranslationMap(
|
jobTitleTranslations = createTranslationMap(
|
||||||
responseData.Data.P_JobTitleTranslations.filter(
|
responseData.Data.P_JobTitleTranslations.filter(({ ClinicID }) =>
|
||||||
({ ClinicID }) => !isDemoClinic(ClinicID),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
clinics = responseData.Data.T_Lic.filter(({ ID }) => isDemoClinic(ID));
|
|
||||||
services = responseData.Data.T_Service.filter(({ ClinicID }) =>
|
|
||||||
isDemoClinic(ClinicID),
|
isDemoClinic(ClinicID),
|
||||||
);
|
),
|
||||||
serviceProviders = responseData.Data.T_Doctor.filter(({ ClinicID }) =>
|
);
|
||||||
isDemoClinic(ClinicID),
|
|
||||||
);
|
|
||||||
jobTitleTranslations = createTranslationMap(
|
|
||||||
responseData.Data.P_JobTitleTranslations.filter(({ ClinicID }) =>
|
|
||||||
isDemoClinic(ClinicID),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const mappedClinics = clinics.map((clinic) => {
|
const mappedClinics = clinics.map((clinic) => {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ export const onUpdateAccount = enhanceAction(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await api.updateAccount(params);
|
await api.updateAccount(params);
|
||||||
console.log('SUCCESS', pathsConfig.auth.updateAccountSuccess);
|
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
if (err instanceof Error) {
|
if (err instanceof Error) {
|
||||||
console.warn('On update account error: ' + err.message);
|
console.warn('On update account error: ' + err.message);
|
||||||
|
|||||||
@@ -2,107 +2,13 @@
|
|||||||
|
|
||||||
import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types';
|
import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types';
|
||||||
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
|
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
|
||||||
import { placeOrder, retrieveCart } from '@lib/data/cart';
|
import { retrieveCart } from '@lib/data/cart';
|
||||||
import { listProductTypes } from '@lib/data/products';
|
|
||||||
import type { StoreOrder } from '@medusajs/types';
|
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
import { AccountWithParams } from '@kit/accounts/types/accounts';
|
import { handlePlaceOrder } from '../../../_lib/server/cart-actions';
|
||||||
import { createNotificationsApi } from '@kit/notifications/api';
|
|
||||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
|
||||||
import { bookAppointment } from '~/lib/services/connected-online.service';
|
|
||||||
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
|
||||||
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
|
||||||
import {
|
|
||||||
createAnalysisOrder,
|
|
||||||
getAnalysisOrder,
|
|
||||||
} from '~/lib/services/order.service';
|
|
||||||
import { getOrderedTtoServices } from '~/lib/services/reservation.service';
|
|
||||||
import { FailureReason } from '~/lib/types/connected-online';
|
|
||||||
|
|
||||||
const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages';
|
|
||||||
const ANALYSIS_TYPE_HANDLE = 'synlab-analysis';
|
|
||||||
const MONTONIO_PAID_STATUS = 'PAID';
|
const MONTONIO_PAID_STATUS = 'PAID';
|
||||||
|
|
||||||
const env = () =>
|
|
||||||
z
|
|
||||||
.object({
|
|
||||||
emailSender: z
|
|
||||||
.string({
|
|
||||||
error: 'EMAIL_SENDER is required',
|
|
||||||
})
|
|
||||||
.min(1),
|
|
||||||
siteUrl: z
|
|
||||||
.string({
|
|
||||||
error: 'NEXT_PUBLIC_SITE_URL is required',
|
|
||||||
})
|
|
||||||
.min(1),
|
|
||||||
isEnabledDispatchOnMontonioCallback: z.boolean({
|
|
||||||
error: 'MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK is required',
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.parse({
|
|
||||||
emailSender: process.env.EMAIL_SENDER,
|
|
||||||
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
|
|
||||||
isEnabledDispatchOnMontonioCallback:
|
|
||||||
process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true',
|
|
||||||
});
|
|
||||||
|
|
||||||
const sendEmail = async ({
|
|
||||||
account,
|
|
||||||
email,
|
|
||||||
analysisPackageName,
|
|
||||||
partnerLocationName,
|
|
||||||
language,
|
|
||||||
}: {
|
|
||||||
account: Pick<AccountWithParams, 'name' | 'id'>;
|
|
||||||
email: string;
|
|
||||||
analysisPackageName: 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: account.name,
|
|
||||||
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,
|
|
||||||
});
|
|
||||||
await createNotificationsApi(client).createNotification({
|
|
||||||
account_id: account.id,
|
|
||||||
body: html,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Failed to send email, message=${error}`);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
async function decodeOrderToken(orderToken: string) {
|
async function decodeOrderToken(orderToken: string) {
|
||||||
const secretKey = process.env.MONTONIO_SECRET_KEY as string;
|
const secretKey = process.env.MONTONIO_SECRET_KEY as string;
|
||||||
|
|
||||||
@@ -129,71 +35,6 @@ async function getCartByOrderToken(decoded: MontonioOrderToken) {
|
|||||||
return cart;
|
return cart;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getOrderResultParameters(medusaOrder: StoreOrder) {
|
|
||||||
const { productTypes } = await listProductTypes();
|
|
||||||
const analysisPackagesType = productTypes.find(
|
|
||||||
({ metadata }) => metadata?.handle === ANALYSIS_PACKAGES_TYPE_HANDLE,
|
|
||||||
);
|
|
||||||
const analysisType = productTypes.find(
|
|
||||||
({ metadata }) => metadata?.handle === ANALYSIS_TYPE_HANDLE,
|
|
||||||
);
|
|
||||||
|
|
||||||
const analysisPackageOrderItem = medusaOrder.items?.find(
|
|
||||||
({ product_type_id }) => product_type_id === analysisPackagesType?.id,
|
|
||||||
);
|
|
||||||
const analysisItems = medusaOrder.items?.filter(
|
|
||||||
({ product_type_id }) => product_type_id === analysisType?.id,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
medusaOrderId: medusaOrder.id,
|
|
||||||
email: medusaOrder.email,
|
|
||||||
analysisPackageOrder: analysisPackageOrderItem
|
|
||||||
? {
|
|
||||||
partnerLocationName:
|
|
||||||
(analysisPackageOrderItem?.metadata
|
|
||||||
?.partner_location_name as string) ?? '',
|
|
||||||
analysisPackageName: analysisPackageOrderItem?.title ?? '',
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
analysisItemsOrder:
|
|
||||||
Array.isArray(analysisItems) && analysisItems.length > 0
|
|
||||||
? analysisItems.map(({ product }) => ({
|
|
||||||
analysisName: product?.title ?? '',
|
|
||||||
analysisId: (product?.metadata?.analysisIdOriginal as string) ?? '',
|
|
||||||
}))
|
|
||||||
: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function sendAnalysisPackageOrderEmail({
|
|
||||||
account,
|
|
||||||
email,
|
|
||||||
analysisPackageOrder,
|
|
||||||
}: {
|
|
||||||
account: AccountWithParams;
|
|
||||||
email: string;
|
|
||||||
analysisPackageOrder: {
|
|
||||||
partnerLocationName: string;
|
|
||||||
analysisPackageName: string;
|
|
||||||
};
|
|
||||||
}) {
|
|
||||||
const { language } = await createI18nServerInstance();
|
|
||||||
const { analysisPackageName, partnerLocationName } = analysisPackageOrder;
|
|
||||||
try {
|
|
||||||
await sendEmail({
|
|
||||||
account: { id: account.id, name: account.name },
|
|
||||||
email,
|
|
||||||
analysisPackageName,
|
|
||||||
partnerLocationName,
|
|
||||||
language,
|
|
||||||
});
|
|
||||||
console.info(`Successfully sent analysis package order email to ${email}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to send email', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function processMontonioCallback(orderToken: string) {
|
export async function processMontonioCallback(orderToken: string) {
|
||||||
const { account } = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
@@ -203,99 +44,8 @@ export async function processMontonioCallback(orderToken: string) {
|
|||||||
try {
|
try {
|
||||||
const decoded = await decodeOrderToken(orderToken);
|
const decoded = await decodeOrderToken(orderToken);
|
||||||
const cart = await getCartByOrderToken(decoded);
|
const cart = await getCartByOrderToken(decoded);
|
||||||
|
const result = await handlePlaceOrder({ cart });
|
||||||
const medusaOrder = await placeOrder(cart.id, {
|
return result;
|
||||||
revalidateCacheTags: false,
|
|
||||||
});
|
|
||||||
const orderedAnalysisElements = await getOrderedAnalysisIds({
|
|
||||||
medusaOrder,
|
|
||||||
});
|
|
||||||
|
|
||||||
const orderContainsSynlabItems = !!orderedAnalysisElements?.length;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const existingAnalysisOrder = await getAnalysisOrder({
|
|
||||||
medusaOrderId: medusaOrder.id,
|
|
||||||
});
|
|
||||||
console.info(
|
|
||||||
`Analysis order already exists for medusaOrderId=${medusaOrder.id}, orderId=${existingAnalysisOrder.id}`,
|
|
||||||
);
|
|
||||||
return { success: true, orderId: existingAnalysisOrder.id };
|
|
||||||
} catch {
|
|
||||||
// ignored
|
|
||||||
}
|
|
||||||
|
|
||||||
let orderId;
|
|
||||||
if (orderContainsSynlabItems) {
|
|
||||||
orderId = await createAnalysisOrder({
|
|
||||||
medusaOrder,
|
|
||||||
orderedAnalysisElements,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const orderResult = await getOrderResultParameters(medusaOrder);
|
|
||||||
|
|
||||||
const { medusaOrderId, email, analysisPackageOrder, analysisItemsOrder } =
|
|
||||||
orderResult;
|
|
||||||
|
|
||||||
const orderedTtoServices = await getOrderedTtoServices({ medusaOrder });
|
|
||||||
let bookServiceResults: {
|
|
||||||
success: boolean;
|
|
||||||
reason?: FailureReason;
|
|
||||||
serviceId?: number;
|
|
||||||
}[] = [];
|
|
||||||
if (orderedTtoServices?.length) {
|
|
||||||
const bookingPromises = orderedTtoServices.map((service) =>
|
|
||||||
bookAppointment(
|
|
||||||
service.service_id,
|
|
||||||
service.clinic_id,
|
|
||||||
service.service_user_id,
|
|
||||||
service.sync_user_id,
|
|
||||||
service.start_time,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
bookServiceResults = await Promise.all(bookingPromises);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (email) {
|
|
||||||
if (analysisPackageOrder) {
|
|
||||||
await sendAnalysisPackageOrderEmail({
|
|
||||||
account,
|
|
||||||
email,
|
|
||||||
analysisPackageOrder,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
console.info(`Order has no analysis package, skipping email.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (analysisItemsOrder) {
|
|
||||||
// @TODO send email for separate analyses
|
|
||||||
console.warn(
|
|
||||||
`Order has analysis items, but no email template exists yet`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
console.info(`Order has no analysis items, skipping email.`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.error('Missing email to send order result email', orderResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (env().isEnabledDispatchOnMontonioCallback && orderContainsSynlabItems) {
|
|
||||||
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (bookServiceResults.some(({ success }) => success === false)) {
|
|
||||||
const failedServiceBookings = bookServiceResults.filter(
|
|
||||||
({ success }) => success === false,
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
failedServiceBookings,
|
|
||||||
orderId,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return { success: true, orderId };
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to place order', error);
|
console.error('Failed to place order', error);
|
||||||
throw new Error(`Failed to place order, message=${error}`);
|
throw new Error(`Failed to place order, message=${error}`);
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { notFound } from 'next/navigation';
|
|
||||||
|
|
||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||||
import { retrieveCart } from '@lib/data/cart';
|
import { retrieveCart } from '@lib/data/cart';
|
||||||
import { listProductTypes } from '@lib/data/products';
|
import { listProductTypes } from '@lib/data/products';
|
||||||
|
|
||||||
|
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
@@ -14,6 +13,7 @@ import { findProductTypeIdByHandle } from '~/lib/utils';
|
|||||||
import Cart from '../../_components/cart';
|
import Cart from '../../_components/cart';
|
||||||
import CartTimer from '../../_components/cart/cart-timer';
|
import CartTimer from '../../_components/cart/cart-timer';
|
||||||
import { EnrichedCartItem } from '../../_components/cart/types';
|
import { EnrichedCartItem } from '../../_components/cart/types';
|
||||||
|
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
@@ -24,12 +24,19 @@ export async function generateMetadata() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function CartPage() {
|
async function CartPage() {
|
||||||
const cart = await retrieveCart().catch((error) => {
|
const [cart, { productTypes }, { account }] = await Promise.all([
|
||||||
console.error('Failed to retrieve cart', error);
|
retrieveCart(),
|
||||||
return notFound();
|
listProductTypes(),
|
||||||
});
|
loadCurrentUserAccount(),
|
||||||
|
]);
|
||||||
|
|
||||||
const { productTypes } = await listProductTypes();
|
if (!account) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const balanceSummary = await new AccountBalanceService().getBalanceSummary(
|
||||||
|
account.id,
|
||||||
|
);
|
||||||
|
|
||||||
const synlabAnalysisTypeId = findProductTypeIdByHandle(
|
const synlabAnalysisTypeId = findProductTypeIdByHandle(
|
||||||
productTypes,
|
productTypes,
|
||||||
@@ -70,9 +77,11 @@ async function CartPage() {
|
|||||||
{isTimerShown && <CartTimer cartItem={item} />}
|
{isTimerShown && <CartTimer cartItem={item} />}
|
||||||
</PageHeader>
|
</PageHeader>
|
||||||
<Cart
|
<Cart
|
||||||
|
accountId={account.id}
|
||||||
cart={cart}
|
cart={cart}
|
||||||
synlabAnalyses={synlabAnalyses}
|
synlabAnalyses={synlabAnalyses}
|
||||||
ttoServiceItems={ttoServiceItems}
|
ttoServiceItems={ttoServiceItems}
|
||||||
|
balanceSummary={balanceSummary}
|
||||||
/>
|
/>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||||
|
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||||
|
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||||
|
import { retrieveOrder } from '@lib/data/orders';
|
||||||
|
import { StoreOrder } from '@medusajs/types';
|
||||||
|
import Divider from '@modules/common/components/divider';
|
||||||
|
|
||||||
|
import { GlobalLoader } from '@kit/ui/makerkit/global-loader';
|
||||||
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { AnalysisOrder } from '~/lib/types/analysis-order';
|
||||||
|
|
||||||
|
function OrderConfirmedLoadingWrapper({
|
||||||
|
medusaOrder: initialMedusaOrder,
|
||||||
|
order,
|
||||||
|
}: {
|
||||||
|
medusaOrder: StoreOrder;
|
||||||
|
order: AnalysisOrder;
|
||||||
|
}) {
|
||||||
|
const [medusaOrder, setMedusaOrder] =
|
||||||
|
useState<StoreOrder>(initialMedusaOrder);
|
||||||
|
const fetchingRef = useRef(false);
|
||||||
|
|
||||||
|
const paymentStatus = medusaOrder.payment_status;
|
||||||
|
const medusaOrderId = order.medusa_order_id;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (paymentStatus === 'captured') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const interval = setInterval(async () => {
|
||||||
|
if (fetchingRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchingRef.current = true;
|
||||||
|
const medusaOrder = await retrieveOrder(medusaOrderId, false);
|
||||||
|
fetchingRef.current = false;
|
||||||
|
|
||||||
|
setMedusaOrder(medusaOrder);
|
||||||
|
}, 2_000);
|
||||||
|
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, [paymentStatus, medusaOrderId]);
|
||||||
|
|
||||||
|
const isPaid = paymentStatus === 'captured';
|
||||||
|
|
||||||
|
if (!isPaid) {
|
||||||
|
return (
|
||||||
|
<PageBody>
|
||||||
|
<div className="flex h-full flex-col items-center justify-start pt-[10vh]">
|
||||||
|
<div>
|
||||||
|
<GlobalLoader />
|
||||||
|
</div>
|
||||||
|
<h4 className="text-center">
|
||||||
|
<Trans i18nKey="cart:orderConfirmed.paymentConfirmationLoading" />
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageBody>
|
||||||
|
<PageHeader title={<Trans i18nKey="cart:orderConfirmed.title" />} />
|
||||||
|
<Divider />
|
||||||
|
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 gap-y-6 lg:px-4">
|
||||||
|
<OrderDetails order={order} />
|
||||||
|
<Divider />
|
||||||
|
<OrderItems medusaOrder={medusaOrder} />
|
||||||
|
<CartTotals medusaOrder={medusaOrder} />
|
||||||
|
</div>
|
||||||
|
</PageBody>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default OrderConfirmedLoadingWrapper;
|
||||||
@@ -1,19 +1,15 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
|
||||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
|
||||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
|
||||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
import { retrieveOrder } from '@lib/data/orders';
|
import { retrieveOrder } from '@lib/data/orders';
|
||||||
import Divider from '@modules/common/components/divider';
|
|
||||||
|
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
import { getAnalysisOrder } from '~/lib/services/order.service';
|
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||||
|
|
||||||
|
import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
@@ -42,16 +38,7 @@ async function OrderConfirmedPage(props: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageBody>
|
<OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />
|
||||||
<PageHeader title={<Trans i18nKey="cart:orderConfirmed.title" />} />
|
|
||||||
<Divider />
|
|
||||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 gap-y-6 lg:px-4">
|
|
||||||
<OrderDetails order={order} />
|
|
||||||
<Divider />
|
|
||||||
<OrderItems medusaOrder={medusaOrder} />
|
|
||||||
<CartTotals medusaOrder={medusaOrder} />
|
|
||||||
</div>
|
|
||||||
</PageBody>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import { listOrders } from '~/medusa/lib/data/orders';
|
|||||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||||
import OrderBlock from '../../_components/orders/order-block';
|
import OrderBlock from '../../_components/orders/order-block';
|
||||||
|
|
||||||
|
const ORDERS_LIMIT = 50;
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
|
|
||||||
@@ -27,10 +29,13 @@ export async function generateMetadata() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function OrdersPage() {
|
async function OrdersPage() {
|
||||||
const medusaOrders = await listOrders();
|
const [medusaOrders, analysisOrders, ttoOrders, { productTypes }] =
|
||||||
const analysisOrders = await getAnalysisOrders();
|
await Promise.all([
|
||||||
const ttoOrders = await getTtoOrders();
|
listOrders(ORDERS_LIMIT),
|
||||||
const { productTypes } = await listProductTypes();
|
getAnalysisOrders(),
|
||||||
|
getTtoOrders(),
|
||||||
|
listProductTypes(),
|
||||||
|
]);
|
||||||
|
|
||||||
if (!medusaOrders || !productTypes || !ttoOrders) {
|
if (!medusaOrders || !productTypes || !ttoOrders) {
|
||||||
redirect(pathsConfig.auth.signIn);
|
redirect(pathsConfig.auth.signIn);
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import Dashboard from '../_components/dashboard';
|
|||||||
import DashboardCards from '../_components/dashboard-cards';
|
import DashboardCards from '../_components/dashboard-cards';
|
||||||
import Recommendations from '../_components/recommendations';
|
import Recommendations from '../_components/recommendations';
|
||||||
import RecommendationsSkeleton from '../_components/recommendations-skeleton';
|
import RecommendationsSkeleton from '../_components/recommendations-skeleton';
|
||||||
|
import { isValidOpenAiEnv } from '../_lib/server/is-valid-open-ai-env';
|
||||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||||
|
|
||||||
export const generateMetadata = async () => {
|
export const generateMetadata = async () => {
|
||||||
@@ -52,17 +53,16 @@ async function UserHomePage() {
|
|||||||
/>
|
/>
|
||||||
<PageBody>
|
<PageBody>
|
||||||
<Dashboard account={account} bmiThresholds={bmiThresholds} />
|
<Dashboard account={account} bmiThresholds={bmiThresholds} />
|
||||||
{process.env.OPENAI_API_KEY &&
|
{(await isValidOpenAiEnv()) && (
|
||||||
process.env.PROMPT_ID_ANALYSIS_RECOMMENDATIONS && (
|
<>
|
||||||
<>
|
<h4>
|
||||||
<h4>
|
<Trans i18nKey="dashboard:recommendations.title" />
|
||||||
<Trans i18nKey="dashboard:recommendations.title" />
|
</h4>
|
||||||
</h4>
|
<Suspense fallback={<RecommendationsSkeleton />}>
|
||||||
<Suspense fallback={<RecommendationsSkeleton />}>
|
<Recommendations account={account} />
|
||||||
<Recommendations account={account} />
|
</Suspense>
|
||||||
</Suspense>
|
</>
|
||||||
</>
|
)}
|
||||||
)}
|
|
||||||
</PageBody>
|
</PageBody>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -32,7 +32,16 @@ const BookingContainer = ({
|
|||||||
<BookingProvider category={{ products }} service={cartItem?.product}>
|
<BookingProvider category={{ products }} service={cartItem?.product}>
|
||||||
<div className="xs:flex-row flex max-h-full flex-col gap-6">
|
<div className="xs:flex-row flex max-h-full flex-col gap-6">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<ServiceSelector products={products} />
|
<ServiceSelector
|
||||||
|
products={products.filter((product) => {
|
||||||
|
if (product.metadata?.serviceIds) {
|
||||||
|
return Array.isArray(
|
||||||
|
JSON.parse(product.metadata.serviceIds as string),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})}
|
||||||
|
/>
|
||||||
<BookingCalendar />
|
<BookingCalendar />
|
||||||
<LocationSelector />
|
<LocationSelector />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
113
app/home/(user)/_components/booking/booking-pagination.tsx
Normal file
113
app/home/(user)/_components/booking/booking-pagination.tsx
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { Trans } from '@kit/ui/makerkit/trans';
|
||||||
|
import { cn } from '@kit/ui/shadcn';
|
||||||
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
|
|
||||||
|
const BookingPagination = ({
|
||||||
|
totalPages,
|
||||||
|
setCurrentPage,
|
||||||
|
currentPage,
|
||||||
|
}: {
|
||||||
|
totalPages: number;
|
||||||
|
setCurrentPage: (page: number) => void;
|
||||||
|
currentPage: number;
|
||||||
|
}) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const generatePageNumbers = () => {
|
||||||
|
const pages = [];
|
||||||
|
const maxVisiblePages = 5;
|
||||||
|
|
||||||
|
if (totalPages <= maxVisiblePages) {
|
||||||
|
for (let i = 1; i <= totalPages; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (currentPage <= 3) {
|
||||||
|
for (let i = 1; i <= 4; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
pages.push('...');
|
||||||
|
pages.push(totalPages);
|
||||||
|
} else if (currentPage >= totalPages - 2) {
|
||||||
|
pages.push(1);
|
||||||
|
pages.push('...');
|
||||||
|
for (let i = totalPages - 3; i <= totalPages; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
pages.push(1);
|
||||||
|
pages.push('...');
|
||||||
|
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
pages.push('...');
|
||||||
|
pages.push(totalPages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pages;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (totalPages === 0) {
|
||||||
|
return (
|
||||||
|
<div className="wrap text-muted-foreground flex size-full content-center-safe justify-center-safe">
|
||||||
|
<p>{t('booking:noResults')}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
totalPages > 1 && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="text-muted-foreground text-sm">
|
||||||
|
{t('common:pageOfPages', {
|
||||||
|
page: currentPage,
|
||||||
|
total: totalPages,
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage(currentPage - 1)}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
>
|
||||||
|
<Trans i18nKey="common:previous" defaultValue="Previous" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{generatePageNumbers().map((page, index) => (
|
||||||
|
<Button
|
||||||
|
key={index}
|
||||||
|
variant={page === currentPage ? 'default' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => typeof page === 'number' && setCurrentPage(page)}
|
||||||
|
disabled={page === '...'}
|
||||||
|
className={cn(
|
||||||
|
'min-w-[2rem]',
|
||||||
|
page === '...' && 'cursor-default hover:bg-transparent',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{page}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage(currentPage + 1)}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
>
|
||||||
|
<Trans i18nKey="common:next" defaultValue="Next" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default BookingPagination;
|
||||||
@@ -45,7 +45,6 @@ export const BookingProvider: React.FC<{
|
|||||||
const updateTimeSlots = async (serviceIds: number[]) => {
|
const updateTimeSlots = async (serviceIds: number[]) => {
|
||||||
setIsLoadingTimeSlots(true);
|
setIsLoadingTimeSlots(true);
|
||||||
try {
|
try {
|
||||||
console.log('serviceIds', serviceIds, selectedLocationId);
|
|
||||||
const response = await getAvailableTimeSlotsForDisplay(
|
const response = await getAvailableTimeSlotsForDisplay(
|
||||||
serviceIds,
|
serviceIds,
|
||||||
selectedLocationId,
|
selectedLocationId,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { pathsConfig } from '@kit/shared/config';
|
|||||||
import { formatDateAndTime } from '@kit/shared/utils';
|
import { formatDateAndTime } from '@kit/shared/utils';
|
||||||
import { Button } from '@kit/ui/shadcn/button';
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
import { Card } from '@kit/ui/shadcn/card';
|
import { Card } from '@kit/ui/shadcn/card';
|
||||||
|
import { Skeleton } from '@kit/ui/shadcn/skeleton';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { toast } from '@kit/ui/sonner';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { cn } from '@kit/ui/utils';
|
import { cn } from '@kit/ui/utils';
|
||||||
@@ -19,6 +20,7 @@ import { updateReservationTime } from '~/lib/services/reservation.service';
|
|||||||
|
|
||||||
import { createInitialReservationAction } from '../../_lib/server/actions';
|
import { createInitialReservationAction } from '../../_lib/server/actions';
|
||||||
import { EnrichedCartItem } from '../cart/types';
|
import { EnrichedCartItem } from '../cart/types';
|
||||||
|
import BookingPagination from './booking-pagination';
|
||||||
import { ServiceProvider, TimeSlot } from './booking.context';
|
import { ServiceProvider, TimeSlot } from './booking.context';
|
||||||
import { useBooking } from './booking.provider';
|
import { useBooking } from './booking.provider';
|
||||||
|
|
||||||
@@ -68,57 +70,16 @@ const TimeSlots = ({
|
|||||||
}) ?? [],
|
}) ?? [],
|
||||||
'StartTime',
|
'StartTime',
|
||||||
'asc',
|
'asc',
|
||||||
),
|
).filter(({ StartTime }) => isSameDay(StartTime, selectedDate)),
|
||||||
[booking.timeSlots, selectedDate],
|
[booking.timeSlots, selectedDate],
|
||||||
);
|
);
|
||||||
|
|
||||||
const totalPages = Math.ceil(filteredBookings.length / PAGE_SIZE);
|
|
||||||
|
|
||||||
const paginatedBookings = useMemo(() => {
|
const paginatedBookings = useMemo(() => {
|
||||||
const startIndex = (currentPage - 1) * PAGE_SIZE;
|
const startIndex = (currentPage - 1) * PAGE_SIZE;
|
||||||
const endIndex = startIndex + PAGE_SIZE;
|
const endIndex = startIndex + PAGE_SIZE;
|
||||||
return filteredBookings.slice(startIndex, endIndex);
|
return filteredBookings.slice(startIndex, endIndex);
|
||||||
}, [filteredBookings, currentPage, PAGE_SIZE]);
|
}, [filteredBookings, currentPage, PAGE_SIZE]);
|
||||||
|
|
||||||
const handlePageChange = (page: number) => {
|
|
||||||
setCurrentPage(page);
|
|
||||||
};
|
|
||||||
|
|
||||||
const generatePageNumbers = () => {
|
|
||||||
const pages = [];
|
|
||||||
const maxVisiblePages = 5;
|
|
||||||
|
|
||||||
if (totalPages <= maxVisiblePages) {
|
|
||||||
for (let i = 1; i <= totalPages; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (currentPage <= 3) {
|
|
||||||
for (let i = 1; i <= 4; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
pages.push('...');
|
|
||||||
pages.push(totalPages);
|
|
||||||
} else if (currentPage >= totalPages - 2) {
|
|
||||||
pages.push(1);
|
|
||||||
pages.push('...');
|
|
||||||
for (let i = totalPages - 3; i <= totalPages; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
pages.push(1);
|
|
||||||
pages.push('...');
|
|
||||||
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
pages.push('...');
|
|
||||||
pages.push(totalPages);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return pages;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!booking?.timeSlots?.length) {
|
if (!booking?.timeSlots?.length) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -143,12 +104,17 @@ const TimeSlots = ({
|
|||||||
timeSlot.StartTime,
|
timeSlot.StartTime,
|
||||||
booking.selectedLocationId ? booking.selectedLocationId : null,
|
booking.selectedLocationId ? booking.selectedLocationId : null,
|
||||||
comments,
|
comments,
|
||||||
).then(() => {
|
)
|
||||||
if (onComplete) {
|
.then(() => {
|
||||||
onComplete();
|
if (onComplete) {
|
||||||
}
|
onComplete();
|
||||||
router.push(pathsConfig.app.cart);
|
}
|
||||||
});
|
router.push(pathsConfig.app.cart);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Booking error: ', error);
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
|
||||||
toast.promise(() => bookTimePromise, {
|
toast.promise(() => bookTimePromise, {
|
||||||
success: <Trans i18nKey={'booking:bookTimeSuccess'} />,
|
success: <Trans i18nKey={'booking:bookTimeSuccess'} />,
|
||||||
@@ -203,10 +169,13 @@ const TimeSlots = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex w-full flex-col gap-4">
|
<Skeleton
|
||||||
|
isLoading={booking.isLoadingTimeSlots}
|
||||||
|
className="flex w-full flex-col gap-4"
|
||||||
|
>
|
||||||
<div className="flex h-full w-full flex-col gap-2 overflow-auto">
|
<div className="flex h-full w-full flex-col gap-2 overflow-auto">
|
||||||
{paginatedBookings.map((timeSlot, index) => {
|
{paginatedBookings.map((timeSlot, index) => {
|
||||||
const isEHIF = timeSlot.HKServiceID > 0;
|
const isHaigeKassa = timeSlot.HKServiceID > 0;
|
||||||
const serviceProviderTitle = getServiceProviderTitle(
|
const serviceProviderTitle = getServiceProviderTitle(
|
||||||
currentLocale,
|
currentLocale,
|
||||||
timeSlot.serviceProvider,
|
timeSlot.serviceProvider,
|
||||||
@@ -214,6 +183,7 @@ const TimeSlots = ({
|
|||||||
const price =
|
const price =
|
||||||
booking.selectedService?.variants?.[0]?.calculated_price
|
booking.selectedService?.variants?.[0]?.calculated_price
|
||||||
?.calculated_amount ?? cartItem?.unit_price;
|
?.calculated_amount ?? cartItem?.unit_price;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className="xs:flex xs:justify-between grid w-full justify-center-safe gap-3 p-4"
|
className="xs:flex xs:justify-between grid w-full justify-center-safe gap-3 p-4"
|
||||||
@@ -224,7 +194,7 @@ const TimeSlots = ({
|
|||||||
<div className="flex">
|
<div className="flex">
|
||||||
<h5
|
<h5
|
||||||
className={cn(
|
className={cn(
|
||||||
(serviceProviderTitle || isEHIF) &&
|
(serviceProviderTitle || isHaigeKassa) &&
|
||||||
"after:mx-2 after:content-['·']",
|
"after:mx-2 after:content-['·']",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -232,12 +202,14 @@ const TimeSlots = ({
|
|||||||
</h5>
|
</h5>
|
||||||
{serviceProviderTitle && (
|
{serviceProviderTitle && (
|
||||||
<span
|
<span
|
||||||
className={cn(isEHIF && "after:mx-2 after:content-['·']")}
|
className={cn(
|
||||||
|
isHaigeKassa && "after:mx-2 after:content-['·']",
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
{serviceProviderTitle}
|
{serviceProviderTitle}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{isEHIF && <span>{t('booking:ehifBooking')}</span>}
|
{isHaigeKassa && <span>{t('booking:ehifBooking')}</span>}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex text-xs">{timeSlot.location?.address}</div>
|
<div className="flex text-xs">{timeSlot.location?.address}</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -256,63 +228,14 @@ const TimeSlots = ({
|
|||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{!paginatedBookings.length && (
|
|
||||||
<div className="wrap text-muted-foreground flex size-full content-center-safe justify-center-safe">
|
|
||||||
<p>{t('booking:noResults')}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{totalPages > 1 && (
|
<BookingPagination
|
||||||
<div className="flex items-center justify-between">
|
totalPages={Math.ceil(filteredBookings.length / PAGE_SIZE)}
|
||||||
<div className="text-muted-foreground text-sm">
|
setCurrentPage={setCurrentPage}
|
||||||
{t('common:pageOfPages', {
|
currentPage={currentPage}
|
||||||
page: currentPage,
|
/>
|
||||||
total: totalPages,
|
</Skeleton>
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handlePageChange(currentPage - 1)}
|
|
||||||
disabled={currentPage === 1}
|
|
||||||
>
|
|
||||||
<Trans i18nKey="common:previous" defaultValue="Previous" />
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{generatePageNumbers().map((page, index) => (
|
|
||||||
<Button
|
|
||||||
key={index}
|
|
||||||
variant={page === currentPage ? 'default' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() =>
|
|
||||||
typeof page === 'number' && handlePageChange(page)
|
|
||||||
}
|
|
||||||
disabled={page === '...'}
|
|
||||||
className={cn(
|
|
||||||
'min-w-[2rem]',
|
|
||||||
page === '...' && 'cursor-default hover:bg-transparent',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{page}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handlePageChange(currentPage + 1)}
|
|
||||||
disabled={currentPage === totalPages}
|
|
||||||
>
|
|
||||||
<Trans i18nKey="common:next" defaultValue="Next" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,17 +2,19 @@
|
|||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
import { handleNavigateToPayment } from '@/lib/services/medusaCart.service';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
import { initiatePaymentSession } from '@lib/data/cart';
|
|
||||||
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||||
import { Loader2 } from 'lucide-react';
|
import { Loader2 } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardContent, CardHeader } from '@kit/ui/card';
|
import { Card, CardContent, CardHeader } from '@kit/ui/card';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { initiatePayment } from '../../_lib/server/cart-actions';
|
||||||
import AnalysisLocation from './analysis-location';
|
import AnalysisLocation from './analysis-location';
|
||||||
import CartItems from './cart-items';
|
import CartItems from './cart-items';
|
||||||
import CartServiceItems from './cart-service-items';
|
import CartServiceItems from './cart-service-items';
|
||||||
@@ -22,25 +24,31 @@ import { EnrichedCartItem } from './types';
|
|||||||
const IS_DISCOUNT_SHOWN = true as boolean;
|
const IS_DISCOUNT_SHOWN = true as boolean;
|
||||||
|
|
||||||
export default function Cart({
|
export default function Cart({
|
||||||
|
accountId,
|
||||||
cart,
|
cart,
|
||||||
synlabAnalyses,
|
synlabAnalyses,
|
||||||
ttoServiceItems,
|
ttoServiceItems,
|
||||||
|
balanceSummary,
|
||||||
}: {
|
}: {
|
||||||
|
accountId: string;
|
||||||
cart: StoreCart | null;
|
cart: StoreCart | null;
|
||||||
synlabAnalyses: StoreCartLineItem[];
|
synlabAnalyses: StoreCartLineItem[];
|
||||||
ttoServiceItems: EnrichedCartItem[];
|
ttoServiceItems: EnrichedCartItem[];
|
||||||
|
balanceSummary: AccountBalanceSummary | null;
|
||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
i18n: { language },
|
i18n: { language },
|
||||||
} = useTranslation();
|
} = useTranslation();
|
||||||
|
|
||||||
const [isInitiatingSession, setIsInitiatingSession] = useState(false);
|
const [isInitiatingSession, setIsInitiatingSession] = useState(false);
|
||||||
|
const router = useRouter();
|
||||||
const [unavailableLineItemIds, setUnavailableLineItemIds] =
|
const [unavailableLineItemIds, setUnavailableLineItemIds] =
|
||||||
useState<string[]>();
|
useState<string[]>();
|
||||||
|
|
||||||
const items = cart?.items ?? [];
|
const items = cart?.items ?? [];
|
||||||
|
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
||||||
|
|
||||||
if (!cart || items.length === 0) {
|
if (!hasCartItems) {
|
||||||
return (
|
return (
|
||||||
<div className="content-container py-5 lg:px-4">
|
<div className="content-container py-5 lg:px-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -60,32 +68,42 @@ export default function Cart({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function initiatePayment() {
|
async function initiateSession() {
|
||||||
setIsInitiatingSession(true);
|
setIsInitiatingSession(true);
|
||||||
const response = await initiatePaymentSession(cart!, {
|
|
||||||
provider_id: 'pp_montonio_montonio',
|
try {
|
||||||
});
|
const { url, isFullyPaidByBenefits, orderId, unavailableLineItemIds } =
|
||||||
if (response.payment_collection) {
|
await initiatePayment({
|
||||||
const { payment_sessions } = response.payment_collection;
|
accountId,
|
||||||
const paymentSessionId = payment_sessions![0]!.id;
|
balanceSummary: balanceSummary!,
|
||||||
const result = await handleNavigateToPayment({
|
cart: cart!,
|
||||||
language,
|
language,
|
||||||
paymentSessionId,
|
});
|
||||||
});
|
if (unavailableLineItemIds) {
|
||||||
if (result.url) {
|
setUnavailableLineItemIds(unavailableLineItemIds);
|
||||||
window.location.href = result.url;
|
|
||||||
}
|
}
|
||||||
if (result.unavailableLineItemIds) {
|
if (url) {
|
||||||
setUnavailableLineItemIds(result.unavailableLineItemIds);
|
window.location.href = url;
|
||||||
|
} else if (isFullyPaidByBenefits) {
|
||||||
|
if (typeof orderId !== 'number') {
|
||||||
|
throw new Error('Order ID is missing');
|
||||||
|
}
|
||||||
|
router.push(`/home/order/${orderId}/confirmed`);
|
||||||
}
|
}
|
||||||
} else {
|
} catch (error) {
|
||||||
|
console.error('Failed to initiate payment', error);
|
||||||
setIsInitiatingSession(false);
|
setIsInitiatingSession(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasCartItems = Array.isArray(cart.items) && cart.items.length > 0;
|
|
||||||
const isLocationsShown = synlabAnalyses.length > 0;
|
const isLocationsShown = synlabAnalyses.length > 0;
|
||||||
|
|
||||||
|
const companyBenefitsTotal = balanceSummary?.totalBalance ?? 0;
|
||||||
|
const montonioTotal =
|
||||||
|
cart && companyBenefitsTotal > 0
|
||||||
|
? cart.total - companyBenefitsTotal
|
||||||
|
: cart.total;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 lg:px-4">
|
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 lg:px-4">
|
||||||
<div className="flex flex-col gap-y-6 bg-white">
|
<div className="flex flex-col gap-y-6 bg-white">
|
||||||
@@ -119,7 +137,7 @@ export default function Cart({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
||||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||||
<Trans i18nKey="cart:order.promotionsTotal" />
|
<Trans i18nKey="cart:order.promotionsTotal" />
|
||||||
@@ -135,6 +153,27 @@ export default function Cart({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{companyBenefitsTotal > 0 && (
|
||||||
|
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||||
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
|
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||||
|
<Trans i18nKey="cart:order.companyBenefitsTotal" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||||
|
<p className="text-right text-sm">
|
||||||
|
{formatCurrency({
|
||||||
|
value:
|
||||||
|
companyBenefitsTotal > cart.total
|
||||||
|
? cart.total
|
||||||
|
: companyBenefitsTotal,
|
||||||
|
currencyCode: cart.currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
|
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
|
||||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
<p className="ml-0 text-sm font-bold">
|
<p className="ml-0 text-sm font-bold">
|
||||||
@@ -144,7 +183,7 @@ export default function Cart({
|
|||||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||||
<p className="text-right text-sm">
|
<p className="text-right text-sm">
|
||||||
{formatCurrency({
|
{formatCurrency({
|
||||||
value: cart.total,
|
value: montonioTotal < 0 ? 0 : montonioTotal,
|
||||||
currencyCode: cart.currency_code,
|
currencyCode: cart.currency_code,
|
||||||
locale: language,
|
locale: language,
|
||||||
})}
|
})}
|
||||||
@@ -180,10 +219,6 @@ export default function Cart({
|
|||||||
cart={{ ...cart }}
|
cart={{ ...cart }}
|
||||||
synlabAnalyses={synlabAnalyses}
|
synlabAnalyses={synlabAnalyses}
|
||||||
/>
|
/>
|
||||||
<AnalysisLocation
|
|
||||||
cart={{ ...cart }}
|
|
||||||
synlabAnalyses={synlabAnalyses}
|
|
||||||
/>
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
@@ -192,7 +227,7 @@ export default function Cart({
|
|||||||
<div>
|
<div>
|
||||||
<Button
|
<Button
|
||||||
className="h-10"
|
className="h-10"
|
||||||
onClick={initiatePayment}
|
onClick={initiateSession}
|
||||||
disabled={isInitiatingSession}
|
disabled={isInitiatingSession}
|
||||||
>
|
>
|
||||||
{isInitiatingSession && (
|
{isInitiatingSession && (
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { StoreCartLineItem } from "@medusajs/types";
|
import { StoreCartLineItem } from '@medusajs/types';
|
||||||
import { Reservation } from "~/lib/types/reservation";
|
|
||||||
|
import { Reservation } from '~/lib/types/reservation';
|
||||||
|
|
||||||
export interface MontonioOrderToken {
|
export interface MontonioOrderToken {
|
||||||
uuid: string;
|
uuid: string;
|
||||||
@@ -12,7 +13,7 @@ export interface MontonioOrderToken {
|
|||||||
| 'CANCELLED'
|
| 'CANCELLED'
|
||||||
| 'PENDING'
|
| 'PENDING'
|
||||||
| 'EXPIRED'
|
| 'EXPIRED'
|
||||||
| 'REFUNDED';
|
| 'REFUNDED'
|
||||||
| 'PAID'
|
| 'PAID'
|
||||||
| 'FAILED'
|
| 'FAILED'
|
||||||
| 'CANCELLED'
|
| 'CANCELLED'
|
||||||
|
|||||||
@@ -1,14 +1,39 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
import { ChevronRight, HeartPulse } from 'lucide-react';
|
import { ChevronRight, HeartPulse } from 'lucide-react';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Card, CardDescription, CardFooter, CardHeader } from '@kit/ui/card';
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardFooter,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from '@kit/ui/card';
|
||||||
|
import { cn } from '@kit/ui/lib/utils';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
export default function DashboardCards() {
|
import { getAccountBalanceSummary } from '../_lib/server/balance-actions';
|
||||||
|
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||||
|
|
||||||
|
export default async function DashboardCards() {
|
||||||
|
const { language } = await createI18nServerInstance();
|
||||||
|
|
||||||
|
const { account } = await loadCurrentUserAccount();
|
||||||
|
const balanceSummary = account
|
||||||
|
? await getAccountBalanceSummary(account.id)
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex gap-4">
|
<div
|
||||||
|
className={cn(
|
||||||
|
'grid grid-cols-1 gap-4',
|
||||||
|
'md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
|
||||||
|
)}
|
||||||
|
>
|
||||||
<Card
|
<Card
|
||||||
variant="gradient-success"
|
variant="gradient-success"
|
||||||
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
||||||
@@ -38,6 +63,34 @@ export default function DashboardCards() {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<Card className="flex flex-col justify-center">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle size="h5">
|
||||||
|
<Trans i18nKey="dashboard:heroCard.benefits.title" />
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent>
|
||||||
|
<Figure>
|
||||||
|
{formatCurrency({
|
||||||
|
value: balanceSummary?.totalBalance || 0,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
|
</Figure>
|
||||||
|
<CardDescription>
|
||||||
|
<Trans
|
||||||
|
i18nKey="dashboard:heroCard.benefits.validUntil"
|
||||||
|
values={{ date: '31.12.2025' }}
|
||||||
|
/>
|
||||||
|
</CardDescription>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Figure(props: React.PropsWithChildren) {
|
||||||
|
return <div className={'text-3xl font-bold'}>{props.children}</div>;
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
|
||||||
import { BlendingModeIcon, RulerHorizontalIcon } from '@radix-ui/react-icons';
|
import { BlendingModeIcon, RulerHorizontalIcon } from '@radix-ui/react-icons';
|
||||||
import { isNil } from 'lodash';
|
import { isNil } from 'lodash';
|
||||||
import {
|
import {
|
||||||
@@ -15,7 +14,10 @@ import {
|
|||||||
User,
|
User,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
import type {
|
||||||
|
AccountWithParams,
|
||||||
|
BmiThresholds,
|
||||||
|
} from '@kit/accounts/types/accounts';
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import {
|
import {
|
||||||
@@ -138,10 +140,7 @@ export default function Dashboard({
|
|||||||
bmiThresholds,
|
bmiThresholds,
|
||||||
}: {
|
}: {
|
||||||
account: AccountWithParams;
|
account: AccountWithParams;
|
||||||
bmiThresholds: Omit<
|
bmiThresholds: Omit<BmiThresholds, 'id'>[];
|
||||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
|
||||||
'id'
|
|
||||||
>[];
|
|
||||||
}) {
|
}) {
|
||||||
const height = account.accountParams?.height || 0;
|
const height = account.accountParams?.height || 0;
|
||||||
const weight = account.accountParams?.weight || 0;
|
const weight = account.accountParams?.weight || 0;
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ import { useTranslation } from 'react-i18next';
|
|||||||
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
const PaymentProviderIds = {
|
||||||
|
COMPANY_BENEFITS: 'pp_company-benefits_company-benefits',
|
||||||
|
MONTONIO: 'pp_montonio_montonio',
|
||||||
|
};
|
||||||
|
|
||||||
export default function CartTotals({
|
export default function CartTotals({
|
||||||
medusaOrder,
|
medusaOrder,
|
||||||
}: {
|
}: {
|
||||||
@@ -20,11 +25,18 @@ export default function CartTotals({
|
|||||||
currency_code,
|
currency_code,
|
||||||
total,
|
total,
|
||||||
subtotal,
|
subtotal,
|
||||||
tax_total,
|
|
||||||
discount_total,
|
discount_total,
|
||||||
gift_card_total,
|
gift_card_total,
|
||||||
|
payment_collections,
|
||||||
} = medusaOrder;
|
} = medusaOrder;
|
||||||
|
|
||||||
|
const montonioPayment = payment_collections?.[0]?.payments?.find(
|
||||||
|
({ provider_id }) => provider_id === PaymentProviderIds.MONTONIO,
|
||||||
|
);
|
||||||
|
const companyBenefitsPayment = payment_collections?.[0]?.payments?.find(
|
||||||
|
({ provider_id }) => provider_id === PaymentProviderIds.COMPANY_BENEFITS,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="txt-medium text-ui-fg-subtle flex flex-col gap-y-2">
|
<div className="txt-medium text-ui-fg-subtle flex flex-col gap-y-2">
|
||||||
@@ -87,7 +99,9 @@ export default function CartTotals({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="my-4 h-px w-full border-b border-gray-200" />
|
<div className="my-4 h-px w-full border-b border-gray-200" />
|
||||||
|
|
||||||
<div className="text-ui-fg-base txt-medium mb-2 flex items-center justify-between">
|
<div className="text-ui-fg-base txt-medium mb-2 flex items-center justify-between">
|
||||||
<span className="font-bold">
|
<span className="font-bold">
|
||||||
<Trans i18nKey="cart:order.total" />
|
<Trans i18nKey="cart:order.total" />
|
||||||
@@ -104,7 +118,48 @@ export default function CartTotals({
|
|||||||
})}
|
})}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-4 h-px w-full border-b border-gray-200" />
|
|
||||||
|
<div className="my-4 h-px w-full border-b border-gray-200" />
|
||||||
|
|
||||||
|
<div className="txt-medium text-ui-fg-subtle flex flex-col gap-y-2">
|
||||||
|
{companyBenefitsPayment && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="flex items-center gap-x-1">
|
||||||
|
<Trans i18nKey="cart:order.benefitsTotal" />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
data-testid="cart-subtotal"
|
||||||
|
data-value={companyBenefitsPayment.amount || 0}
|
||||||
|
>
|
||||||
|
-{' '}
|
||||||
|
{formatCurrency({
|
||||||
|
value: companyBenefitsPayment.amount ?? 0,
|
||||||
|
currencyCode: currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{montonioPayment && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="flex items-center gap-x-1">
|
||||||
|
<Trans i18nKey="cart:order.montonioTotal" />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
data-testid="cart-subtotal"
|
||||||
|
data-value={montonioPayment.amount || 0}
|
||||||
|
>
|
||||||
|
-{' '}
|
||||||
|
{formatCurrency({
|
||||||
|
value: montonioPayment.amount ?? 0,
|
||||||
|
currencyCode: currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ import { formatDate } from 'date-fns';
|
|||||||
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import type { AnalysisOrder } from '~/lib/types/order';
|
|
||||||
|
|
||||||
export default function OrderDetails({
|
export default function OrderDetails({
|
||||||
order,
|
order,
|
||||||
}: {
|
}: {
|
||||||
@@ -15,7 +13,7 @@ export default function OrderDetails({
|
|||||||
<span className="font-bold">
|
<span className="font-bold">
|
||||||
<Trans i18nKey="cart:orderConfirmed.orderNumber" />:{' '}
|
<Trans i18nKey="cart:orderConfirmed.orderNumber" />:{' '}
|
||||||
</span>
|
</span>
|
||||||
<span>{order.id}</span>
|
<span className="break-all">{order.id}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
18
app/home/(user)/_lib/server/balance-actions.ts
Normal file
18
app/home/(user)/_lib/server/balance-actions.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import {
|
||||||
|
AccountBalanceService,
|
||||||
|
AccountBalanceSummary,
|
||||||
|
} from '@kit/accounts/services/account-balance.service';
|
||||||
|
|
||||||
|
export async function getAccountBalanceSummary(
|
||||||
|
accountId: string,
|
||||||
|
): Promise<AccountBalanceSummary | null> {
|
||||||
|
try {
|
||||||
|
const service = new AccountBalanceService();
|
||||||
|
return await service.getBalanceSummary(accountId);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting account balance summary:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
365
app/home/(user)/_lib/server/cart-actions.ts
Normal file
365
app/home/(user)/_lib/server/cart-actions.ts
Normal file
@@ -0,0 +1,365 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||||
|
import { createNotificationsApi } from '@/packages/features/notifications/src/server/api';
|
||||||
|
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
||||||
|
import { listProductTypes } from '@lib/data';
|
||||||
|
import { initiateMultiPaymentSession, placeOrder } from '@lib/data/cart';
|
||||||
|
import type { StoreCart, StoreOrder } from '@medusajs/types';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import type { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
||||||
|
|
||||||
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
|
import { bookAppointment } from '~/lib/services/connected-online.service';
|
||||||
|
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
||||||
|
import { handleNavigateToPayment } from '~/lib/services/medusaCart.service';
|
||||||
|
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
||||||
|
import {
|
||||||
|
createAnalysisOrder,
|
||||||
|
getAnalysisOrder,
|
||||||
|
} from '~/lib/services/order.service';
|
||||||
|
import { getOrderedTtoServices } from '~/lib/services/reservation.service';
|
||||||
|
import { FailureReason } from '~/lib/types/connected-online';
|
||||||
|
|
||||||
|
import { loadCurrentUserAccount } from './load-user-account';
|
||||||
|
|
||||||
|
const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages';
|
||||||
|
const ANALYSIS_TYPE_HANDLE = 'synlab-analysis';
|
||||||
|
|
||||||
|
const env = () =>
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
emailSender: z
|
||||||
|
.string({
|
||||||
|
error: 'EMAIL_SENDER is required',
|
||||||
|
})
|
||||||
|
.min(1),
|
||||||
|
siteUrl: z
|
||||||
|
.string({
|
||||||
|
error: 'NEXT_PUBLIC_SITE_URL is required',
|
||||||
|
})
|
||||||
|
.min(1),
|
||||||
|
isEnabledDispatchOnMontonioCallback: z.boolean({
|
||||||
|
error: 'MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK is required',
|
||||||
|
}),
|
||||||
|
medusaBackendPublicUrl: z
|
||||||
|
.string({
|
||||||
|
error: 'MEDUSA_BACKEND_PUBLIC_URL is required',
|
||||||
|
})
|
||||||
|
.min(1),
|
||||||
|
companyBenefitsPaymentSecretKey: z
|
||||||
|
.string({
|
||||||
|
error: 'COMPANY_BENEFITS_PAYMENT_SECRET_KEY is required',
|
||||||
|
})
|
||||||
|
.min(1),
|
||||||
|
})
|
||||||
|
.parse({
|
||||||
|
emailSender: process.env.EMAIL_SENDER,
|
||||||
|
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
|
||||||
|
isEnabledDispatchOnMontonioCallback:
|
||||||
|
process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true',
|
||||||
|
medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!,
|
||||||
|
companyBenefitsPaymentSecretKey:
|
||||||
|
process.env.COMPANY_BENEFITS_PAYMENT_SECRET_KEY!,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const initiatePayment = async ({
|
||||||
|
accountId,
|
||||||
|
balanceSummary,
|
||||||
|
cart,
|
||||||
|
language,
|
||||||
|
}: {
|
||||||
|
accountId: string;
|
||||||
|
balanceSummary: AccountBalanceSummary;
|
||||||
|
cart: StoreCart;
|
||||||
|
language: string;
|
||||||
|
}) => {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
montonioPaymentSessionId,
|
||||||
|
companyBenefitsPaymentSessionId,
|
||||||
|
totalByMontonio,
|
||||||
|
totalByBenefits,
|
||||||
|
isFullyPaidByBenefits,
|
||||||
|
} = await initiateMultiPaymentSession(cart, balanceSummary.totalBalance);
|
||||||
|
|
||||||
|
if (!isFullyPaidByBenefits) {
|
||||||
|
if (!montonioPaymentSessionId) {
|
||||||
|
throw new Error('Montonio payment session ID is missing');
|
||||||
|
}
|
||||||
|
const props = await handleNavigateToPayment({
|
||||||
|
language,
|
||||||
|
paymentSessionId: montonioPaymentSessionId,
|
||||||
|
amount: totalByMontonio,
|
||||||
|
currencyCode: cart.currency_code,
|
||||||
|
cartId: cart.id,
|
||||||
|
});
|
||||||
|
return { ...props, isFullyPaidByBenefits };
|
||||||
|
} else {
|
||||||
|
// place order if all paid already
|
||||||
|
const { orderId } = await handlePlaceOrder({ cart });
|
||||||
|
|
||||||
|
const companyBenefitsOrderToken = jwt.sign(
|
||||||
|
{
|
||||||
|
accountId,
|
||||||
|
companyBenefitsPaymentSessionId,
|
||||||
|
orderId,
|
||||||
|
totalByBenefits,
|
||||||
|
},
|
||||||
|
env().companyBenefitsPaymentSecretKey,
|
||||||
|
{
|
||||||
|
algorithm: 'HS256',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const webhookResponse = await fetch(
|
||||||
|
`${env().medusaBackendPublicUrl}/hooks/payment/company-benefits_company-benefits`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
orderToken: companyBenefitsOrderToken,
|
||||||
|
}),
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!webhookResponse.ok) {
|
||||||
|
throw new Error('Failed to send company benefits webhook');
|
||||||
|
}
|
||||||
|
return { isFullyPaidByBenefits, orderId, unavailableLineItemIds: [] };
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error initiating payment', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
url: null,
|
||||||
|
isFullyPaidByBenefits: false,
|
||||||
|
orderId: null,
|
||||||
|
unavailableLineItemIds: [],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
|
||||||
|
const { account } = await loadCurrentUserAccount();
|
||||||
|
if (!account) {
|
||||||
|
throw new Error('Account not found in context');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const medusaOrder = await placeOrder(cart.id, {
|
||||||
|
revalidateCacheTags: false,
|
||||||
|
});
|
||||||
|
const orderedAnalysisElements = await getOrderedAnalysisIds({
|
||||||
|
medusaOrder,
|
||||||
|
});
|
||||||
|
|
||||||
|
const orderContainsSynlabItems = !!orderedAnalysisElements?.length;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const existingAnalysisOrder = await getAnalysisOrder({
|
||||||
|
medusaOrderId: medusaOrder.id,
|
||||||
|
});
|
||||||
|
console.info(
|
||||||
|
`Analysis order already exists for medusaOrderId=${medusaOrder.id}, orderId=${existingAnalysisOrder.id}`,
|
||||||
|
);
|
||||||
|
return { success: true, orderId: existingAnalysisOrder.id };
|
||||||
|
} catch {
|
||||||
|
// ignored
|
||||||
|
}
|
||||||
|
|
||||||
|
let orderId: number | undefined = undefined;
|
||||||
|
if (orderContainsSynlabItems) {
|
||||||
|
orderId = await createAnalysisOrder({
|
||||||
|
medusaOrder,
|
||||||
|
orderedAnalysisElements,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderResult = await getOrderResultParameters(medusaOrder);
|
||||||
|
|
||||||
|
const { medusaOrderId, email, analysisPackageOrder, analysisItemsOrder } =
|
||||||
|
orderResult;
|
||||||
|
|
||||||
|
const orderedTtoServices = await getOrderedTtoServices({ medusaOrder });
|
||||||
|
let bookServiceResults: {
|
||||||
|
success: boolean;
|
||||||
|
reason?: FailureReason;
|
||||||
|
serviceId?: number;
|
||||||
|
}[] = [];
|
||||||
|
if (orderedTtoServices?.length) {
|
||||||
|
const bookingPromises = orderedTtoServices.map((service) =>
|
||||||
|
bookAppointment(
|
||||||
|
service.service_id,
|
||||||
|
service.clinic_id,
|
||||||
|
service.service_user_id,
|
||||||
|
service.sync_user_id,
|
||||||
|
service.start_time,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
bookServiceResults = await Promise.all(bookingPromises);
|
||||||
|
}
|
||||||
|
// TODO: SEND EMAIL
|
||||||
|
|
||||||
|
if (email) {
|
||||||
|
if (analysisPackageOrder) {
|
||||||
|
await sendAnalysisPackageOrderEmail({
|
||||||
|
account,
|
||||||
|
email,
|
||||||
|
analysisPackageOrder,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.info(`Order has no analysis package, skipping email.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (analysisItemsOrder) {
|
||||||
|
// @TODO send email for separate analyses
|
||||||
|
console.warn(
|
||||||
|
`Order has analysis items, but no email template exists yet`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.info(`Order has no analysis items, skipping email.`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('Missing email to send order result email', orderResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (env().isEnabledDispatchOnMontonioCallback) {
|
||||||
|
await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bookServiceResults.some(({ success }) => success === false)) {
|
||||||
|
const failedServiceBookings = bookServiceResults.filter(
|
||||||
|
({ success }) => success === false,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
failedServiceBookings,
|
||||||
|
orderId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, orderId };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to place order', error);
|
||||||
|
throw new Error(`Failed to place order, message=${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendAnalysisPackageOrderEmail({
|
||||||
|
account,
|
||||||
|
email,
|
||||||
|
analysisPackageOrder,
|
||||||
|
}: {
|
||||||
|
account: AccountWithParams;
|
||||||
|
email: string;
|
||||||
|
analysisPackageOrder: {
|
||||||
|
partnerLocationName: string;
|
||||||
|
analysisPackageName: string;
|
||||||
|
};
|
||||||
|
}) {
|
||||||
|
const { language } = await createI18nServerInstance();
|
||||||
|
const { analysisPackageName, partnerLocationName } = analysisPackageOrder;
|
||||||
|
try {
|
||||||
|
await sendEmail({
|
||||||
|
account: { id: account.id, name: account.name },
|
||||||
|
email,
|
||||||
|
analysisPackageName,
|
||||||
|
partnerLocationName,
|
||||||
|
language,
|
||||||
|
});
|
||||||
|
console.info(`Successfully sent analysis package order email to ${email}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`Failed to send analysis package order email to ${email}`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getOrderResultParameters(medusaOrder: StoreOrder) {
|
||||||
|
const { productTypes } = await listProductTypes();
|
||||||
|
const analysisPackagesType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === ANALYSIS_PACKAGES_TYPE_HANDLE,
|
||||||
|
);
|
||||||
|
const analysisType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === ANALYSIS_TYPE_HANDLE,
|
||||||
|
);
|
||||||
|
|
||||||
|
const analysisPackageOrderItem = medusaOrder.items?.find(
|
||||||
|
({ product_type_id }) => product_type_id === analysisPackagesType?.id,
|
||||||
|
);
|
||||||
|
const analysisItems = medusaOrder.items?.filter(
|
||||||
|
({ product_type_id }) => product_type_id === analysisType?.id,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
medusaOrderId: medusaOrder.id,
|
||||||
|
email: medusaOrder.email,
|
||||||
|
analysisPackageOrder: analysisPackageOrderItem
|
||||||
|
? {
|
||||||
|
partnerLocationName:
|
||||||
|
(analysisPackageOrderItem?.metadata
|
||||||
|
?.partner_location_name as string) ?? '',
|
||||||
|
analysisPackageName: analysisPackageOrderItem?.title ?? '',
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
analysisItemsOrder:
|
||||||
|
Array.isArray(analysisItems) && analysisItems.length > 0
|
||||||
|
? analysisItems.map(({ product }) => ({
|
||||||
|
analysisName: product?.title ?? '',
|
||||||
|
analysisId: (product?.metadata?.analysisIdOriginal as string) ?? '',
|
||||||
|
}))
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const sendEmail = async ({
|
||||||
|
account,
|
||||||
|
email,
|
||||||
|
analysisPackageName,
|
||||||
|
partnerLocationName,
|
||||||
|
language,
|
||||||
|
}: {
|
||||||
|
account: Pick<AccountWithParams, 'name' | 'id'>;
|
||||||
|
email: string;
|
||||||
|
analysisPackageName: 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: account.name,
|
||||||
|
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}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
12
app/home/(user)/_lib/server/is-valid-open-ai-env.ts
Normal file
12
app/home/(user)/_lib/server/is-valid-open-ai-env.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import OpenAI from 'openai';
|
||||||
|
|
||||||
|
export const isValidOpenAiEnv = async () => {
|
||||||
|
try {
|
||||||
|
const client = new OpenAI();
|
||||||
|
await client.models.list();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
console.log('AI not enabled');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { Trans } from 'react-i18next';
|
|
||||||
|
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
||||||
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { Trans } from 'react-i18next';
|
|
||||||
|
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
||||||
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
|
|||||||
@@ -1,23 +1,14 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
|
||||||
|
|
||||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
|
||||||
import { PiggyBankIcon, Settings } from 'lucide-react';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { createPath, pathsConfig } from '@kit/shared/config';
|
|
||||||
import { Card, CardTitle } from '@kit/ui/card';
|
import { Card, CardTitle } from '@kit/ui/card';
|
||||||
import { cn } from '@kit/ui/lib/utils';
|
import { cn } from '@kit/ui/lib/utils';
|
||||||
import { Button } from '@kit/ui/shadcn/button';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
interface TeamAccountBenefitStatisticsProps {
|
import { TeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
employeeCount: number;
|
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
|
||||||
accountSlug: string;
|
|
||||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
|
||||||
}
|
|
||||||
|
|
||||||
const StatisticsCard = ({ children }: { children: React.ReactNode }) => {
|
const StatisticsCard = ({ children }: { children: React.ReactNode }) => {
|
||||||
return <Card className="p-4">{children}</Card>;
|
return <Card className="p-4">{children}</Card>;
|
||||||
@@ -46,126 +37,90 @@ const StatisticsValue = ({ children }: { children: React.ReactNode }) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const TeamAccountBenefitStatistics = ({
|
const TeamAccountBenefitStatistics = ({
|
||||||
employeeCount,
|
accountBenefitStatistics,
|
||||||
accountSlug,
|
expensesOverview,
|
||||||
companyParams,
|
}: {
|
||||||
}: TeamAccountBenefitStatisticsProps) => {
|
accountBenefitStatistics: AccountBenefitStatistics;
|
||||||
|
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||||
|
}) => {
|
||||||
const {
|
const {
|
||||||
i18n: { language },
|
i18n: { language },
|
||||||
} = useTranslation();
|
} = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full w-full flex-col gap-2 sm:flex-row">
|
<div className="flex h-full w-full flex-col gap-2 sm:flex-row">
|
||||||
<Card className="relative flex flex-row">
|
|
||||||
<div className="p-6">
|
|
||||||
<Button
|
|
||||||
onClick={() =>
|
|
||||||
redirect(createPath(pathsConfig.app.accountBilling, accountSlug))
|
|
||||||
}
|
|
||||||
variant="outline"
|
|
||||||
className="absolute top-1 right-1 p-3"
|
|
||||||
>
|
|
||||||
<Settings />
|
|
||||||
</Button>
|
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-orange-100">
|
|
||||||
<PiggyBankIcon className="h-[32px] w-[32px] stroke-orange-400 stroke-2" />
|
|
||||||
</div>
|
|
||||||
<p className="mt-4 text-sm font-medium">
|
|
||||||
<Trans i18nKey="teams:benefitStatistics.budget.title" />
|
|
||||||
</p>
|
|
||||||
<h3 className="text-2xl">
|
|
||||||
<Trans
|
|
||||||
i18nKey="teams:benefitStatistics.budget.balance"
|
|
||||||
values={{
|
|
||||||
balance: formatCurrency({
|
|
||||||
value: 11800,
|
|
||||||
locale: language,
|
|
||||||
currencyCode: 'EUR',
|
|
||||||
}),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</h3>
|
|
||||||
<StatisticsDescription>
|
|
||||||
<Trans
|
|
||||||
i18nKey="teams:benefitStatistics.budget.volume"
|
|
||||||
values={{
|
|
||||||
volume: formatCurrency({
|
|
||||||
value:
|
|
||||||
(Number(companyParams.benefit_amount) || 0) * employeeCount,
|
|
||||||
locale: language,
|
|
||||||
currencyCode: 'EUR',
|
|
||||||
}),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</StatisticsDescription>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="grid flex-2 grid-cols-2 gap-2 sm:grid-cols-3 sm:grid-rows-2">
|
<div className="grid flex-2 grid-cols-2 gap-2 sm:grid-cols-3 sm:grid-rows-2">
|
||||||
<StatisticsCard>
|
<StatisticsCard>
|
||||||
<StatisticsCardTitle className="text-lg font-bold">
|
<StatisticsCardTitle className="text-lg font-bold">
|
||||||
<Trans i18nKey="teams:benefitStatistics.data.serviceSum" />
|
<Trans i18nKey="teams:benefitStatistics.budget.membersCount" />
|
||||||
</StatisticsCardTitle>
|
</StatisticsCardTitle>
|
||||||
<StatisticsValue>1800 €</StatisticsValue>
|
<StatisticsValue>
|
||||||
|
{accountBenefitStatistics.companyAccountsCount}
|
||||||
|
</StatisticsValue>
|
||||||
</StatisticsCard>
|
</StatisticsCard>
|
||||||
|
|
||||||
|
<StatisticsCard>
|
||||||
|
<StatisticsCardTitle className="text-lg font-bold">
|
||||||
|
<Trans i18nKey="teams:benefitStatistics.data.totalSum" />
|
||||||
|
</StatisticsCardTitle>
|
||||||
|
<StatisticsValue>
|
||||||
|
{formatCurrency({
|
||||||
|
value: accountBenefitStatistics.orders.totalSum,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
|
</StatisticsValue>
|
||||||
|
</StatisticsCard>
|
||||||
|
|
||||||
|
<StatisticsCard>
|
||||||
|
<StatisticsCardTitle className="text-lg font-bold">
|
||||||
|
<Trans i18nKey="teams:benefitStatistics.data.currentMonthUsageTotal" />
|
||||||
|
</StatisticsCardTitle>
|
||||||
|
<StatisticsValue>
|
||||||
|
{formatCurrency({
|
||||||
|
value: expensesOverview.currentMonthUsageTotal,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
|
</StatisticsValue>
|
||||||
|
</StatisticsCard>
|
||||||
|
|
||||||
<StatisticsCard>
|
<StatisticsCard>
|
||||||
<StatisticsCardTitle>
|
<StatisticsCardTitle>
|
||||||
<Trans i18nKey="teams:benefitStatistics.data.analysis" />
|
<Trans i18nKey="teams:benefitStatistics.data.analysis" />
|
||||||
</StatisticsCardTitle>
|
</StatisticsCardTitle>
|
||||||
<StatisticsValue>200 €</StatisticsValue>
|
<StatisticsValue>
|
||||||
|
{formatCurrency({
|
||||||
|
value: accountBenefitStatistics.orders.analysesSum,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
|
</StatisticsValue>
|
||||||
<StatisticsDescription>
|
<StatisticsDescription>
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey="teams:benefitStatistics.data.reservations"
|
i18nKey="teams:benefitStatistics.data.reservations"
|
||||||
values={{ value: 36 }}
|
values={{ value: accountBenefitStatistics.orders.analysesCount }}
|
||||||
/>
|
|
||||||
</StatisticsDescription>
|
|
||||||
</StatisticsCard>
|
|
||||||
<StatisticsCard>
|
|
||||||
<StatisticsCardTitle>
|
|
||||||
<Trans i18nKey="teams:benefitStatistics.data.doctorsAndSpecialists" />
|
|
||||||
</StatisticsCardTitle>
|
|
||||||
<StatisticsValue>200 €</StatisticsValue>
|
|
||||||
<StatisticsDescription>
|
|
||||||
<Trans
|
|
||||||
i18nKey="teams:benefitStatistics.data.reservations"
|
|
||||||
values={{ value: 44 }}
|
|
||||||
/>
|
|
||||||
</StatisticsDescription>
|
|
||||||
</StatisticsCard>
|
|
||||||
<StatisticsCard>
|
|
||||||
<StatisticsCardTitle>
|
|
||||||
<Trans i18nKey="teams:benefitStatistics.data.researches" />
|
|
||||||
</StatisticsCardTitle>
|
|
||||||
<StatisticsValue>200 €</StatisticsValue>
|
|
||||||
<StatisticsDescription>
|
|
||||||
<Trans
|
|
||||||
i18nKey="teams:benefitStatistics.data.reservations"
|
|
||||||
values={{ value: 40 }}
|
|
||||||
/>
|
|
||||||
</StatisticsDescription>
|
|
||||||
</StatisticsCard>
|
|
||||||
<StatisticsCard>
|
|
||||||
<StatisticsCardTitle>
|
|
||||||
<Trans i18nKey="teams:benefitStatistics.data.eclinic" />
|
|
||||||
</StatisticsCardTitle>
|
|
||||||
<StatisticsValue>200 €</StatisticsValue>
|
|
||||||
<StatisticsDescription>
|
|
||||||
<Trans
|
|
||||||
i18nKey="teams:benefitStatistics.data.reservations"
|
|
||||||
values={{ value: 34 }}
|
|
||||||
/>
|
/>
|
||||||
</StatisticsDescription>
|
</StatisticsDescription>
|
||||||
</StatisticsCard>
|
</StatisticsCard>
|
||||||
|
|
||||||
<StatisticsCard>
|
<StatisticsCard>
|
||||||
<StatisticsCardTitle>
|
<StatisticsCardTitle>
|
||||||
<Trans i18nKey="teams:benefitStatistics.data.healthResearchPlans" />
|
<Trans i18nKey="teams:benefitStatistics.data.analysisPackages" />
|
||||||
</StatisticsCardTitle>
|
</StatisticsCardTitle>
|
||||||
<StatisticsValue>200 €</StatisticsValue>
|
<StatisticsValue>
|
||||||
|
{formatCurrency({
|
||||||
|
value: accountBenefitStatistics.orders.analysisPackagesSum,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
|
</StatisticsValue>
|
||||||
<StatisticsDescription>
|
<StatisticsDescription>
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey="teams:benefitStatistics.data.serviceUsage"
|
i18nKey="teams:benefitStatistics.data.analysisPackagesCount"
|
||||||
values={{ value: 46 }}
|
values={{
|
||||||
|
value: accountBenefitStatistics.orders.analysisPackagesCount,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</StatisticsDescription>
|
</StatisticsDescription>
|
||||||
</StatisticsCard>
|
</StatisticsCard>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React from 'react';
|
|||||||
|
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { Database } from '@/packages/supabase/src/database.types';
|
||||||
|
|
||||||
|
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||||
import { Card } from '@kit/ui/card';
|
import { Card } from '@kit/ui/card';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { cn } from '@kit/ui/utils';
|
import { cn } from '@kit/ui/utils';
|
||||||
@@ -15,10 +16,7 @@ const TeamAccountHealthDetails = ({
|
|||||||
members,
|
members,
|
||||||
}: {
|
}: {
|
||||||
memberParams: TeamAccountStatisticsProps['memberParams'];
|
memberParams: TeamAccountStatisticsProps['memberParams'];
|
||||||
bmiThresholds: Omit<
|
bmiThresholds: Omit<BmiThresholds, 'id'>[];
|
||||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
|
||||||
'id'
|
|
||||||
>[];
|
|
||||||
members: Database['medreport']['Functions']['get_account_members']['Returns'];
|
members: Database['medreport']['Functions']['get_account_members']['Returns'];
|
||||||
}) => {
|
}) => {
|
||||||
const accountHealthDetailsFields = getAccountHealthDetailsFields(
|
const accountHealthDetailsFields = getAccountHealthDetailsFields(
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ import { useState } from 'react';
|
|||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
|
import type {
|
||||||
|
Account,
|
||||||
|
AccountParams,
|
||||||
|
BmiThresholds,
|
||||||
|
} from '@/packages/features/accounts/src/types/accounts';
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { Database } from '@/packages/supabase/src/database.types';
|
||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
import { enGB, et } from 'date-fns/locale';
|
import { enGB, et } from 'date-fns/locale';
|
||||||
@@ -14,28 +19,20 @@ import { createPath, pathsConfig } from '@kit/shared/config';
|
|||||||
import { Card } from '@kit/ui/card';
|
import { Card } from '@kit/ui/card';
|
||||||
import { Trans } from '@kit/ui/makerkit/trans';
|
import { Trans } from '@kit/ui/makerkit/trans';
|
||||||
import { Button } from '@kit/ui/shadcn/button';
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
import { Calendar, DateRange } from '@kit/ui/shadcn/calendar';
|
import { DateRange } from '@kit/ui/shadcn/calendar';
|
||||||
import {
|
|
||||||
Popover,
|
|
||||||
PopoverContent,
|
|
||||||
PopoverTrigger,
|
|
||||||
} from '@kit/ui/shadcn/popover';
|
|
||||||
|
|
||||||
|
import { TeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
|
||||||
import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
|
import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
|
||||||
import TeamAccountHealthDetails from './team-account-health-details';
|
import TeamAccountHealthDetails from './team-account-health-details';
|
||||||
|
|
||||||
export interface TeamAccountStatisticsProps {
|
export interface TeamAccountStatisticsProps {
|
||||||
teamAccount: Database['medreport']['Tables']['accounts']['Row'];
|
teamAccount: Account;
|
||||||
memberParams: Pick<
|
memberParams: Pick<AccountParams, 'weight' | 'height'>[];
|
||||||
Database['medreport']['Tables']['account_params']['Row'],
|
bmiThresholds: Omit<BmiThresholds, 'id'>[];
|
||||||
'weight' | 'height'
|
|
||||||
>[];
|
|
||||||
bmiThresholds: Omit<
|
|
||||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
|
||||||
'id'
|
|
||||||
>[];
|
|
||||||
members: Database['medreport']['Functions']['get_account_members']['Returns'];
|
members: Database['medreport']['Functions']['get_account_members']['Returns'];
|
||||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
accountBenefitStatistics: AccountBenefitStatistics;
|
||||||
|
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TeamAccountStatistics({
|
export default function TeamAccountStatistics({
|
||||||
@@ -43,11 +40,13 @@ export default function TeamAccountStatistics({
|
|||||||
memberParams,
|
memberParams,
|
||||||
bmiThresholds,
|
bmiThresholds,
|
||||||
members,
|
members,
|
||||||
companyParams,
|
accountBenefitStatistics,
|
||||||
|
expensesOverview,
|
||||||
}: TeamAccountStatisticsProps) {
|
}: TeamAccountStatisticsProps) {
|
||||||
|
const currentDate = new Date();
|
||||||
const [date, setDate] = useState<DateRange | undefined>({
|
const [date, setDate] = useState<DateRange | undefined>({
|
||||||
from: new Date(),
|
from: new Date(currentDate.getFullYear(), currentDate.getMonth(), 1),
|
||||||
to: new Date(),
|
to: new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0),
|
||||||
});
|
});
|
||||||
const {
|
const {
|
||||||
i18n: { language },
|
i18n: { language },
|
||||||
@@ -58,7 +57,7 @@ export default function TeamAccountStatistics({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="mt-4 flex items-center justify-between">
|
<div className="mt-4 flex flex-col items-center justify-between gap-4 sm:flex-row sm:gap-0">
|
||||||
<h4 className="font-bold">
|
<h4 className="font-bold">
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey={'teams:home.headerTitle'}
|
i18nKey={'teams:home.headerTitle'}
|
||||||
@@ -66,28 +65,16 @@ export default function TeamAccountStatistics({
|
|||||||
/>
|
/>
|
||||||
</h4>
|
</h4>
|
||||||
|
|
||||||
<Popover>
|
<Button variant="outline" data-empty={!date}>
|
||||||
<PopoverTrigger asChild>
|
<CalendarIcon />
|
||||||
<Button variant="outline" data-empty={!date}>
|
{date?.from && date?.to ? (
|
||||||
<CalendarIcon />
|
`${format(date.from, 'd MMMM yyyy', dateFormatOptions)} - ${format(date.to, 'd MMMM yyyy', dateFormatOptions)}`
|
||||||
{date?.from && date?.to ? (
|
) : (
|
||||||
`${format(date.from, 'd MMMM yyyy', dateFormatOptions)} - ${format(date.to, 'd MMMM yyyy', dateFormatOptions)}`
|
<span>
|
||||||
) : (
|
<Trans i18nKey="common:formField.selectDate" />
|
||||||
<span>
|
</span>
|
||||||
<Trans i18nKey="common:formField.selectDate" />
|
)}
|
||||||
</span>
|
</Button>
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-auto p-0">
|
|
||||||
<Calendar
|
|
||||||
mode="range"
|
|
||||||
selected={date}
|
|
||||||
onSelect={setDate}
|
|
||||||
locale={language === 'et' ? et : enGB}
|
|
||||||
/>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@@ -96,9 +83,8 @@ export default function TeamAccountStatistics({
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<TeamAccountBenefitStatistics
|
<TeamAccountBenefitStatistics
|
||||||
employeeCount={members.length}
|
accountBenefitStatistics={accountBenefitStatistics}
|
||||||
accountSlug={teamAccount.slug || ''}
|
expensesOverview={expensesOverview}
|
||||||
companyParams={companyParams}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<h5 className="mt-4 mb-2">
|
<h5 className="mt-4 mb-2">
|
||||||
@@ -146,10 +132,7 @@ export default function TeamAccountStatistics({
|
|||||||
className="border-warning/40 hover:bg-warning/20 relative flex h-full cursor-pointer flex-col justify-center px-6 py-4 transition-colors"
|
className="border-warning/40 hover:bg-warning/20 relative flex h-full cursor-pointer flex-col justify-center px-6 py-4 transition-colors"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
redirect(
|
redirect(
|
||||||
createPath(
|
createPath(pathsConfig.app.accountBilling, teamAccount.slug!),
|
||||||
pathsConfig.app.accountBilling,
|
|
||||||
teamAccount.slug || '',
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||||
|
|
||||||
|
import { loadCompanyPersonalAccountsBalanceEntries } from './load-team-account-benefit-statistics';
|
||||||
|
|
||||||
|
export interface TeamAccountBenefitExpensesOverview {
|
||||||
|
benefitAmount: number | null;
|
||||||
|
benefitOccurrence: 'yearly' | 'monthly' | 'quarterly' | null;
|
||||||
|
currentMonthUsageTotal: number;
|
||||||
|
managementFee: number;
|
||||||
|
managementFeeTotal: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MANAGEMENT_FEE = 5.5;
|
||||||
|
|
||||||
|
const MONTHS = 12;
|
||||||
|
const QUARTERS = 4;
|
||||||
|
|
||||||
|
export async function loadTeamAccountBenefitExpensesOverview({
|
||||||
|
companyId,
|
||||||
|
employeeCount,
|
||||||
|
}: {
|
||||||
|
companyId: string;
|
||||||
|
employeeCount: number;
|
||||||
|
}): Promise<TeamAccountBenefitExpensesOverview> {
|
||||||
|
const supabase = getSupabaseServerClient();
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('benefit_distribution_schedule')
|
||||||
|
.select('*')
|
||||||
|
.eq('company_id', companyId)
|
||||||
|
.eq('is_active', true)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
let benefitAmount: TeamAccountBenefitExpensesOverview['benefitAmount'] = null;
|
||||||
|
let benefitOccurrence: TeamAccountBenefitExpensesOverview['benefitOccurrence'] =
|
||||||
|
null;
|
||||||
|
if (error) {
|
||||||
|
console.warn('Failed to load team account benefit expenses overview');
|
||||||
|
} else {
|
||||||
|
benefitAmount =
|
||||||
|
data.benefit_amount as TeamAccountBenefitExpensesOverview['benefitAmount'];
|
||||||
|
benefitOccurrence =
|
||||||
|
data.benefit_occurrence as TeamAccountBenefitExpensesOverview['benefitOccurrence'];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { purchaseEntriesTotal } =
|
||||||
|
await loadCompanyPersonalAccountsBalanceEntries({ accountId: companyId });
|
||||||
|
|
||||||
|
return {
|
||||||
|
benefitAmount,
|
||||||
|
benefitOccurrence,
|
||||||
|
currentMonthUsageTotal: purchaseEntriesTotal,
|
||||||
|
managementFee: MANAGEMENT_FEE,
|
||||||
|
managementFeeTotal: MANAGEMENT_FEE * employeeCount,
|
||||||
|
total: (() => {
|
||||||
|
if (typeof benefitAmount !== 'number') {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentDate = new Date();
|
||||||
|
const createdAt = new Date(data.created_at);
|
||||||
|
const isCreatedThisYear =
|
||||||
|
createdAt.getFullYear() === currentDate.getFullYear();
|
||||||
|
if (benefitOccurrence === 'yearly') {
|
||||||
|
return benefitAmount * employeeCount;
|
||||||
|
} else if (benefitOccurrence === 'monthly') {
|
||||||
|
const monthsLeft = isCreatedThisYear
|
||||||
|
? MONTHS - createdAt.getMonth()
|
||||||
|
: MONTHS;
|
||||||
|
return benefitAmount * employeeCount * monthsLeft;
|
||||||
|
} else if (benefitOccurrence === 'quarterly') {
|
||||||
|
const quartersLeft = isCreatedThisYear
|
||||||
|
? QUARTERS - Math.ceil(createdAt.getMonth() / 3)
|
||||||
|
: QUARTERS;
|
||||||
|
return benefitAmount * employeeCount * quartersLeft;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
})(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||||
|
|
||||||
|
export interface AccountBenefitStatistics {
|
||||||
|
benefitDistributionSchedule: {
|
||||||
|
amount: number;
|
||||||
|
};
|
||||||
|
companyAccountsCount: number;
|
||||||
|
periodTotal: number;
|
||||||
|
orders: {
|
||||||
|
totalSum: number;
|
||||||
|
|
||||||
|
analysesCount: number;
|
||||||
|
analysesSum: number;
|
||||||
|
|
||||||
|
analysisPackagesCount: number;
|
||||||
|
analysisPackagesSum: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const loadCompanyPersonalAccountsBalanceEntries = async ({
|
||||||
|
accountId,
|
||||||
|
}: {
|
||||||
|
accountId: string;
|
||||||
|
}) => {
|
||||||
|
const supabase = getSupabaseServerAdminClient();
|
||||||
|
|
||||||
|
const { count, data: accountMemberships } = await supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('accounts_memberships')
|
||||||
|
.select('user_id', { count: 'exact' })
|
||||||
|
.eq('account_id', accountId)
|
||||||
|
.throwOnError();
|
||||||
|
|
||||||
|
const { data: accountBalanceEntries } = await supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('account_balance_entries')
|
||||||
|
.select('*')
|
||||||
|
.eq('is_active', true)
|
||||||
|
.in(
|
||||||
|
'account_id',
|
||||||
|
accountMemberships.map(({ user_id }) => user_id),
|
||||||
|
)
|
||||||
|
.throwOnError();
|
||||||
|
|
||||||
|
const purchaseEntries = accountBalanceEntries.filter(
|
||||||
|
({ entry_type }) => entry_type === 'purchase',
|
||||||
|
);
|
||||||
|
const analysesEntries = purchaseEntries.filter(
|
||||||
|
({ is_analysis_order }) => is_analysis_order,
|
||||||
|
);
|
||||||
|
const analysisPackagesEntries = purchaseEntries.filter(
|
||||||
|
({ is_analysis_package_order }) => is_analysis_package_order,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
accountBalanceEntries,
|
||||||
|
analysesEntries,
|
||||||
|
analysisPackagesEntries,
|
||||||
|
companyAccountsCount: count || 0,
|
||||||
|
purchaseEntries,
|
||||||
|
purchaseEntriesTotal: purchaseEntries.reduce(
|
||||||
|
(acc, { amount }) => acc + Math.abs(amount || 0),
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const loadAccountBenefitStatistics = async (
|
||||||
|
accountId: string,
|
||||||
|
): Promise<AccountBenefitStatistics> => {
|
||||||
|
const supabase = getSupabaseServerAdminClient();
|
||||||
|
|
||||||
|
const {
|
||||||
|
analysesEntries,
|
||||||
|
analysisPackagesEntries,
|
||||||
|
companyAccountsCount,
|
||||||
|
purchaseEntriesTotal,
|
||||||
|
} = await loadCompanyPersonalAccountsBalanceEntries({ accountId });
|
||||||
|
|
||||||
|
const { data: benefitDistributionSchedule } = await supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('benefit_distribution_schedule')
|
||||||
|
.select('*')
|
||||||
|
.eq('company_id', accountId)
|
||||||
|
.eq('is_active', true)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
const scheduleAmount = benefitDistributionSchedule?.benefit_amount || 0;
|
||||||
|
return {
|
||||||
|
companyAccountsCount,
|
||||||
|
benefitDistributionSchedule: {
|
||||||
|
amount: benefitDistributionSchedule?.benefit_amount || 0,
|
||||||
|
},
|
||||||
|
periodTotal: scheduleAmount * companyAccountsCount,
|
||||||
|
orders: {
|
||||||
|
totalSum: purchaseEntriesTotal,
|
||||||
|
|
||||||
|
analysesCount: analysesEntries.length,
|
||||||
|
analysesSum: analysesEntries.reduce(
|
||||||
|
(acc, { amount }) => acc + Math.abs(amount || 0),
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
|
||||||
|
analysisPackagesCount: analysisPackagesEntries.length,
|
||||||
|
analysisPackagesSum: analysisPackagesEntries.reduce(
|
||||||
|
(acc, { amount }) => acc + Math.abs(amount || 0),
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -4,6 +4,8 @@ import { Database } from '@/packages/supabase/src/database.types';
|
|||||||
import Isikukood from 'isikukood';
|
import Isikukood from 'isikukood';
|
||||||
import { Clock, TrendingUp, User } from 'lucide-react';
|
import { Clock, TrendingUp, User } from 'lucide-react';
|
||||||
|
|
||||||
|
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
bmiFromMetric,
|
bmiFromMetric,
|
||||||
getBmiBackgroundColor,
|
getBmiBackgroundColor,
|
||||||
@@ -25,10 +27,7 @@ interface AccountHealthDetailsField {
|
|||||||
|
|
||||||
export const getAccountHealthDetailsFields = (
|
export const getAccountHealthDetailsFields = (
|
||||||
memberParams: TeamAccountStatisticsProps['memberParams'],
|
memberParams: TeamAccountStatisticsProps['memberParams'],
|
||||||
bmiThresholds: Omit<
|
bmiThresholds: Omit<BmiThresholds, 'id'>[],
|
||||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
|
||||||
'id'
|
|
||||||
>[],
|
|
||||||
members: Database['medreport']['Functions']['get_account_members']['Returns'],
|
members: Database['medreport']['Functions']['get_account_members']['Returns'],
|
||||||
): AccountHealthDetailsField[] => {
|
): AccountHealthDetailsField[] => {
|
||||||
const averageWeight =
|
const averageWeight =
|
||||||
@@ -64,13 +63,13 @@ export const getAccountHealthDetailsFields = (
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
title: 'teams:healthDetails.women',
|
title: 'teams:healthDetails.women',
|
||||||
value: `${femalePercentage}% (${numberOfFemaleMembers})`,
|
value: `${femalePercentage.toFixed(0)}% (${numberOfFemaleMembers})`,
|
||||||
Icon: User,
|
Icon: User,
|
||||||
iconBg: 'bg-success',
|
iconBg: 'bg-success',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'teams:healthDetails.men',
|
title: 'teams:healthDetails.men',
|
||||||
value: `${malePercentage}% (${numberOfMaleMembers})`,
|
value: `${malePercentage.toFixed(0)}% (${numberOfMaleMembers})`,
|
||||||
Icon: User,
|
Icon: User,
|
||||||
iconBg: 'bg-success',
|
iconBg: 'bg-success',
|
||||||
},
|
},
|
||||||
@@ -82,7 +81,7 @@ export const getAccountHealthDetailsFields = (
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'teams:healthDetails.bmi',
|
title: 'teams:healthDetails.bmi',
|
||||||
value: averageBMI,
|
value: averageBMI!,
|
||||||
Icon: TrendingUp,
|
Icon: TrendingUp,
|
||||||
iconBg: getBmiBackgroundColor(bmiStatus),
|
iconBg: getBmiBackgroundColor(bmiStatus),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
import { UpdateHealthBenefitSchema } from '@/packages/billing/core/src/schema';
|
||||||
|
import {
|
||||||
|
Account,
|
||||||
|
CompanyParams,
|
||||||
|
} from '@/packages/features/accounts/src/types/accounts';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { Form } from '@kit/ui/form';
|
||||||
|
import { Spinner } from '@kit/ui/makerkit/spinner';
|
||||||
|
import { toast } from '@kit/ui/shadcn/sonner';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { cn } from '~/lib/utils';
|
||||||
|
|
||||||
|
import { updateHealthBenefit } from '../_lib/server/server-actions';
|
||||||
|
import HealthBenefitFields from './health-benefit-fields';
|
||||||
|
|
||||||
|
const HealthBenefitFormClient = ({
|
||||||
|
account,
|
||||||
|
companyParams,
|
||||||
|
}: {
|
||||||
|
account: Account;
|
||||||
|
companyParams: CompanyParams;
|
||||||
|
}) => {
|
||||||
|
const { t } = useTranslation('account');
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const [currentCompanyParams, setCurrentCompanyParams] =
|
||||||
|
useState<CompanyParams>(companyParams);
|
||||||
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
|
|
||||||
|
const form = useForm({
|
||||||
|
resolver: zodResolver(UpdateHealthBenefitSchema),
|
||||||
|
mode: 'onChange',
|
||||||
|
defaultValues: {
|
||||||
|
occurrence: currentCompanyParams.benefit_occurance || 'yearly',
|
||||||
|
amount: currentCompanyParams.benefit_amount || 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const isDirty = form.formState.isDirty;
|
||||||
|
|
||||||
|
const onSubmit = (data: { occurrence: string; amount: number }) => {
|
||||||
|
const promise = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
await updateHealthBenefit({ ...data, accountId: account.id });
|
||||||
|
setCurrentCompanyParams((prev) => ({
|
||||||
|
...prev,
|
||||||
|
benefit_amount: data.amount,
|
||||||
|
benefit_occurance: data.occurrence,
|
||||||
|
}));
|
||||||
|
} finally {
|
||||||
|
form.reset(data);
|
||||||
|
setIsLoading(false);
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
toast.promise(promise, {
|
||||||
|
success: t('account:healthBenefitForm.updateSuccess'),
|
||||||
|
error: 'error',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form {...form}>
|
||||||
|
<form
|
||||||
|
className="flex flex-col gap-6"
|
||||||
|
onSubmit={form.handleSubmit(onSubmit)}
|
||||||
|
>
|
||||||
|
<HealthBenefitFields />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="relative"
|
||||||
|
disabled={!isDirty || isLoading}
|
||||||
|
>
|
||||||
|
{isLoading && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center">
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className={cn({ invisible: isLoading })}>
|
||||||
|
<Trans i18nKey="account:saveChanges" />
|
||||||
|
</div>
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default HealthBenefitFormClient;
|
||||||
@@ -1,138 +1,73 @@
|
|||||||
'use client';
|
import {
|
||||||
|
Account,
|
||||||
import { useState } from 'react';
|
CompanyParams,
|
||||||
|
} from '@/packages/features/accounts/src/types/accounts';
|
||||||
import { UpdateHealthBenefitSchema } from '@/packages/billing/core/src/schema';
|
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import { PiggyBankIcon } from 'lucide-react';
|
import { PiggyBankIcon } from 'lucide-react';
|
||||||
import { useForm } from 'react-hook-form';
|
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
|
||||||
import { Form } from '@kit/ui/form';
|
|
||||||
import { Spinner } from '@kit/ui/makerkit/spinner';
|
|
||||||
import { Separator } from '@kit/ui/shadcn/separator';
|
import { Separator } from '@kit/ui/shadcn/separator';
|
||||||
import { toast } from '@kit/ui/shadcn/sonner';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { cn } from '~/lib/utils';
|
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
import HealthBenefitFormClient from './health-benefit-form-client';
|
||||||
import { updateHealthBenefit } from '../_lib/server/server-actions';
|
|
||||||
import HealthBenefitFields from './health-benefit-fields';
|
|
||||||
import YearlyExpensesOverview from './yearly-expenses-overview';
|
import YearlyExpensesOverview from './yearly-expenses-overview';
|
||||||
|
|
||||||
const HealthBenefitForm = ({
|
const HealthBenefitForm = async ({
|
||||||
account,
|
account,
|
||||||
companyParams,
|
companyParams,
|
||||||
employeeCount,
|
employeeCount,
|
||||||
|
expensesOverview,
|
||||||
}: {
|
}: {
|
||||||
account: Database['medreport']['Tables']['accounts']['Row'];
|
account: Account;
|
||||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
companyParams: CompanyParams;
|
||||||
employeeCount: number;
|
employeeCount: number;
|
||||||
|
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||||
}) => {
|
}) => {
|
||||||
const [currentCompanyParams, setCurrentCompanyParams] =
|
|
||||||
useState<Database['medreport']['Tables']['company_params']['Row']>(
|
|
||||||
companyParams,
|
|
||||||
);
|
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
|
||||||
const form = useForm({
|
|
||||||
resolver: zodResolver(UpdateHealthBenefitSchema),
|
|
||||||
mode: 'onChange',
|
|
||||||
defaultValues: {
|
|
||||||
occurrence: currentCompanyParams.benefit_occurance || 'yearly',
|
|
||||||
amount: currentCompanyParams.benefit_amount || 0,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const isDirty = form.formState.isDirty;
|
|
||||||
|
|
||||||
const onSubmit = (data: { occurrence: string; amount: number }) => {
|
|
||||||
const promise = async () => {
|
|
||||||
setIsLoading(true);
|
|
||||||
try {
|
|
||||||
await updateHealthBenefit({ ...data, accountId: account.id });
|
|
||||||
setCurrentCompanyParams((prev) => ({
|
|
||||||
...prev,
|
|
||||||
benefit_amount: data.amount,
|
|
||||||
benefit_occurance: data.occurrence,
|
|
||||||
}));
|
|
||||||
} finally {
|
|
||||||
form.reset(data);
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
toast.promise(promise, {
|
|
||||||
success: 'Andmed uuendatud',
|
|
||||||
error: 'error',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form {...form}>
|
<div className="flex flex-col gap-6 px-6 text-left">
|
||||||
<form
|
<div className="mt-8 flex items-center justify-between">
|
||||||
className="flex flex-col gap-6 px-6 text-left"
|
<div>
|
||||||
onSubmit={form.handleSubmit(onSubmit)}
|
<h4>
|
||||||
>
|
<Trans
|
||||||
<div className="mt-8 flex items-center justify-between">
|
i18nKey="billing:pageTitle"
|
||||||
<div>
|
values={{ companyName: account.name }}
|
||||||
<h4>
|
|
||||||
<Trans
|
|
||||||
i18nKey="billing:pageTitle"
|
|
||||||
values={{ companyName: account.name }}
|
|
||||||
/>
|
|
||||||
</h4>
|
|
||||||
<p className="text-muted-foreground text-sm">
|
|
||||||
<Trans i18nKey="billing:description" />
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="relative"
|
|
||||||
disabled={!isDirty || isLoading}
|
|
||||||
>
|
|
||||||
{isLoading && (
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center">
|
|
||||||
<Spinner />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className={cn({ invisible: isLoading })}>
|
|
||||||
<Trans i18nKey="account:saveChanges" />
|
|
||||||
</div>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-row gap-6">
|
|
||||||
<div className="border-border w-1/3 rounded-lg border">
|
|
||||||
<div className="p-6">
|
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-orange-100">
|
|
||||||
<PiggyBankIcon className="h-[32px] w-[32px] stroke-orange-400 stroke-2" />
|
|
||||||
</div>
|
|
||||||
<p className="mt-4 text-sm font-medium">
|
|
||||||
<Trans i18nKey="billing:healthBenefitForm.description" />
|
|
||||||
</p>
|
|
||||||
<p className="pt-2 text-2xl font-semibold">
|
|
||||||
{currentCompanyParams.benefit_amount || 0} €
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Separator />
|
|
||||||
|
|
||||||
<div className="p-6">
|
|
||||||
<HealthBenefitFields />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex-1">
|
|
||||||
<YearlyExpensesOverview
|
|
||||||
employeeCount={employeeCount}
|
|
||||||
companyParams={currentCompanyParams}
|
|
||||||
/>
|
/>
|
||||||
<p className="text-muted-foreground mt-2 text-sm">
|
</h4>
|
||||||
<Trans i18nKey="billing:healthBenefitForm.info" />
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col-reverse gap-6 sm:flex-row">
|
||||||
|
<div className="border-border w-full rounded-lg border sm:w-1/3">
|
||||||
|
<div className="p-6">
|
||||||
|
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-orange-100">
|
||||||
|
<PiggyBankIcon className="h-[32px] w-[32px] stroke-orange-400 stroke-2" />
|
||||||
|
</div>
|
||||||
|
<p className="mt-4 text-sm font-medium">
|
||||||
|
<Trans i18nKey="billing:healthBenefitForm.description" />
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<div className="p-6">
|
||||||
|
<HealthBenefitFormClient
|
||||||
|
account={account}
|
||||||
|
companyParams={companyParams}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
|
||||||
</Form>
|
<div className="flex-1 space-y-6">
|
||||||
|
<YearlyExpensesOverview
|
||||||
|
employeeCount={employeeCount}
|
||||||
|
expensesOverview={expensesOverview}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
<Trans i18nKey="billing:healthBenefitForm.info" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,50 +1,23 @@
|
|||||||
import { useMemo } from 'react';
|
'use client';
|
||||||
|
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { Trans } from '@kit/ui/makerkit/trans';
|
import { Trans } from '@kit/ui/makerkit/trans';
|
||||||
import { Separator } from '@kit/ui/separator';
|
import { Separator } from '@kit/ui/separator';
|
||||||
|
|
||||||
|
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
|
||||||
const YearlyExpensesOverview = ({
|
const YearlyExpensesOverview = ({
|
||||||
employeeCount = 0,
|
employeeCount = 0,
|
||||||
companyParams,
|
expensesOverview,
|
||||||
}: {
|
}: {
|
||||||
employeeCount?: number;
|
employeeCount?: number;
|
||||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||||
}) => {
|
}) => {
|
||||||
const monthlyExpensePerEmployee = useMemo(() => {
|
const {
|
||||||
if (!companyParams.benefit_amount) {
|
i18n: { language },
|
||||||
return '0.00';
|
} = useTranslation();
|
||||||
}
|
|
||||||
|
|
||||||
switch (companyParams.benefit_occurance) {
|
|
||||||
case 'yearly':
|
|
||||||
return (companyParams.benefit_amount / 12).toFixed(2);
|
|
||||||
case 'quarterly':
|
|
||||||
return (companyParams.benefit_amount / 3).toFixed(2);
|
|
||||||
case 'monthly':
|
|
||||||
return companyParams.benefit_amount.toFixed(2);
|
|
||||||
default:
|
|
||||||
return '0.00';
|
|
||||||
}
|
|
||||||
}, [companyParams]);
|
|
||||||
|
|
||||||
const maxYearlyExpensePerEmployee = useMemo(() => {
|
|
||||||
if (!companyParams.benefit_amount) {
|
|
||||||
return '0.00';
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (companyParams.benefit_occurance) {
|
|
||||||
case 'yearly':
|
|
||||||
return companyParams.benefit_amount.toFixed(2);
|
|
||||||
case 'quarterly':
|
|
||||||
return (companyParams.benefit_amount * 3).toFixed(2);
|
|
||||||
case 'monthly':
|
|
||||||
return (companyParams.benefit_amount * 12).toFixed(2);
|
|
||||||
default:
|
|
||||||
return '0.00';
|
|
||||||
}
|
|
||||||
}, [companyParams]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-border rounded-lg border p-6">
|
<div className="border-border rounded-lg border p-6">
|
||||||
@@ -53,41 +26,54 @@ const YearlyExpensesOverview = ({
|
|||||||
</h5>
|
</h5>
|
||||||
<div className="mt-5 flex justify-between">
|
<div className="mt-5 flex justify-between">
|
||||||
<p className="text-sm font-medium">
|
<p className="text-sm font-medium">
|
||||||
<Trans i18nKey="billing:expensesOverview.monthly" />
|
<Trans i18nKey="billing:expensesOverview.employeeCount" />
|
||||||
</p>
|
</p>
|
||||||
<span className="text-primary text-sm font-bold">
|
<span className="text-primary text-sm font-bold">{employeeCount}</span>
|
||||||
{monthlyExpensePerEmployee} €
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 flex justify-between">
|
<div className="mt-3 flex justify-between">
|
||||||
<p className="text-sm font-medium">
|
|
||||||
<Trans i18nKey="billing:expensesOverview.yearly" />
|
|
||||||
</p>
|
|
||||||
<span className="text-sm font-medium">
|
|
||||||
{maxYearlyExpensePerEmployee} €
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="mt-5 mb-3 flex justify-between">
|
|
||||||
<p className="text-sm font-medium">
|
<p className="text-sm font-medium">
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey="billing:expensesOverview.total"
|
i18nKey="billing:expensesOverview.managementFeeTotal"
|
||||||
values={{ employeeCount: employeeCount || 0 }}
|
values={{
|
||||||
|
managementFee: formatCurrency({
|
||||||
|
value: expensesOverview.managementFee,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
}),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</p>
|
</p>
|
||||||
<span className="text-sm font-medium">
|
<span className="text-sm font-medium">
|
||||||
{(Number(maxYearlyExpensePerEmployee) * employeeCount).toFixed(2)} €
|
{formatCurrency({
|
||||||
|
value: expensesOverview.managementFeeTotal,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 mb-4 flex justify-between">
|
||||||
|
<p className="text-sm font-medium">
|
||||||
|
<Trans i18nKey="billing:expensesOverview.currentMonthUsageTotal" />
|
||||||
|
</p>
|
||||||
|
<span className="text-sm font-medium">
|
||||||
|
{formatCurrency({
|
||||||
|
value: expensesOverview.currentMonthUsageTotal,
|
||||||
|
locale: language,
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Separator />
|
<Separator />
|
||||||
<div className="mt-4 flex justify-between">
|
<div className="mt-4 flex justify-between">
|
||||||
<p className="font-semibold">
|
<p className="font-semibold">
|
||||||
<Trans i18nKey="billing:expensesOverview.sum" />
|
<Trans i18nKey="billing:expensesOverview.total" />
|
||||||
</p>
|
</p>
|
||||||
<span className="font-semibold">
|
<span className="font-semibold">
|
||||||
{companyParams.benefit_amount
|
{formatCurrency({
|
||||||
? companyParams.benefit_amount * employeeCount
|
value: expensesOverview.total,
|
||||||
: 0}{' '}
|
locale: language,
|
||||||
€
|
currencyCode: 'EUR',
|
||||||
|
})}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { PageBody } from '@kit/ui/page';
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
|
import { loadTeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
import HealthBenefitForm from './_components/health-benefit-form';
|
import HealthBenefitForm from './_components/health-benefit-form';
|
||||||
|
|
||||||
interface TeamAccountBillingPageProps {
|
interface TeamAccountBillingPageProps {
|
||||||
@@ -27,8 +28,14 @@ async function TeamAccountBillingPage({ params }: TeamAccountBillingPageProps) {
|
|||||||
const api = createTeamAccountsApi(client);
|
const api = createTeamAccountsApi(client);
|
||||||
|
|
||||||
const account = await api.getTeamAccount(accountSlug);
|
const account = await api.getTeamAccount(accountSlug);
|
||||||
const companyParams = await api.getTeamAccountParams(account.id);
|
|
||||||
const { members } = await api.getMembers(accountSlug);
|
const { members } = await api.getMembers(accountSlug);
|
||||||
|
const [expensesOverview, companyParams] = await Promise.all([
|
||||||
|
loadTeamAccountBenefitExpensesOverview({
|
||||||
|
companyId: account.id,
|
||||||
|
employeeCount: members.length,
|
||||||
|
}),
|
||||||
|
api.getTeamAccountParams(account.id),
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageBody>
|
<PageBody>
|
||||||
@@ -36,6 +43,7 @@ async function TeamAccountBillingPage({ params }: TeamAccountBillingPageProps) {
|
|||||||
account={account}
|
account={account}
|
||||||
companyParams={companyParams}
|
companyParams={companyParams}
|
||||||
employeeCount={members.length}
|
employeeCount={members.length}
|
||||||
|
expensesOverview={expensesOverview}
|
||||||
/>
|
/>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import 'server-only';
|
|||||||
|
|
||||||
import { SupabaseClient } from '@supabase/supabase-js';
|
import { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { Database } from '@/packages/supabase/src/database.types';
|
||||||
|
|
||||||
import { loadTeamWorkspace } from '~/home/[account]/_lib/server/team-account-workspace.loader';
|
import { loadTeamWorkspace } from '~/home/[account]/_lib/server/team-account-workspace.loader';
|
||||||
@@ -15,11 +16,16 @@ export async function loadMembersPageData(
|
|||||||
client: SupabaseClient<Database>,
|
client: SupabaseClient<Database>,
|
||||||
slug: string,
|
slug: string,
|
||||||
) {
|
) {
|
||||||
|
const workspace = await loadTeamWorkspace(slug);
|
||||||
return Promise.all([
|
return Promise.all([
|
||||||
loadAccountMembers(client, slug),
|
loadAccountMembers(client, slug),
|
||||||
loadInvitations(client, slug),
|
loadInvitations(client, slug),
|
||||||
canAddMember,
|
canAddMember,
|
||||||
loadTeamWorkspace(slug),
|
workspace,
|
||||||
|
loadAccountMembersBenefitsUsage(
|
||||||
|
getSupabaseServerAdminClient(),
|
||||||
|
workspace.account.id,
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +66,29 @@ async function loadAccountMembers(
|
|||||||
return data ?? [];
|
return data ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function loadAccountMembersBenefitsUsage(
|
||||||
|
client: SupabaseClient<Database>,
|
||||||
|
accountId: string,
|
||||||
|
): Promise<
|
||||||
|
{
|
||||||
|
personal_account_id: string;
|
||||||
|
benefit_amount: number;
|
||||||
|
}[]
|
||||||
|
> {
|
||||||
|
const { data, error } = await client
|
||||||
|
.schema('medreport')
|
||||||
|
.rpc('get_benefits_usages_for_company_members', {
|
||||||
|
p_account_id: accountId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Failed to load account members benefits usage', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return data ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load account invitations
|
* Load account invitations
|
||||||
* @param client
|
* @param client
|
||||||
|
|||||||
@@ -42,8 +42,13 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
|||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
const slug = (await params).account;
|
const slug = (await params).account;
|
||||||
|
|
||||||
const [members, invitations, canAddMember, { user, account }] =
|
const [
|
||||||
await loadMembersPageData(client, slug);
|
members,
|
||||||
|
invitations,
|
||||||
|
canAddMember,
|
||||||
|
{ user, account },
|
||||||
|
membersBenefitsUsage,
|
||||||
|
] = await loadMembersPageData(client, slug);
|
||||||
|
|
||||||
const canManageRoles = account.permissions.includes('roles.manage');
|
const canManageRoles = account.permissions.includes('roles.manage');
|
||||||
const canManageInvitations = account.permissions.includes('invites.manage');
|
const canManageInvitations = account.permissions.includes('invites.manage');
|
||||||
@@ -54,7 +59,7 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<TeamAccountLayoutPageHeader
|
<TeamAccountLayoutPageHeader
|
||||||
title={<Trans i18nKey={'common:routes.members'} />}
|
title={<Trans i18nKey={'common:routes.companyMembers'} />}
|
||||||
description={
|
description={
|
||||||
<AppBreadcrumbs values={{ [account.slug]: account.name }} />
|
<AppBreadcrumbs values={{ [account.slug]: account.name }} />
|
||||||
}
|
}
|
||||||
@@ -98,6 +103,7 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
|||||||
members={members}
|
members={members}
|
||||||
isPrimaryOwner={isPrimaryOwner}
|
isPrimaryOwner={isPrimaryOwner}
|
||||||
canManageRoles={canManageRoles}
|
canManageRoles={canManageRoles}
|
||||||
|
membersBenefitsUsage={membersBenefitsUsage}
|
||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import {
|
|||||||
} from '~/lib/services/audit/pageView.service';
|
} from '~/lib/services/audit/pageView.service';
|
||||||
|
|
||||||
import { Dashboard } from './_components/dashboard';
|
import { Dashboard } from './_components/dashboard';
|
||||||
|
import { loadTeamAccountBenefitExpensesOverview } from './_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
import { loadAccountBenefitStatistics } from './_lib/server/load-team-account-benefit-statistics';
|
||||||
|
|
||||||
interface TeamAccountHomePageProps {
|
interface TeamAccountHomePageProps {
|
||||||
params: Promise<{ account: string }>;
|
params: Promise<{ account: string }>;
|
||||||
@@ -39,8 +41,14 @@ function TeamAccountHomePage({ params }: TeamAccountHomePageProps) {
|
|||||||
const teamAccount = use(teamAccountsApi.getTeamAccount(account));
|
const teamAccount = use(teamAccountsApi.getTeamAccount(account));
|
||||||
const { memberParams, members } = use(teamAccountsApi.getMembers(account));
|
const { memberParams, members } = use(teamAccountsApi.getMembers(account));
|
||||||
const bmiThresholds = use(userAnalysesApi.fetchBmiThresholds());
|
const bmiThresholds = use(userAnalysesApi.fetchBmiThresholds());
|
||||||
const companyParams = use(
|
const accountBenefitStatistics = use(
|
||||||
teamAccountsApi.getTeamAccountParams(teamAccount.id),
|
loadAccountBenefitStatistics(teamAccount.id),
|
||||||
|
);
|
||||||
|
const expensesOverview = use(
|
||||||
|
loadTeamAccountBenefitExpensesOverview({
|
||||||
|
companyId: teamAccount.id,
|
||||||
|
employeeCount: members.length,
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
use(
|
use(
|
||||||
@@ -57,7 +65,8 @@ function TeamAccountHomePage({ params }: TeamAccountHomePageProps) {
|
|||||||
memberParams={memberParams}
|
memberParams={memberParams}
|
||||||
bmiThresholds={bmiThresholds}
|
bmiThresholds={bmiThresholds}
|
||||||
members={members}
|
members={members}
|
||||||
companyParams={companyParams}
|
accountBenefitStatistics={accountBenefitStatistics}
|
||||||
|
expensesOverview={expensesOverview}
|
||||||
/>
|
/>
|
||||||
</PageBody>
|
</PageBody>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { Trans } from '@kit/ui/trans';
|
|||||||
|
|
||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
import { toTitleCase } from '~/lib/utils';
|
||||||
|
|
||||||
interface JoinTeamAccountPageProps {
|
interface JoinTeamAccountPageProps {
|
||||||
searchParams: Promise<{
|
searchParams: Promise<{
|
||||||
@@ -110,12 +111,12 @@ async function JoinTeamAccountPage(props: JoinTeamAccountPageProps) {
|
|||||||
// once the user accepts the invitation, we redirect them to the account home page
|
// once the user accepts the invitation, we redirect them to the account home page
|
||||||
const membershipConfirmation = pathsConfig.auth.membershipConfirmation;
|
const membershipConfirmation = pathsConfig.auth.membershipConfirmation;
|
||||||
|
|
||||||
const email = auth.data.email ?? '';
|
const fullName = toTitleCase(auth.data.user_metadata.full_name ?? '');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthLayoutShell Logo={AppLogo}>
|
<AuthLayoutShell Logo={AppLogo}>
|
||||||
<AcceptInvitationContainer
|
<AcceptInvitationContainer
|
||||||
email={email}
|
fullName={fullName || auth.data.email || ''}
|
||||||
inviteToken={token}
|
inviteToken={token}
|
||||||
invitation={invitation}
|
invitation={invitation}
|
||||||
paths={{
|
paths={{
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export enum NotificationAction {
|
|||||||
PATIENT_ORDER_PROCESSING = 'PATIENT_ORDER_PROCESSING',
|
PATIENT_ORDER_PROCESSING = 'PATIENT_ORDER_PROCESSING',
|
||||||
PATIENT_FIRST_RESULTS_RECEIVED = 'PATIENT_FIRST_RESULTS_RECEIVED',
|
PATIENT_FIRST_RESULTS_RECEIVED = 'PATIENT_FIRST_RESULTS_RECEIVED',
|
||||||
PATIENT_FULL_RESULTS_RECEIVED = 'PATIENT_FULL_RESULTS_RECEIVED',
|
PATIENT_FULL_RESULTS_RECEIVED = 'PATIENT_FULL_RESULTS_RECEIVED',
|
||||||
|
TTO_ORDER_CONFIRMATION = 'TTO_ORDER_CONFIRMATION',
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createNotificationLog = async ({
|
export const createNotificationLog = async ({
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ import {
|
|||||||
upsertAnalysisResponseElement,
|
upsertAnalysisResponseElement,
|
||||||
} from '../analysis-order.service';
|
} from '../analysis-order.service';
|
||||||
import { logMedipostDispatch } from '../audit.service';
|
import { logMedipostDispatch } from '../audit.service';
|
||||||
import { getAnalysisOrder, updateAnalysisOrderStatus } from '../order.service';
|
import { getAnalysisOrder } from '../order.service';
|
||||||
import { parseXML } from '../util/xml.service';
|
import { parseXML } from '../util/xml.service';
|
||||||
import { MedipostValidationError } from './MedipostValidationError';
|
import { MedipostValidationError } from './MedipostValidationError';
|
||||||
import {
|
import {
|
||||||
@@ -43,7 +43,9 @@ const USER = process.env.MEDIPOST_USER!;
|
|||||||
const PASSWORD = process.env.MEDIPOST_PASSWORD!;
|
const PASSWORD = process.env.MEDIPOST_PASSWORD!;
|
||||||
const RECIPIENT = process.env.MEDIPOST_RECIPIENT!;
|
const RECIPIENT = process.env.MEDIPOST_RECIPIENT!;
|
||||||
|
|
||||||
const IS_ENABLED_DELETE_PRIVATE_MESSAGE = false as boolean;
|
const IS_ENABLED_DELETE_PRIVATE_MESSAGE =
|
||||||
|
process.env.MEDIPOST_ENABLE_DELETE_RESPONSE_PRIVATE_MESSAGE_ON_READ ===
|
||||||
|
'true';
|
||||||
|
|
||||||
export async function getLatestPrivateMessageListItem({
|
export async function getLatestPrivateMessageListItem({
|
||||||
excludedMessageIds,
|
excludedMessageIds,
|
||||||
@@ -430,14 +432,21 @@ export async function readPrivateMessageResponse({
|
|||||||
medipostExternalOrderId,
|
medipostExternalOrderId,
|
||||||
});
|
});
|
||||||
if (status.isPartial) {
|
if (status.isPartial) {
|
||||||
await updateAnalysisOrderStatus({
|
await createUserAnalysesApi(
|
||||||
|
getSupabaseServerAdminClient(),
|
||||||
|
).updateAnalysisOrderStatus({
|
||||||
medusaOrderId,
|
medusaOrderId,
|
||||||
orderStatus: 'PARTIAL_ANALYSIS_RESPONSE',
|
orderStatus: 'PARTIAL_ANALYSIS_RESPONSE',
|
||||||
});
|
});
|
||||||
|
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
||||||
|
await deletePrivateMessage(privateMessageId);
|
||||||
|
}
|
||||||
hasAnalysisResponse = true;
|
hasAnalysisResponse = true;
|
||||||
hasPartialAnalysisResponse = true;
|
hasPartialAnalysisResponse = true;
|
||||||
} else if (status.isCompleted) {
|
} else if (status.isCompleted) {
|
||||||
await updateAnalysisOrderStatus({
|
await createUserAnalysesApi(
|
||||||
|
getSupabaseServerAdminClient(),
|
||||||
|
).updateAnalysisOrderStatus({
|
||||||
medusaOrderId,
|
medusaOrderId,
|
||||||
orderStatus: 'FULL_ANALYSIS_RESPONSE',
|
orderStatus: 'FULL_ANALYSIS_RESPONSE',
|
||||||
});
|
});
|
||||||
@@ -622,5 +631,10 @@ export async function sendOrderToMedipost({
|
|||||||
hasAnalysisResults: false,
|
hasAnalysisResults: false,
|
||||||
medusaOrderId,
|
medusaOrderId,
|
||||||
});
|
});
|
||||||
await updateAnalysisOrderStatus({ medusaOrderId, orderStatus: 'PROCESSING' });
|
await createUserAnalysesApi(
|
||||||
|
getSupabaseServerAdminClient(),
|
||||||
|
).updateAnalysisOrderStatus({
|
||||||
|
medusaOrderId,
|
||||||
|
orderStatus: 'PROCESSING',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,8 +31,11 @@ const env = () =>
|
|||||||
.min(1),
|
.min(1),
|
||||||
})
|
})
|
||||||
.parse({
|
.parse({
|
||||||
|
// Use for local testing
|
||||||
medusaBackendPublicUrl: 'http://webhook.site:3000',
|
medusaBackendPublicUrl: 'http://webhook.site:3000',
|
||||||
siteUrl: 'http://webhook.site:3000',
|
siteUrl: 'http://webhook.site:3000',
|
||||||
|
// medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!,
|
||||||
|
// siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function handleAddToCart({
|
export async function handleAddToCart({
|
||||||
@@ -42,6 +45,10 @@ export async function handleAddToCart({
|
|||||||
selectedVariant: Pick<StoreProductVariant, 'id'>;
|
selectedVariant: Pick<StoreProductVariant, 'id'>;
|
||||||
countryCode: string;
|
countryCode: string;
|
||||||
}) {
|
}) {
|
||||||
|
try {
|
||||||
|
} catch (e) {
|
||||||
|
console.error('medusa card error: ', e);
|
||||||
|
}
|
||||||
const { account } = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error('Account not found');
|
throw new Error('Account not found');
|
||||||
@@ -85,9 +92,15 @@ export async function handleDeleteCartItem({ lineId }: { lineId: string }) {
|
|||||||
export async function handleNavigateToPayment({
|
export async function handleNavigateToPayment({
|
||||||
language,
|
language,
|
||||||
paymentSessionId,
|
paymentSessionId,
|
||||||
|
amount,
|
||||||
|
currencyCode,
|
||||||
|
cartId,
|
||||||
}: {
|
}: {
|
||||||
language: string;
|
language: string;
|
||||||
paymentSessionId: string;
|
paymentSessionId: string;
|
||||||
|
amount: number;
|
||||||
|
currencyCode: string;
|
||||||
|
cartId: string;
|
||||||
}) {
|
}) {
|
||||||
const { account } = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
@@ -130,11 +143,11 @@ export async function handleNavigateToPayment({
|
|||||||
await new MontonioOrderHandlerService().getMontonioPaymentLink({
|
await new MontonioOrderHandlerService().getMontonioPaymentLink({
|
||||||
notificationUrl: `${env().medusaBackendPublicUrl}/hooks/payment/montonio_montonio`,
|
notificationUrl: `${env().medusaBackendPublicUrl}/hooks/payment/montonio_montonio`,
|
||||||
returnUrl: `${env().siteUrl}/home/cart/montonio-callback`,
|
returnUrl: `${env().siteUrl}/home/cart/montonio-callback`,
|
||||||
amount: cart.total,
|
amount,
|
||||||
currency: cart.currency_code.toUpperCase(),
|
currency: currencyCode.toUpperCase(),
|
||||||
description: `Order from Medreport`,
|
description: `Order from Medreport`,
|
||||||
locale: language,
|
locale: language,
|
||||||
merchantReference: `${account.id}:${paymentSessionId}:${cart.id}`,
|
merchantReference: `${account.id}:${paymentSessionId}:${cartId}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
await createCartEntriesLog({
|
await createCartEntriesLog({
|
||||||
|
|||||||
@@ -51,48 +51,6 @@ export async function createAnalysisOrder({
|
|||||||
return orderResult.data.id;
|
return orderResult.data.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateAnalysisOrder({
|
|
||||||
orderId,
|
|
||||||
orderStatus,
|
|
||||||
}: {
|
|
||||||
orderId: number;
|
|
||||||
orderStatus: Tables<{ schema: 'medreport' }, 'analysis_orders'>['status'];
|
|
||||||
}) {
|
|
||||||
console.info(`Updating order id=${orderId} status=${orderStatus}`);
|
|
||||||
await getSupabaseServerAdminClient()
|
|
||||||
.schema('medreport')
|
|
||||||
.from('analysis_orders')
|
|
||||||
.update({
|
|
||||||
status: orderStatus,
|
|
||||||
})
|
|
||||||
.eq('id', orderId)
|
|
||||||
.throwOnError();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateAnalysisOrderStatus({
|
|
||||||
orderId,
|
|
||||||
medusaOrderId,
|
|
||||||
orderStatus,
|
|
||||||
}: {
|
|
||||||
orderId?: number;
|
|
||||||
medusaOrderId?: string;
|
|
||||||
orderStatus: Tables<{ schema: 'medreport' }, 'analysis_orders'>['status'];
|
|
||||||
}) {
|
|
||||||
const orderIdParam = orderId;
|
|
||||||
const medusaOrderIdParam = medusaOrderId;
|
|
||||||
if (!orderIdParam && !medusaOrderIdParam) {
|
|
||||||
throw new Error('Either orderId or medusaOrderId must be provided');
|
|
||||||
}
|
|
||||||
await getSupabaseServerAdminClient()
|
|
||||||
.schema('medreport')
|
|
||||||
.rpc('update_analysis_order_status', {
|
|
||||||
order_id: orderIdParam ?? -1,
|
|
||||||
status_param: orderStatus,
|
|
||||||
medusa_order_id_param: medusaOrderIdParam ?? '',
|
|
||||||
})
|
|
||||||
.throwOnError();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAnalysisOrder({
|
export async function getAnalysisOrder({
|
||||||
medusaOrderId,
|
medusaOrderId,
|
||||||
analysisOrderId,
|
analysisOrderId,
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { Database } from '@/packages/supabase/src/database.types';
|
|
||||||
import { type ClassValue, clsx } from 'clsx';
|
import { type ClassValue, clsx } from 'clsx';
|
||||||
import Isikukood, { Gender } from 'isikukood';
|
import Isikukood, { Gender } from 'isikukood';
|
||||||
import { twMerge } from 'tailwind-merge';
|
import { twMerge } from 'tailwind-merge';
|
||||||
|
|
||||||
|
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||||
|
|
||||||
import { BmiCategory } from './types/bmi';
|
import { BmiCategory } from './types/bmi';
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
@@ -45,10 +46,7 @@ export const bmiFromMetric = (kg: number, cm: number) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function getBmiStatus(
|
export function getBmiStatus(
|
||||||
thresholds: Omit<
|
thresholds: Omit<BmiThresholds, 'id'>[],
|
||||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
|
||||||
'id'
|
|
||||||
>[],
|
|
||||||
params: { age: number; height: number; weight: number },
|
params: { age: number; height: number; weight: number },
|
||||||
): BmiCategory | null {
|
): BmiCategory | null {
|
||||||
const age = params.age;
|
const age = params.age;
|
||||||
|
|||||||
@@ -37,10 +37,11 @@ interface MontonioOrderToken {
|
|||||||
exp: number;
|
exp: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { secretKey } = MontonioServerEnvSchema.parse({
|
const env = () =>
|
||||||
apiUrl: process.env.MONTONIO_API_URL,
|
MontonioServerEnvSchema.parse({
|
||||||
secretKey: process.env.MONTONIO_SECRET_KEY,
|
apiUrl: process.env.MONTONIO_API_URL,
|
||||||
});
|
secretKey: process.env.MONTONIO_SECRET_KEY,
|
||||||
|
});
|
||||||
|
|
||||||
export class MontonioWebhookHandlerService
|
export class MontonioWebhookHandlerService
|
||||||
implements BillingWebhookHandlerService
|
implements BillingWebhookHandlerService
|
||||||
@@ -50,6 +51,7 @@ export class MontonioWebhookHandlerService
|
|||||||
|
|
||||||
async verifyWebhookSignature(request: Request) {
|
async verifyWebhookSignature(request: Request) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
|
const { secretKey } = env();
|
||||||
|
|
||||||
let token: string;
|
let token: string;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -48,6 +48,12 @@ class DatabaseWebhookRouterService {
|
|||||||
return this.handleAnalysisOrdersWebhook(payload);
|
return this.handleAnalysisOrdersWebhook(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'connected_online_reservation': {
|
||||||
|
const payload = body as RecordChange<typeof body.table>;
|
||||||
|
|
||||||
|
return this.handleTtoOrdersWebhook(payload);
|
||||||
|
}
|
||||||
|
|
||||||
default: {
|
default: {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -100,13 +106,27 @@ class DatabaseWebhookRouterService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { createAnalysisOrderWebhooksService } = await import(
|
const { createOrderWebhooksService } = await import(
|
||||||
'@kit/notifications/webhooks/analysis-order-notifications.service'
|
'@kit/notifications/webhooks/order-notifications.service'
|
||||||
);
|
);
|
||||||
|
|
||||||
const service = createAnalysisOrderWebhooksService();
|
const service = createOrderWebhooksService();
|
||||||
|
|
||||||
return service.handleStatusChangeWebhook(record);
|
return service.handleStatusChangeWebhook(record);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async handleTtoOrdersWebhook(
|
||||||
|
body: RecordChange<'connected_online_reservation'>,
|
||||||
|
) {
|
||||||
|
if (body.type === 'UPDATE' && body.record) {
|
||||||
|
const { createOrderWebhooksService } = await import(
|
||||||
|
'@kit/notifications/webhooks/order-notifications.service'
|
||||||
|
);
|
||||||
|
|
||||||
|
const service = createOrderWebhooksService();
|
||||||
|
|
||||||
|
return service.handleTtoReservationConfirmationWebhook(body.record);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,17 +4,20 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "git clean -xdf .turbo node_modules",
|
"clean": "git clean -xdf .turbo node_modules",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit",
|
||||||
|
"email:dev": "email dev --dir src/emails --port 3001"
|
||||||
},
|
},
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts"
|
".": "./src/index.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@react-email/components": "0.0.41"
|
"@react-email/components": "0.0.41",
|
||||||
|
"react-email": "4.2.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@kit/i18n": "workspace:*",
|
"@kit/i18n": "workspace:*",
|
||||||
"@kit/tsconfig": "workspace:*"
|
"@kit/tsconfig": "workspace:*",
|
||||||
|
"@react-email/preview-server": "4.2.12"
|
||||||
},
|
},
|
||||||
"typesVersions": {
|
"typesVersions": {
|
||||||
"*": {
|
"*": {
|
||||||
|
|||||||
@@ -6,22 +6,28 @@ import { EmailFooter } from './footer';
|
|||||||
export default function CommonFooter({ t }: { t: TFunction }) {
|
export default function CommonFooter({ t }: { t: TFunction }) {
|
||||||
const namespace = 'common';
|
const namespace = 'common';
|
||||||
|
|
||||||
const lines = [
|
|
||||||
t(`${namespace}:footer.lines1`),
|
|
||||||
t(`${namespace}:footer.lines2`),
|
|
||||||
t(`${namespace}:footer.lines3`),
|
|
||||||
t(`${namespace}:footer.lines4`),
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<EmailFooter>
|
<EmailFooter>
|
||||||
{lines.map((line, index) => (
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
<Text
|
{t(`${namespace}:footer.title`)}
|
||||||
key={index}
|
</Text>
|
||||||
className="text-[16px] leading-[24px] text-[#242424]"
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
dangerouslySetInnerHTML={{ __html: line }}
|
{t(`${namespace}:footer.emailField`)}{' '}
|
||||||
/>
|
<a href={`mailto:${t(`${namespace}:footer.title`)}`}>
|
||||||
))}
|
{t(`${namespace}:footer.email`)}
|
||||||
|
</a>
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:footer.phoneField`)}{' '}
|
||||||
|
<a href={`tel:${t(`${namespace}:footer.phone`)}`}>
|
||||||
|
{t(`${namespace}:footer.phone`)}
|
||||||
|
</a>
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
<a href={`https://${t(`${namespace}:footer.website`)}`}>
|
||||||
|
{t(`${namespace}:footer.website`)}
|
||||||
|
</a>
|
||||||
|
</Text>
|
||||||
</EmailFooter>
|
</EmailFooter>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { Container, Text } from '@react-email/components';
|
import { Container, Section } from '@react-email/components';
|
||||||
|
|
||||||
export function EmailFooter(props: React.PropsWithChildren) {
|
export function EmailFooter(props: React.PropsWithChildren) {
|
||||||
return (
|
return (
|
||||||
<Container className="mt-[24px]">
|
<Container className="mt-[24px]">
|
||||||
<Text className="px-4 text-[12px] leading-[20px] text-gray-300">
|
<Section className="px-4 text-[12px] leading-[20px] text-gray-300">
|
||||||
{props.children}
|
{props.children}
|
||||||
</Text>
|
</Section>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
8
packages/email-templates/src/emails/email.tsx
Normal file
8
packages/email-templates/src/emails/email.tsx
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
const Email = () => {
|
||||||
|
return <div>Email</div>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Email;
|
||||||
|
Email.PreviewProps = {};
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Head,
|
||||||
|
Html,
|
||||||
|
Link,
|
||||||
|
Preview,
|
||||||
|
Tailwind,
|
||||||
|
Text,
|
||||||
|
render,
|
||||||
|
} from '@react-email/components';
|
||||||
|
|
||||||
|
import { BodyStyle } from '../components/body-style';
|
||||||
|
import CommonFooter from '../components/common-footer';
|
||||||
|
import { EmailContent } from '../components/content';
|
||||||
|
import { EmailHeader } from '../components/header';
|
||||||
|
import { EmailHeading } from '../components/heading';
|
||||||
|
import { EmailWrapper } from '../components/wrapper';
|
||||||
|
import { initializeEmailI18n } from '../lib/i18n';
|
||||||
|
|
||||||
|
export async function renderTtoReservationConfirmationEmail({
|
||||||
|
language,
|
||||||
|
recipientName,
|
||||||
|
startTime,
|
||||||
|
orderName,
|
||||||
|
locationName,
|
||||||
|
locationAddress,
|
||||||
|
orderId,
|
||||||
|
serviceProviderName,
|
||||||
|
serviceProviderEmail,
|
||||||
|
serviceProviderPhone,
|
||||||
|
}: {
|
||||||
|
language: string;
|
||||||
|
recipientName: string;
|
||||||
|
startTime: string;
|
||||||
|
orderName: string;
|
||||||
|
locationName?: string;
|
||||||
|
locationAddress?: string | null;
|
||||||
|
orderId: string;
|
||||||
|
serviceProviderName?: string;
|
||||||
|
serviceProviderEmail?: string | null;
|
||||||
|
serviceProviderPhone?: string | null;
|
||||||
|
}) {
|
||||||
|
const namespace = 'tto-reservation-confirmation-email';
|
||||||
|
|
||||||
|
const { t } = await initializeEmailI18n({
|
||||||
|
language,
|
||||||
|
namespace: [namespace, 'common'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const previewText = t(`${namespace}:previewText`, {
|
||||||
|
reservation: orderName,
|
||||||
|
});
|
||||||
|
|
||||||
|
const subject = t(`${namespace}:subject`, {
|
||||||
|
reservation: orderName,
|
||||||
|
});
|
||||||
|
|
||||||
|
const email = (
|
||||||
|
<Html>
|
||||||
|
<Head>
|
||||||
|
<BodyStyle />
|
||||||
|
</Head>
|
||||||
|
|
||||||
|
<Preview>{previewText}</Preview>
|
||||||
|
|
||||||
|
<Tailwind>
|
||||||
|
<Body>
|
||||||
|
<EmailWrapper>
|
||||||
|
<EmailContent>
|
||||||
|
<EmailHeader>
|
||||||
|
<EmailHeading>{previewText}</EmailHeading>
|
||||||
|
</EmailHeader>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:helloName`, { name: recipientName })}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:thankYou`)}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{orderName}, {new Date(startTime).toLocaleString()},{' '}
|
||||||
|
{locationAddress}, {locationName}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
<Link
|
||||||
|
href={`${process.env.NEXT_PUBLIC_SITE_URL}/home/order/${orderId}`}
|
||||||
|
>
|
||||||
|
{t(`${namespace}:viewOrder`)}
|
||||||
|
</Link>
|
||||||
|
</Text>
|
||||||
|
<Text className="mt-10 text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{serviceProviderName}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:customerSupport`)}
|
||||||
|
<Link href={`tel:${serviceProviderPhone})}`}>
|
||||||
|
{serviceProviderPhone}
|
||||||
|
</Link>
|
||||||
|
</Text>
|
||||||
|
<Link href={`mailto:${serviceProviderEmail}`}>
|
||||||
|
{serviceProviderEmail}
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<CommonFooter t={t} />
|
||||||
|
</EmailContent>
|
||||||
|
</EmailWrapper>
|
||||||
|
</Body>
|
||||||
|
</Tailwind>
|
||||||
|
</Html>
|
||||||
|
);
|
||||||
|
|
||||||
|
const html = await render(email);
|
||||||
|
|
||||||
|
return {
|
||||||
|
html,
|
||||||
|
subject,
|
||||||
|
email,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const PreviewEmail = async () => {
|
||||||
|
const { email } = await renderTtoReservationConfirmationEmail({
|
||||||
|
language: 'et',
|
||||||
|
recipientName: 'John Doe',
|
||||||
|
startTime: '2025-09-27 05:45:00+00',
|
||||||
|
orderName: 'Hambaarst',
|
||||||
|
locationName: 'Tallinn',
|
||||||
|
locationAddress: 'Põhja puiestee, 2/3A',
|
||||||
|
orderId: '123123',
|
||||||
|
serviceProviderName: 'Dentas OÜ',
|
||||||
|
serviceProviderEmail: 'email@example.ee',
|
||||||
|
serviceProviderPhone: '+372111111',
|
||||||
|
});
|
||||||
|
return email;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PreviewEmail;
|
||||||
|
PreviewEmail.PreviewProps = {};
|
||||||
@@ -11,3 +11,4 @@ export * from './emails/order-processing.email';
|
|||||||
export * from './emails/patient-first-results-received.email';
|
export * from './emails/patient-first-results-received.email';
|
||||||
export * from './emails/patient-full-results-received.email';
|
export * from './emails/patient-full-results-received.email';
|
||||||
export * from './emails/book-time-failed.email';
|
export * from './emails/book-time-failed.email';
|
||||||
|
export * from './emails/tto-reservation-confirmation.email';
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"previewText": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"subject": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"helloName": "Hello, {{name}}!",
|
||||||
|
"thankYou": "Thank you for your order!",
|
||||||
|
"viewOrder": "See booking",
|
||||||
|
"customerSupport": "Customer support: "
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
{
|
{
|
||||||
"footer": {
|
"footer": {
|
||||||
"lines1": "MedReport",
|
"title": "MedReport",
|
||||||
"lines2": "E-mail: <a href=\"mailto:info@medreport.ee\">info@medreport.ee</a>",
|
"emailField": "E-mail:",
|
||||||
"lines3": "Klienditugi: <a href=\"tel:+37258871517\">+372 5887 1517</a>",
|
"email": "info@medreport.ee",
|
||||||
"lines4": "<a href=\"https://www.medreport.ee\">www.medreport.ee</a>"
|
"phoneField": "Klienditugi:",
|
||||||
|
"phone": "+372 5887 1517",
|
||||||
|
"website": "www.medreport.ee"
|
||||||
},
|
},
|
||||||
"helloName": "Tere, {{name}}",
|
"helloName": "Tere, {{name}}",
|
||||||
"hello": "Tere"
|
"hello": "Tere"
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"previewText": "Teie broneering on kinnitatud! - {{reservation}}",
|
||||||
|
"subject": "Teie broneering on kinnitatud! - {{reservation}}",
|
||||||
|
"helloName": "Tere, {{name}}!",
|
||||||
|
"thankYou": "Täname tellimuse eest!",
|
||||||
|
"viewOrder": "Vaata broneeringut",
|
||||||
|
"customerSupport": "Klienditugi: "
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"previewText": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"subject": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"helloName": "Hello, {{name}}!",
|
||||||
|
"thankYou": "Thank you for your order!",
|
||||||
|
"viewOrder": "See booking",
|
||||||
|
"customerSupport": "Customer support: "
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
"./personal-account-settings": "./src/components/personal-account-settings/index.ts",
|
"./personal-account-settings": "./src/components/personal-account-settings/index.ts",
|
||||||
"./components": "./src/components/index.ts",
|
"./components": "./src/components/index.ts",
|
||||||
"./hooks/*": "./src/hooks/*.ts",
|
"./hooks/*": "./src/hooks/*.ts",
|
||||||
|
"./services/*": "./src/server/services/*.ts",
|
||||||
"./api": "./src/server/api.ts",
|
"./api": "./src/server/api.ts",
|
||||||
"./types/*": "./src/types/*.ts"
|
"./types/*": "./src/types/*.ts"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
|
||||||
|
import type { AccountBalanceEntry } from '../../types/account-balance-entry';
|
||||||
|
|
||||||
|
export type AccountBalanceSummary = {
|
||||||
|
totalBalance: number;
|
||||||
|
expiringSoon: number;
|
||||||
|
recentEntries: AccountBalanceEntry[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export class AccountBalanceService {
|
||||||
|
private supabase: ReturnType<typeof getSupabaseServerClient>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.supabase = getSupabaseServerClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current balance for a specific account
|
||||||
|
*/
|
||||||
|
async getAccountBalance(accountId: string): Promise<number> {
|
||||||
|
const { data, error } = await this.supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.rpc('get_account_balance', {
|
||||||
|
p_account_id: accountId,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error getting account balance:', error);
|
||||||
|
throw new Error('Failed to get account balance');
|
||||||
|
}
|
||||||
|
|
||||||
|
return data || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get balance entries for an account with pagination
|
||||||
|
*/
|
||||||
|
async getAccountBalanceEntries(
|
||||||
|
accountId: string,
|
||||||
|
options: {
|
||||||
|
limit?: number;
|
||||||
|
offset?: number;
|
||||||
|
entryType?: string;
|
||||||
|
includeInactive?: boolean;
|
||||||
|
} = {},
|
||||||
|
): Promise<{
|
||||||
|
entries: AccountBalanceEntry[];
|
||||||
|
total: number;
|
||||||
|
}> {
|
||||||
|
const {
|
||||||
|
limit = 50,
|
||||||
|
offset = 0,
|
||||||
|
entryType,
|
||||||
|
includeInactive = false,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
let query = this.supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('account_balance_entries')
|
||||||
|
.select('*', { count: 'exact' })
|
||||||
|
.eq('account_id', accountId)
|
||||||
|
.order('created_at', { ascending: false })
|
||||||
|
.range(offset, offset + limit - 1);
|
||||||
|
|
||||||
|
if (!includeInactive) {
|
||||||
|
query = query.eq('is_active', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entryType) {
|
||||||
|
query = query.eq('entry_type', entryType);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error getting account balance entries:', error);
|
||||||
|
throw new Error('Failed to get account balance entries');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
entries: data || [],
|
||||||
|
total: count || 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get balance summary for dashboard display
|
||||||
|
*/
|
||||||
|
async getBalanceSummary(accountId: string): Promise<AccountBalanceSummary> {
|
||||||
|
const [balance, entries] = await Promise.all([
|
||||||
|
this.getAccountBalance(accountId),
|
||||||
|
this.getAccountBalanceEntries(accountId, { limit: 5 }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Calculate expiring balance (next 30 days)
|
||||||
|
const thirtyDaysFromNow = new Date();
|
||||||
|
thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30);
|
||||||
|
|
||||||
|
const { data: expiringData, error: expiringError } = await this.supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('account_balance_entries')
|
||||||
|
.select('amount')
|
||||||
|
.eq('account_id', accountId)
|
||||||
|
.eq('is_active', true)
|
||||||
|
.not('expires_at', 'is', null)
|
||||||
|
.lte('expires_at', thirtyDaysFromNow.toISOString());
|
||||||
|
|
||||||
|
if (expiringError) {
|
||||||
|
console.error('Error getting expiring balance:', expiringError);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expiringSoon =
|
||||||
|
expiringData?.reduce((sum, entry) => sum + (entry.amount || 0), 0) || 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalBalance: balance,
|
||||||
|
expiringSoon,
|
||||||
|
recentEntries: entries.entries,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async processPeriodicBenefitDistributions(): Promise<void> {
|
||||||
|
console.info('Processing periodic benefit distributions...');
|
||||||
|
const { error } = await this.supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.rpc('process_periodic_benefit_distributions');
|
||||||
|
if (error) {
|
||||||
|
console.error('Error processing periodic benefit distributions:', error);
|
||||||
|
throw new Error('Failed to process periodic benefit distributions');
|
||||||
|
}
|
||||||
|
console.info('Periodic benefit distributions processed successfully');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import type { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
|
export type AccountBalanceEntry =
|
||||||
|
Database['medreport']['Tables']['account_balance_entries']['Row'];
|
||||||
@@ -1,23 +1,26 @@
|
|||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
export type ApplicationRole =
|
export type ApplicationRole = Account['application_role'];
|
||||||
Database['medreport']['Tables']['accounts']['Row']['application_role'];
|
|
||||||
export enum ApplicationRoleEnum {
|
export enum ApplicationRoleEnum {
|
||||||
User = 'user',
|
User = 'user',
|
||||||
Doctor = 'doctor',
|
Doctor = 'doctor',
|
||||||
SuperAdmin = 'super_admin',
|
SuperAdmin = 'super_admin',
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AccountWithParams =
|
export type AccountParams =
|
||||||
Database['medreport']['Tables']['accounts']['Row'] & {
|
Database['medreport']['Tables']['account_params']['Row'];
|
||||||
accountParams:
|
|
||||||
| (Pick<
|
export type Account = Database['medreport']['Tables']['accounts']['Row'];
|
||||||
Database['medreport']['Tables']['account_params']['Row'],
|
export type AccountWithParams = Account & {
|
||||||
'weight' | 'height'
|
accountParams:
|
||||||
> & {
|
| (Pick<AccountParams, 'weight' | 'height'> & {
|
||||||
isSmoker:
|
isSmoker: AccountParams['is_smoker'] | null;
|
||||||
| Database['medreport']['Tables']['account_params']['Row']['is_smoker']
|
})
|
||||||
| null;
|
| null;
|
||||||
})
|
};
|
||||||
| null;
|
|
||||||
};
|
export type CompanyParams =
|
||||||
|
Database['medreport']['Tables']['company_params']['Row'];
|
||||||
|
|
||||||
|
export type BmiThresholds =
|
||||||
|
Database['medreport']['Tables']['bmi_thresholds']['Row'];
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@hookform/resolvers": "^5.0.1",
|
"@hookform/resolvers": "^5.0.1",
|
||||||
"@kit/next": "workspace:*",
|
"@kit/next": "workspace:*",
|
||||||
|
"@kit/accounts": "workspace:*",
|
||||||
"@kit/shared": "workspace:*",
|
"@kit/shared": "workspace:*",
|
||||||
"@kit/supabase": "workspace:*",
|
"@kit/supabase": "workspace:*",
|
||||||
"@kit/tsconfig": "workspace:*",
|
"@kit/tsconfig": "workspace:*",
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { EllipsisVertical } from 'lucide-react';
|
|||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { Database } from '@kit/supabase/database';
|
import type { Account } from '@kit/accounts/types/accounts';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Checkbox } from '@kit/ui/checkbox';
|
import { Checkbox } from '@kit/ui/checkbox';
|
||||||
import {
|
import {
|
||||||
@@ -44,8 +44,6 @@ import { AdminDeleteUserDialog } from './admin-delete-user-dialog';
|
|||||||
import { AdminImpersonateUserDialog } from './admin-impersonate-user-dialog';
|
import { AdminImpersonateUserDialog } from './admin-impersonate-user-dialog';
|
||||||
import { AdminResetPasswordDialog } from './admin-reset-password-dialog';
|
import { AdminResetPasswordDialog } from './admin-reset-password-dialog';
|
||||||
|
|
||||||
type Account = Database['medreport']['Tables']['accounts']['Row'];
|
|
||||||
|
|
||||||
const FiltersSchema = z.object({
|
const FiltersSchema = z.object({
|
||||||
type: z.enum(['all', 'team', 'personal']),
|
type: z.enum(['all', 'team', 'personal']),
|
||||||
query: z.string().optional(),
|
query: z.string().optional(),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { Database } from '@kit/supabase/database';
|
import { ApplicationRole } from '@kit/accounts/types/accounts';
|
||||||
|
|
||||||
const ConfirmationSchema = z.object({
|
const ConfirmationSchema = z.object({
|
||||||
confirmation: z.custom<string>((value) => value === 'CONFIRM'),
|
confirmation: z.custom<string>((value) => value === 'CONFIRM'),
|
||||||
@@ -19,9 +19,7 @@ export const DeleteAccountSchema = ConfirmationSchema.extend({
|
|||||||
accountId: z.string().uuid(),
|
accountId: z.string().uuid(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type ApplicationRoleType =
|
|
||||||
Database['medreport']['Tables']['accounts']['Row']['application_role'];
|
|
||||||
export const UpdateAccountRoleSchema = z.object({
|
export const UpdateAccountRoleSchema = z.object({
|
||||||
accountId: z.string().uuid(),
|
accountId: z.string().uuid(),
|
||||||
role: z.string() as z.ZodType<ApplicationRoleType>,
|
role: z.string() as z.ZodType<ApplicationRole>,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import 'server-only';
|
|||||||
|
|
||||||
import { SupabaseClient } from '@supabase/supabase-js';
|
import { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
import type { ApplicationRole } from '@kit/accounts/types/accounts';
|
||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
export function createAdminAccountsService(client: SupabaseClient<Database>) {
|
export function createAdminAccountsService(client: SupabaseClient<Database>) {
|
||||||
@@ -23,10 +24,7 @@ class AdminAccountsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateRole(
|
async updateRole(accountId: string, role: ApplicationRole) {
|
||||||
accountId: string,
|
|
||||||
role: Database['medreport']['Tables']['accounts']['Row']['application_role'],
|
|
||||||
) {
|
|
||||||
const { error } = await this.adminClient
|
const { error } = await this.adminClient
|
||||||
.schema('medreport')
|
.schema('medreport')
|
||||||
.from('accounts')
|
.from('accounts')
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"@kit/supabase": "workspace:*",
|
"@kit/supabase": "workspace:*",
|
||||||
"@kit/tsconfig": "workspace:*",
|
"@kit/tsconfig": "workspace:*",
|
||||||
"@kit/ui": "workspace:*",
|
"@kit/ui": "workspace:*",
|
||||||
|
"@kit/user-analyses": "workspace:*",
|
||||||
"@makerkit/data-loader-supabase-core": "^0.0.10",
|
"@makerkit/data-loader-supabase-core": "^0.0.10",
|
||||||
"@makerkit/data-loader-supabase-nextjs": "^1.2.5",
|
"@makerkit/data-loader-supabase-nextjs": "^1.2.5",
|
||||||
"@supabase/supabase-js": "2.49.4",
|
"@supabase/supabase-js": "2.49.4",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { isBefore } from 'date-fns';
|
|||||||
import { renderDoctorSummaryReceivedEmail } from '@kit/email-templates';
|
import { renderDoctorSummaryReceivedEmail } from '@kit/email-templates';
|
||||||
import { getFullName } from '@kit/shared/utils';
|
import { getFullName } from '@kit/shared/utils';
|
||||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||||
|
import { createUserAnalysesApi } from '@kit/user-analyses/api';
|
||||||
|
|
||||||
import { sendEmailFromTemplate } from '../../../../../../../lib/services/mailer.service';
|
import { sendEmailFromTemplate } from '../../../../../../../lib/services/mailer.service';
|
||||||
import { AnalysisResultDetails } from '../schema/doctor-analysis-detail-view.schema';
|
import { AnalysisResultDetails } from '../schema/doctor-analysis-detail-view.schema';
|
||||||
@@ -641,7 +642,14 @@ export async function submitFeedback(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (status === 'COMPLETED') {
|
if (status === 'COMPLETED') {
|
||||||
const [{ data: recipient }, { data: analysisOrder }] = await Promise.all([
|
const { data: analysisOrder } = await supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.from('analysis_orders')
|
||||||
|
.select('medusa_order_id, id')
|
||||||
|
.eq('id', analysisOrderId)
|
||||||
|
.limit(1)
|
||||||
|
.throwOnError();
|
||||||
|
const [{ data: recipient }] = await Promise.all([
|
||||||
supabase
|
supabase
|
||||||
.schema('medreport')
|
.schema('medreport')
|
||||||
.from('accounts')
|
.from('accounts')
|
||||||
@@ -649,19 +657,10 @@ export async function submitFeedback(
|
|||||||
.eq('is_personal_account', true)
|
.eq('is_personal_account', true)
|
||||||
.eq('primary_owner_user_id', userId)
|
.eq('primary_owner_user_id', userId)
|
||||||
.throwOnError(),
|
.throwOnError(),
|
||||||
supabase
|
createUserAnalysesApi(supabase).updateAnalysisOrderStatus({
|
||||||
.schema('medreport')
|
orderId: analysisOrderId,
|
||||||
.from('analysis_orders')
|
orderStatus: 'COMPLETED',
|
||||||
.select('medusa_order_id, id')
|
}),
|
||||||
.eq('id', analysisOrderId)
|
|
||||||
.limit(1)
|
|
||||||
.throwOnError(),
|
|
||||||
supabase
|
|
||||||
.schema('medreport')
|
|
||||||
.from('analysis_orders')
|
|
||||||
.update({ status: 'COMPLETED' })
|
|
||||||
.eq('id', analysisOrderId)
|
|
||||||
.throwOnError(),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!recipient?.[0]?.email) {
|
if (!recipient?.[0]?.email) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { redirect } from 'next/navigation';
|
|||||||
|
|
||||||
import { sdk } from '@lib/config';
|
import { sdk } from '@lib/config';
|
||||||
import medusaError from '@lib/util/medusa-error';
|
import medusaError from '@lib/util/medusa-error';
|
||||||
import { HttpTypes } from '@medusajs/types';
|
import { HttpTypes, StoreCart } from '@medusajs/types';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getAuthHeaders,
|
getAuthHeaders,
|
||||||
@@ -258,6 +258,42 @@ export async function setShippingMethod({
|
|||||||
.catch(medusaError);
|
.catch(medusaError);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function initiateMultiPaymentSession(
|
||||||
|
cart: StoreCart,
|
||||||
|
benefitsAmount: number,
|
||||||
|
) {
|
||||||
|
const headers = {
|
||||||
|
...(await getAuthHeaders()),
|
||||||
|
};
|
||||||
|
|
||||||
|
return sdk.client
|
||||||
|
.fetch<unknown>(`/store/multi-payment`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: { cartId: cart.id, benefitsAmount },
|
||||||
|
headers,
|
||||||
|
})
|
||||||
|
.then(async (response) => {
|
||||||
|
console.info('Payment session initiated:', response);
|
||||||
|
const cartCacheTag = await getCacheTag('carts');
|
||||||
|
revalidateTag(cartCacheTag);
|
||||||
|
return response as {
|
||||||
|
montonioPaymentSessionId: string | null;
|
||||||
|
companyBenefitsPaymentSessionId: string | null;
|
||||||
|
totalByBenefits: number;
|
||||||
|
totalByMontonio: number;
|
||||||
|
isFullyPaidByBenefits: boolean;
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(
|
||||||
|
'Error initiating payment session:',
|
||||||
|
e,
|
||||||
|
JSON.stringify(Object.keys(e)),
|
||||||
|
);
|
||||||
|
return medusaError(e);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function initiatePaymentSession(
|
export async function initiatePaymentSession(
|
||||||
cart: HttpTypes.StoreCart,
|
cart: HttpTypes.StoreCart,
|
||||||
data: HttpTypes.StoreInitializePaymentSession,
|
data: HttpTypes.StoreInitializePaymentSession,
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export const listCollections = async (
|
|||||||
|
|
||||||
queryParams.limit = queryParams.limit || '100';
|
queryParams.limit = queryParams.limit || '100';
|
||||||
queryParams.offset = queryParams.offset || '0';
|
queryParams.offset = queryParams.offset || '0';
|
||||||
console.log('SDK_CONFIG: ', SDK_CONFIG.baseUrl);
|
|
||||||
return sdk.client
|
return sdk.client
|
||||||
.fetch<{ collections: HttpTypes.StoreCollection[]; count: number }>(
|
.fetch<{ collections: HttpTypes.StoreCollection[]; count: number }>(
|
||||||
'/store/collections',
|
'/store/collections',
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { HttpTypes } from '@medusajs/types';
|
|||||||
|
|
||||||
import { getAuthHeaders, getCacheOptions } from './cookies';
|
import { getAuthHeaders, getCacheOptions } from './cookies';
|
||||||
|
|
||||||
export const retrieveOrder = async (id: string) => {
|
export const retrieveOrder = async (id: string, allowCache = true) => {
|
||||||
const headers = {
|
const headers = {
|
||||||
...(await getAuthHeaders()),
|
...(await getAuthHeaders()),
|
||||||
};
|
};
|
||||||
@@ -24,7 +24,8 @@ export const retrieveOrder = async (id: string) => {
|
|||||||
},
|
},
|
||||||
headers,
|
headers,
|
||||||
next,
|
next,
|
||||||
cache: 'force-cache',
|
...(allowCache ? { cache: 'force-cache' } : {}),
|
||||||
|
credentials: 'include',
|
||||||
})
|
})
|
||||||
.then(({ order }) => order)
|
.then(({ order }) => order)
|
||||||
.catch((err) => medusaError(err));
|
.catch((err) => medusaError(err));
|
||||||
@@ -55,6 +56,7 @@ export const listOrders = async (
|
|||||||
},
|
},
|
||||||
headers,
|
headers,
|
||||||
next,
|
next,
|
||||||
|
credentials: 'include',
|
||||||
})
|
})
|
||||||
.then(({ orders }) => orders)
|
.then(({ orders }) => orders)
|
||||||
.catch((err) => medusaError(err));
|
.catch((err) => medusaError(err));
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
|
import { sdk } from '@lib/config';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
renderAllResultsReceivedEmail,
|
renderAllResultsReceivedEmail,
|
||||||
renderFirstResultsReceivedEmail,
|
renderFirstResultsReceivedEmail,
|
||||||
renderOrderProcessingEmail,
|
renderOrderProcessingEmail,
|
||||||
renderPatientFirstResultsReceivedEmail,
|
renderPatientFirstResultsReceivedEmail,
|
||||||
renderPatientFullResultsReceivedEmail,
|
renderPatientFullResultsReceivedEmail,
|
||||||
|
renderTtoReservationConfirmationEmail,
|
||||||
} from '@kit/email-templates';
|
} from '@kit/email-templates';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { getFullName } from '@kit/shared/utils';
|
import { getFullName } from '@kit/shared/utils';
|
||||||
@@ -25,13 +28,15 @@ import {
|
|||||||
} from '~/lib/services/mailer.service';
|
} from '~/lib/services/mailer.service';
|
||||||
|
|
||||||
type AnalysisOrder = Database['medreport']['Tables']['analysis_orders']['Row'];
|
type AnalysisOrder = Database['medreport']['Tables']['analysis_orders']['Row'];
|
||||||
|
type TtoReservation =
|
||||||
|
Database['medreport']['Tables']['connected_online_reservation']['Row'];
|
||||||
|
|
||||||
export function createAnalysisOrderWebhooksService() {
|
export function createOrderWebhooksService() {
|
||||||
return new AnalysisOrderWebhooksService();
|
return new OrderWebhooksService();
|
||||||
}
|
}
|
||||||
|
|
||||||
class AnalysisOrderWebhooksService {
|
class OrderWebhooksService {
|
||||||
private readonly namespace = 'analysis_orders.webhooks';
|
private readonly namespace = 'orders.webhooks';
|
||||||
|
|
||||||
async handleStatusChangeWebhook(analysisOrder: AnalysisOrder) {
|
async handleStatusChangeWebhook(analysisOrder: AnalysisOrder) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
@@ -90,6 +95,128 @@ class AnalysisOrderWebhooksService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async handleTtoReservationConfirmationWebhook(
|
||||||
|
ttoReservation: TtoReservation,
|
||||||
|
) {
|
||||||
|
const logger = await getLogger();
|
||||||
|
const ctx = {
|
||||||
|
ttoReservationId: ttoReservation.id,
|
||||||
|
namespace: this.namespace,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userContact = await getUserContactAdmin(ttoReservation.user_id);
|
||||||
|
if (!userContact.email) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No email found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: ttoReservation.id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No email found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const supabaseClient = getSupabaseServerAdminClient();
|
||||||
|
if (!ttoReservation.medusa_cart_line_item_id) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No cart item id found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: ttoReservation.id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No cart item id found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const [
|
||||||
|
{ data: cartItem },
|
||||||
|
{ data: location },
|
||||||
|
{ data: serviceProvider },
|
||||||
|
] = await Promise.all([
|
||||||
|
supabaseClient
|
||||||
|
.from('cart_line_item')
|
||||||
|
.select('cart_id,title')
|
||||||
|
.eq('id', ttoReservation.medusa_cart_line_item_id)
|
||||||
|
.single(),
|
||||||
|
supabaseClient
|
||||||
|
.schema('medreport')
|
||||||
|
.from('connected_online_locations')
|
||||||
|
.select('name,address')
|
||||||
|
.eq('sync_id', ttoReservation.location_sync_id || 0)
|
||||||
|
.single(),
|
||||||
|
supabaseClient
|
||||||
|
.schema('medreport')
|
||||||
|
.from('connected_online_providers')
|
||||||
|
.select('email,phone_number,name')
|
||||||
|
.eq('id', ttoReservation.clinic_id)
|
||||||
|
.single(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!cartItem) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No medusa cart item found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: ttoReservation.medusa_cart_line_item_id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No cart item found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [{ data: orderCart }] = await Promise.all([
|
||||||
|
supabaseClient
|
||||||
|
.from('order_cart')
|
||||||
|
.select('order_id')
|
||||||
|
.eq('cart_id', cartItem.cart_id)
|
||||||
|
.single(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!orderCart) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No medusa order cart found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: cartItem.cart_id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No order cart found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await sendEmailFromTemplate(
|
||||||
|
renderTtoReservationConfirmationEmail,
|
||||||
|
{
|
||||||
|
language: userContact.preferred_locale ?? 'et',
|
||||||
|
recipientName: getFullName(userContact.name, userContact.last_name),
|
||||||
|
startTime: ttoReservation.start_time,
|
||||||
|
orderName: cartItem.title,
|
||||||
|
locationName: location?.name,
|
||||||
|
locationAddress: location?.address,
|
||||||
|
orderId: orderCart.order_id,
|
||||||
|
serviceProviderName: serviceProvider?.name,
|
||||||
|
serviceProviderEmail: serviceProvider?.email,
|
||||||
|
serviceProviderPhone: serviceProvider?.phone_number,
|
||||||
|
},
|
||||||
|
userContact.email,
|
||||||
|
);
|
||||||
|
|
||||||
|
return createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'SUCCESS',
|
||||||
|
relatedRecordId: orderCart.order_id,
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: e?.message,
|
||||||
|
relatedRecordId: ttoReservation.id,
|
||||||
|
});
|
||||||
|
logger.error(
|
||||||
|
ctx,
|
||||||
|
`Error while processing tto reservation: ${JSON.stringify(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async sendProcessingNotification(analysisOrder: AnalysisOrder) {
|
async sendProcessingNotification(analysisOrder: AnalysisOrder) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
const supabase = getSupabaseServerAdminClient();
|
const supabase = getSupabaseServerAdminClient();
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
|
|
||||||
import { useDismissNotification } from '@kit/notifications/hooks';
|
|
||||||
import { Heading } from '@kit/ui/heading';
|
import { Heading } from '@kit/ui/heading';
|
||||||
import { If } from '@kit/ui/if';
|
import { If } from '@kit/ui/if';
|
||||||
import { Separator } from '@kit/ui/separator';
|
import { Separator } from '@kit/ui/separator';
|
||||||
@@ -12,7 +11,7 @@ import { SignOutInvitationButton } from './sign-out-invitation-button';
|
|||||||
|
|
||||||
export function AcceptInvitationContainer(props: {
|
export function AcceptInvitationContainer(props: {
|
||||||
inviteToken: string;
|
inviteToken: string;
|
||||||
email: string;
|
fullName: string;
|
||||||
|
|
||||||
invitation: {
|
invitation: {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -76,7 +75,7 @@ export function AcceptInvitationContainer(props: {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<InvitationSubmitButton
|
<InvitationSubmitButton
|
||||||
email={props.email}
|
fullName={props.fullName}
|
||||||
accountName={props.invitation.account.name}
|
accountName={props.invitation.account.name}
|
||||||
/>
|
/>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { Trans } from '@kit/ui/trans';
|
|||||||
|
|
||||||
export function InvitationSubmitButton(props: {
|
export function InvitationSubmitButton(props: {
|
||||||
accountName: string;
|
accountName: string;
|
||||||
email: string;
|
fullName: string;
|
||||||
}) {
|
}) {
|
||||||
const { pending } = useFormStatus();
|
const { pending } = useFormStatus();
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ export function InvitationSubmitButton(props: {
|
|||||||
i18nKey={pending ? 'teams:joiningTeam' : 'teams:continueAs'}
|
i18nKey={pending ? 'teams:joiningTeam' : 'teams:continueAs'}
|
||||||
values={{
|
values={{
|
||||||
accountName: props.accountName,
|
accountName: props.accountName,
|
||||||
email: props.email,
|
fullName: props.fullName,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { ColumnDef } from '@tanstack/react-table';
|
|||||||
import { Ellipsis } from 'lucide-react';
|
import { Ellipsis } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { formatCurrency } from '@kit/shared/utils';
|
||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -42,6 +43,10 @@ type AccountMembersTableProps = {
|
|||||||
userRoleHierarchy: number;
|
userRoleHierarchy: number;
|
||||||
isPrimaryOwner: boolean;
|
isPrimaryOwner: boolean;
|
||||||
canManageRoles: boolean;
|
canManageRoles: boolean;
|
||||||
|
membersBenefitsUsage: {
|
||||||
|
personal_account_id: string;
|
||||||
|
benefit_amount: number;
|
||||||
|
}[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export function AccountMembersTable({
|
export function AccountMembersTable({
|
||||||
@@ -51,6 +56,7 @@ export function AccountMembersTable({
|
|||||||
isPrimaryOwner,
|
isPrimaryOwner,
|
||||||
userRoleHierarchy,
|
userRoleHierarchy,
|
||||||
canManageRoles,
|
canManageRoles,
|
||||||
|
membersBenefitsUsage,
|
||||||
}: AccountMembersTableProps) {
|
}: AccountMembersTableProps) {
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
const { t } = useTranslation('teams');
|
const { t } = useTranslation('teams');
|
||||||
@@ -73,6 +79,7 @@ export function AccountMembersTable({
|
|||||||
currentUserId,
|
currentUserId,
|
||||||
currentAccountId,
|
currentAccountId,
|
||||||
currentRoleHierarchy: userRoleHierarchy,
|
currentRoleHierarchy: userRoleHierarchy,
|
||||||
|
membersBenefitsUsage,
|
||||||
});
|
});
|
||||||
|
|
||||||
const filteredMembers = members
|
const filteredMembers = members
|
||||||
@@ -122,9 +129,16 @@ function useGetColumns(
|
|||||||
currentUserId: string;
|
currentUserId: string;
|
||||||
currentAccountId: string;
|
currentAccountId: string;
|
||||||
currentRoleHierarchy: number;
|
currentRoleHierarchy: number;
|
||||||
|
membersBenefitsUsage: {
|
||||||
|
personal_account_id: string;
|
||||||
|
benefit_amount: number;
|
||||||
|
}[];
|
||||||
},
|
},
|
||||||
): ColumnDef<Members[0]>[] {
|
): ColumnDef<Members[0]>[] {
|
||||||
const { t } = useTranslation('teams');
|
const {
|
||||||
|
t,
|
||||||
|
i18n: { language },
|
||||||
|
} = useTranslation('teams');
|
||||||
|
|
||||||
return useMemo(
|
return useMemo(
|
||||||
() => [
|
() => [
|
||||||
@@ -168,6 +182,23 @@ function useGetColumns(
|
|||||||
return row.original.personal_code ?? '-';
|
return row.original.personal_code ?? '-';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
header: t('distributedBenefitsAmount'),
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const benefitAmount = params.membersBenefitsUsage.find(
|
||||||
|
(usage) => usage.personal_account_id === row.original.id,
|
||||||
|
)?.benefit_amount;
|
||||||
|
if (typeof benefitAmount !== 'number') {
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
return formatCurrency({
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
locale: language,
|
||||||
|
value: benefitAmount,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
header: t('roleLabel'),
|
header: t('roleLabel'),
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
@@ -175,7 +206,11 @@ function useGetColumns(
|
|||||||
const isPrimaryOwner = primary_owner_user_id === user_id;
|
const isPrimaryOwner = primary_owner_user_id === user_id;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className={'flex items-center space-x-1'}>
|
<span
|
||||||
|
className={
|
||||||
|
'flex flex-wrap items-center space-y-1 space-x-1 sm:flex-nowrap sm:space-y-0'
|
||||||
|
}
|
||||||
|
>
|
||||||
<RoleBadge role={role} />
|
<RoleBadge role={role} />
|
||||||
|
|
||||||
<If condition={isPrimaryOwner}>
|
<If condition={isPrimaryOwner}>
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import { TeamAccountDangerZone } from './team-account-danger-zone';
|
|||||||
import { UpdateTeamAccountImage } from './update-team-account-image-container';
|
import { UpdateTeamAccountImage } from './update-team-account-image-container';
|
||||||
import { UpdateTeamAccountNameForm } from './update-team-account-name-form';
|
import { UpdateTeamAccountNameForm } from './update-team-account-name-form';
|
||||||
|
|
||||||
|
const SHOW_TEAM_LOGO = false as boolean;
|
||||||
|
|
||||||
export function TeamAccountSettingsContainer(props: {
|
export function TeamAccountSettingsContainer(props: {
|
||||||
account: {
|
account: {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -32,21 +34,23 @@ export function TeamAccountSettingsContainer(props: {
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className={'flex w-full flex-col space-y-4'}>
|
<div className={'flex w-full flex-col space-y-4'}>
|
||||||
<Card>
|
{SHOW_TEAM_LOGO && (
|
||||||
<CardHeader>
|
<Card>
|
||||||
<CardTitle>
|
<CardHeader>
|
||||||
<Trans i18nKey={'teams:settings.teamLogo'} />
|
<CardTitle>
|
||||||
</CardTitle>
|
<Trans i18nKey={'teams:settings.teamLogo'} />
|
||||||
|
</CardTitle>
|
||||||
|
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
<Trans i18nKey={'teams:settings.teamLogoDescription'} />
|
<Trans i18nKey={'teams:settings.teamLogoDescription'} />
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<UpdateTeamAccountImage account={props.account} />
|
<UpdateTeamAccountImage account={props.account} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { redirect } from 'next/navigation';
|
|||||||
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||||
import { enhanceAction } from '@kit/next/actions';
|
import { enhanceAction } from '@kit/next/actions';
|
||||||
import { createNotificationsApi } from '@kit/notifications/api';
|
import { createNotificationsApi } from '@kit/notifications/api';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
@@ -148,6 +149,7 @@ export const updateInvitationAction = enhanceAction(
|
|||||||
export const acceptInvitationAction = enhanceAction(
|
export const acceptInvitationAction = enhanceAction(
|
||||||
async (data: FormData, user) => {
|
async (data: FormData, user) => {
|
||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
|
const accountBalanceService = new AccountBalanceService();
|
||||||
|
|
||||||
const { inviteToken, nextPath } = AcceptInvitationSchema.parse(
|
const { inviteToken, nextPath } = AcceptInvitationSchema.parse(
|
||||||
Object.fromEntries(data),
|
Object.fromEntries(data),
|
||||||
@@ -171,6 +173,9 @@ export const acceptInvitationAction = enhanceAction(
|
|||||||
throw new Error('Failed to accept invitation');
|
throw new Error('Failed to accept invitation');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Make sure new account gets company benefits added to balance
|
||||||
|
await accountBalanceService.processPeriodicBenefitDistributions();
|
||||||
|
|
||||||
// Increase the seats for the account
|
// Increase the seats for the account
|
||||||
await perSeatBillingService.increaseSeats(accountId);
|
await perSeatBillingService.increaseSeats(accountId);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import type { Account } from '@kit/accounts/types/accounts';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { Database } from '@kit/supabase/database';
|
|
||||||
|
|
||||||
type Account = Database['medreport']['Tables']['accounts']['Row'];
|
|
||||||
|
|
||||||
export function createAccountWebhooksService() {
|
export function createAccountWebhooksService() {
|
||||||
return new AccountWebhooksService();
|
return new AccountWebhooksService();
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import type { UuringuVastus } from '@kit/shared/types/medipost-analysis';
|
|||||||
import { toArray } from '@kit/shared/utils';
|
import { toArray } from '@kit/shared/utils';
|
||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
import type { AnalysisOrder } from '../types/analysis-orders';
|
import type {
|
||||||
|
AnalysisOrder,
|
||||||
|
AnalysisOrderStatus,
|
||||||
|
} from '../types/analysis-orders';
|
||||||
import type {
|
import type {
|
||||||
AnalysisResultDetailsElement,
|
AnalysisResultDetailsElement,
|
||||||
AnalysisResultDetailsMapped,
|
AnalysisResultDetailsMapped,
|
||||||
@@ -450,6 +453,34 @@ class UserAnalysesApi {
|
|||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateAnalysisOrderStatus({
|
||||||
|
orderId,
|
||||||
|
medusaOrderId,
|
||||||
|
orderStatus,
|
||||||
|
}: {
|
||||||
|
orderId?: number;
|
||||||
|
medusaOrderId?: string;
|
||||||
|
orderStatus: AnalysisOrderStatus;
|
||||||
|
}) {
|
||||||
|
const orderIdParam = orderId;
|
||||||
|
const medusaOrderIdParam = medusaOrderId;
|
||||||
|
|
||||||
|
console.info(
|
||||||
|
`Updating order id=${orderId} medusaOrderId=${medusaOrderId} status=${orderStatus}`,
|
||||||
|
);
|
||||||
|
if (!orderIdParam && !medusaOrderIdParam) {
|
||||||
|
throw new Error('Either orderId or medusaOrderId must be provided');
|
||||||
|
}
|
||||||
|
await this.client
|
||||||
|
.schema('medreport')
|
||||||
|
.rpc('update_analysis_order_status', {
|
||||||
|
order_id: orderIdParam ?? -1,
|
||||||
|
status_param: orderStatus,
|
||||||
|
medusa_order_id_param: medusaOrderIdParam ?? '',
|
||||||
|
})
|
||||||
|
.throwOnError();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createUserAnalysesApi(client: SupabaseClient<Database>) {
|
export function createUserAnalysesApi(client: SupabaseClient<Database>) {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
import { Tables } from '@kit/supabase/database';
|
import { Tables } from '@kit/supabase/database';
|
||||||
|
|
||||||
export type AnalysisOrder = Tables<{ schema: 'medreport' }, 'analysis_orders'>;
|
export type AnalysisOrder = Tables<{ schema: 'medreport' }, 'analysis_orders'>;
|
||||||
|
export type AnalysisOrderStatus = AnalysisOrder['status'];
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { CreditCard, LayoutDashboard, Settings, Users } from 'lucide-react';
|
import { Euro, LayoutDashboard, Settings, Users } from 'lucide-react';
|
||||||
|
|
||||||
import { NavigationConfigSchema } from '@kit/ui/navigation-schema';
|
import { NavigationConfigSchema } from '@kit/ui/navigation-schema';
|
||||||
|
|
||||||
import pathsConfig from './paths.config';
|
|
||||||
import featureFlagsConfig from './feature-flags.config';
|
import featureFlagsConfig from './feature-flags.config';
|
||||||
|
import pathsConfig from './paths.config';
|
||||||
|
|
||||||
const iconClasses = 'w-4';
|
const iconClasses = 'w-4';
|
||||||
|
|
||||||
@@ -11,18 +11,13 @@ const getRoutes = (account: string) => [
|
|||||||
{
|
{
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
label: 'common:routes.dashboard',
|
label: 'common:routes.companyDashboard',
|
||||||
path: pathsConfig.app.accountHome.replace('[account]', account),
|
path: pathsConfig.app.accountHome.replace('[account]', account),
|
||||||
Icon: <LayoutDashboard className={iconClasses} />,
|
Icon: <LayoutDashboard className={iconClasses} />,
|
||||||
end: true,
|
end: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'common:routes.settings',
|
label: 'common:routes.companyMembers',
|
||||||
path: createPath(pathsConfig.app.accountSettings, account),
|
|
||||||
Icon: <Settings className={iconClasses} />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'common:routes.members',
|
|
||||||
path: createPath(pathsConfig.app.accountMembers, account),
|
path: createPath(pathsConfig.app.accountMembers, account),
|
||||||
Icon: <Users className={iconClasses} />,
|
Icon: <Users className={iconClasses} />,
|
||||||
},
|
},
|
||||||
@@ -30,9 +25,14 @@ const getRoutes = (account: string) => [
|
|||||||
? {
|
? {
|
||||||
label: 'common:routes.billing',
|
label: 'common:routes.billing',
|
||||||
path: createPath(pathsConfig.app.accountBilling, account),
|
path: createPath(pathsConfig.app.accountBilling, account),
|
||||||
Icon: <CreditCard className={iconClasses} />,
|
Icon: <Euro className={iconClasses} />,
|
||||||
}
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
|
{
|
||||||
|
label: 'common:routes.companySettings',
|
||||||
|
path: createPath(pathsConfig.app.accountSettings, account),
|
||||||
|
Icon: <Settings className={iconClasses} />,
|
||||||
|
},
|
||||||
].filter(Boolean),
|
].filter(Boolean),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
|||||||
* @name getSupabaseServerClient
|
* @name getSupabaseServerClient
|
||||||
* @description Creates a Supabase client for use in the Server.
|
* @description Creates a Supabase client for use in the Server.
|
||||||
*/
|
*/
|
||||||
export function getSupabaseServerClient<GenericSchema = Database>() {
|
export function getSupabaseServerClient() {
|
||||||
const keys = getSupabaseClientKeys();
|
const keys = getSupabaseClientKeys();
|
||||||
|
|
||||||
return createServerClient<GenericSchema>(keys.url, keys.anonKey, {
|
return createServerClient<Database>(keys.url, keys.anonKey, {
|
||||||
auth: {
|
auth: {
|
||||||
flowType: 'pkce',
|
flowType: 'pkce',
|
||||||
autoRefreshToken: true,
|
autoRefreshToken: true,
|
||||||
|
|||||||
@@ -348,6 +348,8 @@ export type Database = {
|
|||||||
expires_at: string | null
|
expires_at: string | null
|
||||||
id: string
|
id: string
|
||||||
is_active: boolean
|
is_active: boolean
|
||||||
|
is_analysis_order: boolean
|
||||||
|
is_analysis_package_order: boolean
|
||||||
reference_id: string | null
|
reference_id: string | null
|
||||||
source_company_id: string | null
|
source_company_id: string | null
|
||||||
}
|
}
|
||||||
@@ -361,6 +363,8 @@ export type Database = {
|
|||||||
expires_at?: string | null
|
expires_at?: string | null
|
||||||
id?: string
|
id?: string
|
||||||
is_active?: boolean
|
is_active?: boolean
|
||||||
|
is_analysis_order?: boolean
|
||||||
|
is_analysis_package_order?: boolean
|
||||||
reference_id?: string | null
|
reference_id?: string | null
|
||||||
source_company_id?: string | null
|
source_company_id?: string | null
|
||||||
}
|
}
|
||||||
@@ -374,6 +378,8 @@ export type Database = {
|
|||||||
expires_at?: string | null
|
expires_at?: string | null
|
||||||
id?: string
|
id?: string
|
||||||
is_active?: boolean
|
is_active?: boolean
|
||||||
|
is_analysis_order?: boolean
|
||||||
|
is_analysis_package_order?: boolean
|
||||||
reference_id?: string | null
|
reference_id?: string | null
|
||||||
source_company_id?: string | null
|
source_company_id?: string | null
|
||||||
}
|
}
|
||||||
@@ -2310,6 +2316,15 @@ export type Database = {
|
|||||||
user_id: string
|
user_id: string
|
||||||
}[]
|
}[]
|
||||||
}
|
}
|
||||||
|
get_benefits_usages_for_company_members: {
|
||||||
|
Args: {
|
||||||
|
p_account_id: string
|
||||||
|
}
|
||||||
|
Returns: {
|
||||||
|
personal_account_id: string
|
||||||
|
benefit_amount: number
|
||||||
|
}
|
||||||
|
}
|
||||||
get_config: {
|
get_config: {
|
||||||
Args: Record<PropertyKey, never>
|
Args: Record<PropertyKey, never>
|
||||||
Returns: Json
|
Returns: Json
|
||||||
|
|||||||
@@ -3,21 +3,23 @@ import { cn } from '../lib/utils';
|
|||||||
function Skeleton({
|
function Skeleton({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
|
isLoading = true,
|
||||||
...props
|
...props
|
||||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
}: React.HTMLAttributes<HTMLDivElement> & { isLoading?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn('relative inline-block align-top', className)}
|
className={cn('relative inline-block align-top', className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<div className="invisible">
|
<div className={cn({ invisible: isLoading })}>
|
||||||
{children ?? <span className="block h-4 w-24" />}
|
{children ?? <span className="block h-4 w-24" />}
|
||||||
</div>
|
</div>
|
||||||
|
{isLoading && (
|
||||||
<div
|
<div
|
||||||
aria-hidden
|
aria-hidden
|
||||||
className="bg-primary/10 absolute inset-0 animate-pulse rounded-md"
|
className="bg-primary/10 absolute inset-0 animate-pulse rounded-md"
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
3027
pnpm-lock.yaml
generated
3027
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -169,5 +169,8 @@
|
|||||||
"updateAccountError": "Updating account details failed",
|
"updateAccountError": "Updating account details failed",
|
||||||
"updateAccountPreferencesSuccess": "Account preferences updated",
|
"updateAccountPreferencesSuccess": "Account preferences updated",
|
||||||
"updateAccountPreferencesError": "Updating account preferences failed",
|
"updateAccountPreferencesError": "Updating account preferences failed",
|
||||||
"consents": "Consents"
|
"consents": "Consents",
|
||||||
|
"healthBenefitForm": {
|
||||||
|
"updateSuccess": "Health benefit updated"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,7 +121,6 @@
|
|||||||
"label": "Cart ({{ items }})"
|
"label": "Cart ({{ items }})"
|
||||||
},
|
},
|
||||||
"pageTitle": "{{companyName}} budget",
|
"pageTitle": "{{companyName}} budget",
|
||||||
"description": "Configure company budget..",
|
|
||||||
"saveChanges": "Save changes",
|
"saveChanges": "Save changes",
|
||||||
"healthBenefitForm": {
|
"healthBenefitForm": {
|
||||||
"title": "Health benefit form",
|
"title": "Health benefit form",
|
||||||
@@ -134,10 +133,10 @@
|
|||||||
"monthly": "Monthly"
|
"monthly": "Monthly"
|
||||||
},
|
},
|
||||||
"expensesOverview": {
|
"expensesOverview": {
|
||||||
"title": "Expenses overview 2025",
|
"title": "Health account budget overview 2025",
|
||||||
"monthly": "Expense per employee per month *",
|
"employeeCount": "Health account users",
|
||||||
"yearly": "Maximum expense per employee per year *",
|
"managementFeeTotal": "Health account management fee {{managementFee}} per employee per month *",
|
||||||
"total": "Maximum expense per {{employeeCount}} employee(s) per year *",
|
"currentMonthUsageTotal": "Health account current month usage",
|
||||||
"sum": "Total"
|
"total": "Health account budget total"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,10 @@
|
|||||||
"order": {
|
"order": {
|
||||||
"title": "Order",
|
"title": "Order",
|
||||||
"promotionsTotal": "Promotions total",
|
"promotionsTotal": "Promotions total",
|
||||||
|
"companyBenefitsTotal": "Company benefits total",
|
||||||
"subtotal": "Subtotal",
|
"subtotal": "Subtotal",
|
||||||
|
"benefitsTotal": "Paid with benefits",
|
||||||
|
"montonioTotal": "Paid with Montonio",
|
||||||
"total": "Total",
|
"total": "Total",
|
||||||
"giftCard": "Gift card"
|
"giftCard": "Gift card"
|
||||||
},
|
},
|
||||||
@@ -76,7 +79,8 @@
|
|||||||
"orderNumber": "Order number",
|
"orderNumber": "Order number",
|
||||||
"orderStatus": "Order status",
|
"orderStatus": "Order status",
|
||||||
"paymentStatus": "Payment status",
|
"paymentStatus": "Payment status",
|
||||||
"discount": "Discount"
|
"discount": "Discount",
|
||||||
|
"paymentConfirmationLoading": "Payment confirmation..."
|
||||||
},
|
},
|
||||||
"montonioCallback": {
|
"montonioCallback": {
|
||||||
"title": "Montonio checkout",
|
"title": "Montonio checkout",
|
||||||
|
|||||||
@@ -75,10 +75,10 @@
|
|||||||
"orderAnalysis": "Order analysis",
|
"orderAnalysis": "Order analysis",
|
||||||
"orderHealthAnalysis": "Order health check",
|
"orderHealthAnalysis": "Order health check",
|
||||||
"account": "Account",
|
"account": "Account",
|
||||||
"members": "Members",
|
"companyMembers": "Manage employees",
|
||||||
"billing": "Billing",
|
"billing": "Billing",
|
||||||
"dashboard": "Dashboard",
|
"companyDashboard": "Dashboard",
|
||||||
"settings": "Settings",
|
"companySettings": "Settings",
|
||||||
"profile": "Profile",
|
"profile": "Profile",
|
||||||
"pickTime": "Pick time",
|
"pickTime": "Pick time",
|
||||||
"preferences": "Preferences",
|
"preferences": "Preferences",
|
||||||
|
|||||||
@@ -17,9 +17,13 @@
|
|||||||
"orderAnalysis": {
|
"orderAnalysis": {
|
||||||
"title": "Order analysis",
|
"title": "Order analysis",
|
||||||
"description": "Select an analysis to get started"
|
"description": "Select an analysis to get started"
|
||||||
|
},
|
||||||
|
"benefits": {
|
||||||
|
"title": "Your company benefits"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"recommendations": {
|
"recommendations": {
|
||||||
"title": "Medreport recommends"
|
"title": "Medreport recommends",
|
||||||
|
"validUntil": "Valid until {{date}}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
{
|
{
|
||||||
"home": {
|
"home": {
|
||||||
"pageTitle": "Company Dashboard"
|
"pageTitle": "Company Dashboard",
|
||||||
|
"headerTitle": "{{companyName}} Health Dashboard",
|
||||||
|
"healthDetails": "Company Health Details",
|
||||||
|
"membersSettingsButtonTitle": "Manage Members",
|
||||||
|
"membersSettingsButtonDescription": "Add, edit, or remove members.",
|
||||||
|
"membersBillingButtonTitle": "Manage Billing",
|
||||||
|
"membersBillingButtonDescription": "Select how you want to distribute the budget between members."
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"pageTitle": "Company Settings",
|
"pageTitle": "Company Settings",
|
||||||
@@ -18,6 +24,34 @@
|
|||||||
"billing": {
|
"billing": {
|
||||||
"pageTitle": "Company Billing"
|
"pageTitle": "Company Billing"
|
||||||
},
|
},
|
||||||
|
"benefitStatistics": {
|
||||||
|
"budget": {
|
||||||
|
"title": "Company Health Account Balance",
|
||||||
|
"balance": "Budget Balance {{balance}}",
|
||||||
|
"volume": "Budget Volume",
|
||||||
|
"membersCount": "Members Count"
|
||||||
|
},
|
||||||
|
"data": {
|
||||||
|
"reservations": "{{value}} services",
|
||||||
|
"analysis": "Analyses",
|
||||||
|
"doctorsAndSpecialists": "Doctors and Specialists",
|
||||||
|
"researches": "Researches",
|
||||||
|
"analysisPackages": "Health Analysis Packages",
|
||||||
|
"analysisPackagesCount": "{{value}} service usage",
|
||||||
|
"totalSum": "Total Sum",
|
||||||
|
"eclinic": "E-Clinic",
|
||||||
|
"currentMonthUsageTotal": "Current Month Usage"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"healthDetails": {
|
||||||
|
"women": "Women",
|
||||||
|
"men": "Men",
|
||||||
|
"avgAge": "Average Age",
|
||||||
|
"bmi": "BMI",
|
||||||
|
"cholesterol": "Cholesterol",
|
||||||
|
"vitaminD": "Vitamin D",
|
||||||
|
"smokers": "Smokers"
|
||||||
|
},
|
||||||
"yourTeams": "Your Companies ({{teamsCount}})",
|
"yourTeams": "Your Companies ({{teamsCount}})",
|
||||||
"createTeam": "Create a Company",
|
"createTeam": "Create a Company",
|
||||||
"creatingTeam": "Creating Company...",
|
"creatingTeam": "Creating Company...",
|
||||||
@@ -28,7 +62,7 @@
|
|||||||
"youLabel": "You",
|
"youLabel": "You",
|
||||||
"emailLabel": "Email",
|
"emailLabel": "Email",
|
||||||
"roleLabel": "Role",
|
"roleLabel": "Role",
|
||||||
"primaryOwnerLabel": "Primary Admin",
|
"primaryOwnerLabel": "Manager",
|
||||||
"joinedAtLabel": "Joined at",
|
"joinedAtLabel": "Joined at",
|
||||||
"invitedAtLabel": "Invited at",
|
"invitedAtLabel": "Invited at",
|
||||||
"inviteMembersPageSubheading": "Invite members to your Company",
|
"inviteMembersPageSubheading": "Invite members to your Company",
|
||||||
@@ -153,12 +187,14 @@
|
|||||||
"signInWithDifferentAccountDescription": "If you wish to accept the invitation with a different account, please sign out and back in with the account you wish to use.",
|
"signInWithDifferentAccountDescription": "If you wish to accept the invitation with a different account, please sign out and back in with the account you wish to use.",
|
||||||
"acceptInvitationHeading": "Accept Invitation to join {{accountName}}",
|
"acceptInvitationHeading": "Accept Invitation to join {{accountName}}",
|
||||||
"acceptInvitationDescription": "You have been invited to join the company {{accountName}}. If you wish to accept the invitation, please click the button below.",
|
"acceptInvitationDescription": "You have been invited to join the company {{accountName}}. If you wish to accept the invitation, please click the button below.",
|
||||||
"continueAs": "Continue as {{email}}",
|
"continueAs": "Continue as {{fullName}}",
|
||||||
"joinTeamAccount": "Join Company",
|
"joinTeamAccount": "Join Company",
|
||||||
"joiningTeam": "Joining company...",
|
"joiningTeam": "Joining company...",
|
||||||
"leaveTeamInputLabel": "Please type LEAVE to confirm leaving the company.",
|
"leaveTeamInputLabel": "Please type LEAVE to confirm leaving the company.",
|
||||||
"leaveTeamInputDescription": "By leaving the company, you will no longer have access to it.",
|
"leaveTeamInputDescription": "By leaving the company, you will no longer have access to it.",
|
||||||
"reservedNameError": "This name is reserved. Please choose a different one.",
|
"reservedNameError": "This name is reserved. Please choose a different one.",
|
||||||
"specialCharactersError": "This name cannot contain special characters. Please choose a different one.",
|
"specialCharactersError": "This name cannot contain special characters. Please choose a different one.",
|
||||||
"personalCode": "Personal Code"
|
"personalCode": "Personal Code",
|
||||||
|
"teamOwnerPersonalCodeLabel": "Owner's Personal Code",
|
||||||
|
"distributedBenefitsAmount": "Assigned benefits"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -169,5 +169,8 @@
|
|||||||
"updateAccountError": "Konto andmete uuendamine ebaõnnestus",
|
"updateAccountError": "Konto andmete uuendamine ebaõnnestus",
|
||||||
"updateAccountPreferencesSuccess": "Konto eelistused uuendatud",
|
"updateAccountPreferencesSuccess": "Konto eelistused uuendatud",
|
||||||
"updateAccountPreferencesError": "Konto eelistused uuendamine ebaõnnestus",
|
"updateAccountPreferencesError": "Konto eelistused uuendamine ebaõnnestus",
|
||||||
"consents": "Nõusolekud"
|
"consents": "Nõusolekud",
|
||||||
|
"healthBenefitForm": {
|
||||||
|
"updateSuccess": "Tervisekonto andmed uuendatud"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,11 +121,10 @@
|
|||||||
"label": "Cart ({{ items }})"
|
"label": "Cart ({{ items }})"
|
||||||
},
|
},
|
||||||
"pageTitle": "{{companyName}} eelarve",
|
"pageTitle": "{{companyName}} eelarve",
|
||||||
"description": "Muuda ettevõtte eelarve seadistusi.",
|
|
||||||
"saveChanges": "Salvesta muudatused",
|
"saveChanges": "Salvesta muudatused",
|
||||||
"healthBenefitForm": {
|
"healthBenefitForm": {
|
||||||
"title": "Tervisetoetuse vorm",
|
"title": "Tervisetoetuse vorm",
|
||||||
"description": "Ettevõtte Tervisekassa toetus töötajale",
|
"description": "Ettevõtte tervisekonto seadistamine",
|
||||||
"info": "* Hindadele lisanduvad riigipoolsed maksud"
|
"info": "* Hindadele lisanduvad riigipoolsed maksud"
|
||||||
},
|
},
|
||||||
"occurrence": {
|
"occurrence": {
|
||||||
@@ -134,10 +133,10 @@
|
|||||||
"monthly": "Kord kuus"
|
"monthly": "Kord kuus"
|
||||||
},
|
},
|
||||||
"expensesOverview": {
|
"expensesOverview": {
|
||||||
"title": "Kulude ülevaade 2025 aasta raames",
|
"title": "Tervisekonto eelarve ülevaade 2025",
|
||||||
"monthly": "Kulu töötaja kohta kuus *",
|
"employeeCount": "Tervisekonto kasutajate arv",
|
||||||
"yearly": "Maksimaalne kulu inimese kohta kokku aastas *",
|
"managementFeeTotal": "Tervisekonto haldustasu {{managementFee}} kuus töötaja kohta*",
|
||||||
"total": "Maksimaalne kulu {{employeeCount}} töötaja kohta aastas *",
|
"currentMonthUsageTotal": "Tervisekonto jooksva kuu kasutus",
|
||||||
"sum": "Kokku"
|
"total": "Tervisekonto eelarve maht kokku"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,10 @@
|
|||||||
"order": {
|
"order": {
|
||||||
"title": "Tellimus",
|
"title": "Tellimus",
|
||||||
"promotionsTotal": "Soodustuse summa",
|
"promotionsTotal": "Soodustuse summa",
|
||||||
|
"companyBenefitsTotal": "Toetuse summa",
|
||||||
"subtotal": "Vahesumma",
|
"subtotal": "Vahesumma",
|
||||||
|
"benefitsTotal": "Tasutud tervisetoetusest",
|
||||||
|
"montonioTotal": "Tasutud Montonio'ga",
|
||||||
"total": "Summa",
|
"total": "Summa",
|
||||||
"giftCard": "Kinkekaart"
|
"giftCard": "Kinkekaart"
|
||||||
},
|
},
|
||||||
@@ -76,7 +79,8 @@
|
|||||||
"orderNumber": "Tellimuse number",
|
"orderNumber": "Tellimuse number",
|
||||||
"orderStatus": "Tellimuse olek",
|
"orderStatus": "Tellimuse olek",
|
||||||
"paymentStatus": "Makse olek",
|
"paymentStatus": "Makse olek",
|
||||||
"discount": "Soodus"
|
"discount": "Soodus",
|
||||||
|
"paymentConfirmationLoading": "Makse kinnitamine..."
|
||||||
},
|
},
|
||||||
"montonioCallback": {
|
"montonioCallback": {
|
||||||
"title": "Montonio makseprotsess",
|
"title": "Montonio makseprotsess",
|
||||||
|
|||||||
@@ -75,10 +75,10 @@
|
|||||||
"orderAnalysis": "Telli analüüs",
|
"orderAnalysis": "Telli analüüs",
|
||||||
"orderHealthAnalysis": "Telli terviseuuring",
|
"orderHealthAnalysis": "Telli terviseuuring",
|
||||||
"account": "Konto",
|
"account": "Konto",
|
||||||
"members": "Liikmed",
|
"companyMembers": "Töötajate haldamine",
|
||||||
"billing": "Arveldamine",
|
"billing": "Eelarve",
|
||||||
"dashboard": "Ülevaade",
|
"companyDashboard": "Ülevaade",
|
||||||
"settings": "Seaded",
|
"companySettings": "Seaded",
|
||||||
"profile": "Profiil",
|
"profile": "Profiil",
|
||||||
"pickTime": "Vali aeg",
|
"pickTime": "Vali aeg",
|
||||||
"preferences": "Eelistused",
|
"preferences": "Eelistused",
|
||||||
|
|||||||
@@ -17,9 +17,14 @@
|
|||||||
"orderAnalysis": {
|
"orderAnalysis": {
|
||||||
"title": "Telli analüüs",
|
"title": "Telli analüüs",
|
||||||
"description": "Telli endale sobiv analüüs"
|
"description": "Telli endale sobiv analüüs"
|
||||||
|
},
|
||||||
|
"benefits": {
|
||||||
|
"title": "Sinu Medreport konto seis",
|
||||||
|
"validUntil": "Kehtiv kuni {{date}}"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"recommendations": {
|
"recommendations": {
|
||||||
"title": "Medreport soovitab teile"
|
"title": "Medreport soovitab teile",
|
||||||
|
"validUntil": "Kehtiv kuni {{date}}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"home": {
|
"home": {
|
||||||
"pageTitle": "Ettevõtte ülevaade",
|
"pageTitle": "Ettevõtte ülevaade",
|
||||||
"headerTitle": "{{companyName}} Tervisekassa kokkuvõte",
|
"headerTitle": "{{companyName}} tervise ülevaade",
|
||||||
"healthDetails": "Ettevõtte terviseandmed",
|
"healthDetails": "Ettevõtte terviseandmed",
|
||||||
"membersSettingsButtonTitle": "Halda töötajaid",
|
"membersSettingsButtonTitle": "Halda töötajaid",
|
||||||
"membersSettingsButtonDescription": "Lisa, muuda või eemalda töötajaid.",
|
"membersSettingsButtonDescription": "Lisa, muuda või eemalda töötajaid.",
|
||||||
@@ -28,17 +28,19 @@
|
|||||||
"budget": {
|
"budget": {
|
||||||
"title": "Ettevõtte Tervisekassa seis",
|
"title": "Ettevõtte Tervisekassa seis",
|
||||||
"balance": "Eelarve jääk {{balance}}",
|
"balance": "Eelarve jääk {{balance}}",
|
||||||
"volume": "Eelarve maht {{volume}}"
|
"volume": "Eelarve maht",
|
||||||
|
"membersCount": "Töötajate arv"
|
||||||
},
|
},
|
||||||
"data": {
|
"data": {
|
||||||
"reservations": "{{value}} teenust",
|
"reservations": "{{value}} tellimus(t)",
|
||||||
"analysis": "Analüüsid",
|
"analysis": "Analüüsid",
|
||||||
"doctorsAndSpecialists": "Eriarstid ja spetsialistid",
|
"doctorsAndSpecialists": "Eriarstid ja spetsialistid",
|
||||||
"researches": "Uuringud",
|
"researches": "Uuringud",
|
||||||
"healthResearchPlans": "Terviseuuringute paketid",
|
"analysisPackages": "Terviseuuringute paketid",
|
||||||
"serviceUsage": "{{value}} teenuse kasutust",
|
"analysisPackagesCount": "{{value}} tellimus(t)",
|
||||||
"serviceSum": "Teenuste summa",
|
"totalSum": "Tellitud teenuste summa",
|
||||||
"eclinic": "Digikliinik"
|
"eclinic": "Digikliinik",
|
||||||
|
"currentMonthUsageTotal": "Kasutatud eelarve"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"healthDetails": {
|
"healthDetails": {
|
||||||
@@ -60,7 +62,7 @@
|
|||||||
"youLabel": "Sina",
|
"youLabel": "Sina",
|
||||||
"emailLabel": "E-post",
|
"emailLabel": "E-post",
|
||||||
"roleLabel": "Roll",
|
"roleLabel": "Roll",
|
||||||
"primaryOwnerLabel": "Peaadministraator",
|
"primaryOwnerLabel": "Haldur",
|
||||||
"joinedAtLabel": "Liitus",
|
"joinedAtLabel": "Liitus",
|
||||||
"invitedAtLabel": "Kutsutud",
|
"invitedAtLabel": "Kutsutud",
|
||||||
"inviteMembersPageSubheading": "Kutsu töötajaid oma ettevõttesse",
|
"inviteMembersPageSubheading": "Kutsu töötajaid oma ettevõttesse",
|
||||||
@@ -185,7 +187,7 @@
|
|||||||
"signInWithDifferentAccountDescription": "Kui soovid kutse vastu võtta teise kontoga, logi välja ja tagasi sisse soovitud kontoga.",
|
"signInWithDifferentAccountDescription": "Kui soovid kutse vastu võtta teise kontoga, logi välja ja tagasi sisse soovitud kontoga.",
|
||||||
"acceptInvitationHeading": "Võta kutse vastu, et liituda ettevõttega {{accountName}}",
|
"acceptInvitationHeading": "Võta kutse vastu, et liituda ettevõttega {{accountName}}",
|
||||||
"acceptInvitationDescription": "Sind on kutsutud liituma ettevõttega {{accountName}}. Kui soovid kutse vastu võtta, vajuta allolevat nuppu.",
|
"acceptInvitationDescription": "Sind on kutsutud liituma ettevõttega {{accountName}}. Kui soovid kutse vastu võtta, vajuta allolevat nuppu.",
|
||||||
"continueAs": "Jätka kui {{email}}",
|
"continueAs": "Jätka kui {{fullName}}",
|
||||||
"joinTeamAccount": "Liitu ettevõttega",
|
"joinTeamAccount": "Liitu ettevõttega",
|
||||||
"joiningTeam": "Ettevõttega liitumine...",
|
"joiningTeam": "Ettevõttega liitumine...",
|
||||||
"leaveTeamInputLabel": "Palun kirjuta LEAVE kinnituseks, et ettevõttest lahkuda.",
|
"leaveTeamInputLabel": "Palun kirjuta LEAVE kinnituseks, et ettevõttest lahkuda.",
|
||||||
@@ -193,5 +195,6 @@
|
|||||||
"reservedNameError": "See nimi on reserveeritud. Palun vali mõni teine.",
|
"reservedNameError": "See nimi on reserveeritud. Palun vali mõni teine.",
|
||||||
"specialCharactersError": "Nimi ei tohi sisaldada erimärke. Palun vali mõni teine.",
|
"specialCharactersError": "Nimi ei tohi sisaldada erimärke. Palun vali mõni teine.",
|
||||||
"personalCode": "Isikukood",
|
"personalCode": "Isikukood",
|
||||||
"teamOwnerPersonalCodeLabel": "Omaniku isikukood"
|
"teamOwnerPersonalCodeLabel": "Omaniku isikukood",
|
||||||
|
"distributedBenefitsAmount": "Väljastatud toetus"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -169,5 +169,8 @@
|
|||||||
"updateAccountError": "Не удалось обновить данные аккаунта",
|
"updateAccountError": "Не удалось обновить данные аккаунта",
|
||||||
"updateAccountPreferencesSuccess": "Предпочтения аккаунта обновлены",
|
"updateAccountPreferencesSuccess": "Предпочтения аккаунта обновлены",
|
||||||
"updateAccountPreferencesError": "Не удалось обновить предпочтения аккаунта",
|
"updateAccountPreferencesError": "Не удалось обновить предпочтения аккаунта",
|
||||||
"consents": "Согласия"
|
"consents": "Согласия",
|
||||||
|
"healthBenefitForm": {
|
||||||
|
"updateSuccess": "Данные о выгоде обновлены"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,7 +121,6 @@
|
|||||||
"label": "Корзина ({{ items }})"
|
"label": "Корзина ({{ items }})"
|
||||||
},
|
},
|
||||||
"pageTitle": "Бюджет {{companyName}}",
|
"pageTitle": "Бюджет {{companyName}}",
|
||||||
"description": "Измените настройки бюджета компании.",
|
|
||||||
"saveChanges": "Сохранить изменения",
|
"saveChanges": "Сохранить изменения",
|
||||||
"healthBenefitForm": {
|
"healthBenefitForm": {
|
||||||
"title": "Форма здоровья",
|
"title": "Форма здоровья",
|
||||||
@@ -135,9 +134,9 @@
|
|||||||
},
|
},
|
||||||
"expensesOverview": {
|
"expensesOverview": {
|
||||||
"title": "Обзор расходов за 2025 год",
|
"title": "Обзор расходов за 2025 год",
|
||||||
"monthly": "Расход на одного сотрудника в месяц *",
|
"employeeCount": "Сотрудники корпоративного фонда здоровья",
|
||||||
"yearly": "Максимальный расход на одного человека в год *",
|
"managementFeeTotal": "Расходы на управление корпоративным фондом здоровья {{managementFee}} в месяц на одного сотрудника *",
|
||||||
"total": "Максимальный расход на {{employeeCount}} сотрудников в год *",
|
"currentMonthUsageTotal": "Расходы на корпоративный фонд здоровья в текущем месяце",
|
||||||
"sum": "Итого"
|
"total": "Общая сумма расходов на корпоративный фонд здоровья"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,10 @@
|
|||||||
"order": {
|
"order": {
|
||||||
"title": "Заказ",
|
"title": "Заказ",
|
||||||
"promotionsTotal": "Скидка",
|
"promotionsTotal": "Скидка",
|
||||||
|
"companyBenefitsTotal": "Скидка компании",
|
||||||
"subtotal": "Промежуточный итог",
|
"subtotal": "Промежуточный итог",
|
||||||
|
"benefitsTotal": "Оплачено за счет выгод",
|
||||||
|
"montonioTotal": "Оплачено за счет Montonio",
|
||||||
"total": "Сумма",
|
"total": "Сумма",
|
||||||
"giftCard": "Подарочная карта"
|
"giftCard": "Подарочная карта"
|
||||||
},
|
},
|
||||||
@@ -76,7 +79,8 @@
|
|||||||
"orderNumber": "Номер заказа",
|
"orderNumber": "Номер заказа",
|
||||||
"orderStatus": "Статус заказа",
|
"orderStatus": "Статус заказа",
|
||||||
"paymentStatus": "Статус оплаты",
|
"paymentStatus": "Статус оплаты",
|
||||||
"discount": "Скидка"
|
"discount": "Скидка",
|
||||||
|
"paymentConfirmationLoading": "Ожидание подтверждения оплаты..."
|
||||||
},
|
},
|
||||||
"montonioCallback": {
|
"montonioCallback": {
|
||||||
"title": "Процесс оплаты Montonio",
|
"title": "Процесс оплаты Montonio",
|
||||||
|
|||||||
@@ -75,10 +75,10 @@
|
|||||||
"orderAnalysis": "Заказать анализ",
|
"orderAnalysis": "Заказать анализ",
|
||||||
"orderHealthAnalysis": "Заказать обследование",
|
"orderHealthAnalysis": "Заказать обследование",
|
||||||
"account": "Аккаунт",
|
"account": "Аккаунт",
|
||||||
"members": "Участники",
|
"companyMembers": "Участники",
|
||||||
"billing": "Оплата",
|
"billing": "Оплата",
|
||||||
"dashboard": "Обзор",
|
"companyDashboard": "Обзор",
|
||||||
"settings": "Настройки",
|
"companySettings": "Настройки",
|
||||||
"profile": "Профиль",
|
"profile": "Профиль",
|
||||||
"pickTime": "Выбрать время",
|
"pickTime": "Выбрать время",
|
||||||
"preferences": "Предпочтения",
|
"preferences": "Предпочтения",
|
||||||
|
|||||||
@@ -17,9 +17,14 @@
|
|||||||
"orderAnalysis": {
|
"orderAnalysis": {
|
||||||
"title": "Заказать анализ",
|
"title": "Заказать анализ",
|
||||||
"description": "Закажите подходящий для вас анализ"
|
"description": "Закажите подходящий для вас анализ"
|
||||||
|
},
|
||||||
|
"benefits": {
|
||||||
|
"title": "Ваш счет Medreport",
|
||||||
|
"validUntil": "Действителен до {{date}}"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"recommendations": {
|
"recommendations": {
|
||||||
"title": "Medreport recommends"
|
"title": "Medreport рекомендует",
|
||||||
|
"validUntil": "Действителен до {{date}}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,17 +28,19 @@
|
|||||||
"budget": {
|
"budget": {
|
||||||
"title": "Баланс Tervisekassa компании",
|
"title": "Баланс Tervisekassa компании",
|
||||||
"balance": "Остаток бюджета {{balance}}",
|
"balance": "Остаток бюджета {{balance}}",
|
||||||
"volume": "Объем бюджета {{volume}}"
|
"volume": "Объем бюджета",
|
||||||
|
"membersCount": "Количество сотрудников"
|
||||||
},
|
},
|
||||||
"data": {
|
"data": {
|
||||||
"reservations": "{{value}} услуги",
|
"reservations": "{{value}} услуги",
|
||||||
"analysis": "Анализы",
|
"analysis": "Анализы",
|
||||||
"doctorsAndSpecialists": "Врачи и специалисты",
|
"doctorsAndSpecialists": "Врачи и специалисты",
|
||||||
"researches": "Исследования",
|
"researches": "Исследования",
|
||||||
"healthResearchPlans": "Пакеты медицинских исследований",
|
"analysisPackages": "Пакеты медицинских исследований",
|
||||||
"serviceUsage": "{{value}} использование услуг",
|
"analysisPackagesCount": "{{value}} использование услуг",
|
||||||
"serviceSum": "Сумма услуг",
|
"totalSum": "Сумма услуг",
|
||||||
"eclinic": "Дигиклиника"
|
"eclinic": "Дигиклиника",
|
||||||
|
"currentMonthUsageTotal": "Текущее использование бюджета"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"healthDetails": {
|
"healthDetails": {
|
||||||
@@ -185,7 +187,7 @@
|
|||||||
"signInWithDifferentAccountDescription": "Если вы хотите принять приглашение с другим аккаунтом, выйдите из системы и войдите с нужным аккаунтом.",
|
"signInWithDifferentAccountDescription": "Если вы хотите принять приглашение с другим аккаунтом, выйдите из системы и войдите с нужным аккаунтом.",
|
||||||
"acceptInvitationHeading": "Принять приглашение для присоединения к {{accountName}}",
|
"acceptInvitationHeading": "Принять приглашение для присоединения к {{accountName}}",
|
||||||
"acceptInvitationDescription": "Вас пригласили присоединиться к компании {{accountName}}. Чтобы принять приглашение, нажмите кнопку ниже.",
|
"acceptInvitationDescription": "Вас пригласили присоединиться к компании {{accountName}}. Чтобы принять приглашение, нажмите кнопку ниже.",
|
||||||
"continueAs": "Продолжить как {{email}}",
|
"continueAs": "Продолжить как {{fullName}}",
|
||||||
"joinTeamAccount": "Присоединиться к компании",
|
"joinTeamAccount": "Присоединиться к компании",
|
||||||
"joiningTeam": "Присоединение к компании...",
|
"joiningTeam": "Присоединение к компании...",
|
||||||
"leaveTeamInputLabel": "Пожалуйста, введите LEAVE для подтверждения выхода из компании.",
|
"leaveTeamInputLabel": "Пожалуйста, введите LEAVE для подтверждения выхода из компании.",
|
||||||
@@ -193,5 +195,6 @@
|
|||||||
"reservedNameError": "Это имя зарезервировано. Пожалуйста, выберите другое.",
|
"reservedNameError": "Это имя зарезервировано. Пожалуйста, выберите другое.",
|
||||||
"specialCharactersError": "Это имя не может содержать специальные символы. Пожалуйста, выберите другое.",
|
"specialCharactersError": "Это имя не может содержать специальные символы. Пожалуйста, выберите другое.",
|
||||||
"personalCode": "Идентификационный код",
|
"personalCode": "Идентификационный код",
|
||||||
"teamOwnerPersonalCodeLabel": "Идентификационный код владельца"
|
"teamOwnerPersonalCodeLabel": "Идентификационный код владельца",
|
||||||
|
"distributedBenefitsAmount": "Распределенные выплаты"
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user