From f3f043d4e83d7b10e19f91e9740330a75d653282 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Wed, 25 Nov 2026 16:35:45 +0330 Subject: [PATCH] Add owner reminders for recurring treasury patterns with once-or-daily cadence. Co-authored-by: Cursor --- .../migration.sql | 6 + .../migration.sql | 2 + apps/api/prisma/schema.prisma | 9 + apps/api/src/treasury/treasury-ops.service.ts | 209 ++++++- apps/api/src/treasury/treasury.controller.ts | 9 + apps/api/src/treasury/treasury.module.ts | 3 +- .../views/treasury/TreasuryRecurringView.vue | 529 ++++++++++++++---- 7 files changed, 666 insertions(+), 101 deletions(-) create mode 100644 apps/api/prisma/migrations/20261125160000_recurring_reminders/migration.sql create mode 100644 apps/api/prisma/migrations/20261125170000_recurring_reminder_repeat/migration.sql 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/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/treasury/treasury-ops.service.ts b/apps/api/src/treasury/treasury-ops.service.ts index f2f2ab4..2c95475 100644 --- a/apps/api/src/treasury/treasury-ops.service.ts +++ b/apps/api/src/treasury/treasury-ops.service.ts @@ -13,6 +13,9 @@ import { 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'; @@ -54,6 +57,23 @@ function jalaliMonthLabel(key: string) { 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'; @@ -73,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({ @@ -333,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, })); } @@ -349,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); @@ -356,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, @@ -369,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(); @@ -413,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}`); 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, diff --git a/apps/web/src/views/treasury/TreasuryRecurringView.vue b/apps/web/src/views/treasury/TreasuryRecurringView.vue index 43a78ad..dd0c9f1 100644 --- a/apps/web/src/views/treasury/TreasuryRecurringView.vue +++ b/apps/web/src/views/treasury/TreasuryRecurringView.vue @@ -1,23 +1,28 @@