merge: bring latest origin/main into dev (design local, logic main)
This commit is contained in:
@@ -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;
|
||||||
@@ -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';
|
||||||
@@ -2520,6 +2520,15 @@ model FinancialRecurringItem {
|
|||||||
categoryId String?
|
categoryId String?
|
||||||
isActive Boolean @default(true)
|
isActive Boolean @default(true)
|
||||||
createdById String?
|
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[]
|
occurrences FinancialRecurringOccurrence[]
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import {
|
|||||||
import { CompaniesService } from './companies.service';
|
import { CompaniesService } from './companies.service';
|
||||||
import { PeopleService } from './people.service';
|
import { PeopleService } from './people.service';
|
||||||
import { normalizeEmail, normalizePhone } from './normalize';
|
import { normalizeEmail, normalizePhone } from './normalize';
|
||||||
import { normalizePersonImportSource } from './person-source';
|
import { resolveDidarSourceRef } from './person-source';
|
||||||
import {
|
import {
|
||||||
CustomerGroupsService,
|
CustomerGroupsService,
|
||||||
splitGroupNames,
|
splitGroupNames,
|
||||||
@@ -397,7 +397,10 @@ export class ContactsExcelService {
|
|||||||
const groupText = groupNamesText(p.groups, extra.group);
|
const groupText = groupNamesText(p.groups, extra.group);
|
||||||
return {
|
return {
|
||||||
_type: 'Contact',
|
_type: 'Contact',
|
||||||
didarId: extra.didarId ?? p.id,
|
didarId:
|
||||||
|
p.importSource === 'didar'
|
||||||
|
? p.sourceRef || extra.didarId || ''
|
||||||
|
: '',
|
||||||
customerCode: extra.customerCode ?? '',
|
customerCode: extra.customerCode ?? '',
|
||||||
title: extra.title ?? '',
|
title: extra.title ?? '',
|
||||||
firstName: p.firstName,
|
firstName: p.firstName,
|
||||||
@@ -586,14 +589,13 @@ export class ContactsExcelService {
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const didarId = customFields.didarId?.trim() || '';
|
const didarId = resolveDidarSourceRef(customFields.didarId);
|
||||||
const customerCode = customFields.customerCode?.trim() || '';
|
const customerCode = customFields.customerCode?.trim() || '';
|
||||||
const sourceCol = customFields.source?.trim() || '';
|
// ایمپورت اکسل فقط با کد مبدأ واقعی دیدار برچسب «دیدار» میگیرد؛
|
||||||
const importSource = didarId
|
// cuid داخلی یا ستون «منبع اطلاعات» باعث دیدار شدن نمیشود.
|
||||||
? 'didar'
|
if (didarId) customFields.didarId = didarId;
|
||||||
: sourceCol
|
else delete customFields.didarId;
|
||||||
? normalizePersonImportSource(sourceCol)
|
const importSource = didarId ? 'didar' : 'excel';
|
||||||
: 'excel';
|
|
||||||
const sourceRef = didarId || customerCode || null;
|
const sourceRef = didarId || customerCode || null;
|
||||||
const groupIds = await this.groups.idsForNames(actor.organizationId, groupNames);
|
const groupIds = await this.groups.idsForNames(actor.organizationId, groupNames);
|
||||||
|
|
||||||
@@ -691,7 +693,7 @@ export class ContactsExcelService {
|
|||||||
else ownerMissing = true;
|
else ownerMissing = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const didarId = row.didarId?.trim() || '';
|
const didarId = resolveDidarSourceRef(row.didarId) || '';
|
||||||
const customFields: Record<string, string> = {};
|
const customFields: Record<string, string> = {};
|
||||||
const visibility = row.visibility?.trim();
|
const visibility = row.visibility?.trim();
|
||||||
if (visibility) customFields.visibility = visibility;
|
if (visibility) customFields.visibility = visibility;
|
||||||
@@ -800,7 +802,7 @@ export class ContactsExcelService {
|
|||||||
didarId?: string,
|
didarId?: string,
|
||||||
phone?: string,
|
phone?: string,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const ref = didarId?.trim() || '';
|
const ref = resolveDidarSourceRef(didarId) || '';
|
||||||
if (ref) {
|
if (ref) {
|
||||||
const byRef = await this.prisma.company.findFirst({
|
const byRef = await this.prisma.company.findFirst({
|
||||||
where: {
|
where: {
|
||||||
|
|||||||
@@ -29,6 +29,20 @@ export function personImportSourceLabel(source: string): string {
|
|||||||
return source || PERSON_IMPORT_SOURCE_LABELS.manual;
|
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 = {
|
type SourceSnapshot = {
|
||||||
importSource?: string | null;
|
importSource?: string | null;
|
||||||
sourceRef?: string | null;
|
sourceRef?: string | null;
|
||||||
@@ -40,8 +54,10 @@ type SourceSnapshot = {
|
|||||||
function didarIdFrom(customFields: unknown): string | null {
|
function didarIdFrom(customFields: unknown): string | null {
|
||||||
if (!customFields || typeof customFields !== 'object') return null;
|
if (!customFields || typeof customFields !== 'object') return null;
|
||||||
const raw = (customFields as Record<string, unknown>).didarId;
|
const raw = (customFields as Record<string, unknown>).didarId;
|
||||||
if (typeof raw === 'number' && Number.isFinite(raw)) return String(raw);
|
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
||||||
if (typeof raw === 'string' && raw.trim()) return raw.trim();
|
return resolveDidarSourceRef(String(raw));
|
||||||
|
}
|
||||||
|
if (typeof raw === 'string') return resolveDidarSourceRef(raw);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,10 +61,11 @@ function parseTags(raw?: string) {
|
|||||||
.slice(0, 20);
|
.slice(0, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** کدهای دیدار: «0» و خالی یعنی بدون کد */
|
/** کدهای دیدار: «0»، خالی، و cuid داخلی یعنی بدون کد مبدأ واقعی */
|
||||||
function cleanCode(raw?: string): string {
|
function cleanCode(raw?: string): string {
|
||||||
const v = toAsciiDigits(raw ?? '').trim();
|
const v = toAsciiDigits(raw ?? '').trim();
|
||||||
if (!v || /^0+$/.test(v)) return '';
|
if (!v || /^0+$/.test(v)) return '';
|
||||||
|
if (/^c[a-z0-9]{20,32}$/i.test(v)) return '';
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,9 +127,18 @@ export class DealsExcelService {
|
|||||||
lastName: true,
|
lastName: true,
|
||||||
mobile: true,
|
mobile: true,
|
||||||
sourceRef: 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 } },
|
owner: { select: { fullName: true } },
|
||||||
createdBy: { select: { fullName: true } },
|
createdBy: { select: { fullName: true } },
|
||||||
pipeline: { select: { name: true } },
|
pipeline: { select: { name: true } },
|
||||||
@@ -157,7 +167,7 @@ export class DealsExcelService {
|
|||||||
const extra = asCustomFields(row.customFields);
|
const extra = asCustomFields(row.customFields);
|
||||||
const base: Record<string, string | number | null> = {
|
const base: Record<string, string | number | null> = {
|
||||||
_type: 'Deal',
|
_type: 'Deal',
|
||||||
didarId: row.sourceRef ?? row.id,
|
didarId: row.importSource === 'didar' ? row.sourceRef || '' : '',
|
||||||
code: row.code ?? '',
|
code: row.code ?? '',
|
||||||
title: row.title,
|
title: row.title,
|
||||||
amount: row.amount == null ? 0 : Number(row.amount),
|
amount: row.amount == null ? 0 : Number(row.amount),
|
||||||
@@ -181,10 +191,12 @@ export class DealsExcelService {
|
|||||||
stageName: row.stage.name,
|
stageName: row.stage.name,
|
||||||
personFirstName: row.person?.firstName ?? '',
|
personFirstName: row.person?.firstName ?? '',
|
||||||
personName: row.person?.lastName ?? '',
|
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 ?? '',
|
personMobile: row.person?.mobile ?? '',
|
||||||
companyName: row.company?.name ?? '',
|
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 ?? '',
|
companyPhone: row.company?.phone ?? '',
|
||||||
};
|
};
|
||||||
for (const d of defs) {
|
for (const d of defs) {
|
||||||
|
|||||||
@@ -3,7 +3,19 @@ import { Cron } from '@nestjs/schedule';
|
|||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import ExcelJS from 'exceljs';
|
import ExcelJS from 'exceljs';
|
||||||
import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
||||||
|
import {
|
||||||
|
addJalaliMonths,
|
||||||
|
dateToJalali,
|
||||||
|
endOfJalaliMonth,
|
||||||
|
formatTehranJalali,
|
||||||
|
jalaliMonthKey,
|
||||||
|
jalaliMonthName,
|
||||||
|
startOfJalaliMonth,
|
||||||
|
} from '../common/jalali';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
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 type { Actor } from '../common/record-scope';
|
||||||
import { invoiceSalesInPeriod } from './invoice-ledger';
|
import { invoiceSalesInPeriod } from './invoice-ledger';
|
||||||
|
|
||||||
@@ -22,6 +34,46 @@ function parseDate(iso?: string | null) {
|
|||||||
const d = new Date(iso);
|
const d = new Date(iso);
|
||||||
return Number.isNaN(d.getTime()) ? null : d;
|
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) {
|
function payrollStatus(payable: Prisma.Decimal, paid: Prisma.Decimal) {
|
||||||
if (paid.lessThanOrEqualTo(0)) return 'open';
|
if (paid.lessThanOrEqualTo(0)) return 'open';
|
||||||
if (paid.greaterThanOrEqualTo(payable)) return 'settled';
|
if (paid.greaterThanOrEqualTo(payable)) return 'settled';
|
||||||
@@ -41,7 +93,11 @@ function addInterval(date: Date, interval: string) {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class TreasuryOpsService {
|
export class TreasuryOpsService {
|
||||||
private readonly logger = new Logger(TreasuryOpsService.name);
|
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) {
|
async listPayroll(actor: Actor) {
|
||||||
const rows = await this.prisma.financialPayroll.findMany({
|
const rows = await this.prisma.financialPayroll.findMany({
|
||||||
@@ -301,8 +357,13 @@ export class TreasuryOpsService {
|
|||||||
kind: row.kind,
|
kind: row.kind,
|
||||||
amount: money(row.amount),
|
amount: money(row.amount),
|
||||||
interval: row.interval,
|
interval: row.interval,
|
||||||
|
startDate: row.startDate.toISOString(),
|
||||||
nextDue: row.nextDue.toISOString(),
|
nextDue: row.nextDue.toISOString(),
|
||||||
isActive: row.isActive,
|
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;
|
endDate?: string | null;
|
||||||
accountId?: string | null;
|
accountId?: string | null;
|
||||||
categoryId?: string | null;
|
categoryId?: string | null;
|
||||||
|
reminderDaysBefore?: number | null;
|
||||||
|
reminderRepeatDaily?: boolean;
|
||||||
|
reminderNotifyApp?: boolean;
|
||||||
|
reminderNotifySms?: boolean;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const amount = dec(input.amount);
|
const amount = dec(input.amount);
|
||||||
@@ -324,6 +389,7 @@ export class TreasuryOpsService {
|
|||||||
throw new BadRequestException('عنوان و مبلغ تکرارشونده لازم است.');
|
throw new BadRequestException('عنوان و مبلغ تکرارشونده لازم است.');
|
||||||
}
|
}
|
||||||
const start = parseDate(input.startDate) ?? new Date();
|
const start = parseDate(input.startDate) ?? new Date();
|
||||||
|
const reminderDaysBefore = normalizeReminderDays(input.reminderDaysBefore);
|
||||||
const row = await this.prisma.financialRecurringItem.create({
|
const row = await this.prisma.financialRecurringItem.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
@@ -337,11 +403,178 @@ export class TreasuryOpsService {
|
|||||||
accountId: input.accountId || null,
|
accountId: input.accountId || null,
|
||||||
categoryId: input.categoryId || null,
|
categoryId: input.categoryId || null,
|
||||||
createdById: actor.userId,
|
createdById: actor.userId,
|
||||||
|
reminderDaysBefore,
|
||||||
|
reminderRepeatDaily: input.reminderRepeatDaily !== false,
|
||||||
|
reminderNotifyApp: input.reminderNotifyApp !== false,
|
||||||
|
reminderNotifySms: input.reminderNotifySms !== false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return { id: row.id };
|
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 * * *')
|
@Cron('30 8 * * *')
|
||||||
async spawnRecurring() {
|
async spawnRecurring() {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -381,7 +614,11 @@ export class TreasuryOpsService {
|
|||||||
}
|
}
|
||||||
await this.prisma.financialRecurringItem.update({
|
await this.prisma.financialRecurringItem.update({
|
||||||
where: { id: item.id },
|
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}`);
|
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) {
|
async report(actor: Actor, fromIso?: string, toIso?: string) {
|
||||||
const to = parseDate(toIso) ?? new Date();
|
const now = new Date();
|
||||||
const from = parseDate(fromIso) ?? new Date(to.getFullYear(), to.getMonth(), 1);
|
const jalaliNow = dateToJalali(now);
|
||||||
const span = to.getTime() - from.getTime();
|
const to = endOfDay(parseDay(toIso) ?? now);
|
||||||
const prevTo = new Date(from.getTime() - 1);
|
const from = startOfDay(
|
||||||
const prevFrom = new Date(prevTo.getTime() - span);
|
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 current = await this.period(actor.organizationId, from, to);
|
||||||
const previous = await this.period(actor.organizationId, prevFrom, prevTo);
|
const previous = await this.period(actor.organizationId, prevFrom, prevTo);
|
||||||
const breakdown = await this.breakdown(actor.organizationId);
|
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(
|
async reportExcel(
|
||||||
@@ -469,6 +723,15 @@ export class TreasuryOpsService {
|
|||||||
const data = await this.report(actor, from, to);
|
const data = await this.report(actor, from, to);
|
||||||
const book = new ExcelJS.Workbook();
|
const book = new ExcelJS.Workbook();
|
||||||
const sheet = book.addWorksheet('گزارش مالی');
|
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(['شاخص', 'این دوره', 'دوره قبل']);
|
sheet.addRow(['شاخص', 'این دوره', 'دوره قبل']);
|
||||||
const rows: Array<[string, string, string]> = [
|
const rows: Array<[string, string, string]> = [
|
||||||
['درآمد ثبتشده', data.current.bookedIncome, data.previous.bookedIncome],
|
['درآمد ثبتشده', data.current.bookedIncome, data.previous.bookedIncome],
|
||||||
@@ -591,7 +854,7 @@ export class TreasuryOpsService {
|
|||||||
]);
|
]);
|
||||||
const payablesByMonth = new Map<string, Prisma.Decimal>();
|
const payablesByMonth = new Map<string, Prisma.Decimal>();
|
||||||
const addMonth = (date: Date, amount: Prisma.Decimal) => {
|
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));
|
payablesByMonth.set(key, (payablesByMonth.get(key) ?? new Prisma.Decimal(0)).plus(amount));
|
||||||
};
|
};
|
||||||
for (const doc of docs) {
|
for (const doc of docs) {
|
||||||
@@ -611,8 +874,17 @@ export class TreasuryOpsService {
|
|||||||
receivablesByParty.set(name, (receivablesByParty.get(name) ?? new Prisma.Decimal(0)).plus(left));
|
receivablesByParty.set(name, (receivablesByParty.get(name) ?? new Prisma.Decimal(0)).plus(left));
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
payablesByMonth: [...payablesByMonth.entries()].map(([month, amount]) => ({ month, amount: money(amount) })),
|
payablesByMonth: [...payablesByMonth.entries()]
|
||||||
receivablesByParty: [...receivablesByParty.entries()].map(([name, amount]) => ({ name, amount: money(amount) })),
|
.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),
|
||||||
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -323,6 +323,15 @@ export class TreasuryController {
|
|||||||
return this.ops.createRecurring(user, body);
|
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')
|
@Get('reports')
|
||||||
report(
|
report(
|
||||||
@CurrentUser() user: Actor,
|
@CurrentUser() user: Actor,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
|||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
import { ContactsModule } from '../contacts/contacts.module';
|
import { ContactsModule } from '../contacts/contacts.module';
|
||||||
import { NotificationsModule } from '../notifications/notifications.module';
|
import { NotificationsModule } from '../notifications/notifications.module';
|
||||||
|
import { SmsBillingModule } from '../sms-billing/sms-billing.module';
|
||||||
import { TreasuryController } from './treasury.controller';
|
import { TreasuryController } from './treasury.controller';
|
||||||
import { TreasuryAccessGuard } from './treasury-access.guard';
|
import { TreasuryAccessGuard } from './treasury-access.guard';
|
||||||
import { TreasuryBridgeService } from './treasury-bridge.service';
|
import { TreasuryBridgeService } from './treasury-bridge.service';
|
||||||
@@ -10,7 +11,7 @@ import { TreasuryReceivablesService } from './treasury-receivables.service';
|
|||||||
import { TreasuryService } from './treasury.service';
|
import { TreasuryService } from './treasury.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [AuthModule, NotificationsModule, ContactsModule],
|
imports: [AuthModule, NotificationsModule, ContactsModule, SmsBillingModule],
|
||||||
controllers: [TreasuryController],
|
controllers: [TreasuryController],
|
||||||
providers: [
|
providers: [
|
||||||
TreasuryService,
|
TreasuryService,
|
||||||
|
|||||||
Reference in New Issue
Block a user