Add owner reminders for recurring treasury patterns with once-or-daily cadence.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-25 16:35:45 +03:30
co-authored by Cursor
parent c5ff3597db
commit f3f043d4e8
7 changed files with 666 additions and 101 deletions
@@ -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);
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "FinancialRecurringItem" ADD COLUMN "reminderRepeatDaily" BOOLEAN NOT NULL DEFAULT true;
+9
View File
@@ -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
+207 -2
View File
@@ -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}`);
@@ -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<TreasuryOpsService['updateRecurring']>[2],
) {
return this.ops.updateRecurring(user, id, body);
}
@Get('reports')
report(
@CurrentUser() user: Actor,
+2 -1
View File
@@ -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,