446 lines
13 KiB
TypeScript
446 lines
13 KiB
TypeScript
import {
|
|
BillingLedgerPartyKind,
|
|
BillingObligationSourceType,
|
|
LinkStatus,
|
|
PartnerPaymentRecordedBy,
|
|
PartnerPaymentStatus,
|
|
Prisma,
|
|
PrismaClient,
|
|
} from '@prisma/client';
|
|
import * as bcrypt from 'bcrypt';
|
|
import { staffBillingPeriodForDate } from '../src/modules/billing/staff-billing-period';
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
const IDS = {
|
|
treatment: '10000000-0000-4000-8000-000000000001',
|
|
labCase: '10000000-0000-4000-8000-000000000002',
|
|
patientPayment: '10000000-0000-4000-8000-000000000003',
|
|
partnerPayment: '10000000-0000-4000-8000-000000000004',
|
|
staffPayment: '10000000-0000-4000-8000-000000000005',
|
|
pendingLabCase: '10000000-0000-4000-8000-000000000006',
|
|
};
|
|
|
|
function money(value: number) {
|
|
return new Prisma.Decimal(value.toFixed(2));
|
|
}
|
|
|
|
async function main() {
|
|
let link = await prisma.organizationLink.findFirst({
|
|
where: { status: LinkStatus.ACTIVE },
|
|
include: {
|
|
organizationA: { include: { type: true } },
|
|
organizationB: { include: { type: true } },
|
|
},
|
|
});
|
|
if (!link) {
|
|
const [clinicType, labType, plan] = await Promise.all([
|
|
prisma.organizationType.findUnique({ where: { name: 'CLINIC' } }),
|
|
prisma.organizationType.findUnique({ where: { name: 'LAB' } }),
|
|
prisma.plan.findUnique({ where: { name: 'base' } }),
|
|
]);
|
|
if (!clinicType || !labType) {
|
|
throw new Error('Run npm run prisma:seed before the billing demo seed.');
|
|
}
|
|
const passwordHash = await bcrypt.hash('Demo123!', 10);
|
|
async function ensureOrganization(type: { id: string }, label: 'Clinic' | 'Lab') {
|
|
const existing = await prisma.organization.findFirst({
|
|
where: { typeId: type.id },
|
|
include: { type: true },
|
|
orderBy: { createdAt: 'asc' },
|
|
});
|
|
if (existing) return existing;
|
|
const email = `billing.demo.${label.toLowerCase()}@dyolink.local`;
|
|
const owner = await prisma.user.upsert({
|
|
where: { email },
|
|
create: { email, name: `Billing Demo ${label} Owner`, passwordHash },
|
|
update: { passwordHash },
|
|
});
|
|
const organization = await prisma.organization.upsert({
|
|
where: {
|
|
ownerId_name: { ownerId: owner.id, name: `Billing Demo ${label}` },
|
|
},
|
|
create: {
|
|
name: `Billing Demo ${label}`,
|
|
typeId: type.id,
|
|
ownerId: owner.id,
|
|
planId: plan?.id ?? null,
|
|
billingCurrency: 'TOMAN',
|
|
},
|
|
update: { planId: plan?.id ?? null, billingCurrency: 'TOMAN' },
|
|
include: { type: true },
|
|
});
|
|
const membership = await prisma.membership.upsert({
|
|
where: {
|
|
userId_organizationId: {
|
|
userId: owner.id,
|
|
organizationId: organization.id,
|
|
},
|
|
},
|
|
create: {
|
|
userId: owner.id,
|
|
organizationId: organization.id,
|
|
isOwner: true,
|
|
isActive: true,
|
|
},
|
|
update: { isOwner: true, isActive: true },
|
|
});
|
|
await prisma.organizationSeat.upsert({
|
|
where: { membershipId: membership.id },
|
|
create: {
|
|
organizationId: organization.id,
|
|
membershipId: membership.id,
|
|
kind: 'BASE',
|
|
endsAt: new Date(Date.UTC(2035, 0, 1)),
|
|
},
|
|
update: { endsAt: new Date(Date.UTC(2035, 0, 1)) },
|
|
});
|
|
return organization;
|
|
}
|
|
const clinic = await ensureOrganization(clinicType, 'Clinic');
|
|
const lab = await ensureOrganization(labType, 'Lab');
|
|
const existingLink = await prisma.organizationLink.findFirst({
|
|
where: {
|
|
OR: [
|
|
{ organizationAId: clinic.id, organizationBId: lab.id },
|
|
{ organizationAId: lab.id, organizationBId: clinic.id },
|
|
],
|
|
},
|
|
});
|
|
if (existingLink) {
|
|
await prisma.organizationLink.update({
|
|
where: { id: existingLink.id },
|
|
data: { status: LinkStatus.ACTIVE },
|
|
});
|
|
} else {
|
|
await prisma.organizationLink.create({
|
|
data: {
|
|
organizationAId: clinic.id,
|
|
organizationBId: lab.id,
|
|
status: LinkStatus.ACTIVE,
|
|
sharedDataTypes: [],
|
|
},
|
|
});
|
|
}
|
|
link = await prisma.organizationLink.findFirst({
|
|
where: {
|
|
status: LinkStatus.ACTIVE,
|
|
OR: [
|
|
{ organizationAId: clinic.id, organizationBId: lab.id },
|
|
{ organizationAId: lab.id, organizationBId: clinic.id },
|
|
],
|
|
},
|
|
include: {
|
|
organizationA: { include: { type: true } },
|
|
organizationB: { include: { type: true } },
|
|
},
|
|
});
|
|
}
|
|
if (!link) throw new Error('Could not create the billing demo organization link.');
|
|
const organizations = [link.organizationA, link.organizationB];
|
|
const clinic = organizations.find((org) => org.type.name === 'CLINIC');
|
|
const lab = organizations.find((org) => org.type.name === 'LAB');
|
|
if (!clinic || !lab) {
|
|
throw new Error('The first active organization link must connect a clinic and a lab.');
|
|
}
|
|
|
|
const clinicMemberships = await prisma.membership.findMany({
|
|
where: { organizationId: clinic.id, OR: [{ isOwner: true }, { isActive: true }] },
|
|
orderBy: [{ isOwner: 'asc' }, { createdAt: 'asc' }],
|
|
});
|
|
const provider = clinicMemberships[0];
|
|
if (!provider) throw new Error('The clinic needs at least one active member.');
|
|
|
|
let patient = await prisma.patient.findFirst({
|
|
where: { createdByOrganizationId: clinic.id, isWalkIn: false },
|
|
orderBy: { createdAt: 'asc' },
|
|
});
|
|
patient ??= await prisma.patient.create({
|
|
data: {
|
|
firstName: 'Billing',
|
|
lastName: 'Demo Patient',
|
|
identification: `billing-demo-${clinic.id}`,
|
|
mobile: '0000000000',
|
|
createdByOrganizationId: clinic.id,
|
|
},
|
|
});
|
|
|
|
const now = new Date();
|
|
const staffPeriod = staffBillingPeriodForDate(
|
|
now,
|
|
clinic.billingCurrency ?? 'TOMAN',
|
|
);
|
|
const treatment = await prisma.treatment.upsert({
|
|
where: { id: IDS.treatment },
|
|
create: {
|
|
id: IDS.treatment,
|
|
organizationId: clinic.id,
|
|
patientId: patient.id,
|
|
providerUserId: provider.userId,
|
|
title: 'Billing demo treatment',
|
|
treatmentAt: now,
|
|
calculatedAmount: money(1_500_000),
|
|
billedAmount: money(1_500_000),
|
|
billedAmountManual: true,
|
|
},
|
|
update: {
|
|
organizationId: clinic.id,
|
|
patientId: patient.id,
|
|
providerUserId: provider.userId,
|
|
billedAmount: money(1_500_000),
|
|
billedAmountManual: true,
|
|
},
|
|
});
|
|
const labCase = await prisma.labCase.upsert({
|
|
where: { id: IDS.labCase },
|
|
create: {
|
|
id: IDS.labCase,
|
|
treatmentId: treatment.id,
|
|
destinationOrganizationId: lab.id,
|
|
sentAt: now,
|
|
externalCode: 'BILLING-DEMO',
|
|
patientDisplayName: `${patient.firstName} ${patient.lastName}`.trim(),
|
|
calculatedAmount: money(800_000),
|
|
billedAmount: money(800_000),
|
|
},
|
|
update: {
|
|
treatmentId: treatment.id,
|
|
destinationOrganizationId: lab.id,
|
|
sentAt: now,
|
|
billedAmount: money(800_000),
|
|
},
|
|
});
|
|
const pendingLabCase = await prisma.labCase.upsert({
|
|
where: { id: IDS.pendingLabCase },
|
|
create: {
|
|
id: IDS.pendingLabCase,
|
|
treatmentId: treatment.id,
|
|
destinationOrganizationId: lab.id,
|
|
sentAt: now,
|
|
externalCode: 'BILLING-PENDING',
|
|
patientDisplayName: `${patient.firstName} ${patient.lastName}`.trim(),
|
|
calculatedAmount: money(0),
|
|
billedAmount: null,
|
|
billedAmountManual: false,
|
|
},
|
|
update: {
|
|
treatmentId: treatment.id,
|
|
destinationOrganizationId: lab.id,
|
|
sentAt: now,
|
|
calculatedAmount: money(0),
|
|
billedAmount: null,
|
|
billedAmountManual: false,
|
|
},
|
|
});
|
|
|
|
await prisma.organization.updateMany({
|
|
where: { id: { in: [clinic.id, lab.id] }, billingCurrency: null },
|
|
data: { billingCurrency: 'TOMAN' },
|
|
});
|
|
await prisma.membership.update({
|
|
where: { id: provider.id },
|
|
data: { fixedMonthlySalary: money(12_000_000) },
|
|
});
|
|
await prisma.commissionEarning.upsert({
|
|
where: {
|
|
treatmentId_catalogCode: {
|
|
treatmentId: treatment.id,
|
|
catalogCode: 'billing_demo_commission',
|
|
},
|
|
},
|
|
create: {
|
|
organizationId: clinic.id,
|
|
userId: provider.userId,
|
|
treatmentId: treatment.id,
|
|
catalogCode: 'billing_demo_commission',
|
|
baseAmount: money(250_000),
|
|
percent: money(0),
|
|
qty: money(1),
|
|
earnedAmount: money(250_000),
|
|
earnedAt: now,
|
|
},
|
|
update: { earnedAmount: money(250_000), earnedAt: now },
|
|
});
|
|
|
|
const obligations = [
|
|
{
|
|
organizationId: clinic.id,
|
|
partyKind: BillingLedgerPartyKind.PATIENT,
|
|
partyId: patient.id,
|
|
sourceType: BillingObligationSourceType.TREATMENT_APPROVE,
|
|
sourceId: treatment.id,
|
|
amount: 1_500_000,
|
|
sign: 1,
|
|
occurredAt: now,
|
|
},
|
|
{
|
|
organizationId: clinic.id,
|
|
partyKind: BillingLedgerPartyKind.ORGANIZATION,
|
|
partyId: lab.id,
|
|
sourceType: BillingObligationSourceType.LAB_CASE,
|
|
sourceId: labCase.id,
|
|
amount: 800_000,
|
|
sign: -1,
|
|
occurredAt: now,
|
|
},
|
|
{
|
|
organizationId: lab.id,
|
|
partyKind: BillingLedgerPartyKind.ORGANIZATION,
|
|
partyId: clinic.id,
|
|
sourceType: BillingObligationSourceType.LAB_CASE,
|
|
sourceId: labCase.id,
|
|
amount: 800_000,
|
|
sign: 1,
|
|
occurredAt: now,
|
|
},
|
|
{
|
|
organizationId: clinic.id,
|
|
partyKind: BillingLedgerPartyKind.STAFF,
|
|
partyId: provider.userId,
|
|
sourceType: BillingObligationSourceType.STAFF_COMMISSION_MONTH,
|
|
sourceId: `${provider.userId}:${staffPeriod.key}:commission`,
|
|
amount: 250_000,
|
|
sign: -1,
|
|
occurredAt: staffPeriod.start,
|
|
},
|
|
{
|
|
organizationId: clinic.id,
|
|
partyKind: BillingLedgerPartyKind.STAFF,
|
|
partyId: provider.userId,
|
|
sourceType: BillingObligationSourceType.STAFF_SALARY_MONTH,
|
|
sourceId: `${provider.userId}:${staffPeriod.key}:salary`,
|
|
amount: 12_000_000,
|
|
sign: -1,
|
|
occurredAt: staffPeriod.start,
|
|
},
|
|
];
|
|
for (const row of obligations) {
|
|
const { sign, amount, ...entry } = row;
|
|
await prisma.billingLedgerEntry.upsert({
|
|
where: {
|
|
organizationId_sourceType_sourceId: {
|
|
organizationId: entry.organizationId,
|
|
sourceType: entry.sourceType,
|
|
sourceId: entry.sourceId,
|
|
},
|
|
},
|
|
create: {
|
|
...entry,
|
|
amount: money(amount),
|
|
signedAmount: money(amount * sign),
|
|
balanceSign: sign,
|
|
},
|
|
update: {
|
|
partyKind: entry.partyKind,
|
|
partyId: entry.partyId,
|
|
amount: money(amount),
|
|
signedAmount: money(amount * sign),
|
|
balanceSign: sign,
|
|
occurredAt: entry.occurredAt,
|
|
},
|
|
});
|
|
}
|
|
for (const row of [
|
|
{
|
|
organizationId: clinic.id,
|
|
partyId: lab.id,
|
|
sign: -1,
|
|
},
|
|
{
|
|
organizationId: lab.id,
|
|
partyId: clinic.id,
|
|
sign: 1,
|
|
},
|
|
]) {
|
|
await prisma.billingLedgerEntry.upsert({
|
|
where: {
|
|
organizationId_sourceType_sourceId: {
|
|
organizationId: row.organizationId,
|
|
sourceType: BillingObligationSourceType.LAB_CASE,
|
|
sourceId: pendingLabCase.id,
|
|
},
|
|
},
|
|
create: {
|
|
organizationId: row.organizationId,
|
|
partyKind: BillingLedgerPartyKind.ORGANIZATION,
|
|
partyId: row.partyId,
|
|
sourceType: BillingObligationSourceType.LAB_CASE,
|
|
sourceId: pendingLabCase.id,
|
|
amount: null,
|
|
signedAmount: null,
|
|
balanceSign: row.sign,
|
|
occurredAt: now,
|
|
},
|
|
update: {
|
|
partyId: row.partyId,
|
|
amount: null,
|
|
signedAmount: null,
|
|
balanceSign: row.sign,
|
|
occurredAt: now,
|
|
},
|
|
});
|
|
}
|
|
|
|
await prisma.patientPayment.upsert({
|
|
where: { id: IDS.patientPayment },
|
|
create: {
|
|
id: IDS.patientPayment,
|
|
organizationId: clinic.id,
|
|
patientId: patient.id,
|
|
amount: money(500_000),
|
|
paidAt: now,
|
|
note: 'Billing demo patient receipt',
|
|
createdByUserId: provider.userId,
|
|
},
|
|
update: { patientId: patient.id, amount: money(500_000), paidAt: now },
|
|
});
|
|
await prisma.partnerPayment.upsert({
|
|
where: { id: IDS.partnerPayment },
|
|
create: {
|
|
id: IDS.partnerPayment,
|
|
fromOrganizationId: clinic.id,
|
|
toOrganizationId: lab.id,
|
|
amount: money(300_000),
|
|
paidAt: now,
|
|
note: 'Billing demo partner payment',
|
|
status: PartnerPaymentStatus.CONFIRMED,
|
|
recordedBy: PartnerPaymentRecordedBy.CLINIC,
|
|
receiptConfirmedAt: now,
|
|
createdByUserId: provider.userId,
|
|
},
|
|
update: {
|
|
fromOrganizationId: clinic.id,
|
|
toOrganizationId: lab.id,
|
|
amount: money(300_000),
|
|
paidAt: now,
|
|
receiptConfirmedAt: now,
|
|
},
|
|
});
|
|
await prisma.staffPayment.upsert({
|
|
where: { id: IDS.staffPayment },
|
|
create: {
|
|
id: IDS.staffPayment,
|
|
organizationId: clinic.id,
|
|
userId: provider.userId,
|
|
amount: money(5_000_000),
|
|
paidAt: now,
|
|
note: 'Billing demo salary payment',
|
|
createdByUserId: provider.userId,
|
|
},
|
|
update: { userId: provider.userId, amount: money(5_000_000), paidAt: now },
|
|
});
|
|
|
|
console.log(`Billing demo ready for clinic "${clinic.name}" and lab "${lab.name}".`);
|
|
console.log(`Patient: ${patient.firstName} ${patient.lastName}; staff user: ${provider.userId}`);
|
|
console.log('Pending amount case: BILLING-PENDING');
|
|
}
|
|
|
|
main()
|
|
.catch((error) => {
|
|
console.error(error);
|
|
process.exitCode = 1;
|
|
})
|
|
.finally(async () => {
|
|
await prisma.$disconnect();
|
|
});
|