@@ -10,6 +10,10 @@ NEXT_PUBLIC_AUTH_PASSWORD=true
|
|||||||
## THIS IS FOR DEVELOPMENT ONLY - DO NOT USE IN PRODUCTION
|
## THIS IS FOR DEVELOPMENT ONLY - DO NOT USE IN PRODUCTION
|
||||||
SUPABASE_DB_WEBHOOK_SECRET=WEBHOOKSECRET
|
SUPABASE_DB_WEBHOOK_SECRET=WEBHOOKSECRET
|
||||||
|
|
||||||
|
# MEDUSA MONTONIO URLS FOR LOCALHOST
|
||||||
|
# Montonio doesn't allow localhost as notification/callback URL
|
||||||
|
DEV_MONTONIO_CALLBACK_URL=http://webhook.site:3000
|
||||||
|
|
||||||
# EMAILS
|
# EMAILS
|
||||||
|
|
||||||
# CONTACT FORM
|
# CONTACT FORM
|
||||||
@@ -34,6 +38,7 @@ MEDIPOST_PASSWORD=SRB48HZMV
|
|||||||
MEDIPOST_RECIPIENT=trvurgtst
|
MEDIPOST_RECIPIENT=trvurgtst
|
||||||
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
MEDIPOST_MESSAGE_SENDER=trvurgtst
|
||||||
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK=true
|
||||||
|
MEDIPOST_ENABLE_DELETE_RESPONSE_PRIVATE_MESSAGE_ON_READ=false
|
||||||
|
|
||||||
#MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
#MEDIPOST_URL=https://medipost2.medisoft.ee:8443/Medipost/MedipostServlet
|
||||||
#MEDIPOST_USER=medreport
|
#MEDIPOST_USER=medreport
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
database.types.ts
|
database.types.ts
|
||||||
playwright-report
|
playwright-report
|
||||||
*.hbs
|
*.hbs
|
||||||
|
.history
|
||||||
|
node_modules
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ export const onUpdateAccount = enhanceAction(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await api.updateAccount(params);
|
await api.updateAccount(params);
|
||||||
console.log('SUCCESS', pathsConfig.auth.updateAccountSuccess);
|
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
if (err instanceof Error) {
|
if (err instanceof Error) {
|
||||||
console.warn('On update account error: ' + err.message);
|
console.warn('On update account error: ' + err.message);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
|||||||
import { retrieveCart } from '@lib/data/cart';
|
import { retrieveCart } from '@lib/data/cart';
|
||||||
import { listProductTypes } from '@lib/data/products';
|
import { listProductTypes } from '@lib/data/products';
|
||||||
|
|
||||||
|
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
@@ -11,9 +12,8 @@ import { findProductTypeIdByHandle } from '~/lib/utils';
|
|||||||
|
|
||||||
import Cart from '../../_components/cart';
|
import Cart from '../../_components/cart';
|
||||||
import CartTimer from '../../_components/cart/cart-timer';
|
import CartTimer from '../../_components/cart/cart-timer';
|
||||||
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
|
||||||
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
|
||||||
import { EnrichedCartItem } from '../../_components/cart/types';
|
import { EnrichedCartItem } from '../../_components/cart/types';
|
||||||
|
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
const { t } = await createI18nServerInstance();
|
const { t } = await createI18nServerInstance();
|
||||||
@@ -24,11 +24,7 @@ export async function generateMetadata() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function CartPage() {
|
async function CartPage() {
|
||||||
const [
|
const [cart, { productTypes }, { account }] = await Promise.all([
|
||||||
cart,
|
|
||||||
{ productTypes },
|
|
||||||
{ account },
|
|
||||||
] = await Promise.all([
|
|
||||||
retrieveCart(),
|
retrieveCart(),
|
||||||
listProductTypes(),
|
listProductTypes(),
|
||||||
loadCurrentUserAccount(),
|
loadCurrentUserAccount(),
|
||||||
@@ -38,7 +34,9 @@ async function CartPage() {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const balanceSummary = await new AccountBalanceService().getBalanceSummary(account.id);
|
const balanceSummary = await new AccountBalanceService().getBalanceSummary(
|
||||||
|
account.id,
|
||||||
|
);
|
||||||
|
|
||||||
const synlabAnalysisTypeId = findProductTypeIdByHandle(
|
const synlabAnalysisTypeId = findProductTypeIdByHandle(
|
||||||
productTypes,
|
productTypes,
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
|
||||||
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
|
||||||
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
import OrderItems from '@/app/home/(user)/_components/order/order-items';
|
||||||
|
import { retrieveOrder } from '@lib/data/orders';
|
||||||
|
import { StoreOrder } from '@medusajs/types';
|
||||||
import Divider from '@modules/common/components/divider';
|
import Divider from '@modules/common/components/divider';
|
||||||
|
|
||||||
|
import { GlobalLoader } from '@kit/ui/makerkit/global-loader';
|
||||||
import { PageBody, PageHeader } from '@kit/ui/page';
|
import { PageBody, PageHeader } from '@kit/ui/page';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { StoreOrder } from '@medusajs/types';
|
|
||||||
import { AnalysisOrder } from '~/lib/types/analysis-order';
|
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({
|
function OrderConfirmedLoadingWrapper({
|
||||||
medusaOrder: initialMedusaOrder,
|
medusaOrder: initialMedusaOrder,
|
||||||
@@ -21,7 +22,8 @@ function OrderConfirmedLoadingWrapper({
|
|||||||
medusaOrder: StoreOrder;
|
medusaOrder: StoreOrder;
|
||||||
order: AnalysisOrder;
|
order: AnalysisOrder;
|
||||||
}) {
|
}) {
|
||||||
const [medusaOrder, setMedusaOrder] = useState<StoreOrder>(initialMedusaOrder);
|
const [medusaOrder, setMedusaOrder] =
|
||||||
|
useState<StoreOrder>(initialMedusaOrder);
|
||||||
const fetchingRef = useRef(false);
|
const fetchingRef = useRef(false);
|
||||||
|
|
||||||
const paymentStatus = medusaOrder.payment_status;
|
const paymentStatus = medusaOrder.payment_status;
|
||||||
@@ -52,7 +54,7 @@ function OrderConfirmedLoadingWrapper({
|
|||||||
if (!isPaid) {
|
if (!isPaid) {
|
||||||
return (
|
return (
|
||||||
<PageBody>
|
<PageBody>
|
||||||
<div className="flex flex-col justify-start items-center h-full pt-[10vh]">
|
<div className="flex h-full flex-col items-center justify-start pt-[10vh]">
|
||||||
<div>
|
<div>
|
||||||
<GlobalLoader />
|
<GlobalLoader />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { pathsConfig } from '@kit/shared/config';
|
|||||||
|
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
import { getAnalysisOrder } from '~/lib/services/order.service';
|
import { getAnalysisOrder } from '~/lib/services/order.service';
|
||||||
|
|
||||||
import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';
|
import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';
|
||||||
|
|
||||||
export async function generateMetadata() {
|
export async function generateMetadata() {
|
||||||
@@ -36,7 +37,9 @@ async function OrderConfirmedPage(props: {
|
|||||||
redirect(pathsConfig.app.myOrders);
|
redirect(pathsConfig.app.myOrders);
|
||||||
}
|
}
|
||||||
|
|
||||||
return <OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />;
|
return (
|
||||||
|
<OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default withI18n(OrderConfirmedPage);
|
export default withI18n(OrderConfirmedPage);
|
||||||
|
|||||||
@@ -29,12 +29,13 @@ export async function generateMetadata() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function OrdersPage() {
|
async function OrdersPage() {
|
||||||
const [medusaOrders, analysisOrders, ttoOrders, { productTypes }] = await Promise.all([
|
const [medusaOrders, analysisOrders, ttoOrders, { productTypes }] =
|
||||||
listOrders(ORDERS_LIMIT),
|
await Promise.all([
|
||||||
getAnalysisOrders(),
|
listOrders(ORDERS_LIMIT),
|
||||||
getTtoOrders(),
|
getAnalysisOrders(),
|
||||||
listProductTypes(),
|
getTtoOrders(),
|
||||||
]);
|
listProductTypes(),
|
||||||
|
]);
|
||||||
|
|
||||||
if (!medusaOrders || !productTypes || !ttoOrders) {
|
if (!medusaOrders || !productTypes || !ttoOrders) {
|
||||||
redirect(pathsConfig.auth.signIn);
|
redirect(pathsConfig.auth.signIn);
|
||||||
|
|||||||
@@ -32,7 +32,16 @@ const BookingContainer = ({
|
|||||||
<BookingProvider category={{ products }} service={cartItem?.product}>
|
<BookingProvider category={{ products }} service={cartItem?.product}>
|
||||||
<div className="xs:flex-row flex max-h-full flex-col gap-6">
|
<div className="xs:flex-row flex max-h-full flex-col gap-6">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<ServiceSelector products={products} />
|
<ServiceSelector
|
||||||
|
products={products.filter((product) => {
|
||||||
|
if (product.metadata?.serviceIds) {
|
||||||
|
return Array.isArray(
|
||||||
|
JSON.parse(product.metadata.serviceIds as string),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})}
|
||||||
|
/>
|
||||||
<BookingCalendar />
|
<BookingCalendar />
|
||||||
<LocationSelector />
|
<LocationSelector />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
113
app/home/(user)/_components/booking/booking-pagination.tsx
Normal file
113
app/home/(user)/_components/booking/booking-pagination.tsx
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { Trans } from '@kit/ui/makerkit/trans';
|
||||||
|
import { cn } from '@kit/ui/shadcn';
|
||||||
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
|
|
||||||
|
const BookingPagination = ({
|
||||||
|
totalPages,
|
||||||
|
setCurrentPage,
|
||||||
|
currentPage,
|
||||||
|
}: {
|
||||||
|
totalPages: number;
|
||||||
|
setCurrentPage: (page: number) => void;
|
||||||
|
currentPage: number;
|
||||||
|
}) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const generatePageNumbers = () => {
|
||||||
|
const pages = [];
|
||||||
|
const maxVisiblePages = 5;
|
||||||
|
|
||||||
|
if (totalPages <= maxVisiblePages) {
|
||||||
|
for (let i = 1; i <= totalPages; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (currentPage <= 3) {
|
||||||
|
for (let i = 1; i <= 4; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
pages.push('...');
|
||||||
|
pages.push(totalPages);
|
||||||
|
} else if (currentPage >= totalPages - 2) {
|
||||||
|
pages.push(1);
|
||||||
|
pages.push('...');
|
||||||
|
for (let i = totalPages - 3; i <= totalPages; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
pages.push(1);
|
||||||
|
pages.push('...');
|
||||||
|
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
pages.push('...');
|
||||||
|
pages.push(totalPages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pages;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (totalPages === 0) {
|
||||||
|
return (
|
||||||
|
<div className="wrap text-muted-foreground flex size-full content-center-safe justify-center-safe">
|
||||||
|
<p>{t('booking:noResults')}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
totalPages > 1 && (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="text-muted-foreground text-sm">
|
||||||
|
{t('common:pageOfPages', {
|
||||||
|
page: currentPage,
|
||||||
|
total: totalPages,
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage(currentPage - 1)}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
>
|
||||||
|
<Trans i18nKey="common:previous" defaultValue="Previous" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{generatePageNumbers().map((page, index) => (
|
||||||
|
<Button
|
||||||
|
key={index}
|
||||||
|
variant={page === currentPage ? 'default' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => typeof page === 'number' && setCurrentPage(page)}
|
||||||
|
disabled={page === '...'}
|
||||||
|
className={cn(
|
||||||
|
'min-w-[2rem]',
|
||||||
|
page === '...' && 'cursor-default hover:bg-transparent',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{page}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage(currentPage + 1)}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
>
|
||||||
|
<Trans i18nKey="common:next" defaultValue="Next" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default BookingPagination;
|
||||||
@@ -45,7 +45,6 @@ export const BookingProvider: React.FC<{
|
|||||||
const updateTimeSlots = async (serviceIds: number[]) => {
|
const updateTimeSlots = async (serviceIds: number[]) => {
|
||||||
setIsLoadingTimeSlots(true);
|
setIsLoadingTimeSlots(true);
|
||||||
try {
|
try {
|
||||||
console.log('serviceIds', serviceIds, selectedLocationId);
|
|
||||||
const response = await getAvailableTimeSlotsForDisplay(
|
const response = await getAvailableTimeSlotsForDisplay(
|
||||||
serviceIds,
|
serviceIds,
|
||||||
selectedLocationId,
|
selectedLocationId,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { pathsConfig } from '@kit/shared/config';
|
|||||||
import { formatDateAndTime } from '@kit/shared/utils';
|
import { formatDateAndTime } from '@kit/shared/utils';
|
||||||
import { Button } from '@kit/ui/shadcn/button';
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
import { Card } from '@kit/ui/shadcn/card';
|
import { Card } from '@kit/ui/shadcn/card';
|
||||||
|
import { Skeleton } from '@kit/ui/shadcn/skeleton';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { toast } from '@kit/ui/sonner';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { cn } from '@kit/ui/utils';
|
import { cn } from '@kit/ui/utils';
|
||||||
@@ -19,6 +20,7 @@ import { updateReservationTime } from '~/lib/services/reservation.service';
|
|||||||
|
|
||||||
import { createInitialReservationAction } from '../../_lib/server/actions';
|
import { createInitialReservationAction } from '../../_lib/server/actions';
|
||||||
import { EnrichedCartItem } from '../cart/types';
|
import { EnrichedCartItem } from '../cart/types';
|
||||||
|
import BookingPagination from './booking-pagination';
|
||||||
import { ServiceProvider, TimeSlot } from './booking.context';
|
import { ServiceProvider, TimeSlot } from './booking.context';
|
||||||
import { useBooking } from './booking.provider';
|
import { useBooking } from './booking.provider';
|
||||||
|
|
||||||
@@ -68,57 +70,16 @@ const TimeSlots = ({
|
|||||||
}) ?? [],
|
}) ?? [],
|
||||||
'StartTime',
|
'StartTime',
|
||||||
'asc',
|
'asc',
|
||||||
),
|
).filter(({ StartTime }) => isSameDay(StartTime, selectedDate)),
|
||||||
[booking.timeSlots, selectedDate],
|
[booking.timeSlots, selectedDate],
|
||||||
);
|
);
|
||||||
|
|
||||||
const totalPages = Math.ceil(filteredBookings.length / PAGE_SIZE);
|
|
||||||
|
|
||||||
const paginatedBookings = useMemo(() => {
|
const paginatedBookings = useMemo(() => {
|
||||||
const startIndex = (currentPage - 1) * PAGE_SIZE;
|
const startIndex = (currentPage - 1) * PAGE_SIZE;
|
||||||
const endIndex = startIndex + PAGE_SIZE;
|
const endIndex = startIndex + PAGE_SIZE;
|
||||||
return filteredBookings.slice(startIndex, endIndex);
|
return filteredBookings.slice(startIndex, endIndex);
|
||||||
}, [filteredBookings, currentPage, PAGE_SIZE]);
|
}, [filteredBookings, currentPage, PAGE_SIZE]);
|
||||||
|
|
||||||
const handlePageChange = (page: number) => {
|
|
||||||
setCurrentPage(page);
|
|
||||||
};
|
|
||||||
|
|
||||||
const generatePageNumbers = () => {
|
|
||||||
const pages = [];
|
|
||||||
const maxVisiblePages = 5;
|
|
||||||
|
|
||||||
if (totalPages <= maxVisiblePages) {
|
|
||||||
for (let i = 1; i <= totalPages; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (currentPage <= 3) {
|
|
||||||
for (let i = 1; i <= 4; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
pages.push('...');
|
|
||||||
pages.push(totalPages);
|
|
||||||
} else if (currentPage >= totalPages - 2) {
|
|
||||||
pages.push(1);
|
|
||||||
pages.push('...');
|
|
||||||
for (let i = totalPages - 3; i <= totalPages; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
pages.push(1);
|
|
||||||
pages.push('...');
|
|
||||||
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
pages.push('...');
|
|
||||||
pages.push(totalPages);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return pages;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!booking?.timeSlots?.length) {
|
if (!booking?.timeSlots?.length) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -143,12 +104,17 @@ const TimeSlots = ({
|
|||||||
timeSlot.StartTime,
|
timeSlot.StartTime,
|
||||||
booking.selectedLocationId ? booking.selectedLocationId : null,
|
booking.selectedLocationId ? booking.selectedLocationId : null,
|
||||||
comments,
|
comments,
|
||||||
).then(() => {
|
)
|
||||||
if (onComplete) {
|
.then(() => {
|
||||||
onComplete();
|
if (onComplete) {
|
||||||
}
|
onComplete();
|
||||||
router.push(pathsConfig.app.cart);
|
}
|
||||||
});
|
router.push(pathsConfig.app.cart);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Booking error: ', error);
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
|
||||||
toast.promise(() => bookTimePromise, {
|
toast.promise(() => bookTimePromise, {
|
||||||
success: <Trans i18nKey={'booking:bookTimeSuccess'} />,
|
success: <Trans i18nKey={'booking:bookTimeSuccess'} />,
|
||||||
@@ -203,10 +169,13 @@ const TimeSlots = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex w-full flex-col gap-4">
|
<Skeleton
|
||||||
|
isLoading={booking.isLoadingTimeSlots}
|
||||||
|
className="flex w-full flex-col gap-4"
|
||||||
|
>
|
||||||
<div className="flex h-full w-full flex-col gap-2 overflow-auto">
|
<div className="flex h-full w-full flex-col gap-2 overflow-auto">
|
||||||
{paginatedBookings.map((timeSlot, index) => {
|
{paginatedBookings.map((timeSlot, index) => {
|
||||||
const isEHIF = timeSlot.HKServiceID > 0;
|
const isHaigeKassa = timeSlot.HKServiceID > 0;
|
||||||
const serviceProviderTitle = getServiceProviderTitle(
|
const serviceProviderTitle = getServiceProviderTitle(
|
||||||
currentLocale,
|
currentLocale,
|
||||||
timeSlot.serviceProvider,
|
timeSlot.serviceProvider,
|
||||||
@@ -214,6 +183,7 @@ const TimeSlots = ({
|
|||||||
const price =
|
const price =
|
||||||
booking.selectedService?.variants?.[0]?.calculated_price
|
booking.selectedService?.variants?.[0]?.calculated_price
|
||||||
?.calculated_amount ?? cartItem?.unit_price;
|
?.calculated_amount ?? cartItem?.unit_price;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className="xs:flex xs:justify-between grid w-full justify-center-safe gap-3 p-4"
|
className="xs:flex xs:justify-between grid w-full justify-center-safe gap-3 p-4"
|
||||||
@@ -224,7 +194,7 @@ const TimeSlots = ({
|
|||||||
<div className="flex">
|
<div className="flex">
|
||||||
<h5
|
<h5
|
||||||
className={cn(
|
className={cn(
|
||||||
(serviceProviderTitle || isEHIF) &&
|
(serviceProviderTitle || isHaigeKassa) &&
|
||||||
"after:mx-2 after:content-['·']",
|
"after:mx-2 after:content-['·']",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -232,12 +202,14 @@ const TimeSlots = ({
|
|||||||
</h5>
|
</h5>
|
||||||
{serviceProviderTitle && (
|
{serviceProviderTitle && (
|
||||||
<span
|
<span
|
||||||
className={cn(isEHIF && "after:mx-2 after:content-['·']")}
|
className={cn(
|
||||||
|
isHaigeKassa && "after:mx-2 after:content-['·']",
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
{serviceProviderTitle}
|
{serviceProviderTitle}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{isEHIF && <span>{t('booking:ehifBooking')}</span>}
|
{isHaigeKassa && <span>{t('booking:ehifBooking')}</span>}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex text-xs">{timeSlot.location?.address}</div>
|
<div className="flex text-xs">{timeSlot.location?.address}</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -256,63 +228,14 @@ const TimeSlots = ({
|
|||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{!paginatedBookings.length && (
|
|
||||||
<div className="wrap text-muted-foreground flex size-full content-center-safe justify-center-safe">
|
|
||||||
<p>{t('booking:noResults')}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{totalPages > 1 && (
|
<BookingPagination
|
||||||
<div className="flex items-center justify-between">
|
totalPages={Math.ceil(filteredBookings.length / PAGE_SIZE)}
|
||||||
<div className="text-muted-foreground text-sm">
|
setCurrentPage={setCurrentPage}
|
||||||
{t('common:pageOfPages', {
|
currentPage={currentPage}
|
||||||
page: currentPage,
|
/>
|
||||||
total: totalPages,
|
</Skeleton>
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handlePageChange(currentPage - 1)}
|
|
||||||
disabled={currentPage === 1}
|
|
||||||
>
|
|
||||||
<Trans i18nKey="common:previous" defaultValue="Previous" />
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{generatePageNumbers().map((page, index) => (
|
|
||||||
<Button
|
|
||||||
key={index}
|
|
||||||
variant={page === currentPage ? 'default' : 'outline'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() =>
|
|
||||||
typeof page === 'number' && handlePageChange(page)
|
|
||||||
}
|
|
||||||
disabled={page === '...'}
|
|
||||||
className={cn(
|
|
||||||
'min-w-[2rem]',
|
|
||||||
page === '...' && 'cursor-default hover:bg-transparent',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{page}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handlePageChange(currentPage + 1)}
|
|
||||||
disabled={currentPage === totalPages}
|
|
||||||
>
|
|
||||||
<Trans i18nKey="common:next" defaultValue="Next" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useFormContext } from 'react-hook-form';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
import { Form } from '@kit/ui/form';
|
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -22,10 +19,6 @@ import { Trans } from '@kit/ui/trans';
|
|||||||
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';
|
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';
|
||||||
import partnerLocations from './partner-locations.json';
|
import partnerLocations from './partner-locations.json';
|
||||||
|
|
||||||
const AnalysisLocationSchema = z.object({
|
|
||||||
locationId: z.string().min(1),
|
|
||||||
});
|
|
||||||
|
|
||||||
export default function AnalysisLocation({
|
export default function AnalysisLocation({
|
||||||
cart,
|
cart,
|
||||||
synlabAnalyses,
|
synlabAnalyses,
|
||||||
@@ -35,21 +28,15 @@ export default function AnalysisLocation({
|
|||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation('cart');
|
const { t } = useTranslation('cart');
|
||||||
|
|
||||||
const form = useForm<z.infer<typeof AnalysisLocationSchema>>({
|
const { watch, setValue } = useFormContext();
|
||||||
defaultValues: {
|
const currentValue = watch('locationId');
|
||||||
locationId: (cart.metadata?.partner_location_id as string) ?? '',
|
|
||||||
},
|
|
||||||
resolver: zodResolver(AnalysisLocationSchema),
|
|
||||||
});
|
|
||||||
|
|
||||||
const getLocation = (locationId: string) =>
|
const getLocation = (locationId: string) =>
|
||||||
partnerLocations.find(({ name }) => name === locationId);
|
partnerLocations.find(({ name }) => name === locationId);
|
||||||
|
|
||||||
const selectedLocation = getLocation(form.watch('locationId'));
|
const selectedLocation = getLocation(currentValue);
|
||||||
|
|
||||||
const onSubmit = async ({
|
const handleUpdateCartPartnerLocation = async (locationId: string) => {
|
||||||
locationId,
|
|
||||||
}: z.infer<typeof AnalysisLocationSchema>) => {
|
|
||||||
const promise = updateCartPartnerLocation({
|
const promise = updateCartPartnerLocation({
|
||||||
cartId: cart.id,
|
cartId: cart.id,
|
||||||
lineIds: synlabAnalyses.map(({ id }) => id),
|
lineIds: synlabAnalyses.map(({ id }) => id),
|
||||||
@@ -70,53 +57,48 @@ export default function AnalysisLocation({
|
|||||||
<Trans i18nKey={'cart:locations.description'} />
|
<Trans i18nKey={'cart:locations.description'} />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<Form {...form}>
|
<div className="mb-2 flex w-full flex-1 gap-x-2">
|
||||||
<form
|
<Select
|
||||||
onSubmit={form.handleSubmit((data) => onSubmit(data))}
|
value={currentValue}
|
||||||
className="mb-2 flex w-full flex-1 gap-x-2"
|
onValueChange={(value) => {
|
||||||
|
setValue('locationId', value, {
|
||||||
|
shouldValidate: true,
|
||||||
|
shouldDirty: true,
|
||||||
|
shouldTouch: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return handleUpdateCartPartnerLocation(value);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Select
|
<SelectTrigger>
|
||||||
value={form.watch('locationId')}
|
<SelectValue placeholder={t('cart:locations.locationSelect')} />
|
||||||
onValueChange={(value) => {
|
</SelectTrigger>
|
||||||
form.setValue('locationId', value, {
|
|
||||||
shouldValidate: true,
|
|
||||||
shouldDirty: true,
|
|
||||||
shouldTouch: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
return onSubmit(form.getValues());
|
<SelectContent>
|
||||||
}}
|
{Object.entries(
|
||||||
>
|
partnerLocations.reduce(
|
||||||
<SelectTrigger>
|
(acc, curr) => ({
|
||||||
<SelectValue placeholder={t('cart:locations.locationSelect')} />
|
...acc,
|
||||||
</SelectTrigger>
|
[curr.city]: [
|
||||||
|
...((acc[curr.city] as typeof partnerLocations) ?? []),
|
||||||
<SelectContent>
|
curr,
|
||||||
{Object.entries(
|
],
|
||||||
partnerLocations.reduce(
|
}),
|
||||||
(acc, curr) => ({
|
{} as Record<string, typeof partnerLocations>,
|
||||||
...acc,
|
),
|
||||||
[curr.city]: [
|
).map(([city, locations]) => (
|
||||||
...((acc[curr.city] as typeof partnerLocations) ?? []),
|
<SelectGroup key={city}>
|
||||||
curr,
|
<SelectLabel>{city}</SelectLabel>
|
||||||
],
|
{locations.map((location) => (
|
||||||
}),
|
<SelectItem key={location.name} value={location.name}>
|
||||||
{} as Record<string, typeof partnerLocations>,
|
{location.name}
|
||||||
),
|
</SelectItem>
|
||||||
).map(([city, locations]) => (
|
))}
|
||||||
<SelectGroup key={city}>
|
</SelectGroup>
|
||||||
<SelectLabel>{city}</SelectLabel>
|
))}
|
||||||
{locations.map((location) => (
|
</SelectContent>
|
||||||
<SelectItem key={location.name} value={location.name}>
|
</Select>
|
||||||
{location.name}
|
</div>
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectGroup>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</form>
|
|
||||||
</Form>
|
|
||||||
|
|
||||||
{selectedLocation && (
|
{selectedLocation && (
|
||||||
<div className="mb-4 flex flex-col gap-y-2">
|
<div className="mb-4 flex flex-col gap-y-2">
|
||||||
|
|||||||
213
app/home/(user)/_components/cart/cart-form-content.tsx
Normal file
213
app/home/(user)/_components/cart/cart-form-content.tsx
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
|
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import { useFormContext } from 'react-hook-form';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { Button } from '@kit/ui/button';
|
||||||
|
import { Card, CardContent, CardHeader } from '@kit/ui/card';
|
||||||
|
import { Checkbox } from '@kit/ui/checkbox';
|
||||||
|
import { FormControl, FormField, FormItem, FormLabel } from '@kit/ui/form';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { cn } from '~/lib/utils';
|
||||||
|
|
||||||
|
import AnalysisLocation from './analysis-location';
|
||||||
|
import CartItems from './cart-items';
|
||||||
|
import CartServiceItems from './cart-service-items';
|
||||||
|
import DiscountCode from './discount-code';
|
||||||
|
import { EnrichedCartItem, GetBalanceSummarySelection } from './types';
|
||||||
|
|
||||||
|
const IS_DISCOUNT_SHOWN = true as boolean;
|
||||||
|
|
||||||
|
export default function CartFormContent({
|
||||||
|
cart,
|
||||||
|
synlabAnalyses,
|
||||||
|
ttoServiceItems,
|
||||||
|
unavailableLineItemIds,
|
||||||
|
isInitiatingSession,
|
||||||
|
getBalanceSummarySelection,
|
||||||
|
}: {
|
||||||
|
cart: StoreCart;
|
||||||
|
synlabAnalyses: StoreCartLineItem[];
|
||||||
|
ttoServiceItems: EnrichedCartItem[];
|
||||||
|
unavailableLineItemIds?: string[];
|
||||||
|
isInitiatingSession: boolean;
|
||||||
|
getBalanceSummarySelection: GetBalanceSummarySelection;
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
i18n: { language },
|
||||||
|
} = useTranslation();
|
||||||
|
const { watch } = useFormContext();
|
||||||
|
|
||||||
|
const items = cart?.items ?? [];
|
||||||
|
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
||||||
|
|
||||||
|
const isLocationsShown = synlabAnalyses.length > 0;
|
||||||
|
|
||||||
|
const useCompanyBenefits = watch('useCompanyBenefits');
|
||||||
|
const balanceSummary = getBalanceSummarySelection({ useCompanyBenefits });
|
||||||
|
|
||||||
|
const { benefitsAmount, benefitsAmountTotal, montonioAmount } =
|
||||||
|
balanceSummary;
|
||||||
|
|
||||||
|
const hasBenefitsApplied = benefitsAmountTotal > 0 && !!useCompanyBenefits;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col gap-y-6 bg-white">
|
||||||
|
<CartItems
|
||||||
|
cart={cart}
|
||||||
|
items={synlabAnalyses}
|
||||||
|
productColumnLabelKey="cart:items.synlabAnalyses.productColumnLabel"
|
||||||
|
/>
|
||||||
|
<CartServiceItems
|
||||||
|
cart={cart}
|
||||||
|
items={ttoServiceItems}
|
||||||
|
productColumnLabelKey="cart:items.ttoServices.productColumnLabel"
|
||||||
|
unavailableLineItemIds={unavailableLineItemIds}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{hasCartItems && (
|
||||||
|
<>
|
||||||
|
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
||||||
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
|
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||||
|
<Trans i18nKey="cart:order.subtotal" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||||
|
<p className="text-right text-sm">
|
||||||
|
{formatCurrency({
|
||||||
|
value: cart.subtotal,
|
||||||
|
currencyCode: cart.currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4',
|
||||||
|
{
|
||||||
|
'py-2 sm:py-4': !hasBenefitsApplied,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
|
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||||
|
<Trans i18nKey="cart:order.promotionsTotal" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||||
|
<p className="text-right text-sm">
|
||||||
|
{formatCurrency({
|
||||||
|
value: cart.discount_total,
|
||||||
|
currencyCode: cart.currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{hasBenefitsApplied && (
|
||||||
|
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||||
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
|
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
||||||
|
<Trans i18nKey="cart:order.companyBenefitsTotal" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||||
|
<p className="text-right text-sm">
|
||||||
|
{formatCurrency({
|
||||||
|
value: benefitsAmount,
|
||||||
|
currencyCode: cart.currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
||||||
|
<div className="w-full sm:mr-[42px] sm:w-auto">
|
||||||
|
<p className="ml-0 text-sm font-bold">
|
||||||
|
<Trans i18nKey="cart:order.total" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
||||||
|
<p className="text-right text-sm">
|
||||||
|
{formatCurrency({
|
||||||
|
value: montonioAmount,
|
||||||
|
currencyCode: cart.currency_code,
|
||||||
|
locale: language,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{benefitsAmountTotal > 0 && (
|
||||||
|
<FormField
|
||||||
|
name="useCompanyBenefits"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-8">
|
||||||
|
<div className="flex flex-row items-center gap-2 pb-1">
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormLabel>
|
||||||
|
<Trans i18nKey={'cart:companyBenefits.label'} />
|
||||||
|
</FormLabel>
|
||||||
|
</div>
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
|
||||||
|
{IS_DISCOUNT_SHOWN && (
|
||||||
|
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<h5>
|
||||||
|
<Trans i18nKey="cart:discountCode.title" />
|
||||||
|
</h5>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="h-full">
|
||||||
|
<DiscountCode cart={{ ...cart }} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isLocationsShown && (
|
||||||
|
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<h5>
|
||||||
|
<Trans i18nKey="cart:locations.title" />
|
||||||
|
</h5>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="h-full">
|
||||||
|
<AnalysisLocation
|
||||||
|
cart={{ ...cart }}
|
||||||
|
synlabAnalyses={synlabAnalyses}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Button className="h-10" type="submit" disabled={isInitiatingSession}>
|
||||||
|
{isInitiatingSession && (
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
)}
|
||||||
|
<Trans i18nKey="cart:checkout.goToCheckout" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
49
app/home/(user)/_components/cart/cart-form.tsx
Normal file
49
app/home/(user)/_components/cart/cart-form.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import type { StoreCart } from '@medusajs/types';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { Form } from '@kit/ui/form';
|
||||||
|
|
||||||
|
const CartFormSchema = z.object({
|
||||||
|
code: z.string().optional(),
|
||||||
|
locationId: z.string().optional(),
|
||||||
|
useCompanyBenefits: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CartFormOnSubmit = (
|
||||||
|
data: z.infer<typeof CartFormSchema>,
|
||||||
|
) => Promise<void>;
|
||||||
|
|
||||||
|
export default function CartForm({
|
||||||
|
children,
|
||||||
|
cart,
|
||||||
|
onSubmit,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
cart: StoreCart;
|
||||||
|
onSubmit: CartFormOnSubmit;
|
||||||
|
}) {
|
||||||
|
const form = useForm<z.infer<typeof CartFormSchema>>({
|
||||||
|
defaultValues: {
|
||||||
|
code: '',
|
||||||
|
locationId: (cart.metadata?.partner_location_id as string) ?? '',
|
||||||
|
useCompanyBenefits: true,
|
||||||
|
},
|
||||||
|
resolver: zodResolver(CartFormSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSubmit: CartFormOnSubmit = async (data) => {
|
||||||
|
await onSubmit(data);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit((data) => handleSubmit(data))}>
|
||||||
|
{children}
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,18 +1,16 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React from 'react';
|
import React, { useState } from 'react';
|
||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import { convertToLocale } from '@lib/util/money';
|
import { convertToLocale } from '@lib/util/money';
|
||||||
import { StoreCart, StorePromotion } from '@medusajs/types';
|
import { StoreCart, StorePromotion } from '@medusajs/types';
|
||||||
import { Badge, Text } from '@medusajs/ui';
|
import { Badge, Text } from '@medusajs/ui';
|
||||||
import Trash from '@modules/common/icons/trash';
|
import Trash from '@modules/common/icons/trash';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useFormContext } from 'react-hook-form';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Form, FormControl, FormField, FormItem } from '@kit/ui/form';
|
import { FormControl, FormField, FormItem } from '@kit/ui/form';
|
||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { toast } from '@kit/ui/sonner';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
@@ -22,10 +20,6 @@ import {
|
|||||||
removePromotionCodeAction,
|
removePromotionCodeAction,
|
||||||
} from './discount-code-actions';
|
} from './discount-code-actions';
|
||||||
|
|
||||||
const DiscountCodeSchema = z.object({
|
|
||||||
code: z.string().min(1),
|
|
||||||
});
|
|
||||||
|
|
||||||
export default function DiscountCode({
|
export default function DiscountCode({
|
||||||
cart,
|
cart,
|
||||||
}: {
|
}: {
|
||||||
@@ -35,8 +29,13 @@ export default function DiscountCode({
|
|||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation('cart');
|
const { t } = useTranslation('cart');
|
||||||
|
|
||||||
|
const { setValue, watch } = useFormContext();
|
||||||
|
const currentValue = watch('code');
|
||||||
|
|
||||||
const { promotions = [] } = cart;
|
const { promotions = [] } = cart;
|
||||||
|
|
||||||
|
const [isAddingPromotionCode, setIsAddingPromotionCode] = useState(false);
|
||||||
|
|
||||||
const removePromotionCode = async (code: string) => {
|
const removePromotionCode = async (code: string) => {
|
||||||
const appliedCodes = promotions
|
const appliedCodes = promotions
|
||||||
.filter((p) => p.code !== undefined)
|
.filter((p) => p.code !== undefined)
|
||||||
@@ -55,57 +54,56 @@ export default function DiscountCode({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const addPromotionCode = async (code: string) => {
|
const addPromotionCode = async (code: string) => {
|
||||||
|
if (!code || code.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsAddingPromotionCode(true);
|
||||||
const loading = toast.loading(t('cart:discountCode.addLoading'));
|
const loading = toast.loading(t('cart:discountCode.addLoading'));
|
||||||
const result = await addPromotionCodeAction(code);
|
const result = await addPromotionCodeAction(code);
|
||||||
|
|
||||||
toast.dismiss(loading);
|
toast.dismiss(loading);
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
toast.success(t('cart:discountCode.addSuccess'));
|
toast.success(t('cart:discountCode.addSuccess'));
|
||||||
form.reset();
|
setValue('code', '');
|
||||||
} else {
|
} else {
|
||||||
toast.error(t('cart:discountCode.addError'));
|
toast.error(t('cart:discountCode.addError'));
|
||||||
}
|
}
|
||||||
|
setIsAddingPromotionCode(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const form = useForm<z.infer<typeof DiscountCodeSchema>>({
|
|
||||||
defaultValues: {
|
|
||||||
code: '',
|
|
||||||
},
|
|
||||||
resolver: zodResolver(DiscountCodeSchema),
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="txt-medium flex h-full w-full flex-col gap-y-4 bg-white">
|
<div className="txt-medium flex h-full w-full flex-col gap-y-4 bg-white">
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground text-sm">
|
||||||
<Trans i18nKey={'cart:discountCode.subtitle'} />
|
<Trans i18nKey={'cart:discountCode.subtitle'} />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<Form {...form}>
|
<div className="mb-2 flex w-full flex-1 flex-col gap-x-2 gap-y-2 sm:flex-row">
|
||||||
<form
|
<FormField
|
||||||
onSubmit={form.handleSubmit((data) => addPromotionCode(data.code))}
|
name={'code'}
|
||||||
className="mb-2 flex w-full flex-1 flex-col gap-x-2 gap-y-2 sm:flex-row"
|
render={({ field }) => (
|
||||||
>
|
<FormItem className="flex-1">
|
||||||
<FormField
|
<FormControl>
|
||||||
name={'code'}
|
<Input
|
||||||
render={({ field }) => (
|
type="text"
|
||||||
<FormItem className="flex-1">
|
{...field}
|
||||||
<FormControl>
|
placeholder={t('cart:discountCode.placeholder')}
|
||||||
<Input
|
/>
|
||||||
required
|
</FormControl>
|
||||||
type="text"
|
</FormItem>
|
||||||
{...field}
|
)}
|
||||||
placeholder={t('cart:discountCode.placeholder')}
|
/>
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Button type="submit" variant="secondary" className="h-min">
|
<Button
|
||||||
<Trans i18nKey={'cart:discountCode.apply'} />
|
type="button"
|
||||||
</Button>
|
variant="secondary"
|
||||||
</form>
|
className="h-min"
|
||||||
</Form>
|
onClick={() => addPromotionCode(currentValue)}
|
||||||
|
disabled={isAddingPromotionCode}
|
||||||
|
>
|
||||||
|
<Trans i18nKey={'cart:discountCode.apply'} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{promotions.length > 0 && (
|
{promotions.length > 0 && (
|
||||||
<div className="mt-4 flex w-full items-center">
|
<div className="mt-4 flex w-full items-center">
|
||||||
|
|||||||
@@ -1,27 +1,20 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
|
||||||
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
|
||||||
import { Loader2 } from 'lucide-react';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
||||||
import { Card, CardContent, CardHeader } from '@kit/ui/card';
|
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
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 { initiatePayment } from '../../_lib/server/cart-actions';
|
||||||
import { useRouter } from 'next/navigation';
|
import CartForm, { CartFormOnSubmit } from './cart-form';
|
||||||
import { AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
import CartFormContent from './cart-form-content';
|
||||||
import { EnrichedCartItem } from './types';
|
import { EnrichedCartItem } from './types';
|
||||||
|
|
||||||
const IS_DISCOUNT_SHOWN = true as boolean;
|
|
||||||
|
|
||||||
export default function Cart({
|
export default function Cart({
|
||||||
accountId,
|
accountId,
|
||||||
cart,
|
cart,
|
||||||
@@ -44,6 +37,47 @@ export default function Cart({
|
|||||||
const [unavailableLineItemIds, setUnavailableLineItemIds] =
|
const [unavailableLineItemIds, setUnavailableLineItemIds] =
|
||||||
useState<string[]>();
|
useState<string[]>();
|
||||||
|
|
||||||
|
const getBalanceSummarySelection = useCallback(
|
||||||
|
({
|
||||||
|
useCompanyBenefits,
|
||||||
|
}: {
|
||||||
|
useCompanyBenefits: boolean;
|
||||||
|
}): {
|
||||||
|
benefitsAmount: number;
|
||||||
|
benefitsAmountTotal: number;
|
||||||
|
montonioAmount: number;
|
||||||
|
} => {
|
||||||
|
if (!cart) {
|
||||||
|
return {
|
||||||
|
benefitsAmount: 0,
|
||||||
|
benefitsAmountTotal: 0,
|
||||||
|
montonioAmount: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const benefitsAmountTotal = balanceSummary?.totalBalance ?? 0;
|
||||||
|
const cartTotal = cart.total;
|
||||||
|
if (!useCompanyBenefits) {
|
||||||
|
return {
|
||||||
|
benefitsAmount: 0,
|
||||||
|
benefitsAmountTotal,
|
||||||
|
montonioAmount: cartTotal,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const benefitsAmount =
|
||||||
|
benefitsAmountTotal > cartTotal ? cartTotal : benefitsAmountTotal;
|
||||||
|
const montonioAmount =
|
||||||
|
benefitsAmount > 0 ? cartTotal - benefitsAmount : cartTotal;
|
||||||
|
return {
|
||||||
|
benefitsAmount,
|
||||||
|
benefitsAmountTotal,
|
||||||
|
montonioAmount,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
[balanceSummary, cart],
|
||||||
|
);
|
||||||
|
|
||||||
const items = cart?.items ?? [];
|
const items = cart?.items ?? [];
|
||||||
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
const hasCartItems = cart && Array.isArray(items) && items.length > 0;
|
||||||
|
|
||||||
@@ -67,16 +101,20 @@ export default function Cart({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function initiateSession() {
|
const initiateSession: CartFormOnSubmit = async ({ useCompanyBenefits }) => {
|
||||||
setIsInitiatingSession(true);
|
setIsInitiatingSession(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { url, isFullyPaidByBenefits, orderId, unavailableLineItemIds } = await initiatePayment({
|
const { benefitsAmount } = getBalanceSummarySelection({
|
||||||
accountId,
|
useCompanyBenefits,
|
||||||
balanceSummary: balanceSummary!,
|
|
||||||
cart: cart!,
|
|
||||||
language,
|
|
||||||
});
|
});
|
||||||
|
const { url, isFullyPaidByBenefits, orderId, unavailableLineItemIds } =
|
||||||
|
await initiatePayment({
|
||||||
|
accountId,
|
||||||
|
benefitsAmount,
|
||||||
|
cart: cart!,
|
||||||
|
language,
|
||||||
|
});
|
||||||
if (unavailableLineItemIds) {
|
if (unavailableLineItemIds) {
|
||||||
setUnavailableLineItemIds(unavailableLineItemIds);
|
setUnavailableLineItemIds(unavailableLineItemIds);
|
||||||
}
|
}
|
||||||
@@ -92,142 +130,20 @@ export default function Cart({
|
|||||||
console.error('Failed to initiate payment', error);
|
console.error('Failed to initiate payment', error);
|
||||||
setIsInitiatingSession(false);
|
setIsInitiatingSession(false);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const isLocationsShown = synlabAnalyses.length > 0;
|
|
||||||
|
|
||||||
const companyBenefitsTotal = balanceSummary?.totalBalance ?? 0;
|
|
||||||
const montonioTotal = cart && companyBenefitsTotal > 0 ? cart.total - companyBenefitsTotal : cart.total;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 lg:px-4">
|
<div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 lg:px-4">
|
||||||
<div className="flex flex-col gap-y-6 bg-white">
|
<CartForm cart={cart} onSubmit={initiateSession}>
|
||||||
<CartItems
|
<CartFormContent
|
||||||
cart={cart}
|
cart={cart}
|
||||||
items={synlabAnalyses}
|
synlabAnalyses={synlabAnalyses}
|
||||||
productColumnLabelKey="cart:items.synlabAnalyses.productColumnLabel"
|
ttoServiceItems={ttoServiceItems}
|
||||||
/>
|
|
||||||
<CartServiceItems
|
|
||||||
cart={cart}
|
|
||||||
items={ttoServiceItems}
|
|
||||||
productColumnLabelKey="cart:items.ttoServices.productColumnLabel"
|
|
||||||
unavailableLineItemIds={unavailableLineItemIds}
|
unavailableLineItemIds={unavailableLineItemIds}
|
||||||
|
isInitiatingSession={isInitiatingSession}
|
||||||
|
getBalanceSummarySelection={getBalanceSummarySelection}
|
||||||
/>
|
/>
|
||||||
</div>
|
</CartForm>
|
||||||
{hasCartItems && (
|
|
||||||
<>
|
|
||||||
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
|
||||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
|
||||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
|
||||||
<Trans i18nKey="cart:order.subtotal" />
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
|
||||||
<p className="text-right text-sm">
|
|
||||||
{formatCurrency({
|
|
||||||
value: cart.subtotal,
|
|
||||||
currencyCode: cart.currency_code,
|
|
||||||
locale: language,
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
|
|
||||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
|
||||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
|
||||||
<Trans i18nKey="cart:order.promotionsTotal" />
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
|
||||||
<p className="text-right text-sm">
|
|
||||||
{formatCurrency({
|
|
||||||
value: cart.discount_total,
|
|
||||||
currencyCode: cart.currency_code,
|
|
||||||
locale: language,
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{companyBenefitsTotal > 0 && (
|
|
||||||
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
|
|
||||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
|
||||||
<p className="text-muted-foreground ml-0 text-sm font-bold">
|
|
||||||
<Trans i18nKey="cart:order.companyBenefitsTotal" />
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
|
||||||
<p className="text-right text-sm">
|
|
||||||
{formatCurrency({
|
|
||||||
value: (companyBenefitsTotal > cart.total ? cart.total : companyBenefitsTotal),
|
|
||||||
currencyCode: cart.currency_code,
|
|
||||||
locale: language,
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
|
|
||||||
<div className="w-full sm:mr-[42px] sm:w-auto">
|
|
||||||
<p className="ml-0 text-sm font-bold">
|
|
||||||
<Trans i18nKey="cart:order.total" />
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className={`sm:mr-[112px] sm:w-[50px]`}>
|
|
||||||
<p className="text-right text-sm">
|
|
||||||
{formatCurrency({
|
|
||||||
value: montonioTotal < 0 ? 0 : montonioTotal,
|
|
||||||
currencyCode: cart.currency_code,
|
|
||||||
locale: language,
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
|
|
||||||
{IS_DISCOUNT_SHOWN && (
|
|
||||||
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
|
||||||
<CardHeader className="pb-4">
|
|
||||||
<h5>
|
|
||||||
<Trans i18nKey="cart:discountCode.title" />
|
|
||||||
</h5>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="h-full">
|
|
||||||
<DiscountCode cart={{ ...cart }} />
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isLocationsShown && (
|
|
||||||
<Card className="flex w-full flex-col justify-between sm:w-1/2">
|
|
||||||
<CardHeader className="pb-4">
|
|
||||||
<h5>
|
|
||||||
<Trans i18nKey="cart:locations.title" />
|
|
||||||
</h5>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="h-full">
|
|
||||||
<AnalysisLocation
|
|
||||||
cart={{ ...cart }}
|
|
||||||
synlabAnalyses={synlabAnalyses}
|
|
||||||
/>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Button
|
|
||||||
className="h-10"
|
|
||||||
onClick={initiateSession}
|
|
||||||
disabled={isInitiatingSession}
|
|
||||||
>
|
|
||||||
{isInitiatingSession && (
|
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
||||||
)}
|
|
||||||
<Trans i18nKey="cart:checkout.goToCheckout" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { StoreCartLineItem } from "@medusajs/types";
|
import { StoreCartLineItem } from '@medusajs/types';
|
||||||
import { Reservation } from "~/lib/types/reservation";
|
|
||||||
|
import { Reservation } from '~/lib/types/reservation';
|
||||||
|
|
||||||
export interface MontonioOrderToken {
|
export interface MontonioOrderToken {
|
||||||
uuid: string;
|
uuid: string;
|
||||||
@@ -13,12 +14,6 @@ export interface MontonioOrderToken {
|
|||||||
| 'PENDING'
|
| 'PENDING'
|
||||||
| 'EXPIRED'
|
| 'EXPIRED'
|
||||||
| 'REFUNDED';
|
| 'REFUNDED';
|
||||||
| 'PAID'
|
|
||||||
| 'FAILED'
|
|
||||||
| 'CANCELLED'
|
|
||||||
| 'PENDING'
|
|
||||||
| 'EXPIRED'
|
|
||||||
| 'REFUNDED';
|
|
||||||
paymentMethod: string;
|
paymentMethod: string;
|
||||||
grandTotal: number;
|
grandTotal: number;
|
||||||
currency: string;
|
currency: string;
|
||||||
@@ -36,3 +31,13 @@ export enum CartItemType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type EnrichedCartItem = StoreCartLineItem & { reservation: Reservation };
|
export type EnrichedCartItem = StoreCartLineItem & { reservation: Reservation };
|
||||||
|
|
||||||
|
export type GetBalanceSummarySelection = ({
|
||||||
|
useCompanyBenefits,
|
||||||
|
}: {
|
||||||
|
useCompanyBenefits: boolean;
|
||||||
|
}) => {
|
||||||
|
benefitsAmount: number;
|
||||||
|
benefitsAmountTotal: number;
|
||||||
|
montonioAmount: number;
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||||
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
import { ChevronRight, HeartPulse } from 'lucide-react';
|
import { ChevronRight, HeartPulse } from 'lucide-react';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -11,25 +13,27 @@ import {
|
|||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from '@kit/ui/card';
|
} 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 { cn } from '@kit/ui/lib/utils';
|
||||||
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import { getAccountBalanceSummary } from '../_lib/server/balance-actions';
|
import { getAccountBalanceSummary } from '../_lib/server/balance-actions';
|
||||||
|
import { loadCurrentUserAccount } from '../_lib/server/load-user-account';
|
||||||
|
|
||||||
export default async function DashboardCards() {
|
export default async function DashboardCards() {
|
||||||
const { language } = await createI18nServerInstance();
|
const { language } = await createI18nServerInstance();
|
||||||
|
|
||||||
const { account } = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
const balanceSummary = account ? await getAccountBalanceSummary(account.id) : null;
|
const balanceSummary = account
|
||||||
|
? await getAccountBalanceSummary(account.id)
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'grid grid-cols-1 gap-4',
|
'grid grid-cols-1 gap-4',
|
||||||
'md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
|
'md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
|
||||||
)}>
|
)}
|
||||||
|
>
|
||||||
<Card
|
<Card
|
||||||
variant="gradient-success"
|
variant="gradient-success"
|
||||||
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
className="xs:w-1/2 flex w-full flex-col justify-between sm:w-auto"
|
||||||
@@ -79,7 +83,7 @@ export default async function DashboardCards() {
|
|||||||
<Trans
|
<Trans
|
||||||
i18nKey="dashboard:heroCard.benefits.validUntil"
|
i18nKey="dashboard:heroCard.benefits.validUntil"
|
||||||
values={{ date: '31.12.2025' }}
|
values={{ date: '31.12.2025' }}
|
||||||
/>
|
/>
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -14,7 +14,10 @@ import {
|
|||||||
User,
|
User,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
import type { AccountWithParams, BmiThresholds } from '@kit/accounts/types/accounts';
|
import type {
|
||||||
|
AccountWithParams,
|
||||||
|
BmiThresholds,
|
||||||
|
} from '@kit/accounts/types/accounts';
|
||||||
import { pathsConfig } from '@kit/shared/config';
|
import { pathsConfig } from '@kit/shared/config';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
const PaymentProviderIds = {
|
const PaymentProviderIds = {
|
||||||
COMPANY_BENEFITS: "pp_company-benefits_company-benefits",
|
COMPANY_BENEFITS: 'pp_company-benefits_company-benefits',
|
||||||
MONTONIO: "pp_montonio_montonio",
|
MONTONIO: 'pp_montonio_montonio',
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function CartTotals({
|
export default function CartTotals({
|
||||||
@@ -30,10 +30,12 @@ export default function CartTotals({
|
|||||||
payment_collections,
|
payment_collections,
|
||||||
} = medusaOrder;
|
} = medusaOrder;
|
||||||
|
|
||||||
const montonioPayment = payment_collections?.[0]?.payments
|
const montonioPayment = payment_collections?.[0]?.payments?.find(
|
||||||
?.find(({ provider_id }) => provider_id === PaymentProviderIds.MONTONIO);
|
({ provider_id }) => provider_id === PaymentProviderIds.MONTONIO,
|
||||||
const companyBenefitsPayment = payment_collections?.[0]?.payments
|
);
|
||||||
?.find(({ provider_id }) => provider_id === PaymentProviderIds.COMPANY_BENEFITS);
|
const companyBenefitsPayment = payment_collections?.[0]?.payments?.find(
|
||||||
|
({ provider_id }) => provider_id === PaymentProviderIds.COMPANY_BENEFITS,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -96,7 +98,6 @@ export default function CartTotals({
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="my-4 h-px w-full border-b border-gray-200" />
|
<div className="my-4 h-px w-full border-b border-gray-200" />
|
||||||
@@ -126,7 +127,10 @@ export default function CartTotals({
|
|||||||
<span className="flex items-center gap-x-1">
|
<span className="flex items-center gap-x-1">
|
||||||
<Trans i18nKey="cart:order.benefitsTotal" />
|
<Trans i18nKey="cart:order.benefitsTotal" />
|
||||||
</span>
|
</span>
|
||||||
<span data-testid="cart-subtotal" data-value={companyBenefitsPayment.amount || 0}>
|
<span
|
||||||
|
data-testid="cart-subtotal"
|
||||||
|
data-value={companyBenefitsPayment.amount || 0}
|
||||||
|
>
|
||||||
-{' '}
|
-{' '}
|
||||||
{formatCurrency({
|
{formatCurrency({
|
||||||
value: companyBenefitsPayment.amount ?? 0,
|
value: companyBenefitsPayment.amount ?? 0,
|
||||||
@@ -142,7 +146,10 @@ export default function CartTotals({
|
|||||||
<span className="flex items-center gap-x-1">
|
<span className="flex items-center gap-x-1">
|
||||||
<Trans i18nKey="cart:order.montonioTotal" />
|
<Trans i18nKey="cart:order.montonioTotal" />
|
||||||
</span>
|
</span>
|
||||||
<span data-testid="cart-subtotal" data-value={montonioPayment.amount || 0}>
|
<span
|
||||||
|
data-testid="cart-subtotal"
|
||||||
|
data-value={montonioPayment.amount || 0}
|
||||||
|
>
|
||||||
-{' '}
|
-{' '}
|
||||||
{formatCurrency({
|
{formatCurrency({
|
||||||
value: montonioPayment.amount ?? 0,
|
value: montonioPayment.amount ?? 0,
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { AccountBalanceService, AccountBalanceSummary } from '@kit/accounts/services/account-balance.service';
|
import {
|
||||||
|
AccountBalanceService,
|
||||||
|
AccountBalanceSummary,
|
||||||
|
} from '@kit/accounts/services/account-balance.service';
|
||||||
|
|
||||||
export async function getAccountBalanceSummary(accountId: string): Promise<AccountBalanceSummary | null> {
|
export async function getAccountBalanceSummary(
|
||||||
|
accountId: string,
|
||||||
|
): Promise<AccountBalanceSummary | null> {
|
||||||
try {
|
try {
|
||||||
const service = new AccountBalanceService();
|
const service = new AccountBalanceService();
|
||||||
return await service.getBalanceSummary(accountId);
|
return await service.getBalanceSummary(accountId);
|
||||||
|
|||||||
@@ -1,25 +1,27 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { z } from 'zod';
|
import { AccountWithParams } from '@/packages/features/accounts/src/types/accounts';
|
||||||
|
import { createNotificationsApi } from '@/packages/features/notifications/src/server/api';
|
||||||
|
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
||||||
|
import { listProductTypes } from '@lib/data';
|
||||||
|
import { initiateMultiPaymentSession, placeOrder } from '@lib/data/cart';
|
||||||
|
import type { StoreCart, StoreOrder } from '@medusajs/types';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
import type { StoreCart, StoreOrder } from "@medusajs/types";
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
|
|
||||||
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';
|
import { bookAppointment } from '~/lib/services/connected-online.service';
|
||||||
|
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
|
||||||
|
import { handleNavigateToPayment } from '~/lib/services/medusaCart.service';
|
||||||
|
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
|
||||||
|
import {
|
||||||
|
createAnalysisOrder,
|
||||||
|
getAnalysisOrder,
|
||||||
|
} from '~/lib/services/order.service';
|
||||||
|
import { getOrderedTtoServices } from '~/lib/services/reservation.service';
|
||||||
|
import { FailureReason } from '~/lib/types/connected-online';
|
||||||
|
|
||||||
|
import { loadCurrentUserAccount } from './load-user-account';
|
||||||
|
|
||||||
const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages';
|
const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages';
|
||||||
const ANALYSIS_TYPE_HANDLE = 'synlab-analysis';
|
const ANALYSIS_TYPE_HANDLE = 'synlab-analysis';
|
||||||
@@ -40,12 +42,16 @@ const env = () =>
|
|||||||
isEnabledDispatchOnMontonioCallback: z.boolean({
|
isEnabledDispatchOnMontonioCallback: z.boolean({
|
||||||
error: 'MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK is required',
|
error: 'MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK is required',
|
||||||
}),
|
}),
|
||||||
medusaBackendPublicUrl: z.string({
|
medusaBackendPublicUrl: z
|
||||||
error: 'MEDUSA_BACKEND_PUBLIC_URL is required',
|
.string({
|
||||||
}).min(1),
|
error: 'MEDUSA_BACKEND_PUBLIC_URL is required',
|
||||||
companyBenefitsPaymentSecretKey: z.string({
|
})
|
||||||
error: 'COMPANY_BENEFITS_PAYMENT_SECRET_KEY is required',
|
.min(1),
|
||||||
}).min(1),
|
companyBenefitsPaymentSecretKey: z
|
||||||
|
.string({
|
||||||
|
error: 'COMPANY_BENEFITS_PAYMENT_SECRET_KEY is required',
|
||||||
|
})
|
||||||
|
.min(1),
|
||||||
})
|
})
|
||||||
.parse({
|
.parse({
|
||||||
emailSender: process.env.EMAIL_SENDER,
|
emailSender: process.env.EMAIL_SENDER,
|
||||||
@@ -53,17 +59,18 @@ const env = () =>
|
|||||||
isEnabledDispatchOnMontonioCallback:
|
isEnabledDispatchOnMontonioCallback:
|
||||||
process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true',
|
process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true',
|
||||||
medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!,
|
medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!,
|
||||||
companyBenefitsPaymentSecretKey: process.env.COMPANY_BENEFITS_PAYMENT_SECRET_KEY!,
|
companyBenefitsPaymentSecretKey:
|
||||||
|
process.env.COMPANY_BENEFITS_PAYMENT_SECRET_KEY!,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const initiatePayment = async ({
|
export const initiatePayment = async ({
|
||||||
accountId,
|
accountId,
|
||||||
balanceSummary,
|
benefitsAmount,
|
||||||
cart,
|
cart,
|
||||||
language,
|
language,
|
||||||
}: {
|
}: {
|
||||||
accountId: string;
|
accountId: string;
|
||||||
balanceSummary: AccountBalanceSummary;
|
benefitsAmount: number;
|
||||||
cart: StoreCart;
|
cart: StoreCart;
|
||||||
language: string;
|
language: string;
|
||||||
}) => {
|
}) => {
|
||||||
@@ -74,7 +81,7 @@ export const initiatePayment = async ({
|
|||||||
totalByMontonio,
|
totalByMontonio,
|
||||||
totalByBenefits,
|
totalByBenefits,
|
||||||
isFullyPaidByBenefits,
|
isFullyPaidByBenefits,
|
||||||
} = await initiateMultiPaymentSession(cart, balanceSummary.totalBalance);
|
} = await initiateMultiPaymentSession(cart, benefitsAmount);
|
||||||
|
|
||||||
if (!isFullyPaidByBenefits) {
|
if (!isFullyPaidByBenefits) {
|
||||||
if (!montonioPaymentSessionId) {
|
if (!montonioPaymentSessionId) {
|
||||||
@@ -92,23 +99,30 @@ export const initiatePayment = async ({
|
|||||||
// place order if all paid already
|
// place order if all paid already
|
||||||
const { orderId } = await handlePlaceOrder({ cart });
|
const { orderId } = await handlePlaceOrder({ cart });
|
||||||
|
|
||||||
const companyBenefitsOrderToken = jwt.sign({
|
const companyBenefitsOrderToken = jwt.sign(
|
||||||
accountId,
|
{
|
||||||
companyBenefitsPaymentSessionId,
|
accountId,
|
||||||
orderId,
|
companyBenefitsPaymentSessionId,
|
||||||
totalByBenefits,
|
orderId,
|
||||||
}, env().companyBenefitsPaymentSecretKey, {
|
totalByBenefits,
|
||||||
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',
|
|
||||||
},
|
},
|
||||||
});
|
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) {
|
if (!webhookResponse.ok) {
|
||||||
throw new Error('Failed to send company benefits webhook');
|
throw new Error('Failed to send company benefits webhook');
|
||||||
}
|
}
|
||||||
@@ -118,14 +132,15 @@ export const initiatePayment = async ({
|
|||||||
console.error('Error initiating payment', error);
|
console.error('Error initiating payment', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { url: null, isFullyPaidByBenefits: false, orderId: null, unavailableLineItemIds: [] };
|
return {
|
||||||
}
|
url: null,
|
||||||
|
isFullyPaidByBenefits: false,
|
||||||
|
orderId: null,
|
||||||
|
unavailableLineItemIds: [],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export async function handlePlaceOrder({
|
export async function handlePlaceOrder({ cart }: { cart: StoreCart }) {
|
||||||
cart,
|
|
||||||
}: {
|
|
||||||
cart: StoreCart;
|
|
||||||
}) {
|
|
||||||
const { account } = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error('Account not found in context');
|
throw new Error('Account not found in context');
|
||||||
@@ -184,6 +199,7 @@ export async function handlePlaceOrder({
|
|||||||
);
|
);
|
||||||
bookServiceResults = await Promise.all(bookingPromises);
|
bookServiceResults = await Promise.all(bookingPromises);
|
||||||
}
|
}
|
||||||
|
// TODO: SEND EMAIL
|
||||||
|
|
||||||
if (email) {
|
if (email) {
|
||||||
if (analysisPackageOrder) {
|
if (analysisPackageOrder) {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export const isValidOpenAiEnv = async () => {
|
|||||||
await client.models.list();
|
await client.models.list();
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log('No openAI env');
|
console.log('AI not enabled');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { cache } from 'react';
|
|||||||
import { getAnalysisElementMedusaProductIds } from '@/utils/medusa-product';
|
import { getAnalysisElementMedusaProductIds } from '@/utils/medusa-product';
|
||||||
import { listProductTypes, listProducts } from '@lib/data/products';
|
import { listProductTypes, listProducts } from '@lib/data/products';
|
||||||
import { listRegions } from '@lib/data/regions';
|
import { listRegions } from '@lib/data/regions';
|
||||||
import type { StoreProduct } from '@medusajs/types';
|
import type { StoreProduct, StoreProductType } from '@medusajs/types';
|
||||||
|
|
||||||
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
||||||
import type { AnalysisPackageWithVariant } from '@kit/shared/components/select-analysis-package';
|
import type { AnalysisPackageWithVariant } from '@kit/shared/components/select-analysis-package';
|
||||||
@@ -118,17 +118,12 @@ async function analysisPackageElementsLoader({
|
|||||||
async function analysisPackagesWithVariantLoader({
|
async function analysisPackagesWithVariantLoader({
|
||||||
account,
|
account,
|
||||||
countryCode,
|
countryCode,
|
||||||
|
productType,
|
||||||
}: {
|
}: {
|
||||||
account: AccountWithParams;
|
account: AccountWithParams;
|
||||||
countryCode: string;
|
countryCode: string;
|
||||||
|
productType: StoreProductType;
|
||||||
}) {
|
}) {
|
||||||
const productTypes = await loadProductTypes();
|
|
||||||
const productType = productTypes.find(
|
|
||||||
({ metadata }) => metadata?.handle === 'analysis-packages',
|
|
||||||
);
|
|
||||||
if (!productType) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const analysisPackagesResponse = await listProducts({
|
const analysisPackagesResponse = await listProducts({
|
||||||
countryCode,
|
countryCode,
|
||||||
queryParams: { limit: 100, 'type_id[0]': productType.id },
|
queryParams: { limit: 100, 'type_id[0]': productType.id },
|
||||||
@@ -171,12 +166,23 @@ async function analysisPackagesLoader() {
|
|||||||
throw new Error('Account not found');
|
throw new Error('Account not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const countryCodes = await loadCountryCodes();
|
const [countryCodes, productTypes] = await Promise.all([
|
||||||
|
loadCountryCodes(),
|
||||||
|
loadProductTypes(),
|
||||||
|
]);
|
||||||
const countryCode = countryCodes[0]!;
|
const countryCode = countryCodes[0]!;
|
||||||
|
const productType = productTypes.find(
|
||||||
|
({ metadata }) => metadata?.handle === 'analysis-packages',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!productType) {
|
||||||
|
return { analysisPackageElements: [], analysisPackages: [], countryCode };
|
||||||
|
}
|
||||||
|
|
||||||
const analysisPackagesWithVariant = await analysisPackagesWithVariantLoader({
|
const analysisPackagesWithVariant = await analysisPackagesWithVariantLoader({
|
||||||
account,
|
account,
|
||||||
countryCode,
|
countryCode,
|
||||||
|
productType,
|
||||||
});
|
});
|
||||||
if (!analysisPackagesWithVariant) {
|
if (!analysisPackagesWithVariant) {
|
||||||
return { analysisPackageElements: [], analysisPackages: [], countryCode };
|
return { analysisPackageElements: [], analysisPackages: [], countryCode };
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { Trans } from 'react-i18next';
|
|
||||||
|
|
||||||
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
||||||
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
||||||
@@ -12,6 +11,7 @@ import { Form } from '@kit/ui/form';
|
|||||||
import { LanguageSelector } from '@kit/ui/language-selector';
|
import { LanguageSelector } from '@kit/ui/language-selector';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { toast } from '@kit/ui/sonner';
|
||||||
import { Switch } from '@kit/ui/switch';
|
import { Switch } from '@kit/ui/switch';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AccountPreferences,
|
AccountPreferences,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { Trans } from 'react-i18next';
|
|
||||||
|
|
||||||
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
|
||||||
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
import type { AccountWithParams } from '@kit/accounts/types/accounts';
|
||||||
@@ -24,6 +23,7 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@kit/ui/select';
|
} from '@kit/ui/select';
|
||||||
import { toast } from '@kit/ui/sonner';
|
import { toast } from '@kit/ui/sonner';
|
||||||
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AccountSettings,
|
AccountSettings,
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import React from 'react';
|
|||||||
|
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { Database } from '@/packages/supabase/src/database.types';
|
||||||
|
|
||||||
|
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||||
import { Card } from '@kit/ui/card';
|
import { Card } from '@kit/ui/card';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { cn } from '@kit/ui/utils';
|
import { cn } from '@kit/ui/utils';
|
||||||
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
|
||||||
|
|
||||||
import { getAccountHealthDetailsFields } from '../_lib/server/load-team-account-health-details';
|
import { getAccountHealthDetailsFields } from '../_lib/server/load-team-account-health-details';
|
||||||
import { TeamAccountStatisticsProps } from './team-account-statistics';
|
import { TeamAccountStatisticsProps } from './team-account-statistics';
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ import { useState } from 'react';
|
|||||||
|
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
|
import type {
|
||||||
|
Account,
|
||||||
|
AccountParams,
|
||||||
|
BmiThresholds,
|
||||||
|
} from '@/packages/features/accounts/src/types/accounts';
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { Database } from '@/packages/supabase/src/database.types';
|
||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
import { enGB, et } from 'date-fns/locale';
|
import { enGB, et } from 'date-fns/locale';
|
||||||
@@ -16,11 +21,10 @@ import { Trans } from '@kit/ui/makerkit/trans';
|
|||||||
import { Button } from '@kit/ui/shadcn/button';
|
import { Button } from '@kit/ui/shadcn/button';
|
||||||
import { DateRange } from '@kit/ui/shadcn/calendar';
|
import { DateRange } from '@kit/ui/shadcn/calendar';
|
||||||
|
|
||||||
|
import { TeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
|
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
|
||||||
import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
|
import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
|
||||||
import TeamAccountHealthDetails from './team-account-health-details';
|
import TeamAccountHealthDetails from './team-account-health-details';
|
||||||
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 {
|
export interface TeamAccountStatisticsProps {
|
||||||
teamAccount: Account;
|
teamAccount: Account;
|
||||||
@@ -53,7 +57,7 @@ export default function TeamAccountStatistics({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="mt-4 flex flex-col gap-4 sm:gap-0 sm:flex-row items-center justify-between">
|
<div className="mt-4 flex flex-col items-center justify-between gap-4 sm:flex-row sm:gap-0">
|
||||||
<h4 className="font-bold">
|
<h4 className="font-bold">
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey={'teams:home.headerTitle'}
|
i18nKey={'teams:home.headerTitle'}
|
||||||
@@ -78,7 +82,10 @@ export default function TeamAccountStatistics({
|
|||||||
'animate-in fade-in flex flex-col space-y-4 pb-36 duration-500'
|
'animate-in fade-in flex flex-col space-y-4 pb-36 duration-500'
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<TeamAccountBenefitStatistics accountBenefitStatistics={accountBenefitStatistics} expensesOverview={expensesOverview} />
|
<TeamAccountBenefitStatistics
|
||||||
|
accountBenefitStatistics={accountBenefitStatistics}
|
||||||
|
expensesOverview={expensesOverview}
|
||||||
|
/>
|
||||||
|
|
||||||
<h5 className="mt-4 mb-2">
|
<h5 className="mt-4 mb-2">
|
||||||
<Trans i18nKey="teams:home.healthDetails" />
|
<Trans i18nKey="teams:home.healthDetails" />
|
||||||
@@ -125,10 +132,7 @@ export default function TeamAccountStatistics({
|
|||||||
className="border-warning/40 hover:bg-warning/20 relative flex h-full cursor-pointer flex-col justify-center px-6 py-4 transition-colors"
|
className="border-warning/40 hover:bg-warning/20 relative flex h-full cursor-pointer flex-col justify-center px-6 py-4 transition-colors"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
redirect(
|
redirect(
|
||||||
createPath(
|
createPath(pathsConfig.app.accountBilling, teamAccount.slug!),
|
||||||
pathsConfig.app.accountBilling,
|
|
||||||
teamAccount.slug!,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { getSupabaseServerClient } from "@/packages/supabase/src/clients/server-client";
|
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
|
||||||
import { loadCompanyPersonalAccountsBalanceEntries } from "./load-team-account-benefit-statistics";
|
|
||||||
|
import { loadCompanyPersonalAccountsBalanceEntries } from './load-team-account-benefit-statistics';
|
||||||
|
|
||||||
export interface TeamAccountBenefitExpensesOverview {
|
export interface TeamAccountBenefitExpensesOverview {
|
||||||
benefitAmount: number | null;
|
benefitAmount: number | null;
|
||||||
@@ -10,7 +11,7 @@ export interface TeamAccountBenefitExpensesOverview {
|
|||||||
total: number;
|
total: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MANAGEMENT_FEE = 5.50;
|
const MANAGEMENT_FEE = 5.5;
|
||||||
|
|
||||||
const MONTHS = 12;
|
const MONTHS = 12;
|
||||||
const QUARTERS = 4;
|
const QUARTERS = 4;
|
||||||
@@ -32,15 +33,19 @@ export async function loadTeamAccountBenefitExpensesOverview({
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
let benefitAmount: TeamAccountBenefitExpensesOverview['benefitAmount'] = null;
|
let benefitAmount: TeamAccountBenefitExpensesOverview['benefitAmount'] = null;
|
||||||
let benefitOccurrence: TeamAccountBenefitExpensesOverview['benefitOccurrence'] = null;
|
let benefitOccurrence: TeamAccountBenefitExpensesOverview['benefitOccurrence'] =
|
||||||
|
null;
|
||||||
if (error) {
|
if (error) {
|
||||||
console.warn('Failed to load team account benefit expenses overview');
|
console.warn('Failed to load team account benefit expenses overview');
|
||||||
} else {
|
} else {
|
||||||
benefitAmount = data.benefit_amount as TeamAccountBenefitExpensesOverview['benefitAmount'];
|
benefitAmount =
|
||||||
benefitOccurrence = data.benefit_occurrence as TeamAccountBenefitExpensesOverview['benefitOccurrence'];
|
data.benefit_amount as TeamAccountBenefitExpensesOverview['benefitAmount'];
|
||||||
|
benefitOccurrence =
|
||||||
|
data.benefit_occurrence as TeamAccountBenefitExpensesOverview['benefitOccurrence'];
|
||||||
}
|
}
|
||||||
|
|
||||||
const { purchaseEntriesTotal } = await loadCompanyPersonalAccountsBalanceEntries({ accountId: companyId });
|
const { purchaseEntriesTotal } =
|
||||||
|
await loadCompanyPersonalAccountsBalanceEntries({ accountId: companyId });
|
||||||
|
|
||||||
return {
|
return {
|
||||||
benefitAmount,
|
benefitAmount,
|
||||||
@@ -55,7 +60,8 @@ export async function loadTeamAccountBenefitExpensesOverview({
|
|||||||
|
|
||||||
const currentDate = new Date();
|
const currentDate = new Date();
|
||||||
const createdAt = new Date(data.created_at);
|
const createdAt = new Date(data.created_at);
|
||||||
const isCreatedThisYear = createdAt.getFullYear() === currentDate.getFullYear();
|
const isCreatedThisYear =
|
||||||
|
createdAt.getFullYear() === currentDate.getFullYear();
|
||||||
if (benefitOccurrence === 'yearly') {
|
if (benefitOccurrence === 'yearly') {
|
||||||
return benefitAmount * employeeCount;
|
return benefitAmount * employeeCount;
|
||||||
} else if (benefitOccurrence === 'monthly') {
|
} else if (benefitOccurrence === 'monthly') {
|
||||||
@@ -71,5 +77,5 @@ export async function loadTeamAccountBenefitExpensesOverview({
|
|||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
})(),
|
})(),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export interface AccountBenefitStatistics {
|
|||||||
|
|
||||||
analysisPackagesCount: number;
|
analysisPackagesCount: number;
|
||||||
analysisPackagesSum: number;
|
analysisPackagesSum: number;
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const loadCompanyPersonalAccountsBalanceEntries = async ({
|
export const loadCompanyPersonalAccountsBalanceEntries = async ({
|
||||||
@@ -38,12 +38,21 @@ export const loadCompanyPersonalAccountsBalanceEntries = async ({
|
|||||||
.from('account_balance_entries')
|
.from('account_balance_entries')
|
||||||
.select('*')
|
.select('*')
|
||||||
.eq('is_active', true)
|
.eq('is_active', true)
|
||||||
.in('account_id', accountMemberships.map(({ user_id }) => user_id))
|
.in(
|
||||||
|
'account_id',
|
||||||
|
accountMemberships.map(({ user_id }) => user_id),
|
||||||
|
)
|
||||||
.throwOnError();
|
.throwOnError();
|
||||||
|
|
||||||
const purchaseEntries = accountBalanceEntries.filter(({ entry_type }) => entry_type === 'purchase');
|
const purchaseEntries = accountBalanceEntries.filter(
|
||||||
const analysesEntries = purchaseEntries.filter(({ is_analysis_order }) => is_analysis_order);
|
({ entry_type }) => entry_type === 'purchase',
|
||||||
const analysisPackagesEntries = purchaseEntries.filter(({ is_analysis_package_order }) => is_analysis_package_order);
|
);
|
||||||
|
const analysesEntries = purchaseEntries.filter(
|
||||||
|
({ is_analysis_order }) => is_analysis_order,
|
||||||
|
);
|
||||||
|
const analysisPackagesEntries = purchaseEntries.filter(
|
||||||
|
({ is_analysis_package_order }) => is_analysis_package_order,
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
accountBalanceEntries,
|
accountBalanceEntries,
|
||||||
@@ -51,9 +60,12 @@ export const loadCompanyPersonalAccountsBalanceEntries = async ({
|
|||||||
analysisPackagesEntries,
|
analysisPackagesEntries,
|
||||||
companyAccountsCount: count || 0,
|
companyAccountsCount: count || 0,
|
||||||
purchaseEntries,
|
purchaseEntries,
|
||||||
purchaseEntriesTotal: purchaseEntries.reduce((acc, { amount }) => acc + Math.abs(amount || 0), 0),
|
purchaseEntriesTotal: purchaseEntries.reduce(
|
||||||
|
(acc, { amount }) => acc + Math.abs(amount || 0),
|
||||||
|
0,
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
export const loadAccountBenefitStatistics = async (
|
export const loadAccountBenefitStatistics = async (
|
||||||
accountId: string,
|
accountId: string,
|
||||||
@@ -86,10 +98,16 @@ export const loadAccountBenefitStatistics = async (
|
|||||||
totalSum: purchaseEntriesTotal,
|
totalSum: purchaseEntriesTotal,
|
||||||
|
|
||||||
analysesCount: analysesEntries.length,
|
analysesCount: analysesEntries.length,
|
||||||
analysesSum: analysesEntries.reduce((acc, { amount }) => acc + Math.abs(amount || 0), 0),
|
analysesSum: analysesEntries.reduce(
|
||||||
|
(acc, { amount }) => acc + Math.abs(amount || 0),
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
|
||||||
analysisPackagesCount: analysisPackagesEntries.length,
|
analysisPackagesCount: analysisPackagesEntries.length,
|
||||||
analysisPackagesSum: analysisPackagesEntries.reduce((acc, { amount }) => acc + Math.abs(amount || 0), 0),
|
analysisPackagesSum: analysisPackagesEntries.reduce(
|
||||||
|
(acc, { amount }) => acc + Math.abs(amount || 0),
|
||||||
|
0,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { Database } from '@/packages/supabase/src/database.types';
|
|||||||
import Isikukood from 'isikukood';
|
import Isikukood from 'isikukood';
|
||||||
import { Clock, TrendingUp, User } from 'lucide-react';
|
import { Clock, TrendingUp, User } from 'lucide-react';
|
||||||
|
|
||||||
|
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
bmiFromMetric,
|
bmiFromMetric,
|
||||||
getBmiBackgroundColor,
|
getBmiBackgroundColor,
|
||||||
@@ -11,7 +13,6 @@ import {
|
|||||||
} from '~/lib/utils';
|
} from '~/lib/utils';
|
||||||
|
|
||||||
import { TeamAccountStatisticsProps } from '../../_components/team-account-statistics';
|
import { TeamAccountStatisticsProps } from '../../_components/team-account-statistics';
|
||||||
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
|
||||||
|
|
||||||
interface AccountHealthDetailsField {
|
interface AccountHealthDetailsField {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -62,13 +63,13 @@ export const getAccountHealthDetailsFields = (
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
title: 'teams:healthDetails.women',
|
title: 'teams:healthDetails.women',
|
||||||
value: `${femalePercentage}% (${numberOfFemaleMembers})`,
|
value: `${femalePercentage.toFixed(0)}% (${numberOfFemaleMembers})`,
|
||||||
Icon: User,
|
Icon: User,
|
||||||
iconBg: 'bg-success',
|
iconBg: 'bg-success',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'teams:healthDetails.men',
|
title: 'teams:healthDetails.men',
|
||||||
value: `${malePercentage}% (${numberOfMaleMembers})`,
|
value: `${malePercentage.toFixed(0)}% (${numberOfMaleMembers})`,
|
||||||
Icon: User,
|
Icon: User,
|
||||||
iconBg: 'bg-success',
|
iconBg: 'bg-success',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
import { UpdateHealthBenefitSchema } from '@/packages/billing/core/src/schema';
|
import { UpdateHealthBenefitSchema } from '@/packages/billing/core/src/schema';
|
||||||
|
import {
|
||||||
|
Account,
|
||||||
|
CompanyParams,
|
||||||
|
} from '@/packages/features/accounts/src/types/accounts';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
import { Form } from '@kit/ui/form';
|
import { Form } from '@kit/ui/form';
|
||||||
@@ -17,8 +23,6 @@ import { cn } from '~/lib/utils';
|
|||||||
|
|
||||||
import { updateHealthBenefit } from '../_lib/server/server-actions';
|
import { updateHealthBenefit } from '../_lib/server/server-actions';
|
||||||
import HealthBenefitFields from './health-benefit-fields';
|
import HealthBenefitFields from './health-benefit-fields';
|
||||||
import { Account, CompanyParams } from '@/packages/features/accounts/src/types/accounts';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
|
||||||
|
|
||||||
const HealthBenefitFormClient = ({
|
const HealthBenefitFormClient = ({
|
||||||
account,
|
account,
|
||||||
@@ -29,7 +33,7 @@ const HealthBenefitFormClient = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation('account');
|
const { t } = useTranslation('account');
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const [currentCompanyParams, setCurrentCompanyParams] =
|
const [currentCompanyParams, setCurrentCompanyParams] =
|
||||||
useState<CompanyParams>(companyParams);
|
useState<CompanyParams>(companyParams);
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
@@ -42,7 +46,7 @@ const HealthBenefitFormClient = ({
|
|||||||
amount: currentCompanyParams.benefit_amount || 0,
|
amount: currentCompanyParams.benefit_amount || 0,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const isDirty = form.formState.isDirty;
|
const isDirty = form.formState.isDirty;
|
||||||
|
|
||||||
const onSubmit = (data: { occurrence: string; amount: number }) => {
|
const onSubmit = (data: { occurrence: string; amount: number }) => {
|
||||||
@@ -75,7 +79,7 @@ const HealthBenefitFormClient = ({
|
|||||||
onSubmit={form.handleSubmit(onSubmit)}
|
onSubmit={form.handleSubmit(onSubmit)}
|
||||||
>
|
>
|
||||||
<HealthBenefitFields />
|
<HealthBenefitFields />
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="relative"
|
className="relative"
|
||||||
@@ -96,5 +100,3 @@ const HealthBenefitFormClient = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default HealthBenefitFormClient;
|
export default HealthBenefitFormClient;
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
|
import {
|
||||||
|
Account,
|
||||||
|
CompanyParams,
|
||||||
|
} from '@/packages/features/accounts/src/types/accounts';
|
||||||
import { PiggyBankIcon } from 'lucide-react';
|
import { PiggyBankIcon } from 'lucide-react';
|
||||||
|
|
||||||
import { Separator } from '@kit/ui/shadcn/separator';
|
import { Separator } from '@kit/ui/shadcn/separator';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
|
|
||||||
|
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
import HealthBenefitFormClient from './health-benefit-form-client';
|
import HealthBenefitFormClient from './health-benefit-form-client';
|
||||||
import YearlyExpensesOverview from './yearly-expenses-overview';
|
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 = async ({
|
const HealthBenefitForm = async ({
|
||||||
account,
|
account,
|
||||||
@@ -31,9 +34,9 @@ const HealthBenefitForm = async ({
|
|||||||
</h4>
|
</h4>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col-reverse sm:flex-row gap-6">
|
<div className="flex flex-col-reverse gap-6 sm:flex-row">
|
||||||
<div className="border-border w-full sm:w-1/3 rounded-lg border">
|
<div className="border-border w-full rounded-lg border sm:w-1/3">
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-orange-100">
|
<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" />
|
<PiggyBankIcon className="h-[32px] w-[32px] stroke-orange-400 stroke-2" />
|
||||||
@@ -46,7 +49,7 @@ const HealthBenefitForm = async ({
|
|||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<HealthBenefitFormClient
|
<HealthBenefitFormClient
|
||||||
account={account}
|
account={account}
|
||||||
companyParams={companyParams}
|
companyParams={companyParams}
|
||||||
/>
|
/>
|
||||||
@@ -58,7 +61,7 @@ const HealthBenefitForm = async ({
|
|||||||
employeeCount={employeeCount}
|
employeeCount={employeeCount}
|
||||||
expensesOverview={expensesOverview}
|
expensesOverview={expensesOverview}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground text-sm">
|
||||||
<Trans i18nKey="billing:healthBenefitForm.info" />
|
<Trans i18nKey="billing:healthBenefitForm.info" />
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import { formatCurrency } from '@/packages/shared/src/utils';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { Trans } from '@kit/ui/makerkit/trans';
|
import { Trans } from '@kit/ui/makerkit/trans';
|
||||||
import { Separator } from '@kit/ui/separator';
|
import { Separator } from '@kit/ui/separator';
|
||||||
import { formatCurrency } from '@/packages/shared/src/utils';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
|
||||||
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
import { TeamAccountBenefitExpensesOverview } from '../../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
|
||||||
const YearlyExpensesOverview = ({
|
const YearlyExpensesOverview = ({
|
||||||
@@ -13,7 +15,9 @@ const YearlyExpensesOverview = ({
|
|||||||
employeeCount?: number;
|
employeeCount?: number;
|
||||||
expensesOverview: TeamAccountBenefitExpensesOverview;
|
expensesOverview: TeamAccountBenefitExpensesOverview;
|
||||||
}) => {
|
}) => {
|
||||||
const { i18n: { language } } = useTranslation();
|
const {
|
||||||
|
i18n: { language },
|
||||||
|
} = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-border rounded-lg border p-6">
|
<div className="border-border rounded-lg border p-6">
|
||||||
@@ -24,9 +28,7 @@ const YearlyExpensesOverview = ({
|
|||||||
<p className="text-sm font-medium">
|
<p className="text-sm font-medium">
|
||||||
<Trans i18nKey="billing:expensesOverview.employeeCount" />
|
<Trans i18nKey="billing:expensesOverview.employeeCount" />
|
||||||
</p>
|
</p>
|
||||||
<span className="text-primary text-sm font-bold">
|
<span className="text-primary text-sm font-bold">{employeeCount}</span>
|
||||||
{employeeCount}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 flex justify-between">
|
<div className="mt-3 flex justify-between">
|
||||||
<p className="text-sm font-medium">
|
<p className="text-sm font-medium">
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import { PageBody } from '@kit/ui/page';
|
|||||||
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
|
||||||
import { withI18n } from '~/lib/i18n/with-i18n';
|
import { withI18n } from '~/lib/i18n/with-i18n';
|
||||||
|
|
||||||
import HealthBenefitForm from './_components/health-benefit-form';
|
|
||||||
import { loadTeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
import { loadTeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
import HealthBenefitForm from './_components/health-benefit-form';
|
||||||
|
|
||||||
interface TeamAccountBillingPageProps {
|
interface TeamAccountBillingPageProps {
|
||||||
params: Promise<{ account: string }>;
|
params: Promise<{ account: string }>;
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import 'server-only';
|
|||||||
|
|
||||||
import { SupabaseClient } from '@supabase/supabase-js';
|
import { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
||||||
import { Database } from '@/packages/supabase/src/database.types';
|
import { Database } from '@/packages/supabase/src/database.types';
|
||||||
|
|
||||||
import { loadTeamWorkspace } from '~/home/[account]/_lib/server/team-account-workspace.loader';
|
import { loadTeamWorkspace } from '~/home/[account]/_lib/server/team-account-workspace.loader';
|
||||||
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load data for the members page
|
* Load data for the members page
|
||||||
@@ -22,7 +22,10 @@ export async function loadMembersPageData(
|
|||||||
loadInvitations(client, slug),
|
loadInvitations(client, slug),
|
||||||
canAddMember,
|
canAddMember,
|
||||||
workspace,
|
workspace,
|
||||||
loadAccountMembersBenefitsUsage(getSupabaseServerAdminClient(), workspace.account.id),
|
loadAccountMembersBenefitsUsage(
|
||||||
|
getSupabaseServerAdminClient(),
|
||||||
|
workspace.account.id,
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,16 +63,32 @@ async function loadAccountMembers(
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return data ?? [];
|
const members = data ?? [];
|
||||||
|
|
||||||
|
return members
|
||||||
|
.sort((prev, next) => {
|
||||||
|
if (prev.primary_owner_user_id === prev.user_id) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (prev.role_hierarchy_level < next.role_hierarchy_level) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadAccountMembersBenefitsUsage(
|
export async function loadAccountMembersBenefitsUsage(
|
||||||
client: SupabaseClient<Database>,
|
client: SupabaseClient<Database>,
|
||||||
accountId: string,
|
accountId: string,
|
||||||
): Promise<{
|
): Promise<
|
||||||
personal_account_id: string;
|
{
|
||||||
benefit_amount: number;
|
personal_account_id: string;
|
||||||
}[]> {
|
benefit_amount: number;
|
||||||
|
benefit_unused_amount: number;
|
||||||
|
}[]
|
||||||
|
> {
|
||||||
const { data, error } = await client
|
const { data, error } = await client
|
||||||
.schema('medreport')
|
.schema('medreport')
|
||||||
.rpc('get_benefits_usages_for_company_members', {
|
.rpc('get_benefits_usages_for_company_members', {
|
||||||
@@ -81,7 +100,11 @@ export async function loadAccountMembersBenefitsUsage(
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return data ?? [];
|
return (data ?? []) as unknown as {
|
||||||
|
personal_account_id: string;
|
||||||
|
benefit_amount: number;
|
||||||
|
benefit_unused_amount: number;
|
||||||
|
}[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -42,8 +42,13 @@ async function TeamAccountMembersPage({ params }: TeamAccountMembersPageProps) {
|
|||||||
const client = getSupabaseServerClient();
|
const client = getSupabaseServerClient();
|
||||||
const slug = (await params).account;
|
const slug = (await params).account;
|
||||||
|
|
||||||
const [members, invitations, canAddMember, { user, account }, membersBenefitsUsage] =
|
const [
|
||||||
await loadMembersPageData(client, slug);
|
members,
|
||||||
|
invitations,
|
||||||
|
canAddMember,
|
||||||
|
{ user, account },
|
||||||
|
membersBenefitsUsage,
|
||||||
|
] = await loadMembersPageData(client, slug);
|
||||||
|
|
||||||
const canManageRoles = account.permissions.includes('roles.manage');
|
const canManageRoles = account.permissions.includes('roles.manage');
|
||||||
const canManageInvitations = account.permissions.includes('invites.manage');
|
const canManageInvitations = account.permissions.includes('invites.manage');
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ import {
|
|||||||
} from '~/lib/services/audit/pageView.service';
|
} from '~/lib/services/audit/pageView.service';
|
||||||
|
|
||||||
import { Dashboard } from './_components/dashboard';
|
import { Dashboard } from './_components/dashboard';
|
||||||
import { loadAccountBenefitStatistics } from './_lib/server/load-team-account-benefit-statistics';
|
|
||||||
import { loadTeamAccountBenefitExpensesOverview } from './_lib/server/load-team-account-benefit-expenses-overview';
|
import { loadTeamAccountBenefitExpensesOverview } from './_lib/server/load-team-account-benefit-expenses-overview';
|
||||||
|
import { loadAccountBenefitStatistics } from './_lib/server/load-team-account-benefit-statistics';
|
||||||
|
|
||||||
interface TeamAccountHomePageProps {
|
interface TeamAccountHomePageProps {
|
||||||
params: Promise<{ account: string }>;
|
params: Promise<{ account: string }>;
|
||||||
@@ -41,11 +41,15 @@ function TeamAccountHomePage({ params }: TeamAccountHomePageProps) {
|
|||||||
const teamAccount = use(teamAccountsApi.getTeamAccount(account));
|
const teamAccount = use(teamAccountsApi.getTeamAccount(account));
|
||||||
const { memberParams, members } = use(teamAccountsApi.getMembers(account));
|
const { memberParams, members } = use(teamAccountsApi.getMembers(account));
|
||||||
const bmiThresholds = use(userAnalysesApi.fetchBmiThresholds());
|
const bmiThresholds = use(userAnalysesApi.fetchBmiThresholds());
|
||||||
const accountBenefitStatistics = use(loadAccountBenefitStatistics(teamAccount.id));
|
const accountBenefitStatistics = use(
|
||||||
const expensesOverview = use(loadTeamAccountBenefitExpensesOverview({
|
loadAccountBenefitStatistics(teamAccount.id),
|
||||||
companyId: teamAccount.id,
|
);
|
||||||
employeeCount: members.length,
|
const expensesOverview = use(
|
||||||
}));
|
loadTeamAccountBenefitExpensesOverview({
|
||||||
|
companyId: teamAccount.id,
|
||||||
|
employeeCount: members.length,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
use(
|
use(
|
||||||
createPageViewLog({
|
createPageViewLog({
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export enum NotificationAction {
|
|||||||
PATIENT_ORDER_PROCESSING = 'PATIENT_ORDER_PROCESSING',
|
PATIENT_ORDER_PROCESSING = 'PATIENT_ORDER_PROCESSING',
|
||||||
PATIENT_FIRST_RESULTS_RECEIVED = 'PATIENT_FIRST_RESULTS_RECEIVED',
|
PATIENT_FIRST_RESULTS_RECEIVED = 'PATIENT_FIRST_RESULTS_RECEIVED',
|
||||||
PATIENT_FULL_RESULTS_RECEIVED = 'PATIENT_FULL_RESULTS_RECEIVED',
|
PATIENT_FULL_RESULTS_RECEIVED = 'PATIENT_FULL_RESULTS_RECEIVED',
|
||||||
|
TTO_ORDER_CONFIRMATION = 'TTO_ORDER_CONFIRMATION',
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createNotificationLog = async ({
|
export const createNotificationLog = async ({
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ const USER = process.env.MEDIPOST_USER!;
|
|||||||
const PASSWORD = process.env.MEDIPOST_PASSWORD!;
|
const PASSWORD = process.env.MEDIPOST_PASSWORD!;
|
||||||
const RECIPIENT = process.env.MEDIPOST_RECIPIENT!;
|
const RECIPIENT = process.env.MEDIPOST_RECIPIENT!;
|
||||||
|
|
||||||
const IS_ENABLED_DELETE_PRIVATE_MESSAGE = false as boolean;
|
const IS_ENABLED_DELETE_PRIVATE_MESSAGE =
|
||||||
|
process.env.MEDIPOST_ENABLE_DELETE_RESPONSE_PRIVATE_MESSAGE_ON_READ ===
|
||||||
|
'true';
|
||||||
|
|
||||||
export async function getLatestPrivateMessageListItem({
|
export async function getLatestPrivateMessageListItem({
|
||||||
excludedMessageIds,
|
excludedMessageIds,
|
||||||
@@ -430,19 +432,24 @@ export async function readPrivateMessageResponse({
|
|||||||
medipostExternalOrderId,
|
medipostExternalOrderId,
|
||||||
});
|
});
|
||||||
if (status.isPartial) {
|
if (status.isPartial) {
|
||||||
await createUserAnalysesApi(getSupabaseServerAdminClient())
|
await createUserAnalysesApi(
|
||||||
.updateAnalysisOrderStatus({
|
getSupabaseServerAdminClient(),
|
||||||
medusaOrderId,
|
).updateAnalysisOrderStatus({
|
||||||
orderStatus: 'PARTIAL_ANALYSIS_RESPONSE',
|
medusaOrderId,
|
||||||
});
|
orderStatus: 'PARTIAL_ANALYSIS_RESPONSE',
|
||||||
|
});
|
||||||
|
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
||||||
|
await deletePrivateMessage(privateMessageId);
|
||||||
|
}
|
||||||
hasAnalysisResponse = true;
|
hasAnalysisResponse = true;
|
||||||
hasPartialAnalysisResponse = true;
|
hasPartialAnalysisResponse = true;
|
||||||
} else if (status.isCompleted) {
|
} else if (status.isCompleted) {
|
||||||
await createUserAnalysesApi(getSupabaseServerAdminClient())
|
await createUserAnalysesApi(
|
||||||
.updateAnalysisOrderStatus({
|
getSupabaseServerAdminClient(),
|
||||||
medusaOrderId,
|
).updateAnalysisOrderStatus({
|
||||||
orderStatus: 'FULL_ANALYSIS_RESPONSE',
|
medusaOrderId,
|
||||||
});
|
orderStatus: 'FULL_ANALYSIS_RESPONSE',
|
||||||
|
});
|
||||||
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
if (IS_ENABLED_DELETE_PRIVATE_MESSAGE) {
|
||||||
await deletePrivateMessage(privateMessageId);
|
await deletePrivateMessage(privateMessageId);
|
||||||
}
|
}
|
||||||
@@ -624,9 +631,10 @@ export async function sendOrderToMedipost({
|
|||||||
hasAnalysisResults: false,
|
hasAnalysisResults: false,
|
||||||
medusaOrderId,
|
medusaOrderId,
|
||||||
});
|
});
|
||||||
await createUserAnalysesApi(getSupabaseServerAdminClient())
|
await createUserAnalysesApi(
|
||||||
.updateAnalysisOrderStatus({
|
getSupabaseServerAdminClient(),
|
||||||
medusaOrderId,
|
).updateAnalysisOrderStatus({
|
||||||
orderStatus: 'PROCESSING',
|
medusaOrderId,
|
||||||
});
|
orderStatus: 'PROCESSING',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,8 +31,10 @@ const env = () =>
|
|||||||
.min(1),
|
.min(1),
|
||||||
})
|
})
|
||||||
.parse({
|
.parse({
|
||||||
medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!,
|
medusaBackendPublicUrl: (process.env.DEV_MONTONIO_CALLBACK_URL ||
|
||||||
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
|
process.env.MEDUSA_BACKEND_PUBLIC_URL)!,
|
||||||
|
siteUrl: (process.env.DEV_MONTONIO_CALLBACK_URL ||
|
||||||
|
process.env.NEXT_PUBLIC_SITE_URL)!,
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function handleAddToCart({
|
export async function handleAddToCart({
|
||||||
@@ -42,6 +44,10 @@ export async function handleAddToCart({
|
|||||||
selectedVariant: Pick<StoreProductVariant, 'id'>;
|
selectedVariant: Pick<StoreProductVariant, 'id'>;
|
||||||
countryCode: string;
|
countryCode: string;
|
||||||
}) {
|
}) {
|
||||||
|
try {
|
||||||
|
} catch (e) {
|
||||||
|
console.error('medusa card error: ', e);
|
||||||
|
}
|
||||||
const { account } = await loadCurrentUserAccount();
|
const { account } = await loadCurrentUserAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error('Account not found');
|
throw new Error('Account not found');
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ import { type ClassValue, clsx } from 'clsx';
|
|||||||
import Isikukood, { Gender } from 'isikukood';
|
import Isikukood, { Gender } from 'isikukood';
|
||||||
import { twMerge } from 'tailwind-merge';
|
import { twMerge } from 'tailwind-merge';
|
||||||
|
|
||||||
import { BmiCategory } from './types/bmi';
|
|
||||||
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
import type { BmiThresholds } from '@kit/accounts/types/accounts';
|
||||||
|
|
||||||
|
import { BmiCategory } from './types/bmi';
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs));
|
return twMerge(clsx(inputs));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,12 @@ class DatabaseWebhookRouterService {
|
|||||||
return this.handleAnalysisOrdersWebhook(payload);
|
return this.handleAnalysisOrdersWebhook(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'connected_online_reservation': {
|
||||||
|
const payload = body as RecordChange<typeof body.table>;
|
||||||
|
|
||||||
|
return this.handleTtoOrdersWebhook(payload);
|
||||||
|
}
|
||||||
|
|
||||||
default: {
|
default: {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -100,13 +106,27 @@ class DatabaseWebhookRouterService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { createAnalysisOrderWebhooksService } = await import(
|
const { createOrderWebhooksService } = await import(
|
||||||
'@kit/notifications/webhooks/analysis-order-notifications.service'
|
'@kit/notifications/webhooks/order-notifications.service'
|
||||||
);
|
);
|
||||||
|
|
||||||
const service = createAnalysisOrderWebhooksService();
|
const service = createOrderWebhooksService();
|
||||||
|
|
||||||
return service.handleStatusChangeWebhook(record);
|
return service.handleStatusChangeWebhook(record);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async handleTtoOrdersWebhook(
|
||||||
|
body: RecordChange<'connected_online_reservation'>,
|
||||||
|
) {
|
||||||
|
if (body.type === 'UPDATE' && body.record) {
|
||||||
|
const { createOrderWebhooksService } = await import(
|
||||||
|
'@kit/notifications/webhooks/order-notifications.service'
|
||||||
|
);
|
||||||
|
|
||||||
|
const service = createOrderWebhooksService();
|
||||||
|
|
||||||
|
return service.handleTtoReservationConfirmationWebhook(body.record);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,17 +4,20 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "git clean -xdf .turbo node_modules",
|
"clean": "git clean -xdf .turbo node_modules",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit",
|
||||||
|
"email:dev": "email dev --dir src/emails --port 3001"
|
||||||
},
|
},
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts"
|
".": "./src/index.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@react-email/components": "0.0.41"
|
"@react-email/components": "0.0.41",
|
||||||
|
"react-email": "4.2.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@kit/i18n": "workspace:*",
|
"@kit/i18n": "workspace:*",
|
||||||
"@kit/tsconfig": "workspace:*"
|
"@kit/tsconfig": "workspace:*",
|
||||||
|
"@react-email/preview-server": "4.2.12"
|
||||||
},
|
},
|
||||||
"typesVersions": {
|
"typesVersions": {
|
||||||
"*": {
|
"*": {
|
||||||
|
|||||||
@@ -6,22 +6,28 @@ import { EmailFooter } from './footer';
|
|||||||
export default function CommonFooter({ t }: { t: TFunction }) {
|
export default function CommonFooter({ t }: { t: TFunction }) {
|
||||||
const namespace = 'common';
|
const namespace = 'common';
|
||||||
|
|
||||||
const lines = [
|
|
||||||
t(`${namespace}:footer.lines1`),
|
|
||||||
t(`${namespace}:footer.lines2`),
|
|
||||||
t(`${namespace}:footer.lines3`),
|
|
||||||
t(`${namespace}:footer.lines4`),
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<EmailFooter>
|
<EmailFooter>
|
||||||
{lines.map((line, index) => (
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
<Text
|
{t(`${namespace}:footer.title`)}
|
||||||
key={index}
|
</Text>
|
||||||
className="text-[16px] leading-[24px] text-[#242424]"
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
dangerouslySetInnerHTML={{ __html: line }}
|
{t(`${namespace}:footer.emailField`)}{' '}
|
||||||
/>
|
<a href={`mailto:${t(`${namespace}:footer.title`)}`}>
|
||||||
))}
|
{t(`${namespace}:footer.email`)}
|
||||||
|
</a>
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:footer.phoneField`)}{' '}
|
||||||
|
<a href={`tel:${t(`${namespace}:footer.phone`)}`}>
|
||||||
|
{t(`${namespace}:footer.phone`)}
|
||||||
|
</a>
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
<a href={`https://${t(`${namespace}:footer.website`)}`}>
|
||||||
|
{t(`${namespace}:footer.website`)}
|
||||||
|
</a>
|
||||||
|
</Text>
|
||||||
</EmailFooter>
|
</EmailFooter>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { Container, Text } from '@react-email/components';
|
import { Container, Section } from '@react-email/components';
|
||||||
|
|
||||||
export function EmailFooter(props: React.PropsWithChildren) {
|
export function EmailFooter(props: React.PropsWithChildren) {
|
||||||
return (
|
return (
|
||||||
<Container className="mt-[24px]">
|
<Container className="mt-[24px]">
|
||||||
<Text className="px-4 text-[12px] leading-[20px] text-gray-300">
|
<Section className="px-4 text-[12px] leading-[20px] text-gray-300">
|
||||||
{props.children}
|
{props.children}
|
||||||
</Text>
|
</Section>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
8
packages/email-templates/src/emails/email.tsx
Normal file
8
packages/email-templates/src/emails/email.tsx
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
const Email = () => {
|
||||||
|
return <div>Email</div>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Email;
|
||||||
|
Email.PreviewProps = {};
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Head,
|
||||||
|
Html,
|
||||||
|
Link,
|
||||||
|
Preview,
|
||||||
|
Tailwind,
|
||||||
|
Text,
|
||||||
|
render,
|
||||||
|
} from '@react-email/components';
|
||||||
|
|
||||||
|
import { BodyStyle } from '../components/body-style';
|
||||||
|
import CommonFooter from '../components/common-footer';
|
||||||
|
import { EmailContent } from '../components/content';
|
||||||
|
import { EmailHeader } from '../components/header';
|
||||||
|
import { EmailHeading } from '../components/heading';
|
||||||
|
import { EmailWrapper } from '../components/wrapper';
|
||||||
|
import { initializeEmailI18n } from '../lib/i18n';
|
||||||
|
|
||||||
|
export async function renderTtoReservationConfirmationEmail({
|
||||||
|
language,
|
||||||
|
recipientName,
|
||||||
|
startTime,
|
||||||
|
orderName,
|
||||||
|
locationName,
|
||||||
|
locationAddress,
|
||||||
|
orderId,
|
||||||
|
serviceProviderName,
|
||||||
|
serviceProviderEmail,
|
||||||
|
serviceProviderPhone,
|
||||||
|
}: {
|
||||||
|
language: string;
|
||||||
|
recipientName: string;
|
||||||
|
startTime: string;
|
||||||
|
orderName: string;
|
||||||
|
locationName?: string;
|
||||||
|
locationAddress?: string | null;
|
||||||
|
orderId: string;
|
||||||
|
serviceProviderName?: string;
|
||||||
|
serviceProviderEmail?: string | null;
|
||||||
|
serviceProviderPhone?: string | null;
|
||||||
|
}) {
|
||||||
|
const namespace = 'tto-reservation-confirmation-email';
|
||||||
|
|
||||||
|
const { t } = await initializeEmailI18n({
|
||||||
|
language,
|
||||||
|
namespace: [namespace, 'common'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const previewText = t(`${namespace}:previewText`, {
|
||||||
|
reservation: orderName,
|
||||||
|
});
|
||||||
|
|
||||||
|
const subject = t(`${namespace}:subject`, {
|
||||||
|
reservation: orderName,
|
||||||
|
});
|
||||||
|
|
||||||
|
const email = (
|
||||||
|
<Html>
|
||||||
|
<Head>
|
||||||
|
<BodyStyle />
|
||||||
|
</Head>
|
||||||
|
|
||||||
|
<Preview>{previewText}</Preview>
|
||||||
|
|
||||||
|
<Tailwind>
|
||||||
|
<Body>
|
||||||
|
<EmailWrapper>
|
||||||
|
<EmailContent>
|
||||||
|
<EmailHeader>
|
||||||
|
<EmailHeading>{previewText}</EmailHeading>
|
||||||
|
</EmailHeader>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:helloName`, { name: recipientName })}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:thankYou`)}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{orderName}, {new Date(startTime).toLocaleString()},{' '}
|
||||||
|
{locationAddress}, {locationName}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
<Link
|
||||||
|
href={`${process.env.NEXT_PUBLIC_SITE_URL}/home/order/${orderId}`}
|
||||||
|
>
|
||||||
|
{t(`${namespace}:viewOrder`)}
|
||||||
|
</Link>
|
||||||
|
</Text>
|
||||||
|
<Text className="mt-10 text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{serviceProviderName}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-[16px] leading-[24px] text-[#242424]">
|
||||||
|
{t(`${namespace}:customerSupport`)}
|
||||||
|
<Link href={`tel:${serviceProviderPhone})}`}>
|
||||||
|
{serviceProviderPhone}
|
||||||
|
</Link>
|
||||||
|
</Text>
|
||||||
|
<Link href={`mailto:${serviceProviderEmail}`}>
|
||||||
|
{serviceProviderEmail}
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<CommonFooter t={t} />
|
||||||
|
</EmailContent>
|
||||||
|
</EmailWrapper>
|
||||||
|
</Body>
|
||||||
|
</Tailwind>
|
||||||
|
</Html>
|
||||||
|
);
|
||||||
|
|
||||||
|
const html = await render(email);
|
||||||
|
|
||||||
|
return {
|
||||||
|
html,
|
||||||
|
subject,
|
||||||
|
email,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const PreviewEmail = async () => {
|
||||||
|
const { email } = await renderTtoReservationConfirmationEmail({
|
||||||
|
language: 'et',
|
||||||
|
recipientName: 'John Doe',
|
||||||
|
startTime: '2025-09-27 05:45:00+00',
|
||||||
|
orderName: 'Hambaarst',
|
||||||
|
locationName: 'Tallinn',
|
||||||
|
locationAddress: 'Põhja puiestee, 2/3A',
|
||||||
|
orderId: '123123',
|
||||||
|
serviceProviderName: 'Dentas OÜ',
|
||||||
|
serviceProviderEmail: 'email@example.ee',
|
||||||
|
serviceProviderPhone: '+372111111',
|
||||||
|
});
|
||||||
|
return email;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PreviewEmail;
|
||||||
|
PreviewEmail.PreviewProps = {};
|
||||||
@@ -11,3 +11,4 @@ export * from './emails/order-processing.email';
|
|||||||
export * from './emails/patient-first-results-received.email';
|
export * from './emails/patient-first-results-received.email';
|
||||||
export * from './emails/patient-full-results-received.email';
|
export * from './emails/patient-full-results-received.email';
|
||||||
export * from './emails/book-time-failed.email';
|
export * from './emails/book-time-failed.email';
|
||||||
|
export * from './emails/tto-reservation-confirmation.email';
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"previewText": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"subject": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"helloName": "Hello, {{name}}!",
|
||||||
|
"thankYou": "Thank you for your order!",
|
||||||
|
"viewOrder": "See booking",
|
||||||
|
"customerSupport": "Customer support: "
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
{
|
{
|
||||||
"footer": {
|
"footer": {
|
||||||
"lines1": "MedReport",
|
"title": "MedReport",
|
||||||
"lines2": "E-mail: <a href=\"mailto:info@medreport.ee\">info@medreport.ee</a>",
|
"emailField": "E-mail:",
|
||||||
"lines3": "Klienditugi: <a href=\"tel:+37258871517\">+372 5887 1517</a>",
|
"email": "info@medreport.ee",
|
||||||
"lines4": "<a href=\"https://www.medreport.ee\">www.medreport.ee</a>"
|
"phoneField": "Klienditugi:",
|
||||||
|
"phone": "+372 5887 1517",
|
||||||
|
"website": "www.medreport.ee"
|
||||||
},
|
},
|
||||||
"helloName": "Tere, {{name}}",
|
"helloName": "Tere, {{name}}",
|
||||||
"hello": "Tere"
|
"hello": "Tere"
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"previewText": "Teie broneering on kinnitatud! - {{reservation}}",
|
||||||
|
"subject": "Teie broneering on kinnitatud! - {{reservation}}",
|
||||||
|
"helloName": "Tere, {{name}}!",
|
||||||
|
"thankYou": "Täname tellimuse eest!",
|
||||||
|
"viewOrder": "Vaata broneeringut",
|
||||||
|
"customerSupport": "Klienditugi: "
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"previewText": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"subject": "Your booking is confirmed! - {{reservation}}",
|
||||||
|
"helloName": "Hello, {{name}}!",
|
||||||
|
"thankYou": "Thank you for your order!",
|
||||||
|
"viewOrder": "See booking",
|
||||||
|
"customerSupport": "Customer support: "
|
||||||
|
}
|
||||||
@@ -43,12 +43,17 @@ export class AccountBalanceService {
|
|||||||
offset?: number;
|
offset?: number;
|
||||||
entryType?: string;
|
entryType?: string;
|
||||||
includeInactive?: boolean;
|
includeInactive?: boolean;
|
||||||
} = {}
|
} = {},
|
||||||
): Promise<{
|
): Promise<{
|
||||||
entries: AccountBalanceEntry[];
|
entries: AccountBalanceEntry[];
|
||||||
total: number;
|
total: number;
|
||||||
}> {
|
}> {
|
||||||
const { limit = 50, offset = 0, entryType, includeInactive = false } = options;
|
const {
|
||||||
|
limit = 50,
|
||||||
|
offset = 0,
|
||||||
|
entryType,
|
||||||
|
includeInactive = false,
|
||||||
|
} = options;
|
||||||
|
|
||||||
let query = this.supabase
|
let query = this.supabase
|
||||||
.schema('medreport')
|
.schema('medreport')
|
||||||
@@ -105,7 +110,8 @@ export class AccountBalanceService {
|
|||||||
console.error('Error getting expiring balance:', expiringError);
|
console.error('Error getting expiring balance:', expiringError);
|
||||||
}
|
}
|
||||||
|
|
||||||
const expiringSoon = expiringData?.reduce((sum, entry) => sum + (entry.amount || 0), 0) || 0;
|
const expiringSoon =
|
||||||
|
expiringData?.reduce((sum, entry) => sum + (entry.amount || 0), 0) || 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
totalBalance: balance,
|
totalBalance: balance,
|
||||||
@@ -116,12 +122,13 @@ export class AccountBalanceService {
|
|||||||
|
|
||||||
async processPeriodicBenefitDistributions(): Promise<void> {
|
async processPeriodicBenefitDistributions(): Promise<void> {
|
||||||
console.info('Processing periodic benefit distributions...');
|
console.info('Processing periodic benefit distributions...');
|
||||||
const { error } = await this.supabase.schema('medreport').rpc('process_periodic_benefit_distributions');
|
const { error } = await this.supabase
|
||||||
|
.schema('medreport')
|
||||||
|
.rpc('process_periodic_benefit_distributions');
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error('Error processing periodic benefit distributions:', error);
|
console.error('Error processing periodic benefit distributions:', error);
|
||||||
throw new Error('Failed to process periodic benefit distributions');
|
throw new Error('Failed to process periodic benefit distributions');
|
||||||
}
|
}
|
||||||
console.info('Periodic benefit distributions processed successfully');
|
console.info('Periodic benefit distributions processed successfully');
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
import type { Database } from '@kit/supabase/database';
|
import type { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
export type AccountBalanceEntry = Database['medreport']['Tables']['account_balance_entries']['Row'];
|
export type AccountBalanceEntry =
|
||||||
|
Database['medreport']['Tables']['account_balance_entries']['Row'];
|
||||||
|
|||||||
@@ -22,4 +22,5 @@ export type AccountWithParams = Account & {
|
|||||||
export type CompanyParams =
|
export type CompanyParams =
|
||||||
Database['medreport']['Tables']['company_params']['Row'];
|
Database['medreport']['Tables']['company_params']['Row'];
|
||||||
|
|
||||||
export type BmiThresholds = Database['medreport']['Tables']['bmi_thresholds']['Row'];
|
export type BmiThresholds =
|
||||||
|
Database['medreport']['Tables']['bmi_thresholds']['Row'];
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import 'server-only';
|
|||||||
|
|
||||||
import { SupabaseClient } from '@supabase/supabase-js';
|
import { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
import { Database } from '@kit/supabase/database';
|
|
||||||
import type { ApplicationRole } from '@kit/accounts/types/accounts';
|
import type { ApplicationRole } from '@kit/accounts/types/accounts';
|
||||||
|
import { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
export function createAdminAccountsService(client: SupabaseClient<Database>) {
|
export function createAdminAccountsService(client: SupabaseClient<Database>) {
|
||||||
return new AdminAccountsService(client);
|
return new AdminAccountsService(client);
|
||||||
@@ -24,10 +24,7 @@ class AdminAccountsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateRole(
|
async updateRole(accountId: string, role: ApplicationRole) {
|
||||||
accountId: string,
|
|
||||||
role: ApplicationRole,
|
|
||||||
) {
|
|
||||||
const { error } = await this.adminClient
|
const { error } = await this.adminClient
|
||||||
.schema('medreport')
|
.schema('medreport')
|
||||||
.from('accounts')
|
.from('accounts')
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { redirect } from 'next/navigation';
|
|||||||
|
|
||||||
import { sdk } from '@lib/config';
|
import { sdk } from '@lib/config';
|
||||||
import medusaError from '@lib/util/medusa-error';
|
import medusaError from '@lib/util/medusa-error';
|
||||||
import { HttpTypes } from '@medusajs/types';
|
import { HttpTypes, StoreCart } from '@medusajs/types';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getAuthHeaders,
|
getAuthHeaders,
|
||||||
@@ -259,18 +259,19 @@ export async function setShippingMethod({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function initiateMultiPaymentSession(
|
export async function initiateMultiPaymentSession(
|
||||||
cart: HttpTypes.StoreCart,
|
cart: StoreCart,
|
||||||
benefitsAmount: number,
|
benefitsAmount: number,
|
||||||
) {
|
) {
|
||||||
const headers = {
|
const headers = {
|
||||||
...(await getAuthHeaders()),
|
...(await getAuthHeaders()),
|
||||||
};
|
};
|
||||||
|
|
||||||
return sdk.client.fetch<unknown>(`/store/multi-payment`, {
|
return sdk.client
|
||||||
method: 'POST',
|
.fetch<unknown>(`/store/multi-payment`, {
|
||||||
body: { cartId: cart.id, benefitsAmount },
|
method: 'POST',
|
||||||
headers,
|
body: { cartId: cart.id, benefitsAmount },
|
||||||
})
|
headers,
|
||||||
|
})
|
||||||
.then(async (response) => {
|
.then(async (response) => {
|
||||||
console.info('Payment session initiated:', response);
|
console.info('Payment session initiated:', response);
|
||||||
const cartCacheTag = await getCacheTag('carts');
|
const cartCacheTag = await getCacheTag('carts');
|
||||||
@@ -284,7 +285,11 @@ export async function initiateMultiPaymentSession(
|
|||||||
};
|
};
|
||||||
})
|
})
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
console.error('Error initiating payment session:', e, JSON.stringify(Object.keys(e)));
|
console.error(
|
||||||
|
'Error initiating payment session:',
|
||||||
|
e,
|
||||||
|
JSON.stringify(Object.keys(e)),
|
||||||
|
);
|
||||||
return medusaError(e);
|
return medusaError(e);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export const listCollections = async (
|
|||||||
|
|
||||||
queryParams.limit = queryParams.limit || '100';
|
queryParams.limit = queryParams.limit || '100';
|
||||||
queryParams.offset = queryParams.offset || '0';
|
queryParams.offset = queryParams.offset || '0';
|
||||||
console.log('SDK_CONFIG: ', SDK_CONFIG.baseUrl);
|
|
||||||
return sdk.client
|
return sdk.client
|
||||||
.fetch<{ collections: HttpTypes.StoreCollection[]; count: number }>(
|
.fetch<{ collections: HttpTypes.StoreCollection[]; count: number }>(
|
||||||
'/store/collections',
|
'/store/collections',
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
|
import { sdk } from '@lib/config';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
renderAllResultsReceivedEmail,
|
renderAllResultsReceivedEmail,
|
||||||
renderFirstResultsReceivedEmail,
|
renderFirstResultsReceivedEmail,
|
||||||
renderOrderProcessingEmail,
|
renderOrderProcessingEmail,
|
||||||
renderPatientFirstResultsReceivedEmail,
|
renderPatientFirstResultsReceivedEmail,
|
||||||
renderPatientFullResultsReceivedEmail,
|
renderPatientFullResultsReceivedEmail,
|
||||||
|
renderTtoReservationConfirmationEmail,
|
||||||
} from '@kit/email-templates';
|
} from '@kit/email-templates';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
import { getFullName } from '@kit/shared/utils';
|
import { getFullName } from '@kit/shared/utils';
|
||||||
@@ -25,13 +28,15 @@ import {
|
|||||||
} from '~/lib/services/mailer.service';
|
} from '~/lib/services/mailer.service';
|
||||||
|
|
||||||
type AnalysisOrder = Database['medreport']['Tables']['analysis_orders']['Row'];
|
type AnalysisOrder = Database['medreport']['Tables']['analysis_orders']['Row'];
|
||||||
|
type TtoReservation =
|
||||||
|
Database['medreport']['Tables']['connected_online_reservation']['Row'];
|
||||||
|
|
||||||
export function createAnalysisOrderWebhooksService() {
|
export function createOrderWebhooksService() {
|
||||||
return new AnalysisOrderWebhooksService();
|
return new OrderWebhooksService();
|
||||||
}
|
}
|
||||||
|
|
||||||
class AnalysisOrderWebhooksService {
|
class OrderWebhooksService {
|
||||||
private readonly namespace = 'analysis_orders.webhooks';
|
private readonly namespace = 'orders.webhooks';
|
||||||
|
|
||||||
async handleStatusChangeWebhook(analysisOrder: AnalysisOrder) {
|
async handleStatusChangeWebhook(analysisOrder: AnalysisOrder) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
@@ -90,6 +95,128 @@ class AnalysisOrderWebhooksService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async handleTtoReservationConfirmationWebhook(
|
||||||
|
ttoReservation: TtoReservation,
|
||||||
|
) {
|
||||||
|
const logger = await getLogger();
|
||||||
|
const ctx = {
|
||||||
|
ttoReservationId: ttoReservation.id,
|
||||||
|
namespace: this.namespace,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userContact = await getUserContactAdmin(ttoReservation.user_id);
|
||||||
|
if (!userContact.email) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No email found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: ttoReservation.id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No email found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const supabaseClient = getSupabaseServerAdminClient();
|
||||||
|
if (!ttoReservation.medusa_cart_line_item_id) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No cart item id found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: ttoReservation.id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No cart item id found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const [
|
||||||
|
{ data: cartItem },
|
||||||
|
{ data: location },
|
||||||
|
{ data: serviceProvider },
|
||||||
|
] = await Promise.all([
|
||||||
|
supabaseClient
|
||||||
|
.from('cart_line_item')
|
||||||
|
.select('cart_id,title')
|
||||||
|
.eq('id', ttoReservation.medusa_cart_line_item_id)
|
||||||
|
.single(),
|
||||||
|
supabaseClient
|
||||||
|
.schema('medreport')
|
||||||
|
.from('connected_online_locations')
|
||||||
|
.select('name,address')
|
||||||
|
.eq('sync_id', ttoReservation.location_sync_id || 0)
|
||||||
|
.single(),
|
||||||
|
supabaseClient
|
||||||
|
.schema('medreport')
|
||||||
|
.from('connected_online_providers')
|
||||||
|
.select('email,phone_number,name')
|
||||||
|
.eq('id', ttoReservation.clinic_id)
|
||||||
|
.single(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!cartItem) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No medusa cart item found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: ttoReservation.medusa_cart_line_item_id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No cart item found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [{ data: orderCart }] = await Promise.all([
|
||||||
|
supabaseClient
|
||||||
|
.from('order_cart')
|
||||||
|
.select('order_id')
|
||||||
|
.eq('cart_id', cartItem.cart_id)
|
||||||
|
.single(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!orderCart) {
|
||||||
|
await createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: 'No medusa order cart found for ' + ttoReservation.user_id,
|
||||||
|
relatedRecordId: cartItem.cart_id,
|
||||||
|
});
|
||||||
|
logger.warn(ctx, 'No order cart found ');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await sendEmailFromTemplate(
|
||||||
|
renderTtoReservationConfirmationEmail,
|
||||||
|
{
|
||||||
|
language: userContact.preferred_locale ?? 'et',
|
||||||
|
recipientName: getFullName(userContact.name, userContact.last_name),
|
||||||
|
startTime: ttoReservation.start_time,
|
||||||
|
orderName: cartItem.title,
|
||||||
|
locationName: location?.name,
|
||||||
|
locationAddress: location?.address,
|
||||||
|
orderId: orderCart.order_id,
|
||||||
|
serviceProviderName: serviceProvider?.name,
|
||||||
|
serviceProviderEmail: serviceProvider?.email,
|
||||||
|
serviceProviderPhone: serviceProvider?.phone_number,
|
||||||
|
},
|
||||||
|
userContact.email,
|
||||||
|
);
|
||||||
|
|
||||||
|
return createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'SUCCESS',
|
||||||
|
relatedRecordId: orderCart.order_id,
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
createNotificationLog({
|
||||||
|
action: NotificationAction.TTO_ORDER_CONFIRMATION,
|
||||||
|
status: 'FAIL',
|
||||||
|
comment: e?.message,
|
||||||
|
relatedRecordId: ttoReservation.id,
|
||||||
|
});
|
||||||
|
logger.error(
|
||||||
|
ctx,
|
||||||
|
`Error while processing tto reservation: ${JSON.stringify(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async sendProcessingNotification(analysisOrder: AnalysisOrder) {
|
async sendProcessingNotification(analysisOrder: AnalysisOrder) {
|
||||||
const logger = await getLogger();
|
const logger = await getLogger();
|
||||||
const supabase = getSupabaseServerAdminClient();
|
const supabase = getSupabaseServerAdminClient();
|
||||||
@@ -6,6 +6,7 @@ import { ColumnDef } from '@tanstack/react-table';
|
|||||||
import { Ellipsis } from 'lucide-react';
|
import { Ellipsis } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { formatCurrency } from '@kit/shared/utils';
|
||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
import { Badge } from '@kit/ui/badge';
|
import { Badge } from '@kit/ui/badge';
|
||||||
import { Button } from '@kit/ui/button';
|
import { Button } from '@kit/ui/button';
|
||||||
@@ -20,7 +21,6 @@ import { If } from '@kit/ui/if';
|
|||||||
import { Input } from '@kit/ui/input';
|
import { Input } from '@kit/ui/input';
|
||||||
import { ProfileAvatar } from '@kit/ui/profile-avatar';
|
import { ProfileAvatar } from '@kit/ui/profile-avatar';
|
||||||
import { Trans } from '@kit/ui/trans';
|
import { Trans } from '@kit/ui/trans';
|
||||||
import { formatCurrency } from '@kit/shared/utils';
|
|
||||||
|
|
||||||
import { RemoveMemberDialog } from './remove-member-dialog';
|
import { RemoveMemberDialog } from './remove-member-dialog';
|
||||||
import { RoleBadge } from './role-badge';
|
import { RoleBadge } from './role-badge';
|
||||||
@@ -46,6 +46,7 @@ type AccountMembersTableProps = {
|
|||||||
membersBenefitsUsage: {
|
membersBenefitsUsage: {
|
||||||
personal_account_id: string;
|
personal_account_id: string;
|
||||||
benefit_amount: number;
|
benefit_amount: number;
|
||||||
|
benefit_unused_amount: number;
|
||||||
}[];
|
}[];
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,33 +83,23 @@ export function AccountMembersTable({
|
|||||||
membersBenefitsUsage,
|
membersBenefitsUsage,
|
||||||
});
|
});
|
||||||
|
|
||||||
const filteredMembers = members
|
const searchString = search.toLowerCase();
|
||||||
.filter((member) => {
|
const filteredMembers = searchString.length > 0
|
||||||
const searchString = search.toLowerCase();
|
? members
|
||||||
|
.filter((member) => {
|
||||||
|
const displayName = (
|
||||||
|
member.name ??
|
||||||
|
member.email.split('@')[0] ??
|
||||||
|
''
|
||||||
|
).toLowerCase();
|
||||||
|
|
||||||
const displayName = (
|
return (
|
||||||
member.name ??
|
displayName.includes(searchString) ||
|
||||||
member.email.split('@')[0] ??
|
member.role.toLowerCase().includes(searchString) ||
|
||||||
''
|
(member.personal_code || '').includes(searchString)
|
||||||
).toLowerCase();
|
);
|
||||||
|
})
|
||||||
return (
|
: members;
|
||||||
displayName.includes(searchString) ||
|
|
||||||
member.role.toLowerCase().includes(searchString) ||
|
|
||||||
(member.personal_code || '').includes(searchString)
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.sort((prev, next) => {
|
|
||||||
if (prev.primary_owner_user_id === prev.user_id) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (prev.role_hierarchy_level < next.role_hierarchy_level) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={'flex flex-col space-y-2'}>
|
<div className={'flex flex-col space-y-2'}>
|
||||||
@@ -132,10 +123,14 @@ function useGetColumns(
|
|||||||
membersBenefitsUsage: {
|
membersBenefitsUsage: {
|
||||||
personal_account_id: string;
|
personal_account_id: string;
|
||||||
benefit_amount: number;
|
benefit_amount: number;
|
||||||
|
benefit_unused_amount: number;
|
||||||
}[];
|
}[];
|
||||||
},
|
},
|
||||||
): ColumnDef<Members[0]>[] {
|
): ColumnDef<Members[0]>[] {
|
||||||
const { t, i18n: { language } } = useTranslation('teams');
|
const {
|
||||||
|
t,
|
||||||
|
i18n: { language },
|
||||||
|
} = useTranslation('teams');
|
||||||
|
|
||||||
return useMemo(
|
return useMemo(
|
||||||
() => [
|
() => [
|
||||||
@@ -182,11 +177,11 @@ function useGetColumns(
|
|||||||
{
|
{
|
||||||
header: t('distributedBenefitsAmount'),
|
header: t('distributedBenefitsAmount'),
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const benefitAmount = params.membersBenefitsUsage.find(
|
let benefitAmount = params.membersBenefitsUsage.find(
|
||||||
(usage) => usage.personal_account_id === row.original.id
|
(usage) => usage.personal_account_id === row.original.id,
|
||||||
)?.benefit_amount;
|
)?.benefit_amount;
|
||||||
if (typeof benefitAmount !== 'number') {
|
if (typeof benefitAmount !== 'number') {
|
||||||
return '-';
|
benefitAmount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return formatCurrency({
|
return formatCurrency({
|
||||||
@@ -196,6 +191,23 @@ function useGetColumns(
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
header: t('distributedBenefitsUnusedAmount'),
|
||||||
|
cell: ({ row }) => {
|
||||||
|
let benefitUnusedAmount = params.membersBenefitsUsage.find(
|
||||||
|
(usage) => usage.personal_account_id === row.original.id,
|
||||||
|
)?.benefit_unused_amount;
|
||||||
|
if (typeof benefitUnusedAmount !== 'number') {
|
||||||
|
benefitUnusedAmount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return formatCurrency({
|
||||||
|
currencyCode: 'EUR',
|
||||||
|
locale: language,
|
||||||
|
value: benefitUnusedAmount,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
header: t('roleLabel'),
|
header: t('roleLabel'),
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
@@ -203,7 +215,11 @@ function useGetColumns(
|
|||||||
const isPrimaryOwner = primary_owner_user_id === user_id;
|
const isPrimaryOwner = primary_owner_user_id === user_id;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className={'flex items-center space-x-1 flex-wrap space-y-1 sm:space-y-0 sm:flex-nowrap'}>
|
<span
|
||||||
|
className={
|
||||||
|
'flex flex-wrap items-center space-y-1 space-x-1 sm:flex-nowrap sm:space-y-0'
|
||||||
|
}
|
||||||
|
>
|
||||||
<RoleBadge role={role} />
|
<RoleBadge role={role} />
|
||||||
|
|
||||||
<If condition={isPrimaryOwner}>
|
<If condition={isPrimaryOwner}>
|
||||||
@@ -239,7 +255,7 @@ function useGetColumns(
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[t, params, permissions],
|
[t, params, permissions, language],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { redirect } from 'next/navigation';
|
|||||||
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
||||||
import { enhanceAction } from '@kit/next/actions';
|
import { enhanceAction } from '@kit/next/actions';
|
||||||
import { createNotificationsApi } from '@kit/notifications/api';
|
import { createNotificationsApi } from '@kit/notifications/api';
|
||||||
import { getLogger } from '@kit/shared/logger';
|
import { getLogger } from '@kit/shared/logger';
|
||||||
@@ -18,7 +19,6 @@ import { RenewInvitationSchema } from '../../schema/renew-invitation.schema';
|
|||||||
import { UpdateInvitationSchema } from '../../schema/update-invitation.schema';
|
import { UpdateInvitationSchema } from '../../schema/update-invitation.schema';
|
||||||
import { createAccountInvitationsService } from '../services/account-invitations.service';
|
import { createAccountInvitationsService } from '../services/account-invitations.service';
|
||||||
import { createAccountPerSeatBillingService } from '../services/account-per-seat-billing.service';
|
import { createAccountPerSeatBillingService } from '../services/account-per-seat-billing.service';
|
||||||
import { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @name createInvitationsAction
|
* @name createInvitationsAction
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { getLogger } from '@kit/shared/logger';
|
|
||||||
import type { Account } from '@kit/accounts/types/accounts';
|
import type { Account } from '@kit/accounts/types/accounts';
|
||||||
|
import { getLogger } from '@kit/shared/logger';
|
||||||
|
|
||||||
export function createAccountWebhooksService() {
|
export function createAccountWebhooksService() {
|
||||||
return new AccountWebhooksService();
|
return new AccountWebhooksService();
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import type { UuringuVastus } from '@kit/shared/types/medipost-analysis';
|
|||||||
import { toArray } from '@kit/shared/utils';
|
import { toArray } from '@kit/shared/utils';
|
||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
import type { AnalysisOrder, AnalysisOrderStatus } from '../types/analysis-orders';
|
import type {
|
||||||
|
AnalysisOrder,
|
||||||
|
AnalysisOrderStatus,
|
||||||
|
} from '../types/analysis-orders';
|
||||||
import type {
|
import type {
|
||||||
AnalysisResultDetailsElement,
|
AnalysisResultDetailsElement,
|
||||||
AnalysisResultDetailsMapped,
|
AnalysisResultDetailsMapped,
|
||||||
@@ -462,8 +465,10 @@ class UserAnalysesApi {
|
|||||||
}) {
|
}) {
|
||||||
const orderIdParam = orderId;
|
const orderIdParam = orderId;
|
||||||
const medusaOrderIdParam = medusaOrderId;
|
const medusaOrderIdParam = medusaOrderId;
|
||||||
|
|
||||||
console.info(`Updating order id=${orderId} medusaOrderId=${medusaOrderId} status=${orderStatus}`);
|
console.info(
|
||||||
|
`Updating order id=${orderId} medusaOrderId=${medusaOrderId} status=${orderStatus}`,
|
||||||
|
);
|
||||||
if (!orderIdParam && !medusaOrderIdParam) {
|
if (!orderIdParam && !medusaOrderIdParam) {
|
||||||
throw new Error('Either orderId or medusaOrderId must be provided');
|
throw new Error('Either orderId or medusaOrderId must be provided');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import { Euro, LayoutDashboard, Settings, Users } from 'lucide-react';
|
|||||||
|
|
||||||
import { NavigationConfigSchema } from '@kit/ui/navigation-schema';
|
import { NavigationConfigSchema } from '@kit/ui/navigation-schema';
|
||||||
|
|
||||||
import pathsConfig from './paths.config';
|
|
||||||
import featureFlagsConfig from './feature-flags.config';
|
import featureFlagsConfig from './feature-flags.config';
|
||||||
|
import pathsConfig from './paths.config';
|
||||||
|
|
||||||
const iconClasses = 'w-4';
|
const iconClasses = 'w-4';
|
||||||
|
|
||||||
@@ -23,10 +23,10 @@ const getRoutes = (account: string) => [
|
|||||||
},
|
},
|
||||||
featureFlagsConfig.enableTeamAccountBilling
|
featureFlagsConfig.enableTeamAccountBilling
|
||||||
? {
|
? {
|
||||||
label: 'common:routes.billing',
|
label: 'common:routes.billing',
|
||||||
path: createPath(pathsConfig.app.accountBilling, account),
|
path: createPath(pathsConfig.app.accountBilling, account),
|
||||||
Icon: <Euro className={iconClasses} />,
|
Icon: <Euro className={iconClasses} />,
|
||||||
}
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
{
|
{
|
||||||
label: 'common:routes.companySettings',
|
label: 'common:routes.companySettings',
|
||||||
|
|||||||
@@ -2323,6 +2323,7 @@ export type Database = {
|
|||||||
Returns: {
|
Returns: {
|
||||||
personal_account_id: string
|
personal_account_id: string
|
||||||
benefit_amount: number
|
benefit_amount: number
|
||||||
|
benefit_unused_amount: number
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
get_config: {
|
get_config: {
|
||||||
|
|||||||
@@ -3,21 +3,23 @@ import { cn } from '../lib/utils';
|
|||||||
function Skeleton({
|
function Skeleton({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
|
isLoading = true,
|
||||||
...props
|
...props
|
||||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
}: React.HTMLAttributes<HTMLDivElement> & { isLoading?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn('relative inline-block align-top', className)}
|
className={cn('relative inline-block align-top', className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<div className="invisible">
|
<div className={cn({ invisible: isLoading })}>
|
||||||
{children ?? <span className="block h-4 w-24" />}
|
{children ?? <span className="block h-4 w-24" />}
|
||||||
</div>
|
</div>
|
||||||
|
{isLoading && (
|
||||||
<div
|
<div
|
||||||
aria-hidden
|
aria-hidden
|
||||||
className="bg-primary/10 absolute inset-0 animate-pulse rounded-md"
|
className="bg-primary/10 absolute inset-0 animate-pulse rounded-md"
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
3021
pnpm-lock.yaml
generated
3021
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -63,7 +63,7 @@
|
|||||||
"promotionsTotal": "Promotions total",
|
"promotionsTotal": "Promotions total",
|
||||||
"companyBenefitsTotal": "Company benefits total",
|
"companyBenefitsTotal": "Company benefits total",
|
||||||
"subtotal": "Subtotal",
|
"subtotal": "Subtotal",
|
||||||
"benefitsTotal": "Paid with benefits",
|
"benefitsTotal": "Paid with company benefits",
|
||||||
"montonioTotal": "Paid with Montonio",
|
"montonioTotal": "Paid with Montonio",
|
||||||
"total": "Total",
|
"total": "Total",
|
||||||
"giftCard": "Gift card"
|
"giftCard": "Gift card"
|
||||||
@@ -94,5 +94,8 @@
|
|||||||
"editServiceItem": {
|
"editServiceItem": {
|
||||||
"title": "Edit booking",
|
"title": "Edit booking",
|
||||||
"description": "Edit booking details"
|
"description": "Edit booking details"
|
||||||
|
},
|
||||||
|
"companyBenefits": {
|
||||||
|
"label": "Use company benefits"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -196,5 +196,6 @@
|
|||||||
"specialCharactersError": "This name cannot contain special characters. Please choose a different one.",
|
"specialCharactersError": "This name cannot contain special characters. Please choose a different one.",
|
||||||
"personalCode": "Personal Code",
|
"personalCode": "Personal Code",
|
||||||
"teamOwnerPersonalCodeLabel": "Owner's Personal Code",
|
"teamOwnerPersonalCodeLabel": "Owner's Personal Code",
|
||||||
"distributedBenefitsAmount": "Assigned benefits"
|
"distributedBenefitsAmount": "Assigned benefits",
|
||||||
|
"distributedBenefitsUnusedAmount": "Unused benefits"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@
|
|||||||
"order": {
|
"order": {
|
||||||
"title": "Tellimus",
|
"title": "Tellimus",
|
||||||
"promotionsTotal": "Soodustuse summa",
|
"promotionsTotal": "Soodustuse summa",
|
||||||
"companyBenefitsTotal": "Toetuse summa",
|
"companyBenefitsTotal": "Tööandja katab",
|
||||||
"subtotal": "Vahesumma",
|
"subtotal": "Vahesumma",
|
||||||
"benefitsTotal": "Tasutud tervisetoetusest",
|
"benefitsTotal": "Tasutud tervisetoetusest",
|
||||||
"montonioTotal": "Tasutud Montonio'ga",
|
"montonioTotal": "Tasutud Montonio'ga",
|
||||||
@@ -94,5 +94,8 @@
|
|||||||
"editServiceItem": {
|
"editServiceItem": {
|
||||||
"title": "Muuda broneeringut",
|
"title": "Muuda broneeringut",
|
||||||
"description": "Muuda broneeringu andmeid"
|
"description": "Muuda broneeringu andmeid"
|
||||||
|
},
|
||||||
|
"companyBenefits": {
|
||||||
|
"label": "Kasuta tööandja tervisetoetust"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -196,5 +196,6 @@
|
|||||||
"specialCharactersError": "Nimi ei tohi sisaldada erimärke. Palun vali mõni teine.",
|
"specialCharactersError": "Nimi ei tohi sisaldada erimärke. Palun vali mõni teine.",
|
||||||
"personalCode": "Isikukood",
|
"personalCode": "Isikukood",
|
||||||
"teamOwnerPersonalCodeLabel": "Omaniku isikukood",
|
"teamOwnerPersonalCodeLabel": "Omaniku isikukood",
|
||||||
"distributedBenefitsAmount": "Väljastatud toetus"
|
"distributedBenefitsAmount": "Väljastatud toetus",
|
||||||
|
"distributedBenefitsUnusedAmount": "Jääk"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,5 +94,8 @@
|
|||||||
"editServiceItem": {
|
"editServiceItem": {
|
||||||
"title": "Изменить бронирование",
|
"title": "Изменить бронирование",
|
||||||
"description": "Изменить данные бронирования"
|
"description": "Изменить данные бронирования"
|
||||||
|
},
|
||||||
|
"companyBenefits": {
|
||||||
|
"label": "Использовать выгоды компании"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -196,5 +196,6 @@
|
|||||||
"specialCharactersError": "Это имя не может содержать специальные символы. Пожалуйста, выберите другое.",
|
"specialCharactersError": "Это имя не может содержать специальные символы. Пожалуйста, выберите другое.",
|
||||||
"personalCode": "Идентификационный код",
|
"personalCode": "Идентификационный код",
|
||||||
"teamOwnerPersonalCodeLabel": "Идентификационный код владельца",
|
"teamOwnerPersonalCodeLabel": "Идентификационный код владельца",
|
||||||
"distributedBenefitsAmount": "Распределенные выплаты"
|
"distributedBenefitsAmount": "Распределенные выплаты",
|
||||||
|
"distributedBenefitsUnusedAmount": "Неиспользованные выплаты"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
create trigger tto_order_confirmation_email
|
||||||
|
after update on medreport.connected_online_reservation
|
||||||
|
for each row
|
||||||
|
when (old.status is distinct from new.status and new.status = 'CONFIRMED')
|
||||||
|
execute function supabase_functions.http_request(
|
||||||
|
'http://host.docker.internal:3000/api/db/webhook',
|
||||||
|
'POST',
|
||||||
|
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
||||||
|
'{}',
|
||||||
|
'1000'
|
||||||
|
);
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
DROP FUNCTION IF EXISTS medreport.get_benefits_usages_for_company_members(uuid);
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION medreport.get_benefits_usages_for_company_members(p_account_id uuid)
|
||||||
|
returns table (
|
||||||
|
personal_account_id uuid,
|
||||||
|
benefit_amount numeric,
|
||||||
|
benefit_unused_amount numeric
|
||||||
|
)
|
||||||
|
language plpgsql
|
||||||
|
as $$
|
||||||
|
begin
|
||||||
|
return query
|
||||||
|
with benefit_recipient_accounts as (
|
||||||
|
-- Find all personal accounts that have received benefits from this company
|
||||||
|
select distinct account_id
|
||||||
|
from medreport.account_balance_entries
|
||||||
|
where source_company_id = p_account_id
|
||||||
|
and entry_type = 'benefit'
|
||||||
|
)
|
||||||
|
select
|
||||||
|
bra.account_id as personal_account_id,
|
||||||
|
coalesce(sum(case when abe.entry_type = 'benefit' and abe.source_company_id = p_account_id then abe.amount else 0 end), 0) as benefit_amount,
|
||||||
|
coalesce(sum(case when abe.entry_type = 'benefit' and abe.source_company_id = p_account_id then abe.amount when abe.entry_type = 'purchase' then abe.amount else 0 end), 0) as benefit_unused_amount
|
||||||
|
from benefit_recipient_accounts bra
|
||||||
|
left join medreport.account_balance_entries abe on abe.account_id = bra.account_id
|
||||||
|
group by bra.account_id;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
grant execute on function medreport.get_benefits_usages_for_company_members(uuid) to authenticated, service_role;
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
DROP FUNCTION IF EXISTS medreport.get_account_members(text);
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION medreport.get_account_members(account_slug text)
|
||||||
|
RETURNS TABLE(
|
||||||
|
id uuid,
|
||||||
|
user_id uuid,
|
||||||
|
account_id uuid,
|
||||||
|
role character varying,
|
||||||
|
role_hierarchy_level integer,
|
||||||
|
primary_owner_user_id uuid,
|
||||||
|
name text,
|
||||||
|
email character varying,
|
||||||
|
personal_code text,
|
||||||
|
picture_url character varying,
|
||||||
|
created_at timestamp with time zone,
|
||||||
|
updated_at timestamp with time zone
|
||||||
|
)
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
SET search_path TO ''
|
||||||
|
AS $function$begin
|
||||||
|
return QUERY
|
||||||
|
select
|
||||||
|
acc.id,
|
||||||
|
am.user_id,
|
||||||
|
am.account_id,
|
||||||
|
am.account_role,
|
||||||
|
r.hierarchy_level,
|
||||||
|
a.primary_owner_user_id,
|
||||||
|
TRIM(CONCAT(acc.name, ' ', acc.last_name)) as name,
|
||||||
|
acc.email,
|
||||||
|
acc.personal_code,
|
||||||
|
acc.picture_url,
|
||||||
|
am.created_at,
|
||||||
|
am.updated_at
|
||||||
|
from
|
||||||
|
medreport.accounts_memberships am
|
||||||
|
join medreport.accounts a on a.id = am.account_id
|
||||||
|
join medreport.accounts acc on acc.id = am.user_id
|
||||||
|
join medreport.roles r on r.name = am.account_role
|
||||||
|
where
|
||||||
|
a.slug = account_slug;
|
||||||
|
|
||||||
|
end;$function$
|
||||||
|
;
|
||||||
|
|
||||||
|
grant
|
||||||
|
execute on function medreport.get_account_members (text) to authenticated,
|
||||||
|
service_role;
|
||||||
Reference in New Issue
Block a user