Add owner reminders for recurring treasury patterns with once-or-daily cadence.
Co-authored-by: Cursor <cursoragent@cursor.com>
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;
|
||||
@@ -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
|
||||
|
||||
@@ -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,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,
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Button as AButton,
|
||||
Card as ACard,
|
||||
Checkbox as ACheckbox,
|
||||
Col as ACol,
|
||||
Divider as ADivider,
|
||||
Empty as AEmpty,
|
||||
Flex as AFlex,
|
||||
Form as AForm,
|
||||
FormItem as AFormItem,
|
||||
Input as AInput,
|
||||
List as AList,
|
||||
Modal as AModal,
|
||||
Row as ARow,
|
||||
Select as ASelect,
|
||||
Space as ASpace,
|
||||
Switch as ASwitch,
|
||||
Tag as ATag,
|
||||
Typography,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
import { EditOutlined, PlusOutlined } from '@ant-design/icons-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
@@ -25,14 +30,12 @@ import TreasuryListPagination from '@/components/treasury/TreasuryListPagination
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryListPaging } from './useTreasuryListPaging';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
import { formatJalaliNumeric } from '@/lib/jalali';
|
||||
import { formatJalaliNumeric, formatLocalDateInput, toFaDigits } from '@/lib/jalali';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ASelectOption = ASelect.Option;
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
@@ -40,13 +43,94 @@ type Row = {
|
||||
kind: string;
|
||||
amount: string;
|
||||
interval: string;
|
||||
startDate: string;
|
||||
nextDue: string;
|
||||
isActive: boolean;
|
||||
reminderDaysBefore: number | null;
|
||||
reminderRepeatDaily: boolean;
|
||||
reminderNotifyApp: boolean;
|
||||
reminderNotifySms: boolean;
|
||||
};
|
||||
|
||||
type FormState = {
|
||||
title: string;
|
||||
kind: string;
|
||||
amount: string;
|
||||
interval: string;
|
||||
dueDate: string;
|
||||
reminderDaysBefore: string;
|
||||
reminderRepeatDaily: string;
|
||||
reminderNotifyApp: boolean;
|
||||
reminderNotifySms: boolean;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
const REMINDER_DAY_OPTIONS = [
|
||||
{ value: '', label: 'بدون یادآور' },
|
||||
{ value: '0', label: 'روز سررسید' },
|
||||
{ value: '1', label: '۱ روز قبل' },
|
||||
{ value: '2', label: '۲ روز قبل' },
|
||||
{ value: '3', label: '۳ روز قبل' },
|
||||
{ value: '5', label: '۵ روز قبل' },
|
||||
{ value: '7', label: '۷ روز قبل' },
|
||||
];
|
||||
|
||||
const REMINDER_FREQ_OPTIONS = [
|
||||
{ value: 'once', label: 'فقط یکبار' },
|
||||
{ value: 'daily', label: 'هر روز تا سررسید' },
|
||||
];
|
||||
|
||||
const INTERVAL_LABEL: Record<string, string> = {
|
||||
weekly: 'هفتگی',
|
||||
monthly: 'ماهانه',
|
||||
yearly: 'سالانه',
|
||||
};
|
||||
|
||||
function emptyForm(): FormState {
|
||||
return {
|
||||
title: '',
|
||||
kind: 'expense',
|
||||
amount: '',
|
||||
interval: 'monthly',
|
||||
dueDate: '',
|
||||
reminderDaysBefore: '3',
|
||||
reminderRepeatDaily: 'once',
|
||||
reminderNotifyApp: true,
|
||||
reminderNotifySms: true,
|
||||
isActive: true,
|
||||
};
|
||||
}
|
||||
|
||||
function reminderToSelect(days: number | null | undefined) {
|
||||
return days == null ? '' : String(days);
|
||||
}
|
||||
function reminderFromSelect(value: string) {
|
||||
return value === '' ? null : Number(value);
|
||||
}
|
||||
function freqToSelect(daily: boolean | undefined) {
|
||||
return daily === false ? 'once' : 'daily';
|
||||
}
|
||||
function freqFromSelect(value: string) {
|
||||
return value === 'daily';
|
||||
}
|
||||
|
||||
function reminderLabel(days: number | null | undefined, daily: boolean | undefined) {
|
||||
if (days == null) return 'بدون یادآور';
|
||||
const when = days === 0 ? 'روز سررسید' : `${toFaDigits(days)} روز قبل`;
|
||||
if (days === 0) return when;
|
||||
return daily === false ? `${when} · یکبار` : `${when} · هر روز`;
|
||||
}
|
||||
|
||||
const isMobile = useTreasuryMobile();
|
||||
const rows = ref<Row[]>([]);
|
||||
const error = ref('');
|
||||
const ok = ref('');
|
||||
const saving = ref(false);
|
||||
const createOpen = ref(false);
|
||||
const editOpen = ref(false);
|
||||
const editingId = ref<string | null>(null);
|
||||
const createForm = ref(emptyForm());
|
||||
const editForm = ref(emptyForm());
|
||||
|
||||
const {
|
||||
page,
|
||||
pageSize,
|
||||
@@ -56,39 +140,125 @@ const {
|
||||
onPageSizeChange,
|
||||
showTotal,
|
||||
} = useTreasuryListPaging(() => rows.value, 'treasury.recurring');
|
||||
const form = ref({ title: '', kind: 'expense', amount: '', interval: 'monthly', startDate: '' });
|
||||
|
||||
const createReminderEnabled = computed(() => createForm.value.reminderDaysBefore !== '');
|
||||
const editReminderEnabled = computed(() => editForm.value.reminderDaysBefore !== '');
|
||||
const modalWidth = computed(() => (isMobile.value ? '100%' : 720));
|
||||
|
||||
async function load() {
|
||||
const { data } = await api.get<Row[]>('/treasury/recurring');
|
||||
rows.value = data;
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
error.value = '';
|
||||
createForm.value = emptyForm();
|
||||
createOpen.value = true;
|
||||
}
|
||||
|
||||
function openEdit(item: Row) {
|
||||
error.value = '';
|
||||
editingId.value = item.id;
|
||||
editForm.value = {
|
||||
title: item.title,
|
||||
kind: item.kind,
|
||||
amount: String(item.amount ?? ''),
|
||||
interval: item.interval,
|
||||
dueDate: formatLocalDateInput(new Date(item.nextDue)),
|
||||
reminderDaysBefore: reminderToSelect(item.reminderDaysBefore),
|
||||
reminderRepeatDaily: freqToSelect(item.reminderRepeatDaily),
|
||||
reminderNotifyApp: item.reminderNotifyApp,
|
||||
reminderNotifySms: item.reminderNotifySms,
|
||||
isActive: item.isActive,
|
||||
};
|
||||
editOpen.value = true;
|
||||
}
|
||||
|
||||
function reminderPayload(form: FormState) {
|
||||
const days = reminderFromSelect(form.reminderDaysBefore);
|
||||
return {
|
||||
reminderDaysBefore: days,
|
||||
reminderRepeatDaily: days == null ? true : freqFromSelect(form.reminderRepeatDaily),
|
||||
reminderNotifyApp: days == null ? false : form.reminderNotifyApp,
|
||||
reminderNotifySms: days == null ? false : form.reminderNotifySms,
|
||||
};
|
||||
}
|
||||
|
||||
function onFinishFailed() {
|
||||
message.warning('لطفاً فیلدهای الزامی را کامل کنید.');
|
||||
}
|
||||
|
||||
async function createItem() {
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
saving.value = true;
|
||||
try {
|
||||
const amount = parseMoneyNumber(String(form.value.amount ?? ''), 0);
|
||||
if (!createForm.value.title.trim()) {
|
||||
error.value = 'عنوان الزامی است.';
|
||||
throw new Error(error.value);
|
||||
}
|
||||
const amount = parseMoneyNumber(String(createForm.value.amount ?? ''), 0);
|
||||
if (amount == null || amount <= 0) {
|
||||
error.value = 'مبلغ معتبر نیست.';
|
||||
return;
|
||||
throw new Error(error.value);
|
||||
}
|
||||
await api.post('/treasury/recurring', {
|
||||
...form.value,
|
||||
title: createForm.value.title,
|
||||
kind: createForm.value.kind,
|
||||
amount,
|
||||
startDate: form.value.startDate || undefined,
|
||||
interval: createForm.value.interval,
|
||||
startDate: createForm.value.dueDate || undefined,
|
||||
...reminderPayload(createForm.value),
|
||||
});
|
||||
form.value = { title: '', kind: 'expense', amount: '', interval: 'monthly', startDate: '' };
|
||||
ok.value = 'الگو ثبت شد. در سررسید فقط سند باز ساخته میشود.';
|
||||
createOpen.value = false;
|
||||
createForm.value = emptyForm();
|
||||
message.success('الگو ثبت شد.');
|
||||
await load();
|
||||
} catch (e) {
|
||||
if (!error.value) {
|
||||
error.value = axios.isAxiosError(e)
|
||||
? String((e.response?.data as { message?: string })?.message ?? 'ثبت ناموفق بود.')
|
||||
: 'ثبت ناموفق بود.';
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveEdit() {
|
||||
if (!editingId.value) return;
|
||||
error.value = '';
|
||||
saving.value = true;
|
||||
try {
|
||||
if (!editForm.value.title.trim()) {
|
||||
error.value = 'عنوان الزامی است.';
|
||||
throw new Error(error.value);
|
||||
}
|
||||
const amount = parseMoneyNumber(String(editForm.value.amount ?? ''), 0);
|
||||
if (amount == null || amount <= 0) {
|
||||
error.value = 'مبلغ معتبر نیست.';
|
||||
throw new Error(error.value);
|
||||
}
|
||||
await api.patch(`/treasury/recurring/${editingId.value}`, {
|
||||
title: editForm.value.title,
|
||||
kind: editForm.value.kind,
|
||||
amount,
|
||||
interval: editForm.value.interval,
|
||||
nextDue: editForm.value.dueDate || undefined,
|
||||
isActive: editForm.value.isActive,
|
||||
...reminderPayload(editForm.value),
|
||||
});
|
||||
editOpen.value = false;
|
||||
editingId.value = null;
|
||||
message.success('الگو ذخیره شد.');
|
||||
await load();
|
||||
} catch (e) {
|
||||
if (!error.value) {
|
||||
error.value = axios.isAxiosError(e)
|
||||
? String((e.response?.data as { message?: string })?.message ?? 'ذخیره ناموفق بود.')
|
||||
: 'ذخیره ناموفق بود.';
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
@@ -101,78 +271,61 @@ onMounted(() => {
|
||||
|
||||
<template>
|
||||
<a-flex vertical :gap="16">
|
||||
<a-alert v-if="error" type="error" show-icon :message="error" />
|
||||
<a-alert v-if="ok" type="success" show-icon :message="ok" />
|
||||
<a-alert v-if="error && !createOpen && !editOpen" type="error" show-icon :message="error" />
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-divider orientation="right">الگوی جدید</a-divider>
|
||||
<a-form
|
||||
layout="vertical"
|
||||
:model="form"
|
||||
@finish="createItem"
|
||||
@finishFailed="onFinishFailed"
|
||||
>
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item
|
||||
label="عنوان"
|
||||
name="title"
|
||||
:rules="[{ required: true, message: 'عنوان الزامی است' }]"
|
||||
>
|
||||
<a-input v-model:value="form.title" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="نوع" name="kind" :rules="[{ required: true }]">
|
||||
<a-select show-search option-filter-prop="label" v-model:value="form.kind" style="width: 100%">
|
||||
<a-select-option value="expense" label="هزینه">هزینه</a-select-option>
|
||||
<a-select-option value="income" label="درآمد">درآمد</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item
|
||||
label="مبلغ"
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
|
||||
>
|
||||
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="دوره" name="interval" :rules="[{ required: true }]">
|
||||
<a-select show-search option-filter-prop="label" v-model:value="form.interval" style="width: 100%">
|
||||
<a-select-option value="monthly" label="ماهانه">ماهانه</a-select-option>
|
||||
<a-select-option value="weekly" label="هفتگی">هفتگی</a-select-option>
|
||||
<a-select-option value="yearly" label="سالانه">سالانه</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="شروع" name="startDate">
|
||||
<JalaliDateInput v-model="form.startDate" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
<a-button type="primary" html-type="submit" :loading="saving">ثبت الگو</a-button>
|
||||
</a-form>
|
||||
<a-flex justify="space-between" align="center" :gap="12" wrap="wrap" style="margin-bottom: 16px">
|
||||
<a-typography-text strong>فهرست الگوها</a-typography-text>
|
||||
<a-button type="primary" @click="openCreate">
|
||||
<template #icon><PlusOutlined /></template>
|
||||
الگوی جدید
|
||||
</a-button>
|
||||
</a-flex>
|
||||
|
||||
<a-divider orientation="right">فهرست الگوها</a-divider>
|
||||
<a-empty v-if="!rows.length" description="الگویی ثبت نشده است." />
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedRows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
<a-button type="link" @click="openEdit(item)">
|
||||
<template #icon><EditOutlined /></template>
|
||||
ویرایش
|
||||
</a-button>
|
||||
</template>
|
||||
<a-list-item-meta>
|
||||
<template #title>{{ item.title }}</template>
|
||||
<template #title>
|
||||
<a-flex :gap="8" align="center" wrap="wrap">
|
||||
<span>{{ item.title }}</span>
|
||||
<a-tag v-if="!item.isActive" color="default">غیرفعال</a-tag>
|
||||
</a-flex>
|
||||
</template>
|
||||
<template #description>
|
||||
<a-flex vertical :gap="4">
|
||||
<a-typography-text type="secondary">
|
||||
{{ item.kind === 'income' ? 'درآمد' : 'هزینه' }}
|
||||
· {{ item.interval }}
|
||||
· {{ INTERVAL_LABEL[item.interval] || item.interval }}
|
||||
· بعدی {{ formatJalaliNumeric(new Date(item.nextDue)) }}
|
||||
</a-typography-text>
|
||||
<a-typography-text type="secondary">
|
||||
{{ reminderLabel(item.reminderDaysBefore, item.reminderRepeatDaily) }}
|
||||
<template v-if="item.reminderDaysBefore != null">
|
||||
·
|
||||
{{
|
||||
[
|
||||
item.reminderNotifyApp ? 'ناتیف' : null,
|
||||
item.reminderNotifySms ? 'پیامک' : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' و ') || 'بدون کانال'
|
||||
}}
|
||||
</template>
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
</template>
|
||||
</a-list-item-meta>
|
||||
<div>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
</div>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
@@ -185,5 +338,185 @@ onMounted(() => {
|
||||
@update:page-size="onPageSizeChange"
|
||||
/>
|
||||
</a-card>
|
||||
|
||||
<a-modal
|
||||
v-model:open="createOpen"
|
||||
title="الگوی جدید"
|
||||
ok-text="ثبت الگو"
|
||||
cancel-text="انصراف"
|
||||
:confirm-loading="saving"
|
||||
:width="modalWidth"
|
||||
:centered="isMobile"
|
||||
destroy-on-close
|
||||
@ok="createItem"
|
||||
>
|
||||
<a-alert v-if="error && createOpen" type="error" show-icon :message="error" style="margin-bottom: 12px" />
|
||||
<a-form layout="vertical" :model="createForm" @finish="createItem" @finishFailed="onFinishFailed">
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="عنوان" name="title" :rules="[{ required: true, message: 'عنوان الزامی است' }]">
|
||||
<a-input v-model:value="createForm.title" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="نوع" name="kind" :rules="[{ required: true }]">
|
||||
<a-select
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
v-model:value="createForm.kind"
|
||||
style="width: 100%"
|
||||
>
|
||||
<a-select-option value="expense" label="هزینه">هزینه</a-select-option>
|
||||
<a-select-option value="income" label="درآمد">درآمد</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="مبلغ" name="amount" :rules="[{ required: true, message: 'مبلغ الزامی است' }]">
|
||||
<MoneyInput addon-after="تومان" v-model="createForm.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="دوره" name="interval" :rules="[{ required: true }]">
|
||||
<a-select
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
v-model:value="createForm.interval"
|
||||
style="width: 100%"
|
||||
>
|
||||
<a-select-option value="monthly" label="ماهانه">ماهانه</a-select-option>
|
||||
<a-select-option value="weekly" label="هفتگی">هفتگی</a-select-option>
|
||||
<a-select-option value="yearly" label="سالانه">سالانه</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="شروع / سررسید بعدی" name="dueDate">
|
||||
<JalaliDateInput v-model="createForm.dueDate" style="width: 100%" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="زمان یادآور">
|
||||
<a-select
|
||||
v-model:value="createForm.reminderDaysBefore"
|
||||
style="width: 100%"
|
||||
:options="REMINDER_DAY_OPTIONS"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="createReminderEnabled" :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="تکرار یادآور">
|
||||
<a-select
|
||||
v-model:value="createForm.reminderRepeatDaily"
|
||||
style="width: 100%"
|
||||
:options="REMINDER_FREQ_OPTIONS"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="createReminderEnabled" :span="24">
|
||||
<a-form-item label="کانال یادآور">
|
||||
<a-space :size="24" wrap>
|
||||
<a-checkbox v-model:checked="createForm.reminderNotifyApp">ناتیفیکیشن</a-checkbox>
|
||||
<a-checkbox v-model:checked="createForm.reminderNotifySms">پیامک</a-checkbox>
|
||||
</a-space>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
<a-typography-text type="secondary">
|
||||
مثلاً «۲ روز قبل · فقط یکبار»: یک پیام در همان روز؛ «۳ روز قبل · هر روز»: هر روز تا سررسید برای مالک.
|
||||
</a-typography-text>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
|
||||
<a-modal
|
||||
v-model:open="editOpen"
|
||||
title="ویرایش الگو"
|
||||
ok-text="ذخیره"
|
||||
cancel-text="انصراف"
|
||||
:confirm-loading="saving"
|
||||
:width="modalWidth"
|
||||
:centered="isMobile"
|
||||
destroy-on-close
|
||||
@ok="saveEdit"
|
||||
>
|
||||
<a-alert v-if="error && editOpen" type="error" show-icon :message="error" style="margin-bottom: 12px" />
|
||||
<a-form layout="vertical" :model="editForm" @finish="saveEdit" @finishFailed="onFinishFailed">
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="عنوان" name="title" :rules="[{ required: true, message: 'عنوان الزامی است' }]">
|
||||
<a-input v-model:value="editForm.title" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="نوع" name="kind" :rules="[{ required: true }]">
|
||||
<a-select
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
v-model:value="editForm.kind"
|
||||
style="width: 100%"
|
||||
>
|
||||
<a-select-option value="expense" label="هزینه">هزینه</a-select-option>
|
||||
<a-select-option value="income" label="درآمد">درآمد</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="مبلغ" name="amount" :rules="[{ required: true, message: 'مبلغ الزامی است' }]">
|
||||
<MoneyInput addon-after="تومان" v-model="editForm.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="دوره" name="interval" :rules="[{ required: true }]">
|
||||
<a-select
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
v-model:value="editForm.interval"
|
||||
style="width: 100%"
|
||||
>
|
||||
<a-select-option value="monthly" label="ماهانه">ماهانه</a-select-option>
|
||||
<a-select-option value="weekly" label="هفتگی">هفتگی</a-select-option>
|
||||
<a-select-option value="yearly" label="سالانه">سالانه</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="سررسید بعدی" name="dueDate">
|
||||
<JalaliDateInput v-model="editForm.dueDate" style="width: 100%" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="زمان یادآور">
|
||||
<a-select
|
||||
v-model:value="editForm.reminderDaysBefore"
|
||||
style="width: 100%"
|
||||
:options="REMINDER_DAY_OPTIONS"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="editReminderEnabled" :xs="24" :sm="12" :md="8">
|
||||
<a-form-item label="تکرار یادآور">
|
||||
<a-select
|
||||
v-model:value="editForm.reminderRepeatDaily"
|
||||
style="width: 100%"
|
||||
:options="REMINDER_FREQ_OPTIONS"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="editReminderEnabled" :span="24">
|
||||
<a-form-item label="کانال یادآور">
|
||||
<a-space :size="24" wrap>
|
||||
<a-checkbox v-model:checked="editForm.reminderNotifyApp">ناتیفیکیشن</a-checkbox>
|
||||
<a-checkbox v-model:checked="editForm.reminderNotifySms">پیامک</a-checkbox>
|
||||
</a-space>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :span="24">
|
||||
<a-form-item label="فعال">
|
||||
<a-switch v-model:checked="editForm.isActive" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
</a-flex>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user