Merge pull request #110 from MR-medreport/MED-97
feat(MED-97,MED-98): update company benefits views, payment with only benefits or split with montonio
This commit is contained in:
@@ -2,107 +2,13 @@
|
||||
|
||||
import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types';
|
||||
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
|
||||
import { placeOrder, retrieveCart } from '@lib/data/cart';
|
||||
import { listProductTypes } from '@lib/data/products';
|
||||
import type { StoreOrder } from '@medusajs/types';
|
||||
import { retrieveCart } from '@lib/data/cart';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { AccountWithParams } from '@kit/accounts/types/accounts';
|
||||
import { createNotificationsApi } from '@kit/notifications/api';
|
||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||
import { handlePlaceOrder } from '../../../_lib/server/cart-actions';
|
||||
|
||||
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 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) {
|
||||
const secretKey = process.env.MONTONIO_SECRET_KEY as string;
|
||||
|
||||
@@ -129,71 +35,6 @@ async function getCartByOrderToken(decoded: MontonioOrderToken) {
|
||||
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) {
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
if (!account) {
|
||||
@@ -203,99 +44,8 @@ export async function processMontonioCallback(orderToken: string) {
|
||||
try {
|
||||
const decoded = await decodeOrderToken(orderToken);
|
||||
const cart = await getCartByOrderToken(decoded);
|
||||
|
||||
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;
|
||||
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 };
|
||||
const result = await handlePlaceOrder({ cart });
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Failed to place order', error);
|
||||
throw new Error(`Failed to place order, message=${error}`);
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
import { retrieveCart } from '@lib/data/cart';
|
||||
@@ -13,6 +11,8 @@ import { findProductTypeIdByHandle } from '~/lib/utils';
|
||||
|
||||
import Cart from '../../_components/cart';
|
||||
import CartTimer from '../../_components/cart/cart-timer';
|
||||
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||
import { EnrichedCartItem } from '../../_components/cart/types';
|
||||
|
||||
export async function generateMetadata() {
|
||||
@@ -24,12 +24,21 @@ export async function generateMetadata() {
|
||||
}
|
||||
|
||||
async function CartPage() {
|
||||
const cart = await retrieveCart().catch((error) => {
|
||||
console.error('Failed to retrieve cart', error);
|
||||
return notFound();
|
||||
});
|
||||
const [
|
||||
cart,
|
||||
{ productTypes },
|
||||
{ account },
|
||||
] = await Promise.all([
|
||||
retrieveCart(),
|
||||
listProductTypes(),
|
||||
loadCurrentUserAccount(),
|
||||
]);
|
||||
|
||||
const { productTypes } = await listProductTypes();
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const balanceSummary = await new AccountBalanceService().getBalanceSummary(account.id);
|
||||
|
||||
const synlabAnalysisTypeId = findProductTypeIdByHandle(
|
||||
productTypes,
|
||||
@@ -70,9 +79,11 @@ async function CartPage() {
|
||||
{isTimerShown && <CartTimer cartItem={item} />}
|
||||
</PageHeader>
|
||||
<Cart
|
||||
accountId={account.id}
|
||||
cart={cart}
|
||||
synlabAnalyses={synlabAnalyses}
|
||||
ttoServiceItems={ttoServiceItems}
|
||||
balanceSummary={balanceSummary}
|
||||
/>
|
||||
</PageBody>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
'use client';
|
||||
|
||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||
import Divider from '@modules/common/components/divider';
|
||||
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { StoreOrder } from '@medusajs/types';
|
||||
import { AnalysisOrder } from '~/lib/types/analysis-order';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { retrieveOrder } from '@lib/data/orders';
|
||||
import { GlobalLoader } from '@kit/ui/makerkit/global-loader';
|
||||
|
||||
function OrderConfirmedLoadingWrapper({
|
||||
medusaOrder: initialMedusaOrder,
|
||||
order,
|
||||
}: {
|
||||
medusaOrder: StoreOrder;
|
||||
order: AnalysisOrder;
|
||||
}) {
|
||||
const [medusaOrder, setMedusaOrder] = useState<StoreOrder>(initialMedusaOrder);
|
||||
const fetchingRef = useRef(false);
|
||||
|
||||
const paymentStatus = medusaOrder.payment_status;
|
||||
const medusaOrderId = order.medusa_order_id;
|
||||
|
||||
useEffect(() => {
|
||||
if (paymentStatus === 'captured') {
|
||||
return;
|
||||
}
|
||||
|
||||
const interval = setInterval(async () => {
|
||||
if (fetchingRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetchingRef.current = true;
|
||||
const medusaOrder = await retrieveOrder(medusaOrderId, false);
|
||||
fetchingRef.current = false;
|
||||
|
||||
setMedusaOrder(medusaOrder);
|
||||
}, 2_000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [paymentStatus, medusaOrderId]);
|
||||
|
||||
const isPaid = paymentStatus === 'captured';
|
||||
|
||||
if (!isPaid) {
|
||||
return (
|
||||
<PageBody>
|
||||
<div className="flex flex-col justify-start items-center h-full pt-[10vh]">
|
||||
<div>
|
||||
<GlobalLoader />
|
||||
</div>
|
||||
<h4 className="text-center">
|
||||
<Trans i18nKey="cart:orderConfirmed.paymentConfirmationLoading" />
|
||||
</h4>
|
||||
</div>
|
||||
</PageBody>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageBody>
|
||||
<PageHeader title={<Trans i18nKey="cart:orderConfirmed.title" />} />
|
||||
<Divider />
|
||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 gap-y-6 lg:px-4">
|
||||
<OrderDetails order={order} />
|
||||
<Divider />
|
||||
<OrderItems medusaOrder={medusaOrder} />
|
||||
<CartTotals medusaOrder={medusaOrder} />
|
||||
</div>
|
||||
</PageBody>
|
||||
);
|
||||
}
|
||||
|
||||
export default OrderConfirmedLoadingWrapper;
|
||||
@@ -1,18 +1,13 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import 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 { retrieveOrder } from '@lib/data/orders';
|
||||
import Divider from '@modules/common/components/divider';
|
||||
|
||||
import { pathsConfig } from '@kit/shared/config';
|
||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||
import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
@@ -41,18 +36,7 @@ async function OrderConfirmedPage(props: {
|
||||
redirect(pathsConfig.app.myOrders);
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
return <OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />;
|
||||
}
|
||||
|
||||
export default withI18n(OrderConfirmedPage);
|
||||
|
||||
@@ -18,6 +18,8 @@ import { listOrders } from '~/medusa/lib/data/orders';
|
||||
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
|
||||
import OrderBlock from '../../_components/orders/order-block';
|
||||
|
||||
const ORDERS_LIMIT = 50;
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
@@ -27,10 +29,12 @@ export async function generateMetadata() {
|
||||
}
|
||||
|
||||
async function OrdersPage() {
|
||||
const medusaOrders = await listOrders();
|
||||
const analysisOrders = await getAnalysisOrders();
|
||||
const ttoOrders = await getTtoOrders();
|
||||
const { productTypes } = await listProductTypes();
|
||||
const [medusaOrders, analysisOrders, ttoOrders, { productTypes }] = await Promise.all([
|
||||
listOrders(ORDERS_LIMIT),
|
||||
getAnalysisOrders(),
|
||||
getTtoOrders(),
|
||||
listProductTypes(),
|
||||
]);
|
||||
|
||||
if (!medusaOrders || !productTypes || !ttoOrders) {
|
||||
redirect(pathsConfig.auth.signIn);
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { handleNavigateToPayment } from '@/lib/services/medusaCart.service';
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { initiatePaymentSession } from '@lib/data/cart';
|
||||
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -17,30 +15,39 @@ import AnalysisLocation from './analysis-location';
|
||||
import CartItems from './cart-items';
|
||||
import CartServiceItems from './cart-service-items';
|
||||
import DiscountCode from './discount-code';
|
||||
import { initiatePayment } from '../../_lib/server/cart-actions';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
||||
import { EnrichedCartItem } from './types';
|
||||
|
||||
const IS_DISCOUNT_SHOWN = true as boolean;
|
||||
|
||||
export default function Cart({
|
||||
accountId,
|
||||
cart,
|
||||
synlabAnalyses,
|
||||
ttoServiceItems,
|
||||
balanceSummary,
|
||||
}: {
|
||||
accountId: string;
|
||||
cart: StoreCart | null;
|
||||
synlabAnalyses: StoreCartLineItem[];
|
||||
ttoServiceItems: EnrichedCartItem[];
|
||||
balanceSummary: AccountBalanceSummary | null;
|
||||
}) {
|
||||
const {
|
||||
i18n: { language },
|
||||
} = useTranslation();
|
||||
|
||||
const [isInitiatingSession, setIsInitiatingSession] = useState(false);
|
||||
const router = useRouter();
|
||||
const [unavailableLineItemIds, setUnavailableLineItemIds] =
|
||||
useState<string[]>();
|
||||
|
||||
const items = cart?.items ?? [];
|
||||
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
||||
|
||||
if (!cart || items.length === 0) {
|
||||
if (!hasCartItems) {
|
||||
return (
|
||||
<div className="content-container py-5 lg:px-4">
|
||||
<div>
|
||||
@@ -60,32 +67,38 @@ export default function Cart({
|
||||
);
|
||||
}
|
||||
|
||||
async function initiatePayment() {
|
||||
async function initiateSession() {
|
||||
setIsInitiatingSession(true);
|
||||
const response = await initiatePaymentSession(cart!, {
|
||||
provider_id: 'pp_montonio_montonio',
|
||||
});
|
||||
if (response.payment_collection) {
|
||||
const { payment_sessions } = response.payment_collection;
|
||||
const paymentSessionId = payment_sessions![0]!.id;
|
||||
const result = await handleNavigateToPayment({
|
||||
|
||||
try {
|
||||
const { url, isFullyPaidByBenefits, orderId, unavailableLineItemIds } = await initiatePayment({
|
||||
accountId,
|
||||
balanceSummary: balanceSummary!,
|
||||
cart: cart!,
|
||||
language,
|
||||
paymentSessionId,
|
||||
});
|
||||
if (result.url) {
|
||||
window.location.href = result.url;
|
||||
if (unavailableLineItemIds) {
|
||||
setUnavailableLineItemIds(unavailableLineItemIds);
|
||||
}
|
||||
if (result.unavailableLineItemIds) {
|
||||
setUnavailableLineItemIds(result.unavailableLineItemIds);
|
||||
if (url) {
|
||||
window.location.href = url;
|
||||
} else if (isFullyPaidByBenefits) {
|
||||
if (typeof orderId !== 'number') {
|
||||
throw new Error('Order ID is missing');
|
||||
}
|
||||
} else {
|
||||
router.push(`/home/order/${orderId}/confirmed`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initiate payment', error);
|
||||
setIsInitiatingSession(false);
|
||||
}
|
||||
}
|
||||
|
||||
const hasCartItems = Array.isArray(cart.items) && cart.items.length > 0;
|
||||
const isLocationsShown = synlabAnalyses.length > 0;
|
||||
|
||||
const companyBenefitsTotal = balanceSummary?.totalBalance ?? 0;
|
||||
const montonioTotal = cart && companyBenefitsTotal > 0 ? cart.total - companyBenefitsTotal : cart.total;
|
||||
|
||||
return (
|
||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 lg:px-4">
|
||||
<div className="flex flex-col gap-y-6 bg-white">
|
||||
@@ -119,7 +132,7 @@ export default function Cart({
|
||||
</p>
|
||||
</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">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.promotionsTotal" />
|
||||
@@ -135,6 +148,24 @@ export default function Cart({
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{companyBenefitsTotal > 0 && (
|
||||
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||
<Trans i18nKey="cart:order.companyBenefitsTotal" />
|
||||
</p>
|
||||
</div>
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: (companyBenefitsTotal > cart.total ? cart.total : companyBenefitsTotal),
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
|
||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||
<p className="ml-0 text-sm font-bold">
|
||||
@@ -144,7 +175,7 @@ export default function Cart({
|
||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||
<p className="text-right text-sm">
|
||||
{formatCurrency({
|
||||
value: cart.total,
|
||||
value: montonioTotal < 0 ? 0 : montonioTotal,
|
||||
currencyCode: cart.currency_code,
|
||||
locale: language,
|
||||
})}
|
||||
@@ -180,10 +211,6 @@ export default function Cart({
|
||||
cart={{ ...cart }}
|
||||
synlabAnalyses={synlabAnalyses}
|
||||
/>
|
||||
<AnalysisLocation
|
||||
cart={{ ...cart }}
|
||||
synlabAnalyses={synlabAnalyses}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
@@ -192,7 +219,7 @@ export default function Cart({
|
||||
<div>
|
||||
<Button
|
||||
className="h-10"
|
||||
onClick={initiatePayment}
|
||||
onClick={initiateSession}
|
||||
disabled={isInitiatingSession}
|
||||
>
|
||||
{isInitiatingSession && (
|
||||
|
||||
@@ -3,12 +3,33 @@ import Link from 'next/link';
|
||||
import { ChevronRight, HeartPulse } from 'lucide-react';
|
||||
|
||||
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 { Trans } from '@kit/ui/trans';
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { cn } from '@kit/ui/lib/utils';
|
||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||
import { getAccountBalanceSummary } from '../_lib/server/balance-actions';
|
||||
|
||||
export default async function DashboardCards() {
|
||||
const { language } = await createI18nServerInstance();
|
||||
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
const balanceSummary = account ? await getAccountBalanceSummary(account.id) : null;
|
||||
|
||||
export default function DashboardCards() {
|
||||
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
|
||||
variant="gradient-success"
|
||||
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
||||
@@ -38,6 +59,34 @@ export default function DashboardCards() {
|
||||
</CardDescription>
|
||||
</CardFooter>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
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 { Database } from '@/packages/supabase/src/database.types';
|
||||
import { BlendingModeIcon, RulerHorizontalIcon } from '@radix-ui/react-icons';
|
||||
import { isNil } from 'lodash';
|
||||
import {
|
||||
@@ -15,7 +14,7 @@ import {
|
||||
User,
|
||||
} 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 { Button } from '@kit/ui/button';
|
||||
import {
|
||||
@@ -138,10 +137,7 @@ export default function Dashboard({
|
||||
bmiThresholds,
|
||||
}: {
|
||||
account: AccountWithParams;
|
||||
bmiThresholds: Omit<
|
||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
||||
'id'
|
||||
>[];
|
||||
bmiThresholds: Omit<BmiThresholds, 'id'>[];
|
||||
}) {
|
||||
const height = account.accountParams?.height || 0;
|
||||
const weight = account.accountParams?.weight || 0;
|
||||
|
||||
@@ -8,6 +8,11 @@ import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
const PaymentProviderIds = {
|
||||
COMPANY_BENEFITS: "pp_company-benefits_company-benefits",
|
||||
MONTONIO: "pp_montonio_montonio",
|
||||
};
|
||||
|
||||
export default function CartTotals({
|
||||
medusaOrder,
|
||||
}: {
|
||||
@@ -20,11 +25,16 @@ export default function CartTotals({
|
||||
currency_code,
|
||||
total,
|
||||
subtotal,
|
||||
tax_total,
|
||||
discount_total,
|
||||
gift_card_total,
|
||||
payment_collections,
|
||||
} = 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 (
|
||||
<div>
|
||||
<div className="txt-medium text-ui-fg-subtle flex flex-col gap-y-2">
|
||||
@@ -86,8 +96,11 @@ export default function CartTotals({
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
|
||||
<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">
|
||||
<span className="font-bold">
|
||||
<Trans i18nKey="cart:order.total" />
|
||||
@@ -104,7 +117,42 @@ export default function CartTotals({
|
||||
})}
|
||||
</span>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ import { formatDate } from 'date-fns';
|
||||
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import type { AnalysisOrder } from '~/lib/types/order';
|
||||
|
||||
export default function OrderDetails({
|
||||
order,
|
||||
}: {
|
||||
@@ -15,7 +13,7 @@ export default function OrderDetails({
|
||||
<span className="font-bold">
|
||||
<Trans i18nKey="cart:orderConfirmed.orderNumber" />:{' '}
|
||||
</span>
|
||||
<span>{order.id}</span>
|
||||
<span className="break-all">{order.id}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
|
||||
13
app/home/(user)/_lib/server/balance-actions.ts
Normal file
13
app/home/(user)/_lib/server/balance-actions.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
'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;
|
||||
}
|
||||
}
|
||||
347
app/home/(user)/_lib/server/cart-actions.ts
Normal file
347
app/home/(user)/_lib/server/cart-actions.ts
Normal file
@@ -0,0 +1,347 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import type { StoreCart, StoreOrder } from "@medusajs/types";
|
||||
|
||||
import { initiateMultiPaymentSession, placeOrder } from "@lib/data/cart";
|
||||
import type { AccountBalanceSummary } from "@kit/accounts/services/account-balance.service";
|
||||
import { handleNavigateToPayment } from "~/lib/services/medusaCart.service";
|
||||
import { loadCurrentUserAccount } from "./load-user-account";
|
||||
import { getOrderedAnalysisIds } from "~/lib/services/medusaOrder.service";
|
||||
import { createAnalysisOrder, getAnalysisOrder } from "~/lib/services/order.service";
|
||||
import { listProductTypes } from "@lib/data";
|
||||
import { sendOrderToMedipost } from "~/lib/services/medipost/medipostPrivateMessage.service";
|
||||
import { AccountWithParams } from "@/packages/features/accounts/src/types/accounts";
|
||||
import { createI18nServerInstance } from "~/lib/i18n/i18n.server";
|
||||
import { getSupabaseServerAdminClient } from "@/packages/supabase/src/clients/server-admin-client";
|
||||
import { createNotificationsApi } from "@/packages/features/notifications/src/server/api";
|
||||
import { FailureReason } from '~/lib/types/connected-online';
|
||||
import { getOrderedTtoServices } from '~/lib/services/reservation.service';
|
||||
import { bookAppointment } from '~/lib/services/connected-online.service';
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
};
|
||||
@@ -1,9 +1,8 @@
|
||||
import OpenAI from 'openai';
|
||||
|
||||
export const isValidOpenAiEnv = async () => {
|
||||
const client = new OpenAI();
|
||||
|
||||
try {
|
||||
const client = new OpenAI();
|
||||
await client.models.list();
|
||||
return true;
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,23 +1,14 @@
|
||||
import React from 'react';
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
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 { createPath, pathsConfig } from '@kit/shared/config';
|
||||
import { Card, CardTitle } from '@kit/ui/card';
|
||||
import { cn } from '@kit/ui/lib/utils';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
interface TeamAccountBenefitStatisticsProps {
|
||||
employeeCount: number;
|
||||
accountSlug: string;
|
||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
||||
}
|
||||
import { TeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
|
||||
|
||||
const StatisticsCard = ({ children }: { children: React.ReactNode }) => {
|
||||
return <Card className="p-4">{children}</Card>;
|
||||
@@ -46,126 +37,90 @@ const StatisticsValue = ({ children }: { children: React.ReactNode }) => {
|
||||
};
|
||||
|
||||
const TeamAccountBenefitStatistics = ({
|
||||
employeeCount,
|
||||
accountSlug,
|
||||
companyParams,
|
||||
}: TeamAccountBenefitStatisticsProps) => {
|
||||
accountBenefitStatistics,
|
||||
expensesOverview,
|
||||
}: {
|
||||
accountBenefitStatistics: AccountBenefitStatistics;
|
||||
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||
}) => {
|
||||
const {
|
||||
i18n: { language },
|
||||
} = useTranslation();
|
||||
|
||||
return (
|
||||
<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">
|
||||
<StatisticsCard>
|
||||
<StatisticsCardTitle className="text-lg font-bold">
|
||||
<Trans i18nKey="teams:benefitStatistics.data.serviceSum" />
|
||||
<Trans i18nKey="teams:benefitStatistics.budget.membersCount" />
|
||||
</StatisticsCardTitle>
|
||||
<StatisticsValue>1800 €</StatisticsValue>
|
||||
<StatisticsValue>
|
||||
{accountBenefitStatistics.companyAccountsCount}
|
||||
</StatisticsValue>
|
||||
</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>
|
||||
<StatisticsCardTitle>
|
||||
<Trans i18nKey="teams:benefitStatistics.data.analysis" />
|
||||
</StatisticsCardTitle>
|
||||
<StatisticsValue>200 €</StatisticsValue>
|
||||
<StatisticsValue>
|
||||
{formatCurrency({
|
||||
value: accountBenefitStatistics.orders.analysesSum,
|
||||
locale: language,
|
||||
currencyCode: 'EUR',
|
||||
})}
|
||||
</StatisticsValue>
|
||||
<StatisticsDescription>
|
||||
<Trans
|
||||
i18nKey="teams:benefitStatistics.data.reservations"
|
||||
values={{ value: 36 }}
|
||||
/>
|
||||
</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 }}
|
||||
values={{ value: accountBenefitStatistics.orders.analysesCount }}
|
||||
/>
|
||||
</StatisticsDescription>
|
||||
</StatisticsCard>
|
||||
|
||||
<StatisticsCard>
|
||||
<StatisticsCardTitle>
|
||||
<Trans i18nKey="teams:benefitStatistics.data.healthResearchPlans" />
|
||||
<Trans i18nKey="teams:benefitStatistics.data.analysisPackages" />
|
||||
</StatisticsCardTitle>
|
||||
<StatisticsValue>200 €</StatisticsValue>
|
||||
<StatisticsValue>
|
||||
{formatCurrency({
|
||||
value: accountBenefitStatistics.orders.analysisPackagesSum,
|
||||
locale: language,
|
||||
currencyCode: 'EUR',
|
||||
})}
|
||||
</StatisticsValue>
|
||||
<StatisticsDescription>
|
||||
<Trans
|
||||
i18nKey="teams:benefitStatistics.data.serviceUsage"
|
||||
values={{ value: 46 }}
|
||||
i18nKey="teams:benefitStatistics.data.analysisPackagesCount"
|
||||
values={{
|
||||
value: accountBenefitStatistics.orders.analysisPackagesCount,
|
||||
}}
|
||||
/>
|
||||
</StatisticsDescription>
|
||||
</StatisticsCard>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Database } from '@/packages/supabase/src/database.types';
|
||||
import { Card } from '@kit/ui/card';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { cn } from '@kit/ui/utils';
|
||||
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||
|
||||
import { getAccountHealthDetailsFields } from '../_lib/server/load-team-account-health-details';
|
||||
import { TeamAccountStatisticsProps } from './team-account-statistics';
|
||||
@@ -15,10 +16,7 @@ const TeamAccountHealthDetails = ({
|
||||
members,
|
||||
}: {
|
||||
memberParams: TeamAccountStatisticsProps['memberParams'];
|
||||
bmiThresholds: Omit<
|
||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
||||
'id'
|
||||
>[];
|
||||
bmiThresholds: Omit<BmiThresholds, 'id'>[];
|
||||
members: Database['medreport']['Functions']['get_account_members']['Returns'];
|
||||
}) => {
|
||||
const accountHealthDetailsFields = getAccountHealthDetailsFields(
|
||||
|
||||
@@ -14,28 +14,21 @@ import { createPath, pathsConfig } from '@kit/shared/config';
|
||||
import { Card } from '@kit/ui/card';
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Button } from '@kit/ui/shadcn/button';
|
||||
import { Calendar, DateRange } from '@kit/ui/shadcn/calendar';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@kit/ui/shadcn/popover';
|
||||
import { DateRange } from '@kit/ui/shadcn/calendar';
|
||||
|
||||
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
|
||||
import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
|
||||
import TeamAccountHealthDetails from './team-account-health-details';
|
||||
import type { Account, AccountParams, BmiThresholds } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { TeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||
|
||||
export interface TeamAccountStatisticsProps {
|
||||
teamAccount: Database['medreport']['Tables']['accounts']['Row'];
|
||||
memberParams: Pick<
|
||||
Database['medreport']['Tables']['account_params']['Row'],
|
||||
'weight' | 'height'
|
||||
>[];
|
||||
bmiThresholds: Omit<
|
||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
||||
'id'
|
||||
>[];
|
||||
teamAccount: Account;
|
||||
memberParams: Pick<AccountParams, 'weight' | 'height'>[];
|
||||
bmiThresholds: Omit<BmiThresholds, 'id'>[];
|
||||
members: Database['medreport']['Functions']['get_account_members']['Returns'];
|
||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
||||
accountBenefitStatistics: AccountBenefitStatistics;
|
||||
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||
}
|
||||
|
||||
export default function TeamAccountStatistics({
|
||||
@@ -43,11 +36,13 @@ export default function TeamAccountStatistics({
|
||||
memberParams,
|
||||
bmiThresholds,
|
||||
members,
|
||||
companyParams,
|
||||
accountBenefitStatistics,
|
||||
expensesOverview,
|
||||
}: TeamAccountStatisticsProps) {
|
||||
const currentDate = new Date();
|
||||
const [date, setDate] = useState<DateRange | undefined>({
|
||||
from: new Date(),
|
||||
to: new Date(),
|
||||
from: new Date(currentDate.getFullYear(), currentDate.getMonth(), 1),
|
||||
to: new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0),
|
||||
});
|
||||
const {
|
||||
i18n: { language },
|
||||
@@ -58,7 +53,7 @@ export default function TeamAccountStatistics({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<div className="mt-4 flex flex-col gap-4 sm:gap-0 sm:flex-row items-center justify-between">
|
||||
<h4 className="font-bold">
|
||||
<Trans
|
||||
i18nKey={'teams:home.headerTitle'}
|
||||
@@ -66,8 +61,6 @@ export default function TeamAccountStatistics({
|
||||
/>
|
||||
</h4>
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" data-empty={!date}>
|
||||
<CalendarIcon />
|
||||
{date?.from && date?.to ? (
|
||||
@@ -78,16 +71,6 @@ export default function TeamAccountStatistics({
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0">
|
||||
<Calendar
|
||||
mode="range"
|
||||
selected={date}
|
||||
onSelect={setDate}
|
||||
locale={language === 'et' ? et : enGB}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -95,11 +78,7 @@ export default function TeamAccountStatistics({
|
||||
'animate-in fade-in flex flex-col space-y-4 pb-36 duration-500'
|
||||
}
|
||||
>
|
||||
<TeamAccountBenefitStatistics
|
||||
employeeCount={members.length}
|
||||
accountSlug={teamAccount.slug || ''}
|
||||
companyParams={companyParams}
|
||||
/>
|
||||
<TeamAccountBenefitStatistics accountBenefitStatistics={accountBenefitStatistics} expensesOverview={expensesOverview} />
|
||||
|
||||
<h5 className="mt-4 mb-2">
|
||||
<Trans i18nKey="teams:home.healthDetails" />
|
||||
@@ -148,7 +127,7 @@ export default function TeamAccountStatistics({
|
||||
redirect(
|
||||
createPath(
|
||||
pathsConfig.app.accountBilling,
|
||||
teamAccount.slug || '',
|
||||
teamAccount.slug!,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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.50;
|
||||
|
||||
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,95 @@
|
||||
'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),
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '~/lib/utils';
|
||||
|
||||
import { TeamAccountStatisticsProps } from '../../_components/team-account-statistics';
|
||||
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||
|
||||
interface AccountHealthDetailsField {
|
||||
title: string;
|
||||
@@ -25,10 +26,7 @@ interface AccountHealthDetailsField {
|
||||
|
||||
export const getAccountHealthDetailsFields = (
|
||||
memberParams: TeamAccountStatisticsProps['memberParams'],
|
||||
bmiThresholds: Omit<
|
||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
||||
'id'
|
||||
>[],
|
||||
bmiThresholds: Omit<BmiThresholds, 'id'>[],
|
||||
members: Database['medreport']['Functions']['get_account_members']['Returns'],
|
||||
): AccountHealthDetailsField[] => {
|
||||
const averageWeight =
|
||||
@@ -82,7 +80,7 @@ export const getAccountHealthDetailsFields = (
|
||||
},
|
||||
{
|
||||
title: 'teams:healthDetails.bmi',
|
||||
value: averageBMI,
|
||||
value: averageBMI!,
|
||||
Icon: TrendingUp,
|
||||
iconBg: getBmiBackgroundColor(bmiStatus),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { UpdateHealthBenefitSchema } from '@/packages/billing/core/src/schema';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
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 { 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';
|
||||
import { Account, CompanyParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
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,78 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
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 { 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 { 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';
|
||||
import HealthBenefitFormClient from './health-benefit-form-client';
|
||||
import YearlyExpensesOverview from './yearly-expenses-overview';
|
||||
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
||||
import { Account, CompanyParams } from '@/packages/features/accounts/src/types/accounts';
|
||||
|
||||
const HealthBenefitForm = ({
|
||||
const HealthBenefitForm = async ({
|
||||
account,
|
||||
companyParams,
|
||||
employeeCount,
|
||||
expensesOverview,
|
||||
}: {
|
||||
account: Database['medreport']['Tables']['accounts']['Row'];
|
||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
||||
account: Account;
|
||||
companyParams: CompanyParams;
|
||||
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 (
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="flex flex-col gap-6 px-6 text-left"
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<div className="flex flex-col gap-6 px-6 text-left">
|
||||
<div className="mt-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h4>
|
||||
@@ -81,27 +29,11 @@ const HealthBenefitForm = ({
|
||||
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="flex flex-col-reverse sm:flex-row gap-6">
|
||||
<div className="border-border w-full sm: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" />
|
||||
@@ -109,30 +41,30 @@ const HealthBenefitForm = ({
|
||||
<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 />
|
||||
<HealthBenefitFormClient
|
||||
account={account}
|
||||
companyParams={companyParams}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<div className="flex-1 space-y-6">
|
||||
<YearlyExpensesOverview
|
||||
employeeCount={employeeCount}
|
||||
companyParams={currentCompanyParams}
|
||||
expensesOverview={expensesOverview}
|
||||
/>
|
||||
<p className="text-muted-foreground mt-2 text-sm">
|
||||
|
||||
<p className="text-muted-foreground text-sm">
|
||||
<Trans i18nKey="billing:healthBenefitForm.info" />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,50 +1,19 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { Database } from '@/packages/supabase/src/database.types';
|
||||
'use client';
|
||||
|
||||
import { Trans } from '@kit/ui/makerkit/trans';
|
||||
import { Separator } from '@kit/ui/separator';
|
||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
||||
|
||||
const YearlyExpensesOverview = ({
|
||||
employeeCount = 0,
|
||||
companyParams,
|
||||
expensesOverview,
|
||||
}: {
|
||||
employeeCount?: number;
|
||||
companyParams: Database['medreport']['Tables']['company_params']['Row'];
|
||||
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||
}) => {
|
||||
const monthlyExpensePerEmployee = useMemo(() => {
|
||||
if (!companyParams.benefit_amount) {
|
||||
return '0.00';
|
||||
}
|
||||
|
||||
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]);
|
||||
const { i18n: { language } } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="border-border rounded-lg border p-6">
|
||||
@@ -53,41 +22,56 @@ const YearlyExpensesOverview = ({
|
||||
</h5>
|
||||
<div className="mt-5 flex justify-between">
|
||||
<p className="text-sm font-medium">
|
||||
<Trans i18nKey="billing:expensesOverview.monthly" />
|
||||
<Trans i18nKey="billing:expensesOverview.employeeCount" />
|
||||
</p>
|
||||
<span className="text-primary text-sm font-bold">
|
||||
{monthlyExpensePerEmployee} €
|
||||
{employeeCount}
|
||||
</span>
|
||||
</div>
|
||||
<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">
|
||||
<Trans
|
||||
i18nKey="billing:expensesOverview.total"
|
||||
values={{ employeeCount: employeeCount || 0 }}
|
||||
i18nKey="billing:expensesOverview.managementFeeTotal"
|
||||
values={{
|
||||
managementFee: formatCurrency({
|
||||
value: expensesOverview.managementFee,
|
||||
locale: language,
|
||||
currencyCode: 'EUR',
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</p>
|
||||
<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>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="mt-4 flex justify-between">
|
||||
<p className="font-semibold">
|
||||
<Trans i18nKey="billing:expensesOverview.sum" />
|
||||
<Trans i18nKey="billing:expensesOverview.total" />
|
||||
</p>
|
||||
<span className="font-semibold">
|
||||
{companyParams.benefit_amount
|
||||
? companyParams.benefit_amount * employeeCount
|
||||
: 0}{' '}
|
||||
€
|
||||
{formatCurrency({
|
||||
value: expensesOverview.total,
|
||||
locale: language,
|
||||
currencyCode: 'EUR',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
|
||||
import HealthBenefitForm from './_components/health-benefit-form';
|
||||
import { loadTeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||
|
||||
interface TeamAccountBillingPageProps {
|
||||
params: Promise<{ account: string }>;
|
||||
@@ -27,8 +28,14 @@ async function TeamAccountBillingPage({ params }: TeamAccountBillingPageProps) {
|
||||
const api = createTeamAccountsApi(client);
|
||||
|
||||
const account = await api.getTeamAccount(accountSlug);
|
||||
const companyParams = await api.getTeamAccountParams(account.id);
|
||||
const { members } = await api.getMembers(accountSlug);
|
||||
const [expensesOverview, companyParams] = await Promise.all([
|
||||
loadTeamAccountBenefitExpensesOverview({
|
||||
companyId: account.id,
|
||||
employeeCount: members.length,
|
||||
}),
|
||||
api.getTeamAccountParams(account.id),
|
||||
]);
|
||||
|
||||
return (
|
||||
<PageBody>
|
||||
@@ -36,6 +43,7 @@ async function TeamAccountBillingPage({ params }: TeamAccountBillingPageProps) {
|
||||
account={account}
|
||||
companyParams={companyParams}
|
||||
employeeCount={members.length}
|
||||
expensesOverview={expensesOverview}
|
||||
/>
|
||||
</PageBody>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { SupabaseClient } from '@supabase/supabase-js';
|
||||
import { Database } from '@/packages/supabase/src/database.types';
|
||||
|
||||
import { loadTeamWorkspace } from '~/home/[account]/_lib/server/team-account-workspace.loader';
|
||||
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
||||
|
||||
/**
|
||||
* Load data for the members page
|
||||
@@ -15,11 +16,13 @@ export async function loadMembersPageData(
|
||||
client: SupabaseClient<Database>,
|
||||
slug: string,
|
||||
) {
|
||||
const workspace = await loadTeamWorkspace(slug);
|
||||
return Promise.all([
|
||||
loadAccountMembers(client, slug),
|
||||
loadInvitations(client, slug),
|
||||
canAddMember,
|
||||
loadTeamWorkspace(slug),
|
||||
workspace,
|
||||
loadAccountMembersBenefitsUsage(getSupabaseServerAdminClient(), workspace.account.id),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -60,6 +63,27 @@ async function loadAccountMembers(
|
||||
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
|
||||
* @param client
|
||||
|
||||
@@ -42,7 +42,7 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
||||
const client = getSupabaseServerClient();
|
||||
const slug = (await params).account;
|
||||
|
||||
const [members, invitations, canAddMember, { user, account }] =
|
||||
const [members, invitations, canAddMember, { user, account }, membersBenefitsUsage] =
|
||||
await loadMembersPageData(client, slug);
|
||||
|
||||
const canManageRoles = account.permissions.includes('roles.manage');
|
||||
@@ -54,7 +54,7 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
||||
return (
|
||||
<>
|
||||
<TeamAccountLayoutPageHeader
|
||||
title={<Trans i18nKey={'common:routes.members'} />}
|
||||
title={<Trans i18nKey={'common:routes.companyMembers'} />}
|
||||
description={
|
||||
<AppBreadcrumbs values={{ [account.slug]: account.name }} />
|
||||
}
|
||||
@@ -98,6 +98,7 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
||||
members={members}
|
||||
isPrimaryOwner={isPrimaryOwner}
|
||||
canManageRoles={canManageRoles}
|
||||
membersBenefitsUsage={membersBenefitsUsage}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
} from '~/lib/services/audit/pageView.service';
|
||||
|
||||
import { Dashboard } from './_components/dashboard';
|
||||
import { loadAccountBenefitStatistics } from './_lib/server/load-team-account-benefit-statistics';
|
||||
import { loadTeamAccountBenefitExpensesOverview } from './_lib/server/load-team-account-benefit-expenses-overview';
|
||||
|
||||
interface TeamAccountHomePageProps {
|
||||
params: Promise<{ account: string }>;
|
||||
@@ -39,9 +41,11 @@ function TeamAccountHomePage({ params }: TeamAccountHomePageProps) {
|
||||
const teamAccount = use(teamAccountsApi.getTeamAccount(account));
|
||||
const { memberParams, members } = use(teamAccountsApi.getMembers(account));
|
||||
const bmiThresholds = use(userAnalysesApi.fetchBmiThresholds());
|
||||
const companyParams = use(
|
||||
teamAccountsApi.getTeamAccountParams(teamAccount.id),
|
||||
);
|
||||
const accountBenefitStatistics = use(loadAccountBenefitStatistics(teamAccount.id));
|
||||
const expensesOverview = use(loadTeamAccountBenefitExpensesOverview({
|
||||
companyId: teamAccount.id,
|
||||
employeeCount: members.length,
|
||||
}));
|
||||
|
||||
use(
|
||||
createPageViewLog({
|
||||
@@ -57,7 +61,8 @@ function TeamAccountHomePage({ params }: TeamAccountHomePageProps) {
|
||||
memberParams={memberParams}
|
||||
bmiThresholds={bmiThresholds}
|
||||
members={members}
|
||||
companyParams={companyParams}
|
||||
accountBenefitStatistics={accountBenefitStatistics}
|
||||
expensesOverview={expensesOverview}
|
||||
/>
|
||||
</PageBody>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Trans } from '@kit/ui/trans';
|
||||
|
||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||
import { toTitleCase } from '~/lib/utils';
|
||||
|
||||
interface JoinTeamAccountPageProps {
|
||||
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
|
||||
const membershipConfirmation = pathsConfig.auth.membershipConfirmation;
|
||||
|
||||
const email = auth.data.email ?? '';
|
||||
const fullName = toTitleCase(auth.data.user_metadata.full_name ?? '');
|
||||
|
||||
return (
|
||||
<AuthLayoutShell Logo={AppLogo}>
|
||||
<AcceptInvitationContainer
|
||||
email={email}
|
||||
fullName={fullName || auth.data.email || ''}
|
||||
inviteToken={token}
|
||||
invitation={invitation}
|
||||
paths={{
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
upsertAnalysisResponseElement,
|
||||
} from '../analysis-order.service';
|
||||
import { logMedipostDispatch } from '../audit.service';
|
||||
import { getAnalysisOrder, updateAnalysisOrderStatus } from '../order.service';
|
||||
import { getAnalysisOrder } from '../order.service';
|
||||
import { parseXML } from '../util/xml.service';
|
||||
import { MedipostValidationError } from './MedipostValidationError';
|
||||
import {
|
||||
@@ -430,14 +430,16 @@ export async function readPrivateMessageResponse({
|
||||
medipostExternalOrderId,
|
||||
});
|
||||
if (status.isPartial) {
|
||||
await updateAnalysisOrderStatus({
|
||||
await createUserAnalysesApi(getSupabaseServerAdminClient())
|
||||
.updateAnalysisOrderStatus({
|
||||
medusaOrderId,
|
||||
orderStatus: 'PARTIAL_ANALYSIS_RESPONSE',
|
||||
});
|
||||
hasAnalysisResponse = true;
|
||||
hasPartialAnalysisResponse = true;
|
||||
} else if (status.isCompleted) {
|
||||
await updateAnalysisOrderStatus({
|
||||
await createUserAnalysesApi(getSupabaseServerAdminClient())
|
||||
.updateAnalysisOrderStatus({
|
||||
medusaOrderId,
|
||||
orderStatus: 'FULL_ANALYSIS_RESPONSE',
|
||||
});
|
||||
@@ -622,5 +624,9 @@ export async function sendOrderToMedipost({
|
||||
hasAnalysisResults: false,
|
||||
medusaOrderId,
|
||||
});
|
||||
await updateAnalysisOrderStatus({ medusaOrderId, orderStatus: 'PROCESSING' });
|
||||
await createUserAnalysesApi(getSupabaseServerAdminClient())
|
||||
.updateAnalysisOrderStatus({
|
||||
medusaOrderId,
|
||||
orderStatus: 'PROCESSING',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,9 +85,15 @@ export async function handleDeleteCartItem({ lineId }: { lineId: string }) {
|
||||
export async function handleNavigateToPayment({
|
||||
language,
|
||||
paymentSessionId,
|
||||
amount,
|
||||
currencyCode,
|
||||
cartId,
|
||||
}: {
|
||||
language: string;
|
||||
paymentSessionId: string;
|
||||
amount: number;
|
||||
currencyCode: string;
|
||||
cartId: string;
|
||||
}) {
|
||||
const { account } = await loadCurrentUserAccount();
|
||||
if (!account) {
|
||||
@@ -130,11 +136,11 @@ export async function handleNavigateToPayment({
|
||||
await new MontonioOrderHandlerService().getMontonioPaymentLink({
|
||||
notificationUrl: `${env().medusaBackendPublicUrl}/hooks/payment/montonio_montonio`,
|
||||
returnUrl: `${env().siteUrl}/home/cart/montonio-callback`,
|
||||
amount: cart.total,
|
||||
currency: cart.currency_code.toUpperCase(),
|
||||
amount,
|
||||
currency: currencyCode.toUpperCase(),
|
||||
description: `Order from Medreport`,
|
||||
locale: language,
|
||||
merchantReference: `${account.id}:${paymentSessionId}:${cart.id}`,
|
||||
merchantReference: `${account.id}:${paymentSessionId}:${cartId}`,
|
||||
});
|
||||
|
||||
await createCartEntriesLog({
|
||||
|
||||
@@ -51,48 +51,6 @@ export async function createAnalysisOrder({
|
||||
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({
|
||||
medusaOrderId,
|
||||
analysisOrderId,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Database } from '@/packages/supabase/src/database.types';
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import Isikukood, { Gender } from 'isikukood';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
import { BmiCategory } from './types/bmi';
|
||||
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
@@ -45,10 +45,7 @@ export const bmiFromMetric = (kg: number, cm: number) => {
|
||||
};
|
||||
|
||||
export function getBmiStatus(
|
||||
thresholds: Omit<
|
||||
Database['medreport']['Tables']['bmi_thresholds']['Row'],
|
||||
'id'
|
||||
>[],
|
||||
thresholds: Omit<BmiThresholds, 'id'>[],
|
||||
params: { age: number; height: number; weight: number },
|
||||
): BmiCategory | null {
|
||||
const age = params.age;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"./personal-account-settings": "./src/components/personal-account-settings/index.ts",
|
||||
"./components": "./src/components/index.ts",
|
||||
"./hooks/*": "./src/hooks/*.ts",
|
||||
"./services/*": "./src/server/services/*.ts",
|
||||
"./api": "./src/server/api.ts",
|
||||
"./types/*": "./src/types/*.ts"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
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,3 @@
|
||||
import type { Database } from '@kit/supabase/database';
|
||||
|
||||
export type AccountBalanceEntry = Database['medreport']['Tables']['account_balance_entries']['Row'];
|
||||
@@ -1,23 +1,25 @@
|
||||
import { Database } from '@kit/supabase/database';
|
||||
|
||||
export type ApplicationRole =
|
||||
Database['medreport']['Tables']['accounts']['Row']['application_role'];
|
||||
export type ApplicationRole = Account['application_role'];
|
||||
export enum ApplicationRoleEnum {
|
||||
User = 'user',
|
||||
Doctor = 'doctor',
|
||||
SuperAdmin = 'super_admin',
|
||||
}
|
||||
|
||||
export type AccountWithParams =
|
||||
Database['medreport']['Tables']['accounts']['Row'] & {
|
||||
export type AccountParams =
|
||||
Database['medreport']['Tables']['account_params']['Row'];
|
||||
|
||||
export type Account = Database['medreport']['Tables']['accounts']['Row'];
|
||||
export type AccountWithParams = Account & {
|
||||
accountParams:
|
||||
| (Pick<
|
||||
Database['medreport']['Tables']['account_params']['Row'],
|
||||
'weight' | 'height'
|
||||
> & {
|
||||
isSmoker:
|
||||
| Database['medreport']['Tables']['account_params']['Row']['is_smoker']
|
||||
| null;
|
||||
| (Pick<AccountParams, 'weight' | 'height'> & {
|
||||
isSmoker: AccountParams['is_smoker'] | 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": {
|
||||
"@hookform/resolvers": "^5.0.1",
|
||||
"@kit/next": "workspace:*",
|
||||
"@kit/accounts": "workspace:*",
|
||||
"@kit/shared": "workspace:*",
|
||||
"@kit/supabase": "workspace:*",
|
||||
"@kit/tsconfig": "workspace:*",
|
||||
|
||||
@@ -11,7 +11,7 @@ import { EllipsisVertical } from 'lucide-react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
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 { Checkbox } from '@kit/ui/checkbox';
|
||||
import {
|
||||
@@ -44,8 +44,6 @@ import { AdminDeleteUserDialog } from './admin-delete-user-dialog';
|
||||
import { AdminImpersonateUserDialog } from './admin-impersonate-user-dialog';
|
||||
import { AdminResetPasswordDialog } from './admin-reset-password-dialog';
|
||||
|
||||
type Account = Database['medreport']['Tables']['accounts']['Row'];
|
||||
|
||||
const FiltersSchema = z.object({
|
||||
type: z.enum(['all', 'team', 'personal']),
|
||||
query: z.string().optional(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { Database } from '@kit/supabase/database';
|
||||
import { ApplicationRole } from '@kit/accounts/types/accounts';
|
||||
|
||||
const ConfirmationSchema = z.object({
|
||||
confirmation: z.custom<string>((value) => value === 'CONFIRM'),
|
||||
@@ -19,9 +19,7 @@ export const DeleteAccountSchema = ConfirmationSchema.extend({
|
||||
accountId: z.string().uuid(),
|
||||
});
|
||||
|
||||
type ApplicationRoleType =
|
||||
Database['medreport']['Tables']['accounts']['Row']['application_role'];
|
||||
export const UpdateAccountRoleSchema = z.object({
|
||||
accountId: z.string().uuid(),
|
||||
role: z.string() as z.ZodType<ApplicationRoleType>,
|
||||
role: z.string() as z.ZodType<ApplicationRole>,
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'server-only';
|
||||
import { SupabaseClient } from '@supabase/supabase-js';
|
||||
|
||||
import { Database } from '@kit/supabase/database';
|
||||
import type { ApplicationRole } from '@kit/accounts/types/accounts';
|
||||
|
||||
export function createAdminAccountsService(client: SupabaseClient<Database>) {
|
||||
return new AdminAccountsService(client);
|
||||
@@ -25,7 +26,7 @@ class AdminAccountsService {
|
||||
|
||||
async updateRole(
|
||||
accountId: string,
|
||||
role: Database['medreport']['Tables']['accounts']['Row']['application_role'],
|
||||
role: ApplicationRole,
|
||||
) {
|
||||
const { error } = await this.adminClient
|
||||
.schema('medreport')
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"@kit/supabase": "workspace:*",
|
||||
"@kit/tsconfig": "workspace:*",
|
||||
"@kit/ui": "workspace:*",
|
||||
"@kit/user-analyses": "workspace:*",
|
||||
"@makerkit/data-loader-supabase-core": "^0.0.10",
|
||||
"@makerkit/data-loader-supabase-nextjs": "^1.2.5",
|
||||
"@supabase/supabase-js": "2.49.4",
|
||||
|
||||
@@ -5,6 +5,7 @@ import { isBefore } from 'date-fns';
|
||||
import { renderDoctorSummaryReceivedEmail } from '@kit/email-templates';
|
||||
import { getFullName } from '@kit/shared/utils';
|
||||
import { getSupabaseServerClient } from '@kit/supabase/server-client';
|
||||
import { createUserAnalysesApi } from '@kit/user-analyses/api';
|
||||
|
||||
import { sendEmailFromTemplate } from '../../../../../../../lib/services/mailer.service';
|
||||
import { AnalysisResultDetails } from '../schema/doctor-analysis-detail-view.schema';
|
||||
@@ -641,7 +642,14 @@ export async function submitFeedback(
|
||||
}
|
||||
|
||||
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
|
||||
.schema('medreport')
|
||||
.from('accounts')
|
||||
@@ -649,19 +657,10 @@ export async function submitFeedback(
|
||||
.eq('is_personal_account', true)
|
||||
.eq('primary_owner_user_id', userId)
|
||||
.throwOnError(),
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('analysis_orders')
|
||||
.select('medusa_order_id, id')
|
||||
.eq('id', analysisOrderId)
|
||||
.limit(1)
|
||||
.throwOnError(),
|
||||
supabase
|
||||
.schema('medreport')
|
||||
.from('analysis_orders')
|
||||
.update({ status: 'COMPLETED' })
|
||||
.eq('id', analysisOrderId)
|
||||
.throwOnError(),
|
||||
createUserAnalysesApi(supabase).updateAnalysisOrderStatus({
|
||||
orderId: analysisOrderId,
|
||||
orderStatus: 'COMPLETED',
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!recipient?.[0]?.email) {
|
||||
|
||||
@@ -258,6 +258,37 @@ export async function setShippingMethod({
|
||||
.catch(medusaError);
|
||||
}
|
||||
|
||||
export async function initiateMultiPaymentSession(
|
||||
cart: HttpTypes.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(
|
||||
cart: HttpTypes.StoreCart,
|
||||
data: HttpTypes.StoreInitializePaymentSession,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { HttpTypes } from '@medusajs/types';
|
||||
|
||||
import { getAuthHeaders, getCacheOptions } from './cookies';
|
||||
|
||||
export const retrieveOrder = async (id: string) => {
|
||||
export const retrieveOrder = async (id: string, allowCache = true) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
};
|
||||
@@ -24,7 +24,7 @@ export const retrieveOrder = async (id: string) => {
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: 'force-cache',
|
||||
...(allowCache ? { cache: 'force-cache' } : {}),
|
||||
})
|
||||
.then(({ order }) => order)
|
||||
.catch((err) => medusaError(err));
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import Image from 'next/image';
|
||||
|
||||
import { useDismissNotification } from '@kit/notifications/hooks';
|
||||
import { Heading } from '@kit/ui/heading';
|
||||
import { If } from '@kit/ui/if';
|
||||
import { Separator } from '@kit/ui/separator';
|
||||
@@ -12,7 +11,7 @@ import { SignOutInvitationButton } from './sign-out-invitation-button';
|
||||
|
||||
export function AcceptInvitationContainer(props: {
|
||||
inviteToken: string;
|
||||
email: string;
|
||||
fullName: string;
|
||||
|
||||
invitation: {
|
||||
id: string;
|
||||
@@ -76,7 +75,7 @@ export function AcceptInvitationContainer(props: {
|
||||
/>
|
||||
|
||||
<InvitationSubmitButton
|
||||
email={props.email}
|
||||
fullName={props.fullName}
|
||||
accountName={props.invitation.account.name}
|
||||
/>
|
||||
</form>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Trans } from '@kit/ui/trans';
|
||||
|
||||
export function InvitationSubmitButton(props: {
|
||||
accountName: string;
|
||||
email: string;
|
||||
fullName: string;
|
||||
}) {
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
@@ -17,7 +17,7 @@ export function InvitationSubmitButton(props: {
|
||||
i18nKey={pending ? 'teams:joiningTeam' : 'teams:continueAs'}
|
||||
values={{
|
||||
accountName: props.accountName,
|
||||
email: props.email,
|
||||
fullName: props.fullName,
|
||||
}}
|
||||
/>
|
||||
</Button>
|
||||
|
||||
@@ -20,6 +20,7 @@ import { If } from '@kit/ui/if';
|
||||
import { Input } from '@kit/ui/input';
|
||||
import { ProfileAvatar } from '@kit/ui/profile-avatar';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { formatCurrency } from '@kit/shared/utils';
|
||||
|
||||
import { RemoveMemberDialog } from './remove-member-dialog';
|
||||
import { RoleBadge } from './role-badge';
|
||||
@@ -42,6 +43,10 @@ type AccountMembersTableProps = {
|
||||
userRoleHierarchy: number;
|
||||
isPrimaryOwner: boolean;
|
||||
canManageRoles: boolean;
|
||||
membersBenefitsUsage: {
|
||||
personal_account_id: string;
|
||||
benefit_amount: number;
|
||||
}[];
|
||||
};
|
||||
|
||||
export function AccountMembersTable({
|
||||
@@ -51,6 +56,7 @@ export function AccountMembersTable({
|
||||
isPrimaryOwner,
|
||||
userRoleHierarchy,
|
||||
canManageRoles,
|
||||
membersBenefitsUsage,
|
||||
}: AccountMembersTableProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
const { t } = useTranslation('teams');
|
||||
@@ -73,6 +79,7 @@ export function AccountMembersTable({
|
||||
currentUserId,
|
||||
currentAccountId,
|
||||
currentRoleHierarchy: userRoleHierarchy,
|
||||
membersBenefitsUsage,
|
||||
});
|
||||
|
||||
const filteredMembers = members
|
||||
@@ -122,9 +129,13 @@ function useGetColumns(
|
||||
currentUserId: string;
|
||||
currentAccountId: string;
|
||||
currentRoleHierarchy: number;
|
||||
membersBenefitsUsage: {
|
||||
personal_account_id: string;
|
||||
benefit_amount: number;
|
||||
}[];
|
||||
},
|
||||
): ColumnDef<Members[0]>[] {
|
||||
const { t } = useTranslation('teams');
|
||||
const { t, i18n: { language } } = useTranslation('teams');
|
||||
|
||||
return useMemo(
|
||||
() => [
|
||||
@@ -168,6 +179,23 @@ function useGetColumns(
|
||||
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'),
|
||||
cell: ({ row }) => {
|
||||
@@ -175,7 +203,7 @@ function useGetColumns(
|
||||
const isPrimaryOwner = primary_owner_user_id === user_id;
|
||||
|
||||
return (
|
||||
<span className={'flex items-center space-x-1'}>
|
||||
<span className={'flex items-center space-x-1 flex-wrap space-y-1 sm:space-y-0 sm:flex-nowrap'}>
|
||||
<RoleBadge role={role} />
|
||||
|
||||
<If condition={isPrimaryOwner}>
|
||||
|
||||
@@ -13,6 +13,8 @@ import { TeamAccountDangerZone } from './team-account-danger-zone';
|
||||
import { UpdateTeamAccountImage } from './update-team-account-image-container';
|
||||
import { UpdateTeamAccountNameForm } from './update-team-account-name-form';
|
||||
|
||||
const SHOW_TEAM_LOGO = false as boolean;
|
||||
|
||||
export function TeamAccountSettingsContainer(props: {
|
||||
account: {
|
||||
name: string;
|
||||
@@ -32,6 +34,7 @@ export function TeamAccountSettingsContainer(props: {
|
||||
}) {
|
||||
return (
|
||||
<div className={'flex w-full flex-col space-y-4'}>
|
||||
{SHOW_TEAM_LOGO && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
@@ -47,6 +50,7 @@ export function TeamAccountSettingsContainer(props: {
|
||||
<UpdateTeamAccountImage account={props.account} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -18,6 +18,7 @@ import { RenewInvitationSchema } from '../../schema/renew-invitation.schema';
|
||||
import { UpdateInvitationSchema } from '../../schema/update-invitation.schema';
|
||||
import { createAccountInvitationsService } from '../services/account-invitations.service';
|
||||
import { createAccountPerSeatBillingService } from '../services/account-per-seat-billing.service';
|
||||
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||
|
||||
/**
|
||||
* @name createInvitationsAction
|
||||
@@ -148,6 +149,7 @@ export const updateInvitationAction = enhanceAction(
|
||||
export const acceptInvitationAction = enhanceAction(
|
||||
async (data: FormData, user) => {
|
||||
const client = getSupabaseServerClient();
|
||||
const accountBalanceService = new AccountBalanceService();
|
||||
|
||||
const { inviteToken, nextPath } = AcceptInvitationSchema.parse(
|
||||
Object.fromEntries(data),
|
||||
@@ -171,6 +173,9 @@ export const acceptInvitationAction = enhanceAction(
|
||||
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
|
||||
await perSeatBillingService.increaseSeats(accountId);
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { getLogger } from '@kit/shared/logger';
|
||||
import { Database } from '@kit/supabase/database';
|
||||
|
||||
type Account = Database['medreport']['Tables']['accounts']['Row'];
|
||||
import type { Account } from '@kit/accounts/types/accounts';
|
||||
|
||||
export function createAccountWebhooksService() {
|
||||
return new AccountWebhooksService();
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { UuringuVastus } from '@kit/shared/types/medipost-analysis';
|
||||
import { toArray } from '@kit/shared/utils';
|
||||
import { Database } from '@kit/supabase/database';
|
||||
|
||||
import type { AnalysisOrder } from '../types/analysis-orders';
|
||||
import type { AnalysisOrder, AnalysisOrderStatus } from '../types/analysis-orders';
|
||||
import type {
|
||||
AnalysisResultDetailsElement,
|
||||
AnalysisResultDetailsMapped,
|
||||
@@ -450,6 +450,32 @@ class UserAnalysesApi {
|
||||
|
||||
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>) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Tables } from '@kit/supabase/database';
|
||||
|
||||
export type AnalysisOrder = Tables<{ schema: 'medreport' }, 'analysis_orders'>;
|
||||
export type AnalysisOrderStatus = AnalysisOrder['status'];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CreditCard, LayoutDashboard, Settings, Users } from 'lucide-react';
|
||||
import { Euro, LayoutDashboard, Settings, Users } from 'lucide-react';
|
||||
|
||||
import { NavigationConfigSchema } from '@kit/ui/navigation-schema';
|
||||
|
||||
@@ -11,18 +11,13 @@ const getRoutes = (account: string) => [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
label: 'common:routes.dashboard',
|
||||
label: 'common:routes.companyDashboard',
|
||||
path: pathsConfig.app.accountHome.replace('[account]', account),
|
||||
Icon: <LayoutDashboard className={iconClasses} />,
|
||||
end: true,
|
||||
},
|
||||
{
|
||||
label: 'common:routes.settings',
|
||||
path: createPath(pathsConfig.app.accountSettings, account),
|
||||
Icon: <Settings className={iconClasses} />,
|
||||
},
|
||||
{
|
||||
label: 'common:routes.members',
|
||||
label: 'common:routes.companyMembers',
|
||||
path: createPath(pathsConfig.app.accountMembers, account),
|
||||
Icon: <Users className={iconClasses} />,
|
||||
},
|
||||
@@ -30,9 +25,14 @@ const getRoutes = (account: string) => [
|
||||
? {
|
||||
label: 'common:routes.billing',
|
||||
path: createPath(pathsConfig.app.accountBilling, account),
|
||||
Icon: <CreditCard className={iconClasses} />,
|
||||
Icon: <Euro className={iconClasses} />,
|
||||
}
|
||||
: undefined,
|
||||
{
|
||||
label: 'common:routes.companySettings',
|
||||
path: createPath(pathsConfig.app.accountSettings, account),
|
||||
Icon: <Settings className={iconClasses} />,
|
||||
},
|
||||
].filter(Boolean),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -11,10 +11,10 @@ import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
||||
* @name getSupabaseServerClient
|
||||
* @description Creates a Supabase client for use in the Server.
|
||||
*/
|
||||
export function getSupabaseServerClient<GenericSchema = Database>() {
|
||||
export function getSupabaseServerClient() {
|
||||
const keys = getSupabaseClientKeys();
|
||||
|
||||
return createServerClient<GenericSchema>(keys.url, keys.anonKey, {
|
||||
return createServerClient<Database>(keys.url, keys.anonKey, {
|
||||
auth: {
|
||||
flowType: 'pkce',
|
||||
autoRefreshToken: true,
|
||||
|
||||
@@ -348,6 +348,8 @@ export type Database = {
|
||||
expires_at: string | null
|
||||
id: string
|
||||
is_active: boolean
|
||||
is_analysis_order: boolean
|
||||
is_analysis_package_order: boolean
|
||||
reference_id: string | null
|
||||
source_company_id: string | null
|
||||
}
|
||||
@@ -361,6 +363,8 @@ export type Database = {
|
||||
expires_at?: string | null
|
||||
id?: string
|
||||
is_active?: boolean
|
||||
is_analysis_order?: boolean
|
||||
is_analysis_package_order?: boolean
|
||||
reference_id?: string | null
|
||||
source_company_id?: string | null
|
||||
}
|
||||
@@ -374,6 +378,8 @@ export type Database = {
|
||||
expires_at?: string | null
|
||||
id?: string
|
||||
is_active?: boolean
|
||||
is_analysis_order?: boolean
|
||||
is_analysis_package_order?: boolean
|
||||
reference_id?: string | null
|
||||
source_company_id?: string | null
|
||||
}
|
||||
@@ -2310,6 +2316,15 @@ export type Database = {
|
||||
user_id: string
|
||||
}[]
|
||||
}
|
||||
get_benefits_usages_for_company_members: {
|
||||
Args: {
|
||||
p_account_id: string
|
||||
}
|
||||
Returns: {
|
||||
personal_account_id: string
|
||||
benefit_amount: number
|
||||
}
|
||||
}
|
||||
get_config: {
|
||||
Args: Record<PropertyKey, never>
|
||||
Returns: Json
|
||||
|
||||
6
pnpm-lock.yaml
generated
6
pnpm-lock.yaml
generated
@@ -646,6 +646,9 @@ importers:
|
||||
'@hookform/resolvers':
|
||||
specifier: ^5.0.1
|
||||
version: 5.2.1(react-hook-form@7.62.0(react@19.1.0))
|
||||
'@kit/accounts':
|
||||
specifier: workspace:*
|
||||
version: link:../accounts
|
||||
'@kit/next':
|
||||
specifier: workspace:*
|
||||
version: link:../../next
|
||||
@@ -754,6 +757,9 @@ importers:
|
||||
'@kit/ui':
|
||||
specifier: workspace:*
|
||||
version: link:../../ui
|
||||
'@kit/user-analyses':
|
||||
specifier: workspace:*
|
||||
version: link:../user-analyses
|
||||
'@makerkit/data-loader-supabase-core':
|
||||
specifier: ^0.0.10
|
||||
version: 0.0.10(@supabase/postgrest-js@1.19.4)(@supabase/supabase-js@2.49.4)
|
||||
|
||||
@@ -169,5 +169,8 @@
|
||||
"updateAccountError": "Updating account details failed",
|
||||
"updateAccountPreferencesSuccess": "Account preferences updated",
|
||||
"updateAccountPreferencesError": "Updating account preferences failed",
|
||||
"consents": "Consents"
|
||||
"consents": "Consents",
|
||||
"healthBenefitForm": {
|
||||
"updateSuccess": "Health benefit updated"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,6 @@
|
||||
"label": "Cart ({{ items }})"
|
||||
},
|
||||
"pageTitle": "{{companyName}} budget",
|
||||
"description": "Configure company budget..",
|
||||
"saveChanges": "Save changes",
|
||||
"healthBenefitForm": {
|
||||
"title": "Health benefit form",
|
||||
@@ -134,10 +133,10 @@
|
||||
"monthly": "Monthly"
|
||||
},
|
||||
"expensesOverview": {
|
||||
"title": "Expenses overview 2025",
|
||||
"monthly": "Expense per employee per month *",
|
||||
"yearly": "Maximum expense per employee per year *",
|
||||
"total": "Maximum expense per {{employeeCount}} employee(s) per year *",
|
||||
"sum": "Total"
|
||||
"title": "Health account budget overview 2025",
|
||||
"employeeCount": "Health account users",
|
||||
"managementFeeTotal": "Health account management fee {{managementFee}} per employee per month *",
|
||||
"currentMonthUsageTotal": "Health account current month usage",
|
||||
"total": "Health account budget total"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,10 @@
|
||||
"order": {
|
||||
"title": "Order",
|
||||
"promotionsTotal": "Promotions total",
|
||||
"companyBenefitsTotal": "Company benefits total",
|
||||
"subtotal": "Subtotal",
|
||||
"benefitsTotal": "Paid with benefits",
|
||||
"montonioTotal": "Paid with Montonio",
|
||||
"total": "Total",
|
||||
"giftCard": "Gift card"
|
||||
},
|
||||
@@ -76,7 +79,8 @@
|
||||
"orderNumber": "Order number",
|
||||
"orderStatus": "Order status",
|
||||
"paymentStatus": "Payment status",
|
||||
"discount": "Discount"
|
||||
"discount": "Discount",
|
||||
"paymentConfirmationLoading": "Payment confirmation..."
|
||||
},
|
||||
"montonioCallback": {
|
||||
"title": "Montonio checkout",
|
||||
|
||||
@@ -75,10 +75,10 @@
|
||||
"orderAnalysis": "Order analysis",
|
||||
"orderHealthAnalysis": "Order health check",
|
||||
"account": "Account",
|
||||
"members": "Members",
|
||||
"companyMembers": "Manage employees",
|
||||
"billing": "Billing",
|
||||
"dashboard": "Dashboard",
|
||||
"settings": "Settings",
|
||||
"companyDashboard": "Dashboard",
|
||||
"companySettings": "Settings",
|
||||
"profile": "Profile",
|
||||
"pickTime": "Pick time",
|
||||
"preferences": "Preferences",
|
||||
|
||||
@@ -17,9 +17,13 @@
|
||||
"orderAnalysis": {
|
||||
"title": "Order analysis",
|
||||
"description": "Select an analysis to get started"
|
||||
},
|
||||
"benefits": {
|
||||
"title": "Your company benefits"
|
||||
}
|
||||
},
|
||||
"recommendations": {
|
||||
"title": "Medreport recommends"
|
||||
"title": "Medreport recommends",
|
||||
"validUntil": "Valid until {{date}}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
{
|
||||
"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": {
|
||||
"pageTitle": "Company Settings",
|
||||
@@ -18,6 +24,34 @@
|
||||
"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}})",
|
||||
"createTeam": "Create a Company",
|
||||
"creatingTeam": "Creating Company...",
|
||||
@@ -28,7 +62,7 @@
|
||||
"youLabel": "You",
|
||||
"emailLabel": "Email",
|
||||
"roleLabel": "Role",
|
||||
"primaryOwnerLabel": "Primary Admin",
|
||||
"primaryOwnerLabel": "Manager",
|
||||
"joinedAtLabel": "Joined at",
|
||||
"invitedAtLabel": "Invited at",
|
||||
"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.",
|
||||
"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.",
|
||||
"continueAs": "Continue as {{email}}",
|
||||
"continueAs": "Continue as {{fullName}}",
|
||||
"joinTeamAccount": "Join Company",
|
||||
"joiningTeam": "Joining company...",
|
||||
"leaveTeamInputLabel": "Please type LEAVE to confirm leaving the company.",
|
||||
"leaveTeamInputDescription": "By leaving the company, you will no longer have access to it.",
|
||||
"reservedNameError": "This name is reserved. 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",
|
||||
"updateAccountPreferencesSuccess": "Konto eelistused uuendatud",
|
||||
"updateAccountPreferencesError": "Konto eelistused uuendamine ebaõnnestus",
|
||||
"consents": "Nõusolekud"
|
||||
"consents": "Nõusolekud",
|
||||
"healthBenefitForm": {
|
||||
"updateSuccess": "Tervisekonto andmed uuendatud"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,11 +121,10 @@
|
||||
"label": "Cart ({{ items }})"
|
||||
},
|
||||
"pageTitle": "{{companyName}} eelarve",
|
||||
"description": "Muuda ettevõtte eelarve seadistusi.",
|
||||
"saveChanges": "Salvesta muudatused",
|
||||
"healthBenefitForm": {
|
||||
"title": "Tervisetoetuse vorm",
|
||||
"description": "Ettevõtte Tervisekassa toetus töötajale",
|
||||
"description": "Ettevõtte tervisekonto seadistamine",
|
||||
"info": "* Hindadele lisanduvad riigipoolsed maksud"
|
||||
},
|
||||
"occurrence": {
|
||||
@@ -134,10 +133,10 @@
|
||||
"monthly": "Kord kuus"
|
||||
},
|
||||
"expensesOverview": {
|
||||
"title": "Kulude ülevaade 2025 aasta raames",
|
||||
"monthly": "Kulu töötaja kohta kuus *",
|
||||
"yearly": "Maksimaalne kulu inimese kohta kokku aastas *",
|
||||
"total": "Maksimaalne kulu {{employeeCount}} töötaja kohta aastas *",
|
||||
"sum": "Kokku"
|
||||
"title": "Tervisekonto eelarve ülevaade 2025",
|
||||
"employeeCount": "Tervisekonto kasutajate arv",
|
||||
"managementFeeTotal": "Tervisekonto haldustasu {{managementFee}} kuus töötaja kohta*",
|
||||
"currentMonthUsageTotal": "Tervisekonto jooksva kuu kasutus",
|
||||
"total": "Tervisekonto eelarve maht kokku"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,10 @@
|
||||
"order": {
|
||||
"title": "Tellimus",
|
||||
"promotionsTotal": "Soodustuse summa",
|
||||
"companyBenefitsTotal": "Toetuse summa",
|
||||
"subtotal": "Vahesumma",
|
||||
"benefitsTotal": "Tasutud tervisetoetusest",
|
||||
"montonioTotal": "Tasutud Montonio'ga",
|
||||
"total": "Summa",
|
||||
"giftCard": "Kinkekaart"
|
||||
},
|
||||
@@ -76,7 +79,8 @@
|
||||
"orderNumber": "Tellimuse number",
|
||||
"orderStatus": "Tellimuse olek",
|
||||
"paymentStatus": "Makse olek",
|
||||
"discount": "Soodus"
|
||||
"discount": "Soodus",
|
||||
"paymentConfirmationLoading": "Makse kinnitamine..."
|
||||
},
|
||||
"montonioCallback": {
|
||||
"title": "Montonio makseprotsess",
|
||||
|
||||
@@ -75,10 +75,10 @@
|
||||
"orderAnalysis": "Telli analüüs",
|
||||
"orderHealthAnalysis": "Telli terviseuuring",
|
||||
"account": "Konto",
|
||||
"members": "Liikmed",
|
||||
"billing": "Arveldamine",
|
||||
"dashboard": "Ülevaade",
|
||||
"settings": "Seaded",
|
||||
"companyMembers": "Töötajate haldamine",
|
||||
"billing": "Eelarve",
|
||||
"companyDashboard": "Ülevaade",
|
||||
"companySettings": "Seaded",
|
||||
"profile": "Profiil",
|
||||
"pickTime": "Vali aeg",
|
||||
"preferences": "Eelistused",
|
||||
|
||||
@@ -17,9 +17,14 @@
|
||||
"orderAnalysis": {
|
||||
"title": "Telli analüüs",
|
||||
"description": "Telli endale sobiv analüüs"
|
||||
},
|
||||
"benefits": {
|
||||
"title": "Sinu Medreport konto seis",
|
||||
"validUntil": "Kehtiv kuni {{date}}"
|
||||
}
|
||||
},
|
||||
"recommendations": {
|
||||
"title": "Medreport soovitab teile"
|
||||
"title": "Medreport soovitab teile",
|
||||
"validUntil": "Kehtiv kuni {{date}}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"home": {
|
||||
"pageTitle": "Ettevõtte ülevaade",
|
||||
"headerTitle": "{{companyName}} Tervisekassa kokkuvõte",
|
||||
"headerTitle": "{{companyName}} tervise ülevaade",
|
||||
"healthDetails": "Ettevõtte terviseandmed",
|
||||
"membersSettingsButtonTitle": "Halda töötajaid",
|
||||
"membersSettingsButtonDescription": "Lisa, muuda või eemalda töötajaid.",
|
||||
@@ -28,17 +28,19 @@
|
||||
"budget": {
|
||||
"title": "Ettevõtte Tervisekassa seis",
|
||||
"balance": "Eelarve jääk {{balance}}",
|
||||
"volume": "Eelarve maht {{volume}}"
|
||||
"volume": "Eelarve maht",
|
||||
"membersCount": "Töötajate arv"
|
||||
},
|
||||
"data": {
|
||||
"reservations": "{{value}} teenust",
|
||||
"reservations": "{{value}} tellimus(t)",
|
||||
"analysis": "Analüüsid",
|
||||
"doctorsAndSpecialists": "Eriarstid ja spetsialistid",
|
||||
"researches": "Uuringud",
|
||||
"healthResearchPlans": "Terviseuuringute paketid",
|
||||
"serviceUsage": "{{value}} teenuse kasutust",
|
||||
"serviceSum": "Teenuste summa",
|
||||
"eclinic": "Digikliinik"
|
||||
"analysisPackages": "Terviseuuringute paketid",
|
||||
"analysisPackagesCount": "{{value}} tellimus(t)",
|
||||
"totalSum": "Tellitud teenuste summa",
|
||||
"eclinic": "Digikliinik",
|
||||
"currentMonthUsageTotal": "Kasutatud eelarve"
|
||||
}
|
||||
},
|
||||
"healthDetails": {
|
||||
@@ -60,7 +62,7 @@
|
||||
"youLabel": "Sina",
|
||||
"emailLabel": "E-post",
|
||||
"roleLabel": "Roll",
|
||||
"primaryOwnerLabel": "Peaadministraator",
|
||||
"primaryOwnerLabel": "Haldur",
|
||||
"joinedAtLabel": "Liitus",
|
||||
"invitedAtLabel": "Kutsutud",
|
||||
"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.",
|
||||
"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.",
|
||||
"continueAs": "Jätka kui {{email}}",
|
||||
"continueAs": "Jätka kui {{fullName}}",
|
||||
"joinTeamAccount": "Liitu ettevõttega",
|
||||
"joiningTeam": "Ettevõttega liitumine...",
|
||||
"leaveTeamInputLabel": "Palun kirjuta LEAVE kinnituseks, et ettevõttest lahkuda.",
|
||||
@@ -193,5 +195,6 @@
|
||||
"reservedNameError": "See nimi on reserveeritud. Palun vali mõni teine.",
|
||||
"specialCharactersError": "Nimi ei tohi sisaldada erimärke. Palun vali mõni teine.",
|
||||
"personalCode": "Isikukood",
|
||||
"teamOwnerPersonalCodeLabel": "Omaniku isikukood"
|
||||
"teamOwnerPersonalCodeLabel": "Omaniku isikukood",
|
||||
"distributedBenefitsAmount": "Väljastatud toetus"
|
||||
}
|
||||
|
||||
@@ -169,5 +169,8 @@
|
||||
"updateAccountError": "Не удалось обновить данные аккаунта",
|
||||
"updateAccountPreferencesSuccess": "Предпочтения аккаунта обновлены",
|
||||
"updateAccountPreferencesError": "Не удалось обновить предпочтения аккаунта",
|
||||
"consents": "Согласия"
|
||||
"consents": "Согласия",
|
||||
"healthBenefitForm": {
|
||||
"updateSuccess": "Данные о выгоде обновлены"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,6 @@
|
||||
"label": "Корзина ({{ items }})"
|
||||
},
|
||||
"pageTitle": "Бюджет {{companyName}}",
|
||||
"description": "Измените настройки бюджета компании.",
|
||||
"saveChanges": "Сохранить изменения",
|
||||
"healthBenefitForm": {
|
||||
"title": "Форма здоровья",
|
||||
@@ -135,9 +134,9 @@
|
||||
},
|
||||
"expensesOverview": {
|
||||
"title": "Обзор расходов за 2025 год",
|
||||
"monthly": "Расход на одного сотрудника в месяц *",
|
||||
"yearly": "Максимальный расход на одного человека в год *",
|
||||
"total": "Максимальный расход на {{employeeCount}} сотрудников в год *",
|
||||
"sum": "Итого"
|
||||
"employeeCount": "Сотрудники корпоративного фонда здоровья",
|
||||
"managementFeeTotal": "Расходы на управление корпоративным фондом здоровья {{managementFee}} в месяц на одного сотрудника *",
|
||||
"currentMonthUsageTotal": "Расходы на корпоративный фонд здоровья в текущем месяце",
|
||||
"total": "Общая сумма расходов на корпоративный фонд здоровья"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,10 @@
|
||||
"order": {
|
||||
"title": "Заказ",
|
||||
"promotionsTotal": "Скидка",
|
||||
"companyBenefitsTotal": "Скидка компании",
|
||||
"subtotal": "Промежуточный итог",
|
||||
"benefitsTotal": "Оплачено за счет выгод",
|
||||
"montonioTotal": "Оплачено за счет Montonio",
|
||||
"total": "Сумма",
|
||||
"giftCard": "Подарочная карта"
|
||||
},
|
||||
@@ -76,7 +79,8 @@
|
||||
"orderNumber": "Номер заказа",
|
||||
"orderStatus": "Статус заказа",
|
||||
"paymentStatus": "Статус оплаты",
|
||||
"discount": "Скидка"
|
||||
"discount": "Скидка",
|
||||
"paymentConfirmationLoading": "Ожидание подтверждения оплаты..."
|
||||
},
|
||||
"montonioCallback": {
|
||||
"title": "Процесс оплаты Montonio",
|
||||
|
||||
@@ -75,10 +75,10 @@
|
||||
"orderAnalysis": "Заказать анализ",
|
||||
"orderHealthAnalysis": "Заказать обследование",
|
||||
"account": "Аккаунт",
|
||||
"members": "Участники",
|
||||
"companyMembers": "Участники",
|
||||
"billing": "Оплата",
|
||||
"dashboard": "Обзор",
|
||||
"settings": "Настройки",
|
||||
"companyDashboard": "Обзор",
|
||||
"companySettings": "Настройки",
|
||||
"profile": "Профиль",
|
||||
"pickTime": "Выбрать время",
|
||||
"preferences": "Предпочтения",
|
||||
|
||||
@@ -17,9 +17,14 @@
|
||||
"orderAnalysis": {
|
||||
"title": "Заказать анализ",
|
||||
"description": "Закажите подходящий для вас анализ"
|
||||
},
|
||||
"benefits": {
|
||||
"title": "Ваш счет Medreport",
|
||||
"validUntil": "Действителен до {{date}}"
|
||||
}
|
||||
},
|
||||
"recommendations": {
|
||||
"title": "Medreport recommends"
|
||||
"title": "Medreport рекомендует",
|
||||
"validUntil": "Действителен до {{date}}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,17 +28,19 @@
|
||||
"budget": {
|
||||
"title": "Баланс Tervisekassa компании",
|
||||
"balance": "Остаток бюджета {{balance}}",
|
||||
"volume": "Объем бюджета {{volume}}"
|
||||
"volume": "Объем бюджета",
|
||||
"membersCount": "Количество сотрудников"
|
||||
},
|
||||
"data": {
|
||||
"reservations": "{{value}} услуги",
|
||||
"analysis": "Анализы",
|
||||
"doctorsAndSpecialists": "Врачи и специалисты",
|
||||
"researches": "Исследования",
|
||||
"healthResearchPlans": "Пакеты медицинских исследований",
|
||||
"serviceUsage": "{{value}} использование услуг",
|
||||
"serviceSum": "Сумма услуг",
|
||||
"eclinic": "Дигиклиника"
|
||||
"analysisPackages": "Пакеты медицинских исследований",
|
||||
"analysisPackagesCount": "{{value}} использование услуг",
|
||||
"totalSum": "Сумма услуг",
|
||||
"eclinic": "Дигиклиника",
|
||||
"currentMonthUsageTotal": "Текущее использование бюджета"
|
||||
}
|
||||
},
|
||||
"healthDetails": {
|
||||
@@ -185,7 +187,7 @@
|
||||
"signInWithDifferentAccountDescription": "Если вы хотите принять приглашение с другим аккаунтом, выйдите из системы и войдите с нужным аккаунтом.",
|
||||
"acceptInvitationHeading": "Принять приглашение для присоединения к {{accountName}}",
|
||||
"acceptInvitationDescription": "Вас пригласили присоединиться к компании {{accountName}}. Чтобы принять приглашение, нажмите кнопку ниже.",
|
||||
"continueAs": "Продолжить как {{email}}",
|
||||
"continueAs": "Продолжить как {{fullName}}",
|
||||
"joinTeamAccount": "Присоединиться к компании",
|
||||
"joiningTeam": "Присоединение к компании...",
|
||||
"leaveTeamInputLabel": "Пожалуйста, введите LEAVE для подтверждения выхода из компании.",
|
||||
@@ -193,5 +195,6 @@
|
||||
"reservedNameError": "Это имя зарезервировано. Пожалуйста, выберите другое.",
|
||||
"specialCharactersError": "Это имя не может содержать специальные символы. Пожалуйста, выберите другое.",
|
||||
"personalCode": "Идентификационный код",
|
||||
"teamOwnerPersonalCodeLabel": "Идентификационный код владельца"
|
||||
"teamOwnerPersonalCodeLabel": "Идентификационный код владельца",
|
||||
"distributedBenefitsAmount": "Распределенные выплаты"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
alter table medreport.account_balance_entries add column "is_analysis_order" boolean;
|
||||
alter table medreport.account_balance_entries add column "is_analysis_package_order" boolean;
|
||||
|
||||
drop function if exists medreport.consume_account_balance(uuid, numeric, text, text);
|
||||
|
||||
-- Create function to consume balance (for purchases)
|
||||
create or replace function medreport.consume_account_balance(
|
||||
p_account_id uuid,
|
||||
p_amount numeric,
|
||||
p_description text,
|
||||
p_reference_id text default null,
|
||||
p_is_analysis_order boolean default false,
|
||||
p_is_analysis_package_order boolean default false
|
||||
)
|
||||
returns boolean
|
||||
language plpgsql
|
||||
security definer
|
||||
as $$
|
||||
declare
|
||||
current_balance numeric;
|
||||
remaining_amount numeric := p_amount;
|
||||
entry_record record;
|
||||
consumed_amount numeric;
|
||||
begin
|
||||
-- Get current balance
|
||||
current_balance := medreport.get_account_balance(p_account_id);
|
||||
|
||||
-- Check if sufficient balance
|
||||
if current_balance < p_amount then
|
||||
return false;
|
||||
end if;
|
||||
|
||||
-- Record the consumption
|
||||
insert into medreport.account_balance_entries (
|
||||
account_id,
|
||||
amount,
|
||||
entry_type,
|
||||
description,
|
||||
reference_id,
|
||||
created_by,
|
||||
is_analysis_order,
|
||||
is_analysis_package_order
|
||||
) values (
|
||||
p_account_id,
|
||||
-p_amount,
|
||||
'purchase',
|
||||
p_description,
|
||||
p_reference_id,
|
||||
auth.uid(),
|
||||
p_is_analysis_order,
|
||||
p_is_analysis_package_order
|
||||
);
|
||||
|
||||
return true;
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- Grant execute permission
|
||||
grant execute on function medreport.consume_account_balance(uuid, numeric, text, text, boolean, boolean) to authenticated, service_role;
|
||||
219
supabase/migrations/20250926135946_include_benefit_config_id.sql
Normal file
219
supabase/migrations/20250926135946_include_benefit_config_id.sql
Normal file
@@ -0,0 +1,219 @@
|
||||
ALTER TABLE medreport.account_balance_entries ADD COLUMN benefit_distribution_schedule_id uuid;
|
||||
|
||||
-- Also setting `benefit_distribution_schedule_id` value now
|
||||
drop function if exists medreport.distribute_health_benefits(uuid, numeric, text);
|
||||
create or replace function medreport.distribute_health_benefits(
|
||||
p_benefit_distribution_schedule_id uuid
|
||||
)
|
||||
returns void
|
||||
language plpgsql
|
||||
security definer
|
||||
as $$
|
||||
declare
|
||||
member_record record;
|
||||
expires_date timestamp with time zone;
|
||||
v_company_id uuid;
|
||||
v_benefit_amount numeric;
|
||||
begin
|
||||
-- Expires on first day of next year.
|
||||
expires_date := date_trunc('year', now() + interval '1 year');
|
||||
|
||||
-- Get company_id and benefit_amount from benefit_distribution_schedule
|
||||
select company_id, benefit_amount into v_company_id, v_benefit_amount
|
||||
from medreport.benefit_distribution_schedule
|
||||
where id = p_benefit_distribution_schedule_id;
|
||||
|
||||
-- Get all personal accounts that are members of this company
|
||||
for member_record in
|
||||
select distinct a.id as personal_account_id
|
||||
from medreport.accounts a
|
||||
join medreport.accounts_memberships am on a.id = am.user_id
|
||||
where am.account_id = v_company_id
|
||||
and a.is_personal_account = true
|
||||
loop
|
||||
-- Check if there is already a balance entry for this personal account from the same company in same month
|
||||
if exists (
|
||||
select 1
|
||||
from medreport.account_balance_entries
|
||||
where entry_type = 'benefit'
|
||||
and account_id = member_record.personal_account_id
|
||||
and source_company_id = v_company_id
|
||||
and date_trunc('month', created_at) = date_trunc('month', now())
|
||||
) then
|
||||
continue;
|
||||
end if;
|
||||
|
||||
-- Insert balance entry for each personal account
|
||||
insert into medreport.account_balance_entries (
|
||||
account_id,
|
||||
amount,
|
||||
entry_type,
|
||||
description,
|
||||
source_company_id,
|
||||
created_by,
|
||||
expires_at,
|
||||
benefit_distribution_schedule_id
|
||||
) values (
|
||||
member_record.personal_account_id,
|
||||
v_benefit_amount,
|
||||
'benefit',
|
||||
'Health benefit from company',
|
||||
v_company_id,
|
||||
auth.uid(),
|
||||
expires_date,
|
||||
p_benefit_distribution_schedule_id
|
||||
);
|
||||
end loop;
|
||||
end;
|
||||
$$;
|
||||
|
||||
grant execute on function medreport.distribute_health_benefits(uuid) to authenticated, service_role;
|
||||
|
||||
create or replace function medreport.process_periodic_benefit_distributions()
|
||||
returns void
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
schedule_record record;
|
||||
next_distribution_date timestamp with time zone;
|
||||
begin
|
||||
-- Get all active schedules that are due for distribution
|
||||
for schedule_record in
|
||||
select *
|
||||
from medreport.benefit_distribution_schedule
|
||||
where is_active = true
|
||||
and next_distribution_at <= now()
|
||||
loop
|
||||
-- Distribute benefits
|
||||
perform medreport.distribute_health_benefits(
|
||||
schedule_record.id
|
||||
);
|
||||
|
||||
-- Calculate next distribution date
|
||||
next_distribution_date := medreport.calculate_next_distribution_date(
|
||||
schedule_record.benefit_occurrence,
|
||||
now()
|
||||
);
|
||||
|
||||
-- Update the schedule
|
||||
update medreport.benefit_distribution_schedule
|
||||
set
|
||||
last_distributed_at = now(),
|
||||
next_distribution_at = next_distribution_date,
|
||||
updated_at = now()
|
||||
where id = schedule_record.id;
|
||||
end loop;
|
||||
end;
|
||||
$$;
|
||||
|
||||
DROP FUNCTION IF EXISTS medreport.upsert_benefit_distribution_schedule(uuid,numeric,text);
|
||||
create or replace function medreport.upsert_benefit_distribution_schedule(
|
||||
p_company_id uuid,
|
||||
p_benefit_amount numeric,
|
||||
p_benefit_occurrence text
|
||||
)
|
||||
-- Return schedule row id
|
||||
returns uuid
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
next_distribution_date timestamp with time zone;
|
||||
record_id uuid;
|
||||
begin
|
||||
-- Calculate next distribution date
|
||||
next_distribution_date := medreport.calculate_next_distribution_date(p_benefit_occurrence);
|
||||
|
||||
-- Check if there's an existing record for this company
|
||||
select id into record_id
|
||||
from medreport.benefit_distribution_schedule
|
||||
where company_id = p_company_id
|
||||
limit 1;
|
||||
|
||||
if record_id is not null then
|
||||
-- Update existing record
|
||||
update medreport.benefit_distribution_schedule
|
||||
set
|
||||
benefit_amount = p_benefit_amount,
|
||||
benefit_occurrence = p_benefit_occurrence,
|
||||
next_distribution_at = next_distribution_date,
|
||||
is_active = true,
|
||||
updated_at = now()
|
||||
where id = record_id;
|
||||
else
|
||||
record_id := gen_random_uuid();
|
||||
|
||||
-- Insert new record
|
||||
insert into medreport.benefit_distribution_schedule (
|
||||
id,
|
||||
company_id,
|
||||
benefit_amount,
|
||||
benefit_occurrence,
|
||||
next_distribution_at
|
||||
) values (
|
||||
record_id,
|
||||
p_company_id,
|
||||
p_benefit_amount,
|
||||
p_benefit_occurrence,
|
||||
next_distribution_date
|
||||
);
|
||||
end if;
|
||||
|
||||
return record_id;
|
||||
end;
|
||||
$$;
|
||||
|
||||
grant execute on function medreport.upsert_benefit_distribution_schedule(uuid, numeric, text) to authenticated, service_role;
|
||||
|
||||
create or replace function medreport.trigger_distribute_benefits()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
security definer
|
||||
as $$
|
||||
declare
|
||||
v_benefit_distribution_schedule_id uuid;
|
||||
begin
|
||||
-- Only distribute if benefit_amount is set and greater than 0
|
||||
if new.benefit_amount is not null and new.benefit_amount > 0 then
|
||||
-- Create or update the distribution schedule for future distributions
|
||||
v_benefit_distribution_schedule_id := medreport.upsert_benefit_distribution_schedule(
|
||||
new.account_id,
|
||||
new.benefit_amount,
|
||||
coalesce(new.benefit_occurance, 'yearly')
|
||||
);
|
||||
|
||||
-- Distribute benefits to all company members immediately
|
||||
perform medreport.distribute_health_benefits(
|
||||
v_benefit_distribution_schedule_id
|
||||
);
|
||||
else
|
||||
-- If benefit_amount is 0 or null, deactivate the schedule
|
||||
update medreport.benefit_distribution_schedule
|
||||
set is_active = false, updated_at = now()
|
||||
where company_id = new.account_id;
|
||||
end if;
|
||||
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
|
||||
CREATE OR REPLACE FUNCTION medreport.get_benefits_usages_for_company_members(p_account_id uuid)
|
||||
returns table (
|
||||
personal_account_id uuid,
|
||||
benefit_amount numeric
|
||||
)
|
||||
language plpgsql
|
||||
as $$
|
||||
begin
|
||||
return query
|
||||
select
|
||||
abe.account_id as personal_account_id,
|
||||
sum(abe.amount) as benefit_amount
|
||||
from medreport.account_balance_entries abe
|
||||
where abe.source_company_id = p_account_id
|
||||
and abe.entry_type = 'benefit'
|
||||
group by abe.account_id;
|
||||
end;
|
||||
$$;
|
||||
|
||||
grant execute on function medreport.get_benefits_usages_for_company_members(uuid) to authenticated, service_role;
|
||||
Reference in New Issue
Block a user