diff --git a/apps/api/prisma/migrations/20261125160000_recurring_reminders/migration.sql b/apps/api/prisma/migrations/20261125160000_recurring_reminders/migration.sql new file mode 100644 index 0000000..50e7a24 --- /dev/null +++ b/apps/api/prisma/migrations/20261125160000_recurring_reminders/migration.sql @@ -0,0 +1,6 @@ +-- AlterTable +ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderDaysBefore" INTEGER; +ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderNotifyApp" BOOLEAN NOT NULL DEFAULT true; +ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderNotifySms" BOOLEAN NOT NULL DEFAULT true; +ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderLastSentDay" TEXT; +ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderLastSentDue" TIMESTAMP(3); diff --git a/apps/api/prisma/migrations/20261125170000_recurring_reminder_repeat/migration.sql b/apps/api/prisma/migrations/20261125170000_recurring_reminder_repeat/migration.sql new file mode 100644 index 0000000..81863ee --- /dev/null +++ b/apps/api/prisma/migrations/20261125170000_recurring_reminder_repeat/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderRepeatDaily" BOOLEAN NOT NULL DEFAULT true; diff --git a/apps/api/prisma/migrations/20261125190000_fix_false_didar_import_source/migration.sql b/apps/api/prisma/migrations/20261125190000_fix_false_didar_import_source/migration.sql new file mode 100644 index 0000000..edc1fbb --- /dev/null +++ b/apps/api/prisma/migrations/20261125190000_fix_false_didar_import_source/migration.sql @@ -0,0 +1,25 @@ +-- برچسب اشتباه «دیدار» روی اشخاص/شرکت‌هایی که کد مبدأ واقعی دیدار نداشتند +-- (خروجی اکسل قبلاً id داخلی CRM را در ستون کد دیدار می‌گذاشت). + +UPDATE "Person" +SET + "customFields" = "customFields" - 'didarId', + "sourceRef" = CASE WHEN "sourceRef" = "id" THEN NULL ELSE "sourceRef" END +WHERE ("customFields"->>'didarId') = "id" + OR "sourceRef" = "id"; + +UPDATE "Person" +SET "importSource" = 'excel' +WHERE "importSource" = 'didar'; + +UPDATE "Person" +SET "previousImportSource" = 'excel' +WHERE "previousImportSource" = 'didar'; + +UPDATE "Company" +SET "sourceRef" = CASE WHEN "sourceRef" = "id" THEN NULL ELSE "sourceRef" END +WHERE "sourceRef" = "id"; + +UPDATE "Company" +SET "importSource" = 'excel' +WHERE "importSource" = 'didar'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 2e21b3a..c561835 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -2520,6 +2520,15 @@ model FinancialRecurringItem { categoryId String? isActive Boolean @default(true) createdById String? + /// null = بدون یادآور؛ ۰ = روز سررسید؛ N = N روز قبل از سررسید + reminderDaysBefore Int? + /// true = هر روز از N تا سررسید؛ false = فقط همان روز مشخص‌شده یک‌بار + reminderRepeatDaily Boolean @default(true) + reminderNotifyApp Boolean @default(true) + reminderNotifySms Boolean @default(true) + /// آخرین روزی که برای nextDue فعلی یادآور ارسال شد (YYYY-MM-DD تهران) + reminderLastSentDay String? + reminderLastSentDue DateTime? occurrences FinancialRecurringOccurrence[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/apps/api/src/contacts/contacts-excel.service.ts b/apps/api/src/contacts/contacts-excel.service.ts index 1b85348..c8fb79c 100644 --- a/apps/api/src/contacts/contacts-excel.service.ts +++ b/apps/api/src/contacts/contacts-excel.service.ts @@ -25,7 +25,7 @@ import { import { CompaniesService } from './companies.service'; import { PeopleService } from './people.service'; import { normalizeEmail, normalizePhone } from './normalize'; -import { normalizePersonImportSource } from './person-source'; +import { resolveDidarSourceRef } from './person-source'; import { CustomerGroupsService, splitGroupNames, @@ -397,7 +397,10 @@ export class ContactsExcelService { const groupText = groupNamesText(p.groups, extra.group); return { _type: 'Contact', - didarId: extra.didarId ?? p.id, + didarId: + p.importSource === 'didar' + ? p.sourceRef || extra.didarId || '' + : '', customerCode: extra.customerCode ?? '', title: extra.title ?? '', firstName: p.firstName, @@ -586,14 +589,13 @@ export class ContactsExcelService { })(); try { - const didarId = customFields.didarId?.trim() || ''; + const didarId = resolveDidarSourceRef(customFields.didarId); const customerCode = customFields.customerCode?.trim() || ''; - const sourceCol = customFields.source?.trim() || ''; - const importSource = didarId - ? 'didar' - : sourceCol - ? normalizePersonImportSource(sourceCol) - : 'excel'; + // ایمپورت اکسل فقط با کد مبدأ واقعی دیدار برچسب «دیدار» می‌گیرد؛ + // cuid داخلی یا ستون «منبع اطلاعات» باعث دیدار شدن نمی‌شود. + if (didarId) customFields.didarId = didarId; + else delete customFields.didarId; + const importSource = didarId ? 'didar' : 'excel'; const sourceRef = didarId || customerCode || null; const groupIds = await this.groups.idsForNames(actor.organizationId, groupNames); @@ -691,7 +693,7 @@ export class ContactsExcelService { else ownerMissing = true; } - const didarId = row.didarId?.trim() || ''; + const didarId = resolveDidarSourceRef(row.didarId) || ''; const customFields: Record = {}; const visibility = row.visibility?.trim(); if (visibility) customFields.visibility = visibility; @@ -800,7 +802,7 @@ export class ContactsExcelService { didarId?: string, phone?: string, ): Promise { - const ref = didarId?.trim() || ''; + const ref = resolveDidarSourceRef(didarId) || ''; if (ref) { const byRef = await this.prisma.company.findFirst({ where: { diff --git a/apps/api/src/contacts/person-source.ts b/apps/api/src/contacts/person-source.ts index 1caddae..b5da88e 100644 --- a/apps/api/src/contacts/person-source.ts +++ b/apps/api/src/contacts/person-source.ts @@ -29,6 +29,20 @@ export function personImportSourceLabel(source: string): string { return source || PERSON_IMPORT_SOURCE_LABELS.manual; } +/** + * کد مبدأ واقعی دیدار برای برچسب‌زدن منبع. + * cuid داخلی مونتاکت و مقادیر توخالی را دیدار حساب نکن + * (باگ قبلی: خروجی اکسل id داخلی را در ستون کد دیدار می‌گذاشت). + */ +export function resolveDidarSourceRef(raw?: string | null): string | null { + const v = String(raw ?? '').trim(); + if (!v) return null; + if (/^(0+|-+|\.+|n\/?a|null|undefined|none)$/i.test(v)) return null; + // Prisma/cuid داخلی (~25 کاراکتر با پیشوند c) + if (/^c[a-z0-9]{20,32}$/i.test(v)) return null; + return v; +} + type SourceSnapshot = { importSource?: string | null; sourceRef?: string | null; @@ -40,8 +54,10 @@ type SourceSnapshot = { function didarIdFrom(customFields: unknown): string | null { if (!customFields || typeof customFields !== 'object') return null; const raw = (customFields as Record).didarId; - if (typeof raw === 'number' && Number.isFinite(raw)) return String(raw); - if (typeof raw === 'string' && raw.trim()) return raw.trim(); + if (typeof raw === 'number' && Number.isFinite(raw)) { + return resolveDidarSourceRef(String(raw)); + } + if (typeof raw === 'string') return resolveDidarSourceRef(raw); return null; } diff --git a/apps/api/src/pipelines/deals-excel.service.ts b/apps/api/src/pipelines/deals-excel.service.ts index be79d50..dc7da83 100644 --- a/apps/api/src/pipelines/deals-excel.service.ts +++ b/apps/api/src/pipelines/deals-excel.service.ts @@ -61,10 +61,11 @@ function parseTags(raw?: string) { .slice(0, 20); } -/** کدهای دیدار: «0» و خالی یعنی بدون کد */ +/** کدهای دیدار: «0»، خالی، و cuid داخلی یعنی بدون کد مبدأ واقعی */ function cleanCode(raw?: string): string { const v = toAsciiDigits(raw ?? '').trim(); if (!v || /^0+$/.test(v)) return ''; + if (/^c[a-z0-9]{20,32}$/i.test(v)) return ''; return v; } @@ -126,9 +127,18 @@ export class DealsExcelService { lastName: true, mobile: true, sourceRef: true, + importSource: true, + }, + }, + company: { + select: { + id: true, + name: true, + phone: true, + sourceRef: true, + importSource: true, }, }, - company: { select: { id: true, name: true, phone: true, sourceRef: true } }, owner: { select: { fullName: true } }, createdBy: { select: { fullName: true } }, pipeline: { select: { name: true } }, @@ -157,7 +167,7 @@ export class DealsExcelService { const extra = asCustomFields(row.customFields); const base: Record = { _type: 'Deal', - didarId: row.sourceRef ?? row.id, + didarId: row.importSource === 'didar' ? row.sourceRef || '' : '', code: row.code ?? '', title: row.title, amount: row.amount == null ? 0 : Number(row.amount), @@ -181,10 +191,12 @@ export class DealsExcelService { stageName: row.stage.name, personFirstName: row.person?.firstName ?? '', personName: row.person?.lastName ?? '', - personCode: row.person ? (row.person.sourceRef ?? row.person.id) : '', + personCode: + row.person?.importSource === 'didar' ? row.person.sourceRef || '' : '', personMobile: row.person?.mobile ?? '', companyName: row.company?.name ?? '', - companyCode: row.company ? (row.company.sourceRef ?? row.company.id) : '', + companyCode: + row.company?.importSource === 'didar' ? row.company.sourceRef || '' : '', companyPhone: row.company?.phone ?? '', }; for (const d of defs) { diff --git a/apps/api/src/treasury/treasury-ops.service.ts b/apps/api/src/treasury/treasury-ops.service.ts index 8d3faba..2c95475 100644 --- a/apps/api/src/treasury/treasury-ops.service.ts +++ b/apps/api/src/treasury/treasury-ops.service.ts @@ -3,7 +3,19 @@ import { Cron } from '@nestjs/schedule'; import { Prisma } from '@prisma/client'; import ExcelJS from 'exceljs'; import type { TreasuryPartyBalanceDto } from '@mento/shared'; +import { + addJalaliMonths, + dateToJalali, + endOfJalaliMonth, + formatTehranJalali, + jalaliMonthKey, + jalaliMonthName, + startOfJalaliMonth, +} from '../common/jalali'; import { PrismaService } from '../prisma/prisma.service'; +import { NotificationsService } from '../notifications/notifications.service'; +import { SmsGatewayService } from '../sms-billing/sms-gateway.service'; +import { tehranDayKey } from '../routines/routine-dates'; import type { Actor } from '../common/record-scope'; import { invoiceSalesInPeriod } from './invoice-ledger'; @@ -22,6 +34,46 @@ function parseDate(iso?: string | null) { const d = new Date(iso); return Number.isNaN(d.getTime()) ? null : d; } +/** روز محلی از YYYY-MM-DD (بدون جابه‌جایی UTC) */ +function parseDay(iso?: string | null) { + if (!iso) return null; + const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso.trim()); + if (match) { + return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])); + } + return parseDate(iso); +} +function startOfDay(d: Date) { + return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0); +} +function endOfDay(d: Date) { + return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999); +} +function faDigits(value: string | number) { + return String(value).replace(/\d/g, (d) => '۰۱۲۳۴۵۶۷۸۹'[Number(d)] ?? d); +} +function jalaliMonthLabel(key: string) { + const match = /^(\d{4})-(\d{2})$/.exec(key); + if (!match) return key; + return `${jalaliMonthName(Number(match[2]))} ${faDigits(match[1])}`; +} +function daysUntilTehran(due: Date, now = new Date()) { + const dueKey = tehranDayKey(due); + const todayKey = tehranDayKey(now); + const [dy, dm, dd] = dueKey.split('-').map(Number); + const [ty, tm, td] = todayKey.split('-').map(Number); + const dueMs = Date.UTC(dy!, dm! - 1, dd!); + const todayMs = Date.UTC(ty!, tm! - 1, td!); + return Math.round((dueMs - todayMs) / 86_400_000); +} +function normalizeReminderDays(raw: unknown): number | null { + if (raw === null || raw === undefined || raw === '') return null; + const n = Number(raw); + if (!Number.isFinite(n) || n < 0 || n > 30) { + throw new BadRequestException('تعداد روز یادآور باید بین ۰ تا ۳۰ باشد.'); + } + return Math.floor(n); +} function payrollStatus(payable: Prisma.Decimal, paid: Prisma.Decimal) { if (paid.lessThanOrEqualTo(0)) return 'open'; if (paid.greaterThanOrEqualTo(payable)) return 'settled'; @@ -41,7 +93,11 @@ function addInterval(date: Date, interval: string) { @Injectable() export class TreasuryOpsService { private readonly logger = new Logger(TreasuryOpsService.name); - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly notifications: NotificationsService, + private readonly sms: SmsGatewayService, + ) {} async listPayroll(actor: Actor) { const rows = await this.prisma.financialPayroll.findMany({ @@ -301,8 +357,13 @@ export class TreasuryOpsService { kind: row.kind, amount: money(row.amount), interval: row.interval, + startDate: row.startDate.toISOString(), nextDue: row.nextDue.toISOString(), isActive: row.isActive, + reminderDaysBefore: row.reminderDaysBefore, + reminderRepeatDaily: row.reminderRepeatDaily, + reminderNotifyApp: row.reminderNotifyApp, + reminderNotifySms: row.reminderNotifySms, })); } @@ -317,6 +378,10 @@ export class TreasuryOpsService { endDate?: string | null; accountId?: string | null; categoryId?: string | null; + reminderDaysBefore?: number | null; + reminderRepeatDaily?: boolean; + reminderNotifyApp?: boolean; + reminderNotifySms?: boolean; }, ) { const amount = dec(input.amount); @@ -324,6 +389,7 @@ export class TreasuryOpsService { throw new BadRequestException('عنوان و مبلغ تکرارشونده لازم است.'); } const start = parseDate(input.startDate) ?? new Date(); + const reminderDaysBefore = normalizeReminderDays(input.reminderDaysBefore); const row = await this.prisma.financialRecurringItem.create({ data: { organizationId: actor.organizationId, @@ -337,11 +403,178 @@ export class TreasuryOpsService { accountId: input.accountId || null, categoryId: input.categoryId || null, createdById: actor.userId, + reminderDaysBefore, + reminderRepeatDaily: input.reminderRepeatDaily !== false, + reminderNotifyApp: input.reminderNotifyApp !== false, + reminderNotifySms: input.reminderNotifySms !== false, }, }); return { id: row.id }; } + async updateRecurring( + actor: Actor, + id: string, + input: { + title?: string; + kind?: 'income' | 'expense'; + amount?: string | number; + interval?: 'weekly' | 'monthly' | 'yearly'; + nextDue?: string; + reminderDaysBefore?: number | null; + reminderRepeatDaily?: boolean; + reminderNotifyApp?: boolean; + reminderNotifySms?: boolean; + isActive?: boolean; + }, + ) { + const existing = await this.prisma.financialRecurringItem.findFirst({ + where: { id, organizationId: actor.organizationId }, + }); + if (!existing) throw new NotFoundException('الگوی تکرارشونده پیدا نشد.'); + const data: Prisma.FinancialRecurringItemUpdateInput = {}; + if (input.title !== undefined) { + const title = input.title.trim(); + if (!title) throw new BadRequestException('عنوان لازم است.'); + data.title = title; + } + if (input.kind !== undefined) data.kind = input.kind; + if (input.amount !== undefined) { + const amount = dec(input.amount); + if (!amount.greaterThan(0)) throw new BadRequestException('مبلغ نامعتبر است.'); + data.amount = amount; + } + if (input.interval !== undefined) data.interval = input.interval; + if (input.nextDue !== undefined) { + const nextDue = parseDate(input.nextDue); + if (!nextDue) throw new BadRequestException('تاریخ سررسید نامعتبر است.'); + data.nextDue = nextDue; + data.reminderLastSentDay = null; + data.reminderLastSentDue = null; + } + if ('reminderDaysBefore' in input) { + data.reminderDaysBefore = normalizeReminderDays(input.reminderDaysBefore); + data.reminderLastSentDay = null; + data.reminderLastSentDue = null; + } + if (input.reminderRepeatDaily !== undefined) { + data.reminderRepeatDaily = input.reminderRepeatDaily; + data.reminderLastSentDay = null; + data.reminderLastSentDue = null; + } + if (input.reminderNotifyApp !== undefined) data.reminderNotifyApp = input.reminderNotifyApp; + if (input.reminderNotifySms !== undefined) data.reminderNotifySms = input.reminderNotifySms; + if (input.isActive !== undefined) data.isActive = input.isActive; + const row = await this.prisma.financialRecurringItem.update({ + where: { id }, + data, + }); + return { + id: row.id, + title: row.title, + kind: row.kind, + amount: money(row.amount), + interval: row.interval, + startDate: row.startDate.toISOString(), + nextDue: row.nextDue.toISOString(), + isActive: row.isActive, + reminderDaysBefore: row.reminderDaysBefore, + reminderRepeatDaily: row.reminderRepeatDaily, + reminderNotifyApp: row.reminderNotifyApp, + reminderNotifySms: row.reminderNotifySms, + }; + } + + @Cron('0 8 * * *') + async remindRecurring() { + const todayKey = tehranDayKey(); + const items = await this.prisma.financialRecurringItem.findMany({ + where: { + isActive: true, + reminderDaysBefore: { not: null }, + OR: [{ reminderNotifyApp: true }, { reminderNotifySms: true }], + }, + take: 300, + }); + let sent = 0; + for (const item of items) { + const lead = item.reminderDaysBefore; + if (lead == null) continue; + const daysLeft = daysUntilTehran(item.nextDue); + if (daysLeft < 0 || daysLeft > lead) continue; + if (!item.reminderRepeatDaily && daysLeft !== lead) continue; + const sameDue = + item.reminderLastSentDue && + item.reminderLastSentDue.getTime() === item.nextDue.getTime(); + if (sameDue && item.reminderLastSentDay === todayKey) continue; + + const kindLabel = item.kind === 'income' ? 'درآمد' : 'هزینه'; + const dueLabel = formatTehranJalali(item.nextDue); + const title = + daysLeft === 0 + ? `سررسید امروز · ${kindLabel} تکرارشونده` + : `یادآور ${faDigits(daysLeft)} روز مانده · ${kindLabel} تکرارشونده`; + const body = `${item.title} · ${money(item.amount)} تومان · سررسید ${dueLabel}`; + const recipients = await this.recurringReminderRecipients( + item.organizationId, + item.createdById, + ); + for (const userId of recipients) { + if (item.reminderNotifyApp) { + await this.notifications.create({ + organizationId: item.organizationId, + userId, + type: 'treasury_recurring_reminder', + title, + body, + link: '/finance/recurring', + entityType: 'financial_recurring', + entityId: `${item.id}:${todayKey}`, + dedupe: true, + }); + } + if (item.reminderNotifySms) { + const user = await this.prisma.user.findUnique({ + where: { id: userId }, + select: { mobile: true }, + }); + if (user?.mobile) { + await this.sms + .send({ + organizationId: item.organizationId, + phone: user.mobile, + text: `${title}: ${body}`, + source: 'treasury_recurring_reminder', + }) + .catch(() => undefined); + } + } + } + await this.prisma.financialRecurringItem.update({ + where: { id: item.id }, + data: { + reminderLastSentDay: todayKey, + reminderLastSentDue: item.nextDue, + }, + }); + sent += 1; + } + if (sent) this.logger.log(`recurring reminders sent: ${sent}`); + } + + private async recurringReminderRecipients( + organizationId: string, + createdById: string | null, + ) { + const owners = await this.prisma.membership.findMany({ + where: { organizationId, isActive: true, role: 'owner' }, + select: { userId: true }, + }); + const ids = new Set(owners.map((row) => row.userId)); + if (createdById) ids.add(createdById); + return [...ids]; + } + @Cron('30 8 * * *') async spawnRecurring() { const now = new Date(); @@ -381,7 +614,11 @@ export class TreasuryOpsService { } await this.prisma.financialRecurringItem.update({ where: { id: item.id }, - data: { nextDue: addInterval(item.nextDue, item.interval) }, + data: { + nextDue: addInterval(item.nextDue, item.interval), + reminderLastSentDay: null, + reminderLastSentDue: null, + }, }); } if (items.length) this.logger.log(`recurring finance items: ${items.length}`); @@ -449,15 +686,32 @@ export class TreasuryOpsService { } async report(actor: Actor, fromIso?: string, toIso?: string) { - const to = parseDate(toIso) ?? new Date(); - const from = parseDate(fromIso) ?? new Date(to.getFullYear(), to.getMonth(), 1); - const span = to.getTime() - from.getTime(); - const prevTo = new Date(from.getTime() - 1); - const prevFrom = new Date(prevTo.getTime() - span); + const now = new Date(); + const jalaliNow = dateToJalali(now); + const to = endOfDay(parseDay(toIso) ?? now); + const from = startOfDay( + parseDay(fromIso) ?? startOfJalaliMonth(jalaliNow.jy, jalaliNow.jm), + ); + if (from.getTime() > to.getTime()) { + throw new BadRequestException('بازهٔ تاریخ نامعتبر است.'); + } + // دوره قبل = ماه شمسی کاملِ قبل از ماهی که «از تاریخ» در آن است + const fromJalali = dateToJalali(from); + const prevMonth = addJalaliMonths(fromJalali.jy, fromJalali.jm, -1); + const prevFrom = startOfDay(startOfJalaliMonth(prevMonth.jy, prevMonth.jm)); + const prevTo = endOfDay(endOfJalaliMonth(prevMonth.jy, prevMonth.jm)); const current = await this.period(actor.organizationId, from, to); const previous = await this.period(actor.organizationId, prevFrom, prevTo); const breakdown = await this.breakdown(actor.organizationId); - return { from: from.toISOString(), to: to.toISOString(), current, previous, ...breakdown }; + return { + from: from.toISOString(), + to: to.toISOString(), + previousFrom: prevFrom.toISOString(), + previousTo: prevTo.toISOString(), + current, + previous, + ...breakdown, + }; } async reportExcel( @@ -469,6 +723,15 @@ export class TreasuryOpsService { const data = await this.report(actor, from, to); const book = new ExcelJS.Workbook(); const sheet = book.addWorksheet('گزارش مالی'); + sheet.addRow([ + 'بازه این دوره', + `${formatTehranJalali(new Date(data.from))} تا ${formatTehranJalali(new Date(data.to))}`, + ]); + sheet.addRow([ + 'بازه دوره قبل', + `${formatTehranJalali(new Date(data.previousFrom))} تا ${formatTehranJalali(new Date(data.previousTo))}`, + ]); + sheet.addRow([]); sheet.addRow(['شاخص', 'این دوره', 'دوره قبل']); const rows: Array<[string, string, string]> = [ ['درآمد ثبت‌شده', data.current.bookedIncome, data.previous.bookedIncome], @@ -591,7 +854,7 @@ export class TreasuryOpsService { ]); const payablesByMonth = new Map(); const addMonth = (date: Date, amount: Prisma.Decimal) => { - const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`; + const key = jalaliMonthKey(date); payablesByMonth.set(key, (payablesByMonth.get(key) ?? new Prisma.Decimal(0)).plus(amount)); }; for (const doc of docs) { @@ -611,8 +874,17 @@ export class TreasuryOpsService { receivablesByParty.set(name, (receivablesByParty.get(name) ?? new Prisma.Decimal(0)).plus(left)); } return { - payablesByMonth: [...payablesByMonth.entries()].map(([month, amount]) => ({ month, amount: money(amount) })), - receivablesByParty: [...receivablesByParty.entries()].map(([name, amount]) => ({ name, amount: money(amount) })), + payablesByMonth: [...payablesByMonth.entries()] + .sort((a, b) => b[0].localeCompare(a[0])) + .map(([month, amount]) => ({ + month, + label: jalaliMonthLabel(month), + amount: money(amount), + })), + receivablesByParty: [...receivablesByParty.entries()].map(([name, amount]) => ({ + name, + amount: money(amount), + })), }; } diff --git a/apps/api/src/treasury/treasury.controller.ts b/apps/api/src/treasury/treasury.controller.ts index f0ec94f..5da846a 100644 --- a/apps/api/src/treasury/treasury.controller.ts +++ b/apps/api/src/treasury/treasury.controller.ts @@ -323,6 +323,15 @@ export class TreasuryController { return this.ops.createRecurring(user, body); } + @Patch('recurring/:id') + updateRecurring( + @CurrentUser() user: Actor, + @Param('id') id: string, + @Body() body: Parameters[2], + ) { + return this.ops.updateRecurring(user, id, body); + } + @Get('reports') report( @CurrentUser() user: Actor, diff --git a/apps/api/src/treasury/treasury.module.ts b/apps/api/src/treasury/treasury.module.ts index f9a5fa2..67af6cd 100644 --- a/apps/api/src/treasury/treasury.module.ts +++ b/apps/api/src/treasury/treasury.module.ts @@ -2,6 +2,7 @@ import { Module } from '@nestjs/common'; import { AuthModule } from '../auth/auth.module'; import { ContactsModule } from '../contacts/contacts.module'; import { NotificationsModule } from '../notifications/notifications.module'; +import { SmsBillingModule } from '../sms-billing/sms-billing.module'; import { TreasuryController } from './treasury.controller'; import { TreasuryAccessGuard } from './treasury-access.guard'; import { TreasuryBridgeService } from './treasury-bridge.service'; @@ -10,7 +11,7 @@ import { TreasuryReceivablesService } from './treasury-receivables.service'; import { TreasuryService } from './treasury.service'; @Module({ - imports: [AuthModule, NotificationsModule, ContactsModule], + imports: [AuthModule, NotificationsModule, ContactsModule, SmsBillingModule], controllers: [TreasuryController], providers: [ TreasuryService,