feat: add invoice builder with line detail, address, and person picker.

Enrich invoice line items and previews, migrate several CRM surfaces to Ant, and wire shared money/picker helpers.
This commit is contained in:
2026-11-30 14:34:47 +03:30
parent f1bcb232ee
commit 33c95d72a8
64 changed files with 5813 additions and 2737 deletions
+2 -2
View File
@@ -23,7 +23,7 @@ Legacy CRM UI (`components/ui/*`, `.crm-*`, `.btn` / `.field` in `styles/`) rema
**No raw** `<input>`, `<select>`, `<textarea>`, or `<button>` may remain in the View **or** in those consumed child components. Prefer native Ant equivalents (`a-select` / `mode="multiple|tags"` / `a-time-picker` / …) over custom pickers when logic allows; if domain logic is required (e.g. Jalali), convert that child file to Ant chrome (`a-input` + `a-popover`, etc.) instead of leaving raw HTML. Do **not** leave legacy `UiInput` / `UiSelect` / `UiButton` / `UiField` / `UiTextarea` in the View or those children. **No raw** `<input>`, `<select>`, `<textarea>`, or `<button>` may remain in the View **or** in those consumed child components. Prefer native Ant equivalents (`a-select` / `mode="multiple|tags"` / `a-time-picker` / …) over custom pickers when logic allows; if domain logic is required (e.g. Jalali), convert that child file to Ant chrome (`a-input` + `a-popover`, etc.) instead of leaving raw HTML. Do **not** leave legacy `UiInput` / `UiSelect` / `UiButton` / `UiField` / `UiTextarea` in the View or those children.
3. **Ant-only UI on migrated pages** 3. **Ant-only UI on migrated pages**
On a migrated page, build controls with Ant Design Vue (`a-button`, `a-form`, `a-table`, `a-card`, …) and `@ant-design/icons-vue`. Do **not** introduce new usage of `UiButton`, `UiInput`, `.btn`, `.field`, or ad-hoc HTML form controls for the same job. On a migrated page, build controls with Ant Design Vue (`a-button`, `a-form`, `a-table`, `a-card`, …) and icons via `@/icons/ant-bridge` (Vuesax glyphs behind Ant-shaped `*Outlined` names). Do **not** import `@ant-design/icons-vue` directly. Do **not** introduce new usage of `UiButton`, `UiInput`, `.btn`, `.field`, or ad-hoc HTML form controls for the same job.
4. **Ban manual CSS for layout/look** 4. **Ban manual CSS for layout/look**
On migrated pages: On migrated pages:
@@ -59,7 +59,7 @@ Legacy CRM UI (`components/ui/*`, `.crm-*`, `.btn` / `.field` in `styles/`) rema
Visual tokens (primary, radius, `controlHeight`, padding/margin scale, shadows, Form/Card overrides) live only in `antdTheme.ts`. Do not fork theme objects inside views. Visual tokens (primary, radius, `controlHeight`, padding/margin scale, shadows, Form/Card overrides) live only in `antdTheme.ts`. Do not fork theme objects inside views.
10. **Icons** 10. **Icons**
Use `@ant-design/icons-vue` on migrated pages. Do not expand `UiIcon` for Ant pages. Canonical pack is **Vuesax linear** (`apps/web/src/icons/vuesax-linear.json`), rendered by `VsIcon`. On migrated pages import Ant-shaped names from `@/icons/ant-bridge` (never `@ant-design/icons-vue`). Legacy `UiIcon` also maps to Vuesax — do not expand it for new Ant pages; use `ant-bridge` instead.
11. **Isolation guarantee** 11. **Isolation guarantee**
Infrastructure PRs (deps, vite plugin, theme, App `ConfigProvider`) must not change behavior of unmigrated pages. No `ant-design-vue/dist/reset.css` (or similar global reset) unless explicitly approved — it can break legacy CSS. Infrastructure PRs (deps, vite plugin, theme, App `ConfigProvider`) must not change behavior of unmigrated pages. No `ant-design-vue/dist/reset.css` (or similar global reset) unless explicitly approved — it can break legacy CSS.
@@ -35,7 +35,8 @@ Also read and obey [`.cursor/rules/antd-strict-governance.mdc`](../../rules/antd
| Piece | Location | | Piece | Location |
|---|---| |---|---|
| Dependency | `ant-design-vue` ^4, `@ant-design/icons-vue`, `unplugin-vue-components` in `@mento/web` | | Dependency | `ant-design-vue` ^4, `@ant-design/icons-vue` (dep only; app code uses bridge), `unplugin-vue-components` in `@mento/web` |
| Icons | Canonical = Vuesax via `@/icons/ant-bridge` (Ant `*Outlined` API → `VsIcon`). Never import `@ant-design/icons-vue` in app code. |
| Vite plugin | `apps/web/vite.config.ts` — `Components` + `AntDesignVueResolver` | | Vite plugin | `apps/web/vite.config.ts` — `Components` + `AntDesignVueResolver` |
| Theme | `apps/web/src/theme/antdTheme.ts` (`controlHeight: 36`) | | Theme | `apps/web/src/theme/antdTheme.ts` (`controlHeight: 36`) |
| RTL + locale + theme + StyleProvider | `apps/web/src/App.vue` — `<a-style-provider hash-priority="high">` wrapping `<a-config-provider direction="rtl" :locale="faIR" :theme="antdTheme">` (mandatory so legacy `main.css` cannot override Ant) | | RTL + locale + theme + StyleProvider | `apps/web/src/App.vue` — `<a-style-provider hash-priority="high">` wrapping `<a-config-provider direction="rtl" :locale="faIR" :theme="antdTheme">` (mandatory so legacy `main.css` cannot override Ant) |
@@ -56,7 +57,7 @@ Also read and obey [`.cursor/rules/antd-strict-governance.mdc`](../../rules/antd
- Modal/Drawer → `a-modal` / `a-drawer` - Modal/Drawer → `a-modal` / `a-drawer`
- Table → `a-table` (columns via Ant API) - Table → `a-table` (columns via Ant API)
- Page chrome → `a-card`, title + `a-space`, layout via `a-row`/`a-col` - Page chrome → `a-card`, title + `a-space`, layout via `a-row`/`a-col`
- Icons → `@ant-design/icons-vue` - Icons → `import { … } from '@/icons/ant-bridge'` (Vuesax; never `@ant-design/icons-vue`)
5. Remove page-local CSS that only existed to skin the old controls. 5. Remove page-local CSS that only existed to skin the old controls.
6. Keep business logic, API calls, and router behavior intact. 6. Keep business logic, API calls, and router behavior intact.
7. Grep-verify zero hits for `<input|<select|<textarea|<button|UiInput|UiSelect|UiField|UiTextarea|UiButton` in the View + converted children. 7. Grep-verify zero hits for `<input|<select|<textarea|<button|UiInput|UiSelect|UiField|UiTextarea|UiButton` in the View + converted children.
@@ -73,6 +74,7 @@ Also read and obey [`.cursor/rules/antd-strict-governance.mdc`](../../rules/antd
## Anti-patterns (reject) ## Anti-patterns (reject)
- Importing both `UiButton` and `a-button` on the same migrated page - Importing both `UiButton` and `a-button` on the same migrated page
- Importing icons from `@ant-design/icons-vue` instead of `@/icons/ant-bridge`
- Adding `ant-design-vue/dist/reset.css` “to fix spacing” - Adding `ant-design-vue/dist/reset.css` “to fix spacing”
- Editing `components/ui` to “look more like Ant” - Editing `components/ui` to “look more like Ant”
- `size="small|middle|large"` on Ant controls - `size="small|middle|large"` on Ant controls
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "InvoiceLineItem" ADD COLUMN "unit" TEXT;
ALTER TABLE "InvoiceLineItem" ADD COLUMN "description" TEXT;
ALTER TABLE "InvoiceLineItem" ADD COLUMN "discountAmount" DECIMAL(18,2) NOT NULL DEFAULT 0;
ALTER TABLE "InvoiceLineItem" ADD COLUMN "taxPercent" DECIMAL(8,2) NOT NULL DEFAULT 0;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Invoice" ADD COLUMN "address" TEXT;
+6
View File
@@ -1357,6 +1357,8 @@ model Invoice {
kind String @default("invoice") // invoice | credit kind String @default("invoice") // invoice | credit
currency String @default("IRR") currency String @default("IRR")
notes String? notes String?
/// آدرس صورتحساب / ارسال
address String?
discountAmount Decimal @default(0) @db.Decimal(18, 2) discountAmount Decimal @default(0) @db.Decimal(18, 2)
taxPercent Decimal @default(0) @db.Decimal(8, 2) taxPercent Decimal @default(0) @db.Decimal(8, 2)
issuedAt DateTime? issuedAt DateTime?
@@ -1399,8 +1401,12 @@ model InvoiceLineItem {
productId String? productId String?
product Product? @relation(fields: [productId], references: [id], onDelete: SetNull) product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
name String name String
unit String?
description String?
quantity Decimal @default(1) @db.Decimal(18, 2) quantity Decimal @default(1) @db.Decimal(18, 2)
unitPrice Decimal @db.Decimal(18, 2) unitPrice Decimal @db.Decimal(18, 2)
discountAmount Decimal @default(0) @db.Decimal(18, 2)
taxPercent Decimal @default(0) @db.Decimal(8, 2)
currency String @default("IRR") currency String @default("IRR")
position Int @default(0) position Int @default(0)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
+7 -4
View File
@@ -60,10 +60,13 @@ export class CommissionsService {
return; return;
} }
const subtotal = invoice.lineItems.reduce( const subtotal = invoice.lineItems.reduce((sum, item) => {
(sum, item) => sum + Number(item.quantity) * Number(item.unitPrice), const gross = Number(item.quantity) * Number(item.unitPrice);
0, const discount = Math.max(0, Number(item.discountAmount ?? 0));
); const net = Math.max(0, gross - discount);
const taxPct = Math.max(0, Number(item.taxPercent ?? 0));
return sum + Math.round((net * (1 + taxPct / 100) + Number.EPSILON) * 100) / 100;
}, 0);
const discountAmount = Number(invoice.discountAmount ?? 0); const discountAmount = Number(invoice.discountAmount ?? 0);
const taxPercent = Number(invoice.taxPercent ?? 0); const taxPercent = Number(invoice.taxPercent ?? 0);
const taxAmount = roundMoney( const taxAmount = roundMoney(
+34
View File
@@ -5,6 +5,7 @@ import {
IsNumber, IsNumber,
IsOptional, IsOptional,
IsString, IsString,
Max,
MaxLength, MaxLength,
Min, Min,
MinLength, MinLength,
@@ -40,6 +41,16 @@ export class InvoiceLineItemInputDto {
@MaxLength(200) @MaxLength(200)
name!: string; name!: string;
@IsOptional()
@IsString()
@MaxLength(40)
unit?: string | null;
@IsOptional()
@IsString()
@MaxLength(2000)
description?: string | null;
@Type(() => Number) @Type(() => Number)
@IsNumber() @IsNumber()
@Min(0.01) @Min(0.01)
@@ -50,6 +61,19 @@ export class InvoiceLineItemInputDto {
@Min(0) @Min(0)
unitPrice!: number; unitPrice!: number;
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
discountAmount?: number;
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
@Max(100)
taxPercent?: number;
@IsOptional() @IsOptional()
@IsString() @IsString()
@MaxLength(8) @MaxLength(8)
@@ -95,6 +119,11 @@ export class CreateInvoiceDto {
@MaxLength(4000) @MaxLength(4000)
notes?: string; notes?: string;
@IsOptional()
@IsString()
@MaxLength(2000)
address?: string;
@IsOptional() @IsOptional()
@Type(() => Number) @Type(() => Number)
@IsNumber() @IsNumber()
@@ -190,6 +219,11 @@ export class UpdateInvoiceDto {
@MaxLength(4000) @MaxLength(4000)
notes?: string | null; notes?: string | null;
@IsOptional()
@IsString()
@MaxLength(2000)
address?: string | null;
@IsOptional() @IsOptional()
@Type(() => Number) @Type(() => Number)
@IsNumber() @IsNumber()
+32 -9
View File
@@ -6,9 +6,9 @@ import {
import type { import type {
CreateInvoiceRequest, CreateInvoiceRequest,
CreatePaymentRequest, CreatePaymentRequest,
DealLineItemInput,
InvoiceDto, InvoiceDto,
InvoiceInstallmentInput, InvoiceInstallmentInput,
InvoiceLineItemInput,
PaginatedResponse, PaginatedResponse,
PaymentDto, PaymentDto,
UpdateInvoiceRequest, UpdateInvoiceRequest,
@@ -23,6 +23,7 @@ import { InventoryService } from '../inventory/inventory.service';
import { CommissionsService } from '../finance/commissions.service'; import { CommissionsService } from '../finance/commissions.service';
import { GamificationService } from '../gamification/gamification.service'; import { GamificationService } from '../gamification/gamification.service';
import { TreasuryBridgeService } from '../treasury/treasury-bridge.service'; import { TreasuryBridgeService } from '../treasury/treasury-bridge.service';
import { computeLineTotal, roundMoney } from './line-total';
type InvoiceActor = Pick<Actor, 'userId' | 'role'>; type InvoiceActor = Pick<Actor, 'userId' | 'role'>;
@@ -160,6 +161,7 @@ export class InvoicesService {
let lineItems = dto.lineItems ?? []; let lineItems = dto.lineItems ?? [];
let currency = (dto.currency ?? 'IRR').trim() || 'IRR'; let currency = (dto.currency ?? 'IRR').trim() || 'IRR';
let notes = emptyToNull(dto.notes ?? null); let notes = emptyToNull(dto.notes ?? null);
const address = emptyToNull(dto.address ?? null);
let dueDate = dto.dueDate ? new Date(dto.dueDate) : null; let dueDate = dto.dueDate ? new Date(dto.dueDate) : null;
let issuedAt = dto.issuedAt ? new Date(dto.issuedAt) : null; let issuedAt = dto.issuedAt ? new Date(dto.issuedAt) : null;
let status = (dto.status as never) || 'draft'; let status = (dto.status as never) || 'draft';
@@ -245,6 +247,7 @@ export class InvoicesService {
kind, kind,
currency, currency,
notes, notes,
address,
discountAmount: new Prisma.Decimal(dto.discountAmount ?? 0), discountAmount: new Prisma.Decimal(dto.discountAmount ?? 0),
taxPercent: new Prisma.Decimal(dto.taxPercent ?? 0), taxPercent: new Prisma.Decimal(dto.taxPercent ?? 0),
issuedAt, issuedAt,
@@ -333,6 +336,7 @@ export class InvoicesService {
data.currency = dto.currency.trim() || 'IRR'; data.currency = dto.currency.trim() || 'IRR';
} }
if ('notes' in dto) data.notes = emptyToNull(dto.notes ?? null); if ('notes' in dto) data.notes = emptyToNull(dto.notes ?? null);
if ('address' in dto) data.address = emptyToNull(dto.address ?? null);
if (dto.kind !== undefined) { if (dto.kind !== undefined) {
data.kind = dto.kind === 'credit' ? 'credit' : 'invoice'; data.kind = dto.kind === 'credit' ? 'credit' : 'invoice';
} }
@@ -631,7 +635,14 @@ export class InvoicesService {
} }
const subtotal = invoice.lineItems.reduce( const subtotal = invoice.lineItems.reduce(
(sum, item) => sum + Number(item.quantity) * Number(item.unitPrice), (sum, item) =>
sum +
computeLineTotal(
Number(item.quantity),
Number(item.unitPrice),
Number(item.discountAmount ?? 0),
Number(item.taxPercent ?? 0),
),
0, 0,
); );
const discountAmount = Number(invoice.discountAmount ?? 0); const discountAmount = Number(invoice.discountAmount ?? 0);
@@ -662,15 +673,19 @@ export class InvoicesService {
} }
private lineCreate( private lineCreate(
item: DealLineItemInput, item: InvoiceLineItemInput,
index: number, index: number,
currency: string, currency: string,
) { ) {
return { return {
productId: emptyToNull(item.productId ?? null), productId: emptyToNull(item.productId ?? null),
name: item.name.trim(), name: item.name.trim(),
unit: emptyToNull(item.unit ?? null),
description: emptyToNull(item.description ?? null),
quantity: new Prisma.Decimal(item.quantity), quantity: new Prisma.Decimal(item.quantity),
unitPrice: new Prisma.Decimal(item.unitPrice), unitPrice: new Prisma.Decimal(item.unitPrice),
discountAmount: new Prisma.Decimal(item.discountAmount ?? 0),
taxPercent: new Prisma.Decimal(item.taxPercent ?? 0),
currency: (item.currency ?? currency).trim() || 'IRR', currency: (item.currency ?? currency).trim() || 'IRR',
position: index, position: index,
}; };
@@ -770,7 +785,7 @@ export class InvoicesService {
private async assertProducts( private async assertProducts(
organizationId: string, organizationId: string,
lines: DealLineItemInput[], lines: InvoiceLineItemInput[],
) { ) {
const ids = [ const ids = [
...new Set( ...new Set(
@@ -792,15 +807,26 @@ export class InvoicesService {
const lineItems = row.lineItems.map((item) => { const lineItems = row.lineItems.map((item) => {
const quantity = Number(item.quantity); const quantity = Number(item.quantity);
const unitPrice = Number(item.unitPrice); const unitPrice = Number(item.unitPrice);
const discountAmount = Number(item.discountAmount ?? 0);
const taxPercent = Number(item.taxPercent ?? 0);
return { return {
id: item.id, id: item.id,
productId: item.productId, productId: item.productId,
name: item.name, name: item.name,
unit: item.unit ?? null,
description: item.description ?? null,
quantity, quantity,
unitPrice, unitPrice,
discountAmount,
taxPercent,
currency: item.currency, currency: item.currency,
position: item.position, position: item.position,
lineTotal: quantity * unitPrice, lineTotal: computeLineTotal(
quantity,
unitPrice,
discountAmount,
taxPercent,
),
}; };
}); });
const subtotal = lineItems.reduce((sum, item) => sum + item.lineTotal, 0); const subtotal = lineItems.reduce((sum, item) => sum + item.lineTotal, 0);
@@ -866,6 +892,7 @@ export class InvoicesService {
kind, kind,
currency: row.currency, currency: row.currency,
notes: row.notes, notes: row.notes,
address: row.address ?? null,
discountAmount, discountAmount,
taxPercent, taxPercent,
issuedAt: row.issuedAt?.toISOString() ?? null, issuedAt: row.issuedAt?.toISOString() ?? null,
@@ -914,10 +941,6 @@ function emptyToNull(value?: string | null): string | null {
return trimmed.length ? trimmed : null; return trimmed.length ? trimmed : null;
} }
function roundMoney(value: number): number {
return Math.round((value + Number.EPSILON) * 100) / 100;
}
function invoiceSearchWhere(q?: string): Prisma.InvoiceWhereInput { function invoiceSearchWhere(q?: string): Prisma.InvoiceWhereInput {
const search = buildSearchWhere<Prisma.InvoiceWhereInput>(q, (t) => [ const search = buildSearchWhere<Prisma.InvoiceWhereInput>(q, (t) => [
{ title: ci(t) }, { title: ci(t) },
+21
View File
@@ -0,0 +1,21 @@
/** Round to 2 decimal places (money). */
export function roundMoney(value: number): number {
return Math.round((value + Number.EPSILON) * 100) / 100;
}
/**
* Per-line payable: (qty × unitPrice − discount) × (1 + taxPercent/100).
* Discount and taxPercent default to 0 so legacy rows keep qty × unitPrice.
*/
export function computeLineTotal(
quantity: number,
unitPrice: number,
discountAmount = 0,
taxPercent = 0,
): number {
const gross = Number(quantity) * Number(unitPrice);
const discount = Math.max(0, Number(discountAmount) || 0);
const net = Math.max(0, gross - discount);
const tax = Math.max(0, Number(taxPercent) || 0);
return roundMoney(net * (1 + tax / 100));
}
+43 -7
View File
@@ -21,6 +21,7 @@ import {
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { customersPersonWhere, leadsDeepWhere } from '../common/data-access'; import { customersPersonWhere, leadsDeepWhere } from '../common/data-access';
import { computeLineTotal } from '../invoices/line-total';
import { import {
type Actor, type Actor,
assigneeWhere, assigneeWhere,
@@ -195,6 +196,8 @@ export class ReportsService {
name: true, name: true,
quantity: true, quantity: true,
unitPrice: true, unitPrice: true,
discountAmount: true,
taxPercent: true,
currency: true, currency: true,
product: { select: { name: true, category: true } }, product: { select: { name: true, category: true } },
}, },
@@ -224,7 +227,12 @@ export class ReportsService {
let amount = 0; let amount = 0;
for (const inv of rows) { for (const inv of rows) {
for (const line of inv.lineItems) { for (const line of inv.lineItems) {
const lineTotal = Number(line.quantity) * Number(line.unitPrice); const lineTotal = computeLineTotal(
Number(line.quantity),
Number(line.unitPrice),
Number(line.discountAmount ?? 0),
Number(line.taxPercent ?? 0),
);
amount += toBaseAmount(lineTotal, line.currency, rates); amount += toBaseAmount(lineTotal, line.currency, rates);
} }
} }
@@ -492,14 +500,24 @@ export class ReportsService {
name: string; name: string;
quantity: Prisma.Decimal; quantity: Prisma.Decimal;
unitPrice: Prisma.Decimal; unitPrice: Prisma.Decimal;
discountAmount?: Prisma.Decimal | null;
taxPercent?: Prisma.Decimal | null;
currency: string; currency: string;
product: { name: string; category: string | null } | null; product: { name: string; category: string | null } | null;
}>, }>,
withLineExtras = false,
): LineAgg[] => ): LineAgg[] =>
lines.map((line) => { lines.map((line) => {
const qty = Number(line.quantity); const qty = Number(line.quantity);
const amount = toBaseAmount( const amount = toBaseAmount(
qty * Number(line.unitPrice), withLineExtras
? computeLineTotal(
qty,
Number(line.unitPrice),
Number(line.discountAmount ?? 0),
Number(line.taxPercent ?? 0),
)
: qty * Number(line.unitPrice),
line.currency, line.currency,
rates, rates,
); );
@@ -513,14 +531,14 @@ export class ReportsService {
const invoiceProductLines: LineAgg[] = []; const invoiceProductLines: LineAgg[] = [];
for (const inv of invoicesCur) { for (const inv of invoicesCur) {
invoiceProductLines.push(...collectLines(inv.lineItems)); invoiceProductLines.push(...collectLines(inv.lineItems, true));
} }
let productLines = invoiceProductLines; let productLines = invoiceProductLines;
if (!productLines.length) { if (!productLines.length) {
productLines = []; productLines = [];
for (const d of wonInPeriod) { for (const d of wonInPeriod) {
productLines.push(...collectLines(d.lineItems)); productLines.push(...collectLines(d.lineItems, false));
} }
} }
@@ -1653,7 +1671,13 @@ export class ReportsService {
issuedAt: true, issuedAt: true,
createdAt: true, createdAt: true,
lineItems: { lineItems: {
select: { quantity: true, unitPrice: true, currency: true }, select: {
quantity: true,
unitPrice: true,
discountAmount: true,
taxPercent: true,
currency: true,
},
}, },
}, },
}); });
@@ -1666,7 +1690,12 @@ export class ReportsService {
let amount = 0; let amount = 0;
for (const line of inv.lineItems) { for (const line of inv.lineItems) {
amount += toBaseAmount( amount += toBaseAmount(
Number(line.quantity) * Number(line.unitPrice), computeLineTotal(
Number(line.quantity),
Number(line.unitPrice),
Number(line.discountAmount ?? 0),
Number(line.taxPercent ?? 0),
),
line.currency, line.currency,
rates, rates,
); );
@@ -2173,6 +2202,8 @@ export class ReportsService {
select: { select: {
quantity: true, quantity: true,
unitPrice: true, unitPrice: true,
discountAmount: true,
taxPercent: true,
currency: true, currency: true,
}, },
}, },
@@ -2210,7 +2241,12 @@ export class ReportsService {
for (const inv of invoices) { for (const inv of invoices) {
if (!invoiceInRange(inv, from, to)) continue; if (!invoiceInRange(inv, from, to)) continue;
for (const line of inv.lineItems) { for (const line of inv.lineItems) {
const lineTotal = Number(line.quantity) * Number(line.unitPrice); const lineTotal = computeLineTotal(
Number(line.quantity),
Number(line.unitPrice),
Number(line.discountAmount ?? 0),
Number(line.taxPercent ?? 0),
);
amount += toBaseAmount(lineTotal, line.currency, rates); amount += toBaseAmount(lineTotal, line.currency, rates);
} }
} }
+31 -8
View File
@@ -33,17 +33,26 @@ function round2(value: Prisma.Decimal) {
return value.toDecimalPlaces(2); return value.toDecimalPlaces(2);
} }
/** همان فرمول ماندهٔ فاکتور: جمع ردیف‌ها − تخفیف + مالیات، برگشتی منفی. */ /** همان فرمول ماندهٔ فاکتور: جمع ردیف‌ها − تخفیف فاکتور + مالیات فاکتور، برگشتی منفی. */
export function signedInvoicePayable(invoice: { export function signedInvoicePayable(invoice: {
kind: string; kind: string;
discountAmount: Prisma.Decimal; discountAmount: Prisma.Decimal;
taxPercent: Prisma.Decimal; taxPercent: Prisma.Decimal;
lineItems: Array<{ quantity: Prisma.Decimal; unitPrice: Prisma.Decimal }>; lineItems: Array<{
quantity: Prisma.Decimal;
unitPrice: Prisma.Decimal;
discountAmount?: Prisma.Decimal | null;
taxPercent?: Prisma.Decimal | null;
}>;
}) { }) {
const subtotal = invoice.lineItems.reduce( const subtotal = invoice.lineItems.reduce((sum, line) => {
(sum, line) => sum.plus(line.quantity.mul(line.unitPrice)), const gross = line.quantity.mul(line.unitPrice);
zero(), const lineDiscount = line.discountAmount ?? zero();
); const net = Prisma.Decimal.max(gross.minus(lineDiscount), 0);
const lineTaxPct = line.taxPercent ?? zero();
const lineTotal = net.mul(lineTaxPct.div(100).plus(1));
return sum.plus(lineTotal);
}, zero());
const discount = invoice.discountAmount ?? zero(); const discount = invoice.discountAmount ?? zero();
const taxable = Prisma.Decimal.max(subtotal.minus(discount), 0); const taxable = Prisma.Decimal.max(subtotal.minus(discount), 0);
const tax = taxable.mul(invoice.taxPercent ?? 0).div(100); const tax = taxable.mul(invoice.taxPercent ?? 0).div(100);
@@ -80,7 +89,14 @@ export async function loadInvoicePartyPositions(
companyId: true, companyId: true,
person: { select: { firstName: true, lastName: true } }, person: { select: { firstName: true, lastName: true } },
company: { select: { name: true } }, company: { select: { name: true } },
lineItems: { select: { quantity: true, unitPrice: true } }, lineItems: {
select: {
quantity: true,
unitPrice: true,
discountAmount: true,
taxPercent: true,
},
},
payments: { select: { amount: true } }, payments: { select: { amount: true } },
}, },
}), }),
@@ -190,7 +206,14 @@ export async function invoiceSalesInPeriod(
taxPercent: true, taxPercent: true,
issuedAt: true, issuedAt: true,
createdAt: true, createdAt: true,
lineItems: { select: { quantity: true, unitPrice: true } }, lineItems: {
select: {
quantity: true,
unitPrice: true,
discountAmount: true,
taxPercent: true,
},
},
}, },
}); });
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -6,7 +6,7 @@ import {
ClockCircleOutlined, ClockCircleOutlined,
LeftOutlined, LeftOutlined,
RightOutlined, RightOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import { import {
addJalaliMonths, addJalaliMonths,
dateToJalali, dateToJalali,
+49 -7
View File
@@ -3,10 +3,12 @@ import { nextTick, ref, watch } from 'vue';
import { Input as AInput } from 'ant-design-vue'; import { Input as AInput } from 'ant-design-vue';
import { WalletOutlined } from '@/icons/ant-bridge'; import { WalletOutlined } from '@/icons/ant-bridge';
import { import {
blockNonNumericKeydown,
caretIndexForDigitCount, caretIndexForDigitCount,
countDigitChars, countDigitChars,
formatGroupedInput, formatGroupedInput,
parseMoneyNumber, parseMoneyNumber,
sanitizeNumericClipboard,
} from '@/lib/money'; } from '@/lib/money';
const model = defineModel<string | number | null>({ default: '' }); const model = defineModel<string | number | null>({ default: '' });
@@ -87,19 +89,49 @@ function onBlur() {
text.value = n == null ? '' : formatGroupedInput(n, props.decimals); text.value = n == null ? '' : formatGroupedInput(n, props.decimals);
} }
async function onInput(event: Event) { function onKeydown(event: KeyboardEvent) {
const el = event.target as HTMLInputElement; blockNonNumericKeydown(event, {
const raw = el.value; allowDecimal: props.decimals > 0,
const caret = el.selectionStart ?? raw.length; allowMinus: false,
const digitsBefore = countDigitChars(raw.slice(0, caret)); });
}
function onPaste(event: ClipboardEvent) {
event.preventDefault();
const pasted = event.clipboardData?.getData('text') ?? '';
const cleaned = sanitizeNumericClipboard(pasted, {
allowDecimal: props.decimals > 0,
allowMinus: false,
});
const input = nativeInput();
if (!input) return;
const start = input.selectionStart ?? text.value.length;
const end = input.selectionEnd ?? text.value.length;
const next = `${text.value.slice(0, start)}${cleaned}${text.value.slice(end)}`;
applyRaw(next, start + cleaned.length);
}
async function applyRaw(raw: string, preferredCaretDigits?: number) {
const caret =
preferredCaretDigits == null
? countDigitChars(raw)
: preferredCaretDigits;
const endsWithSep = /[.\u066B]$/.test(normalizeSep(raw)); const endsWithSep = /[.\u066B]$/.test(normalizeSep(raw));
const n = parseMoneyNumber(raw, props.decimals); const n = parseMoneyNumber(raw, props.decimals);
if (n == null) { if (n == null) {
const cleaned = raw.replace(/[^\d۰-۹٠-٩.\u066B٬,،\s-]/g, ''); const cleaned = sanitizeNumericClipboard(raw, {
allowDecimal: props.decimals > 0,
allowMinus: false,
});
text.value = cleaned; text.value = cleaned;
writeModel(null); writeModel(null);
await nextTick();
const input = nativeInput();
if (input) {
const nextCaret = caretIndexForDigitCount(cleaned, caret);
input.setSelectionRange(nextCaret, nextCaret);
}
return; return;
} }
@@ -114,10 +146,18 @@ async function onInput(event: Event) {
await nextTick(); await nextTick();
const input = nativeInput(); const input = nativeInput();
if (!input) return; if (!input) return;
const nextCaret = caretIndexForDigitCount(display, digitsBefore); const nextCaret = caretIndexForDigitCount(display, caret);
input.setSelectionRange(nextCaret, nextCaret); input.setSelectionRange(nextCaret, nextCaret);
} }
async function onInput(event: Event) {
const el = event.target as HTMLInputElement;
const raw = el.value;
const caret = el.selectionStart ?? raw.length;
const digitsBefore = countDigitChars(raw.slice(0, caret));
await applyRaw(raw, digitsBefore);
}
function normalizeSep(raw: string): string { function normalizeSep(raw: string): string {
return raw.replace(/٫/g, '.'); return raw.replace(/٫/g, '.');
} }
@@ -139,6 +179,8 @@ function normalizeSep(raw: string): string {
style="width: 100%; font-variant-numeric: tabular-nums" style="width: 100%; font-variant-numeric: tabular-nums"
@focus="onFocus" @focus="onFocus"
@blur="onBlur" @blur="onBlur"
@keydown="onKeydown"
@paste="onPaste"
@input="onInput" @input="onInput"
> >
<template v-if="showPrefix" #prefix> <template v-if="showPrefix" #prefix>
+177
View File
@@ -0,0 +1,177 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import {
Button as AButton,
Drawer as ADrawer,
Flex as AFlex,
Select as ASelect,
} from 'ant-design-vue';
import { UserAddOutlined } from '@/icons/ant-bridge';
import { api } from '@/lib/api';
import PersonFormView from '@/views/PersonFormView.vue';
import type { PaginatedResponse, PersonDto } from '@mento/shared';
const props = withDefaults(
defineProps<{
modelValue?: string;
placeholder?: string;
allowClear?: boolean;
disabled?: boolean;
addLabel?: string;
seedPeople?: PersonDto[];
}>(),
{
modelValue: '',
placeholder: 'جستجو و انتخاب شخص',
allowClear: true,
disabled: false,
addLabel: 'افزودن شخص جدید',
seedPeople: () => [],
},
);
const emit = defineEmits<{
'update:modelValue': [value: string];
change: [person: PersonDto | null];
created: [person: PersonDto];
}>();
const remembered = ref<PersonDto[]>([]);
const searchResults = ref<PersonDto[] | null>(null);
const searching = ref(false);
const searchQuery = ref('');
const modalOpen = ref(false);
let searchTimer: ReturnType<typeof setTimeout> | undefined;
let searchSeq = 0;
watch(
() => props.seedPeople,
(list) => {
for (const p of list ?? []) {
if (!remembered.value.some((x) => x.id === p.id)) {
remembered.value = [...remembered.value, p];
}
}
},
{ immediate: true, deep: true },
);
function remember(p: PersonDto) {
if (!remembered.value.some((x) => x.id === p.id)) {
remembered.value = [p, ...remembered.value];
}
}
const optionPeople = computed(() => searchResults.value ?? remembered.value);
const selectOptions = computed(() =>
optionPeople.value.map((p) => ({
value: p.id,
label: p.company?.name ? `${p.fullName} · ${p.company.name}` : p.fullName,
})),
);
const selectValue = computed(() => props.modelValue || undefined);
function onSearch(q: string) {
searchQuery.value = q;
if (searchTimer) clearTimeout(searchTimer);
const trimmed = q.trim();
if (!trimmed) {
searchResults.value = null;
searching.value = false;
return;
}
searching.value = true;
const seq = ++searchSeq;
searchTimer = setTimeout(async () => {
try {
const { data } = await api.get<PaginatedResponse<PersonDto>>('/people', {
params: { q: trimmed, limit: 30 },
});
if (seq === searchSeq) searchResults.value = data.items;
} catch {
if (seq === searchSeq) searchResults.value = [];
} finally {
if (seq === searchSeq) searching.value = false;
}
}, 300);
}
function onSelect(value: unknown) {
const pid = typeof value === 'string' ? value : '';
if (!pid) {
emit('update:modelValue', '');
emit('change', null);
return;
}
const p =
optionPeople.value.find((x) => x.id === pid) ??
remembered.value.find((x) => x.id === pid) ??
null;
if (p) remember(p);
emit('update:modelValue', pid);
emit('change', p);
}
function openCreate() {
modalOpen.value = true;
}
function onCreated(p?: PersonDto) {
modalOpen.value = false;
if (!p) return;
searchQuery.value = '';
searchResults.value = null;
remember(p);
emit('update:modelValue', p.id);
emit('created', p);
emit('change', p);
}
</script>
<template>
<a-flex align="center" :gap="8" style="width: 100%">
<a-select
:value="selectValue"
show-search
:allow-clear="allowClear"
:disabled="disabled"
:filter-option="false"
:options="selectOptions"
:loading="searching"
:list-height="160"
:not-found-content="searching ? 'در حال جستجو…' : 'شخصی یافت نشد'"
:placeholder="placeholder"
style="flex: 1; min-width: 0"
@search="onSearch"
@update:value="onSelect"
/>
<a-button
:disabled="disabled"
:title="addLabel"
:aria-label="addLabel"
@click="openCreate"
>
<template #icon><UserAddOutlined /></template>
</a-button>
</a-flex>
<a-drawer
v-model:open="modalOpen"
title="شخص جدید"
placement="right"
:width="720"
:footer="null"
destroy-on-close
@close="modalOpen = false"
>
<PersonFormView
v-if="modalOpen"
embedded
:initial-query="searchQuery"
@saved="onCreated"
@cancel="modalOpen = false"
/>
</a-drawer>
</template>
+201 -562
View File
@@ -14,12 +14,30 @@ import {
SMS_TEMPLATE_NAME_MAX, SMS_TEMPLATE_NAME_MAX,
countSmsParts, countSmsParts,
} from '@mento/shared'; } from '@mento/shared';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
FormItem as AFormItem,
Input as AInput,
List as AList,
Modal as AModal,
Row as ARow,
Space as ASpace,
Tag as ATag,
Textarea as ATextarea,
Typography,
} from 'ant-design-vue';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useFeedback } from '@/composables/useFeedback'; import { useFeedback } from '@/composables/useFeedback';
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali'; import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { formatTahesabBedBes } from '@/lib/tahesab'; import { formatTahesabBedBes } from '@/lib/tahesab';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import { UiButton, UiModal } from '@/components/ui';
const { Text: ATypographyText, Paragraph: ATypographyParagraph } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
@@ -61,8 +79,8 @@ const panel = ref<Panel>('none');
const savingTemplate = ref(false); const savingTemplate = ref(false);
const templateName = ref(''); const templateName = ref('');
const templateBody = ref(''); const templateBody = ref('');
const bodyEl = ref<HTMLTextAreaElement | null>(null); const bodyEl = ref<{ $el?: HTMLElement } | null>(null);
const templateBodyEl = ref<HTMLTextAreaElement | null>(null); const templateBodyEl = ref<{ $el?: HTMLElement } | null>(null);
const history = ref<OutboundSmsLogDto[]>([]); const history = ref<OutboundSmsLogDto[]>([]);
const historyLoading = ref(false); const historyLoading = ref(false);
const templates = ref<SmsTemplateDto[]>([]); const templates = ref<SmsTemplateDto[]>([]);
@@ -116,6 +134,9 @@ const canSaveTemplate = computed(
templates.value.length < SMS_TEMPLATE_MAX && templates.value.length < SMS_TEMPLATE_MAX &&
!savingTemplate.value, !savingTemplate.value,
); );
const canSend = computed(
() => !busy.value && !sent.value && !!props.phone && text.value.trim().length >= 2,
);
watch( watch(
() => props.open, () => props.open,
@@ -216,7 +237,6 @@ function normalizeTemplateKey(key: string) {
.trim(); .trim();
} }
/** پیش‌نمایش؛ اگر مقدار خالی باشد نشانه می‌گذارد تا با فیلد خالی قاطی نشود. */
function fill(source: string) { function fill(source: string) {
const from = fromOrg.value.trim(); const from = fromOrg.value.trim();
const rial = rialBalanceText.value.trim(); const rial = rialBalanceText.value.trim();
@@ -258,11 +278,15 @@ function fill(source: string) {
}); });
} }
function insertInto( function textareaFromRef(comp: { $el?: HTMLElement } | null | undefined) {
target: 'compose' | 'draft', const root = comp?.$el;
token: string, if (!root) return null;
) { if (root instanceof HTMLTextAreaElement) return root;
const el = target === 'compose' ? bodyEl.value : templateBodyEl.value; return root.querySelector?.('textarea') ?? null;
}
function insertInto(target: 'compose' | 'draft', token: string) {
const el = textareaFromRef(target === 'compose' ? bodyEl.value : templateBodyEl.value);
const current = target === 'compose' ? text.value : templateBody.value; const current = target === 'compose' ? text.value : templateBody.value;
const setValue = (next: string) => { const setValue = (next: string) => {
if (target === 'compose') text.value = next; if (target === 'compose') text.value = next;
@@ -315,8 +339,13 @@ async function saveTemplate() {
} }
} }
async function removeTemplate(item: SmsTemplateDto) { function removeTemplate(item: SmsTemplateDto) {
if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return; AModal.confirm({
title: `پیامک آماده «${item.name}» حذف شود؟`,
okText: 'حذف',
cancelText: 'انصراف',
okButtonProps: { danger: true },
async onOk() {
error.value = ''; error.value = '';
try { try {
const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`); const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`);
@@ -325,6 +354,8 @@ async function removeTemplate(item: SmsTemplateDto) {
} catch (e) { } catch (e) {
feedback.fromError(e, 'حذف پیامک آماده ناموفق بود.'); feedback.fromError(e, 'حذف پیامک آماده ناموفق بود.');
} }
},
});
} }
async function send(force = false) { async function send(force = false) {
@@ -342,11 +373,15 @@ async function send(force = false) {
const msg = const msg =
(e.response?.data as { message?: string } | undefined)?.message?.trim() || (e.response?.data as { message?: string } | undefined)?.message?.trim() ||
'قبلاً پیامک تبریک فرستاده شده است. دوباره بفرستیم؟'; 'قبلاً پیامک تبریک فرستاده شده است. دوباره بفرستیم؟';
if (confirm(msg)) { AModal.confirm({
title: msg,
okText: 'ارسال دوباره',
cancelText: 'انصراف',
onOk: async () => {
busy.value = false; busy.value = false;
await send(true); await send(true);
return; },
} });
feedback.warning(msg); feedback.warning(msg);
} else { } else {
feedback.fromError(e, 'ارسال پیامک ناموفق بود.'); feedback.fromError(e, 'ارسال پیامک ناموفق بود.');
@@ -362,597 +397,201 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
</script> </script>
<template> <template>
<UiModal :open="open" :nest="nest" :title="title" @close="emit('close')"> <a-modal
<p class="who"> :open="open"
:title="title"
:confirm-loading="busy"
ok-text="ارسال پیامک"
cancel-text="بستن"
:ok-button-props="{ disabled: !canSend }"
destroy-on-close
:width="720"
:z-index="nest ? 1100 : undefined"
@ok="send()"
@cancel="emit('close')"
>
<a-space direction="vertical" :style="{ width: '100%' }">
<a-typography-text>
برای {{ name || 'این شخص' }} برای {{ name || 'این شخص' }}
<span v-if="phone" dir="ltr">{{ toFaDigits(phone) }}</span> <a-typography-text v-if="phone" type="secondary" dir="ltr">
<span v-else class="warn">شماره موبایل ندارد</span> {{ toFaDigits(phone) }}
</p> </a-typography-text>
<a-tag v-else color="warning">شماره موبایل ندارد</a-tag>
</a-typography-text>
<div class="tools"> <a-space wrap>
<div class="tool-row"> <a-button
<button :type="panel === 'fields' ? 'primary' : 'default'"
type="button"
class="pill"
:class="{ on: panel === 'fields' }"
@click="openPanel('fields')" @click="openPanel('fields')"
> >
فیلدهای پویا فیلدهای پویا
</button> </a-button>
<button <a-button
type="button" :type="panel === 'templates' ? 'primary' : 'default'"
class="pill"
:class="{ on: panel === 'templates' }"
@click="openPanel('templates')" @click="openPanel('templates')"
> >
ساخت پیامک آماده ساخت پیامک آماده
</button> </a-button>
</div> </a-space>
<div v-if="panel === 'fields'" class="panel"> <a-card v-if="panel === 'fields'" size="small">
<p class="panel-hint">روی فیلد بزنید تا داخل متن پیام درج شود.</p> <a-typography-text type="secondary">
<div class="field-grid"> روی فیلد بزنید تا داخل متن پیام درج شود.
<button </a-typography-text>
v-for="item in MESSAGE_AUTOMATION_FIELDS" <a-row :gutter="[8, 8]" :style="{ marginTop: '8px' }">
:key="item.token" <a-col v-for="item in MESSAGE_AUTOMATION_FIELDS" :key="item.token" :span="24">
type="button" <a-button block @click="insertInto('compose', item.token)">
@click="insertInto('compose', item.token)" <a-space :style="{ width: '100%', justifyContent: 'space-between' }">
>
<code>{{ item.token }}</code> <code>{{ item.token }}</code>
<span>{{ item.label }}</span> <span>{{ item.label }}</span>
</button> </a-space>
</div> </a-button>
</div> </a-col>
</a-row>
</a-card>
<div v-if="panel === 'templates'" class="panel"> <a-card v-if="panel === 'templates'" size="small" title="ساخت پیامک آماده جدید">
<div class="draft"> <a-typography-text type="secondary" :style="{ display: 'block', marginBottom: '8px' }">
<strong>ساخت پیامک آماده جدید</strong> این متن جدا از پیام ارسالی است؛ بعد از ذخیره، عنوانش بالا برای استفاده سریع می‌آید.
<p class="panel-hint">این متن جدا از پیام ارسالی است؛ بعد از ذخیره، عنوانش بالا برای استفاده سریع می‌آید.</p> </a-typography-text>
<input <a-form-item label="نام قالب" :style="{ marginBottom: '8px' }">
v-model="templateName" <a-input
type="text" v-model:value="templateName"
:maxlength="SMS_TEMPLATE_NAME_MAX" :maxlength="SMS_TEMPLATE_NAME_MAX"
placeholder="نام قالب (مثلاً پیگیری جلسه)" placeholder="نام قالب (مثلاً پیگیری جلسه)"
autocomplete="off" autocomplete="off"
/> />
<textarea </a-form-item>
<a-form-item label="متن قالب" :style="{ marginBottom: '8px' }">
<a-textarea
ref="templateBodyEl" ref="templateBodyEl"
v-model="templateBody" v-model:value="templateBody"
rows="3" :rows="3"
:maxlength="SMS_TEMPLATE_BODY_MAX" :maxlength="SMS_TEMPLATE_BODY_MAX"
placeholder="متن قالب، مثلاً: سلام {نام} عزیز…" placeholder="متن قالب، مثلاً: سلام {نام} عزیز…"
/> />
<div class="tpl-fields" role="group" aria-label="فیلدهای پویا برای قالب"> </a-form-item>
<span class="tpl-fields-label">درج فیلد در قالب:</span> <a-space wrap :style="{ marginBottom: '8px' }">
<button <a-typography-text type="secondary">درج فیلد در قالب:</a-typography-text>
<a-button
v-for="item in MESSAGE_AUTOMATION_FIELDS" v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="`tpl-${item.token}`" :key="`tpl-${item.token}`"
type="button"
:title="item.label" :title="item.label"
@click="insertInto('draft', item.token)" @click="insertInto('draft', item.token)"
> >
<code>{{ item.token }}</code> <code>{{ item.token }}</code>
</button> </a-button>
</div> </a-space>
<button <a-button
type="button" type="primary"
class="save-btn" :loading="savingTemplate"
:disabled="!canSaveTemplate" :disabled="!canSaveTemplate"
@click="saveTemplate" @click="saveTemplate"
> >
{{ savingTemplate ? 'در حال ذخیره…' : 'ذخیره قالب' }} ذخیره قالب
</button> </a-button>
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted"> <a-typography-text
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است. v-if="templates.length >= SMS_TEMPLATE_MAX"
</p> type="secondary"
</div> :style="{ display: 'block', marginTop: '8px' }"
<div v-if="templates.length" class="manage-list">
<p class="panel-hint">حذف قالب‌های ذخیره‌شده:</p>
<ul class="template-list">
<li v-for="item in templates" :key="`del-${item.id}`">
<span class="pick-name">{{ item.name }}</span>
<button
type="button"
class="del"
:aria-label="`حذف ${item.name}`"
@click="removeTemplate(item)"
> >
حذف سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
</button> </a-typography-text>
</li>
</ul>
</div>
</div>
</div>
<div class="compose-layout"> <template v-if="templates.length">
<div class="compose-main"> <a-typography-text type="secondary" :style="{ display: 'block', marginTop: '12px' }">
<label class="compose-label" for="sms-compose-body">متن پیام ارسالی</label> حذف قالب‌های ذخیره‌شده:
<textarea </a-typography-text>
id="sms-compose-body" <a-list size="small" :data-source="templates" :style="{ marginTop: '8px' }">
<template #renderItem="{ item }">
<a-list-item>
<a-typography-text>{{ item.name }}</a-typography-text>
<template #actions>
<a-button type="link" danger @click="removeTemplate(item)">حذف</a-button>
</template>
</a-list-item>
</template>
</a-list>
</template>
</a-card>
<a-row :gutter="[16, 16]">
<a-col :xs="24" :md="16">
<a-form-item label="متن پیام ارسالی" :style="{ marginBottom: '4px' }">
<a-textarea
ref="bodyEl" ref="bodyEl"
v-model="text" v-model:value="text"
rows="5" :rows="5"
maxlength="500" :maxlength="500"
placeholder="متن پیام را بنویسید یا از ستون قالب‌ها انتخاب کنید" placeholder="متن پیام را بنویسید یا از ستون قالب‌ها انتخاب کنید"
/> />
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p> </a-form-item>
</div> <a-typography-text type="secondary">
{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک
<aside class="quick-col" aria-label="انتخاب سریع پیامک آماده"> </a-typography-text>
<strong class="quick-col-title">قالب‌ها</strong> </a-col>
<div v-if="templatesLoading" class="muted tiny">در حال بارگذاری…</div> <a-col :xs="24" :md="8">
<div <a-card size="small" title="قالب‌ها">
v-else-if="templates.length" <a-typography-text v-if="templatesLoading" type="secondary">
class="quick-templates" در حال بارگذاری…
role="list" </a-typography-text>
> <a-space v-else-if="templates.length" direction="vertical" :style="{ width: '100%' }">
<button <a-button
v-for="item in templates" v-for="item in templates"
:key="item.id" :key="item.id"
type="button" block
class="tpl-chip"
role="listitem"
:title="item.body" :title="item.body"
@click="applyTemplate(item)" @click="applyTemplate(item)"
> >
{{ item.name }} {{ item.name }}
</button> </a-button>
</div> </a-space>
<p v-else class="muted tiny quick-empty"> <a-typography-text v-else type="secondary">
هنوز قالبی نیست. از «ساخت پیامک آماده» بسازید. هنوز قالبی نیست. از «ساخت پیامک آماده» بسازید.
</p> </a-typography-text>
</aside> </a-card>
</div> </a-col>
</a-row>
<div class="preview"> <a-alert
<span>پیش‌نمایش</span> type="info"
<p>{{ preview || 'متن پیام هنوز نوشته نشده است.' }}</p> show-icon
</div> message="پیش‌نمایش"
:description="preview || 'متن پیام هنوز نوشته نشده است.'"
/>
<div v-if="historyEndpoint" class="history"> <a-card v-if="historyEndpoint" size="small" title="پیامک‌های قبلی">
<header> <a-typography-text v-if="historyLoading" type="secondary">در حال بارگذاری…</a-typography-text>
<strong>پیامک‌های قبلی</strong> <a-typography-text v-else-if="!history.length" type="secondary">
<span v-if="historyLoading" class="muted">در حال بارگذاری…</span>
</header>
<p v-if="!historyLoading && !history.length" class="muted empty">
هنوز پیامکی ثبت نشده است. هنوز پیامکی ثبت نشده است.
</p> </a-typography-text>
<ul v-else class="history-list"> <a-list v-else size="small" :data-source="history" :style="{ maxHeight: '220px', overflow: 'auto' }">
<li v-for="item in history" :key="item.id"> <template #renderItem="{ item }">
<div class="meta"> <a-list-item>
<span class="src">{{ item.sourceLabel }}</span> <a-list-item-meta>
<span :class="['st', item.status]">{{ statusLabel(item.status) }}</span> <template #title>
<time>{{ formatJalaliNumeric(new Date(item.createdAt)) }}</time> <a-space wrap>
</div> <a-typography-text strong>{{ item.sourceLabel }}</a-typography-text>
<p>{{ item.body }}</p> <a-tag :color="item.status === 'failed' ? 'error' : 'success'">
</li> {{ statusLabel(item.status) }}
</ul> </a-tag>
</div> <a-typography-text type="secondary">
{{ formatJalaliNumeric(new Date(item.createdAt)) }}
<p v-if="error" class="err">{{ error }}</p> </a-typography-text>
</a-space>
<template #footer>
<UiButton variant="ghost" :disabled="busy" @click="emit('close')">بستن</UiButton>
<UiButton
variant="primary"
:loading="busy"
:disabled="busy || sent || !phone || text.trim().length < 2"
@click="send"
>
ارسال پیامک
</UiButton>
</template> </template>
</UiModal> <template #description>
<a-typography-paragraph :style="{ marginBottom: 0, whiteSpace: 'pre-wrap' }">
{{ item.body }}
</a-typography-paragraph>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
<a-alert v-if="error" type="error" show-icon :message="error" />
</a-space>
</a-modal>
</template> </template>
<style scoped>
.who {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 0 0.7rem;
color: #0f172a;
}
.who span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #64748b;
font-size: 0.85rem;
}
.warn {
color: #b45309;
}
.tools {
margin-bottom: 0.55rem;
}
.tool-row {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.pill {
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: var(--accent-subtle);
color: var(--accent-deep);
border-radius: 999px;
font: inherit;
cursor: pointer;
padding: 0.28rem 0.7rem;
font-size: 0.8rem;
}
.pill.on {
background: var(--accent-deep);
color: #fff;
border-color: var(--accent-deep);
}
.panel {
margin-top: 0.45rem;
display: grid;
gap: 0.45rem;
padding: 0.55rem;
background: #fff;
border: 1px solid #e7eef2;
border-radius: 12px;
}
.panel-hint {
margin: 0;
color: #64748b;
font-size: 0.75rem;
}
.field-grid {
display: grid;
gap: 0.25rem;
}
.field-grid button {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
border-radius: 8px;
padding: 0.35rem 0.5rem;
background: #fff;
text-align: start;
font: inherit;
cursor: pointer;
color: var(--accent-deep);
}
.field-grid code {
color: var(--accent-deep);
}
.template-list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.3rem;
max-height: 9.5rem;
overflow: auto;
}
.template-list li {
display: flex;
align-items: stretch;
gap: 0.3rem;
}
.compose-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 10.5rem;
gap: 0.75rem;
align-items: stretch;
margin-bottom: 0.15rem;
}
.compose-main {
min-width: 0;
display: grid;
align-content: start;
}
.quick-col {
display: flex;
flex-direction: column;
gap: 0.35rem;
min-height: 0;
max-height: 11.5rem;
padding: 0.5rem;
border: 1px solid #e7eef2;
border-radius: 12px;
background: #fafbfc;
}
.quick-col-title {
font-size: 0.78rem;
color: #0f172a;
}
.quick-templates {
display: flex;
flex-direction: column;
gap: 0.3rem;
min-height: 0;
overflow: auto;
flex: 1;
padding-inline-end: 0.1rem;
}
.tpl-chip {
flex: none;
width: 100%;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: #fff;
color: var(--accent-deep);
border-radius: 8px;
font: inherit;
font-size: 0.76rem;
font-weight: 600;
padding: 0.4rem 0.5rem;
cursor: pointer;
text-align: start;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tpl-chip:hover {
background: var(--accent-subtle);
}
.quick-empty {
margin: 0;
}
.tiny {
font-size: 0.72rem;
}
@media (max-width: 640px) {
.compose-layout {
grid-template-columns: 1fr;
}
.quick-col {
max-height: 8.5rem;
}
}
.manage-list {
padding-top: 0.45rem;
border-top: 1px solid #eef2f7;
}
.template-list .pick-name {
flex: 1;
min-width: 0;
padding: 0.4rem 0.5rem;
font-size: 0.82rem;
color: #0f172a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.template-list .del {
flex: none;
border: 0;
border-radius: 8px;
background: transparent;
color: #b91c1c;
font: inherit;
font-size: 0.75rem;
cursor: pointer;
padding: 0.35rem 0.45rem;
}
.draft {
display: grid;
gap: 0.35rem;
padding-top: 0.45rem;
border-top: 1px solid #eef2f7;
}
.draft strong {
font-size: 0.86rem;
color: #0f172a;
}
.draft input,
.draft textarea,
#sms-compose-body {
width: 100%;
box-sizing: border-box;
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 0.55rem 0.7rem;
font: inherit;
color: #0f172a;
}
.draft textarea,
#sms-compose-body {
resize: vertical;
}
.tpl-fields {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.3rem;
}
.tpl-fields-label {
color: #64748b;
font-size: 0.74rem;
margin-inline-end: 0.15rem;
}
.tpl-fields button {
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: #fff;
color: var(--accent-deep);
border-radius: 999px;
font: inherit;
font-size: 0.74rem;
padding: 0.2rem 0.5rem;
cursor: pointer;
}
.tpl-fields code {
color: inherit;
}
.save-btn {
justify-self: start;
border: 0;
border-radius: 8px;
background: #0f766e;
color: #fff;
font: inherit;
font-size: 0.8rem;
padding: 0.45rem 0.75rem;
cursor: pointer;
}
.save-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.compose-label {
display: block;
margin: 0.15rem 0 0.35rem;
color: #475569;
font-size: 0.8rem;
font-weight: 600;
}
.count {
margin: 0.35rem 0 0;
color: #94a3b8;
font-size: 0.75rem;
}
.preview {
margin-top: 0.75rem;
padding: 0.7rem 0.8rem;
border-radius: 12px;
background: var(--accent-subtle);
}
.preview span {
color: var(--accent-deep);
font-size: 0.75rem;
}
.preview p {
margin: 0.3rem 0 0;
color: #134e4a;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.history {
margin-top: 0.9rem;
border-top: 1px solid #eef2f7;
padding-top: 0.75rem;
}
.history header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 0.45rem;
}
.history header strong {
font-size: 0.9rem;
color: #0f172a;
}
.history-list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.45rem;
max-height: 220px;
overflow: auto;
}
.history-list li {
padding: 0.55rem 0.65rem;
border: 1px solid #eef2f7;
border-radius: 10px;
background: #fafbfc;
}
.history-list .meta {
display: flex;
flex-wrap: wrap;
gap: 0.4rem 0.65rem;
align-items: center;
margin-bottom: 0.25rem;
font-size: 0.72rem;
color: #64748b;
}
.history-list .src {
font-weight: 700;
color: #0f766e;
}
.history-list .st.failed {
color: #b91c1c;
}
.history-list .st.sent {
color: #15803d;
}
.history-list p {
margin: 0;
color: #0f172a;
font-size: 0.86rem;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.muted,
.empty {
color: #94a3b8;
font-size: 0.8rem;
margin: 0;
}
.err,
.ok {
margin: 0.55rem 0 0;
font-size: 0.82rem;
}
.err {
color: #dc2626;
}
.ok {
color: #16a34a;
}
</style>
+1 -1
View File
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from 'vue';
import { Button as AButton, Flex as AFlex, theme } from 'ant-design-vue'; import { Button as AButton, Flex as AFlex, theme } from 'ant-design-vue';
import { LeftOutlined } from '@ant-design/icons-vue'; import { LeftOutlined } from '@/icons/ant-bridge';
export type StagePathItem = { export type StagePathItem = {
id: string; id: string;
+1 -1
View File
@@ -7,7 +7,7 @@ import {
Popover as APopover, Popover as APopover,
Typography, Typography,
} from 'ant-design-vue'; } from 'ant-design-vue';
import { SettingOutlined } from '@ant-design/icons-vue'; import { SettingOutlined } from '@/icons/ant-bridge';
import { useTableColumns } from '@/lib/tableColumns'; import { useTableColumns } from '@/lib/tableColumns';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
@@ -19,6 +19,7 @@ import {
Checkbox as ACheckbox, Checkbox as ACheckbox,
Col as ACol, Col as ACol,
Flex as AFlex, Flex as AFlex,
Form as AForm,
FormItem as AFormItem, FormItem as AFormItem,
Input as AInput, Input as AInput,
InputNumber as AInputNumber, InputNumber as AInputNumber,
@@ -239,6 +240,7 @@ watch(
</script> </script>
<template> <template>
<a-form layout="vertical" :colon="false" component="div">
<a-row :gutter="[16, 0]"> <a-row :gutter="[16, 0]">
<a-col <a-col
v-for="f in fields" v-for="f in fields"
@@ -246,10 +248,7 @@ watch(
:xs="24" :xs="24"
:md="fieldSpan(f.type)" :md="fieldSpan(f.type)"
> >
<a-form-item :required="f.required"> <a-form-item :label="f.label" :required="f.required">
<template #label>
{{ f.label }}
</template>
<a-input <a-input
v-if="f.type === 'text' || f.type === 'url'" v-if="f.type === 'text' || f.type === 'url'"
@@ -466,4 +465,5 @@ watch(
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
</a-form>
</template> </template>
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'; import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import axios from 'axios'; import axios from 'axios';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue'; import { CloseOutlined, PlusOutlined } from '@/icons/ant-bridge';
import { import {
Alert as AAlert, Alert as AAlert,
Button as AButton, Button as AButton,
@@ -27,7 +27,7 @@ import {
ScheduleOutlined, ScheduleOutlined,
TeamOutlined, TeamOutlined,
WarningOutlined, WarningOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import type { ActivityDto, ActivityStatus, ActivityType, PaginatedResponse } from '@mento/shared'; import type { ActivityDto, ActivityStatus, ActivityType, PaginatedResponse } from '@mento/shared';
import { ACTIVITY_TYPE_LABELS } from '@mento/shared'; import { ACTIVITY_TYPE_LABELS } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
@@ -389,9 +389,9 @@ function removeBranch(lane: BranchLane) {
> >
<div class="world" :style="worldStyle" :class="{ locked: tool === 'hand' }"> <div class="world" :style="worldStyle" :class="{ locked: tool === 'hand' }">
<div class="flow"> <div class="flow">
<button <a-button
class="node trigger" class="node trigger"
type="button" type="text"
:class="{ on: selected === 'trigger' }" :class="{ on: selected === 'trigger' }"
@click="emit('select', 'trigger')" @click="emit('select', 'trigger')"
> >
@@ -402,7 +402,7 @@ function removeBranch(lane: BranchLane) {
<span class="kind">اگر</span> <span class="kind">اگر</span>
<strong>{{ AUTOMATION_TRIGGER_LABELS[trigger] }}</strong> <strong>{{ AUTOMATION_TRIGGER_LABELS[trigger] }}</strong>
</span> </span>
</button> </a-button>
<template v-for="item in layout.main" :key="item.key"> <template v-for="item in layout.main" :key="item.key">
<div <div
@@ -410,16 +410,16 @@ function removeBranch(lane: BranchLane) {
class="wire" class="wire"
:class="{ open: addAt?.key === item.key, end: item.end }" :class="{ open: addAt?.key === item.key, end: item.end }"
> >
<button <a-button
v-if="canAdd" v-if="canAdd"
class="plus" class="plus"
type="text"
:class="{ big: item.end }" :class="{ big: item.end }"
type="button"
title="افزودن گره" title="افزودن گره"
@click.stop="openAdd(item)" @click.stop="openAdd(item)"
> >
<PlusOutlined :style="{ fontSize: item.end ? '16px' : '14px' }" /> <PlusOutlined :style="{ fontSize: item.end ? '16px' : '14px' }" />
</button> </a-button>
<Transition name="auto-picker"> <Transition name="auto-picker">
<div <div
v-if="addAt?.key === item.key" v-if="addAt?.key === item.key"
@@ -428,9 +428,9 @@ function removeBranch(lane: BranchLane) {
@pointerdown.stop @pointerdown.stop
> >
<div class="picker-head">افزودن گره</div> <div class="picker-head">افزودن گره</div>
<button <a-button
v-if="addAt.allow !== 'action'" v-if="addAt.allow !== 'action'"
type="button" type="text"
class="pick condition" class="pick condition"
@click="pickCondition" @click="pickCondition"
> >
@@ -439,12 +439,12 @@ function removeBranch(lane: BranchLane) {
<strong>شرط</strong> <strong>شرط</strong>
<small>اگر … آنگاه</small> <small>اگر … آنگاه</small>
</span> </span>
</button> </a-button>
<template v-if="addAt.allow !== 'condition'"> <template v-if="addAt.allow !== 'condition'">
<button <a-button
v-for="action in AUTOMATION_ACTIONS" v-for="action in AUTOMATION_ACTIONS"
:key="action" :key="action"
type="button" type="text"
class="pick" class="pick"
:class="action" :class="action"
@click="pickAction(action)" @click="pickAction(action)"
@@ -454,7 +454,7 @@ function removeBranch(lane: BranchLane) {
<strong>{{ actionShort(action) }}</strong> <strong>{{ actionShort(action) }}</strong>
<small>{{ AUTOMATION_ACTION_LABELS[action] }}</small> <small>{{ AUTOMATION_ACTION_LABELS[action] }}</small>
</span> </span>
</button> </a-button>
</template> </template>
</div> </div>
</Transition> </Transition>
@@ -477,14 +477,14 @@ function removeBranch(lane: BranchLane) {
<div v-for="(lane, bi) in layout.branches" :key="lane.key" class="branch"> <div v-for="(lane, bi) in layout.branches" :key="lane.key" class="branch">
<div class="branch-tag"> <div class="branch-tag">
<span>شاخه {{ toFaDigits(bi + 1) }}</span> <span>شاخه {{ toFaDigits(bi + 1) }}</span>
<button <a-button
v-if="canRemoveBranch(lane)" v-if="canRemoveBranch(lane)"
type="button" type="text"
title="حذف این شاخه" title="حذف این شاخه"
@click.stop="removeBranch(lane)" @click.stop="removeBranch(lane)"
> >
<DeleteOutlined :style="{ fontSize: '12px' }" /> <DeleteOutlined :style="{ fontSize: '12px' }" />
</button> </a-button>
</div> </div>
<template v-for="item in lane.items" :key="item.key"> <template v-for="item in lane.items" :key="item.key">
<div <div
@@ -492,15 +492,15 @@ function removeBranch(lane: BranchLane) {
class="wire" class="wire"
:class="{ open: addAt?.key === item.key, end: item.end }" :class="{ open: addAt?.key === item.key, end: item.end }"
> >
<button <a-button
v-if="canAdd" v-if="canAdd"
class="plus" class="plus"
type="button" type="text"
:title="item.allow === 'condition' ? 'افزودن شرط («و»)' : 'افزودن گره'" :title="item.allow === 'condition' ? 'افزودن شرط («و»)' : 'افزودن گره'"
@click.stop="openAdd(item)" @click.stop="openAdd(item)"
> >
<PlusOutlined :style="{ fontSize: '14px' }" /> <PlusOutlined :style="{ fontSize: '14px' }" />
</button> </a-button>
<Transition name="auto-picker"> <Transition name="auto-picker">
<div <div
v-if="addAt?.key === item.key" v-if="addAt?.key === item.key"
@@ -509,9 +509,9 @@ function removeBranch(lane: BranchLane) {
@pointerdown.stop @pointerdown.stop
> >
<div class="picker-head">افزودن گره</div> <div class="picker-head">افزودن گره</div>
<button <a-button
v-if="addAt.allow !== 'action'" v-if="addAt.allow !== 'action'"
type="button" type="text"
class="pick condition" class="pick condition"
@click="pickCondition" @click="pickCondition"
> >
@@ -520,12 +520,12 @@ function removeBranch(lane: BranchLane) {
<strong>شرط</strong> <strong>شرط</strong>
<small>اگر … آنگاه</small> <small>اگر … آنگاه</small>
</span> </span>
</button> </a-button>
<template v-if="addAt.allow !== 'condition'"> <template v-if="addAt.allow !== 'condition'">
<button <a-button
v-for="action in AUTOMATION_ACTIONS" v-for="action in AUTOMATION_ACTIONS"
:key="action" :key="action"
type="button" type="text"
class="pick" class="pick"
:class="action" :class="action"
@click="pickAction(action)" @click="pickAction(action)"
@@ -535,7 +535,7 @@ function removeBranch(lane: BranchLane) {
<strong>{{ actionShort(action) }}</strong> <strong>{{ actionShort(action) }}</strong>
<small>{{ AUTOMATION_ACTION_LABELS[action] }}</small> <small>{{ AUTOMATION_ACTION_LABELS[action] }}</small>
</span> </span>
</button> </a-button>
</template> </template>
</div> </div>
</Transition> </Transition>
@@ -552,16 +552,16 @@ function removeBranch(lane: BranchLane) {
/> />
</template> </template>
</div> </div>
<button <a-button
class="add-branch" class="add-branch"
type="button" type="text"
:disabled="!canAddBranch" :disabled="!canAddBranch"
:title="canAddBranch ? '' : 'ابتدا برای شاخهٔ آخر یک عمل بگذارید'" :title="canAddBranch ? '' : 'ابتدا برای شاخهٔ آخر یک عمل بگذارید'"
@click.stop="emit('addBranch')" @click.stop="emit('addBranch')"
> >
<PlusOutlined :style="{ fontSize: '14px' }" /> <PlusOutlined :style="{ fontSize: '14px' }" />
شاخهٔ جدید شاخهٔ جدید
</button> </a-button>
</div> </div>
</template> </template>
</div> </div>
@@ -711,17 +711,19 @@ function removeBranch(lane: BranchLane) {
.node.trigger { .node.trigger {
width: 14.2rem; width: 14.2rem;
height: auto !important;
min-height: 4.35rem; min-height: 4.35rem;
display: flex; display: flex !important;
align-items: center; align-items: center;
gap: 0.7rem; gap: 0.7rem;
text-align: start; text-align: start;
border-radius: 999px; border-radius: 999px !important;
padding: 0.72rem 1rem; padding: 0.72rem 1rem !important;
border: 1px solid #fdba74; border: 1px solid #fdba74 !important;
background: #fff7ed; background: #fff7ed !important;
box-shadow: 0 10px 24px rgba(23, 33, 28, 0.06); box-shadow: 0 10px 24px rgba(23, 33, 28, 0.06);
cursor: pointer; cursor: pointer;
white-space: normal;
color: inherit; color: inherit;
font: inherit; font: inherit;
flex-shrink: 0; flex-shrink: 0;
@@ -796,13 +798,15 @@ strong {
top: 50%; top: 50%;
left: 50%; left: 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
width: 1.45rem; width: 1.45rem !important;
height: 1.45rem; min-width: 1.45rem !important;
border-radius: 999px; height: 1.45rem !important;
border: 1px solid #99f6e4; padding: 0 !important;
background: #fff; border-radius: 999px !important;
color: #0f766e; border: 1px solid #99f6e4 !important;
display: grid; background: #fff !important;
color: #0f766e !important;
display: grid !important;
place-items: center; place-items: center;
cursor: pointer; cursor: pointer;
z-index: 1; z-index: 1;
@@ -810,8 +814,9 @@ strong {
} }
.plus.big { .plus.big {
width: 2rem; width: 2rem !important;
height: 2rem; min-width: 2rem !important;
height: 2rem !important;
} }
.wire.open .plus, .wire.open .plus,
@@ -898,15 +903,16 @@ strong {
position: absolute; position: absolute;
top: 100%; top: 100%;
inset-inline-start: 0.9rem; inset-inline-start: 0.9rem;
display: inline-flex; height: auto !important;
display: inline-flex !important;
white-space: nowrap; white-space: nowrap;
align-items: center; align-items: center;
gap: 0.35rem; gap: 0.35rem;
border: 1px dashed #f59e0b; border: 1px dashed #f59e0b !important;
background: #fffbeb; background: #fffbeb !important;
color: #b45309; color: #b45309 !important;
border-radius: 999px; border-radius: 999px !important;
padding: 0.35rem 0.8rem; padding: 0.35rem 0.8rem !important;
font: inherit; font: inherit;
font-size: 0.78rem; font-size: 0.78rem;
font-weight: 700; font-weight: 700;
@@ -964,18 +970,20 @@ strong {
} }
.pick { .pick {
display: grid; display: grid !important;
grid-template-columns: 32px 1fr; grid-template-columns: 32px 1fr;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
width: 100%; width: 100%;
border: 0; height: auto !important;
border-radius: 8px; border: 0 !important;
background: transparent; border-radius: 8px !important;
padding: 6px 8px; background: transparent !important;
padding: 6px 8px !important;
text-align: start; text-align: start;
cursor: pointer; cursor: pointer;
font: inherit; font: inherit;
white-space: normal;
color: inherit; color: inherit;
} }
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, type Component } from 'vue'; import { computed, type Component } from 'vue';
import { Button as AButton } from 'ant-design-vue';
import { import {
BellOutlined, BellOutlined,
DeleteOutlined, DeleteOutlined,
@@ -35,9 +36,9 @@ const kindClass = computed(() =>
<template> <template>
<div class="node-wrap"> <div class="node-wrap">
<button <a-button
class="node" class="node"
type="button" type="text"
:class="[kindClass, { on: selected }]" :class="[kindClass, { on: selected }]"
@click="emit('select')" @click="emit('select')"
> >
@@ -49,16 +50,16 @@ const kindClass = computed(() =>
<strong>{{ title }}</strong> <strong>{{ title }}</strong>
<em>{{ hint }}</em> <em>{{ hint }}</em>
</span> </span>
</button> </a-button>
<button <a-button
v-if="removable" v-if="removable"
class="trash" class="trash"
type="button" type="text"
title="حذف" title="حذف"
@click.stop="emit('remove')" @click.stop="emit('remove')"
> >
<DeleteOutlined /> <DeleteOutlined />
</button> </a-button>
</div> </div>
</template> </template>
@@ -71,19 +72,21 @@ const kindClass = computed(() =>
.node { .node {
width: 13.6rem; width: 13.6rem;
display: flex; height: auto !important;
display: flex !important;
align-items: center; align-items: center;
gap: 0.7rem; gap: 0.7rem;
text-align: start; text-align: start;
padding: 0.72rem 0.8rem; padding: 0.72rem 0.8rem !important;
border-radius: var(--radius); border-radius: var(--radius);
border: 1px solid #d5ddd8; border: 1px solid #d5ddd8 !important;
border-inline-start-width: 5px; border-inline-start-width: 5px !important;
background: #fff; background: #fff !important;
box-shadow: 0 10px 24px rgba(23, 33, 28, 0.06); box-shadow: 0 10px 24px rgba(23, 33, 28, 0.06);
cursor: pointer; cursor: pointer;
color: inherit; color: inherit;
font: inherit; font: inherit;
white-space: normal;
} }
.node.create_activity { .node.create_activity {
@@ -180,13 +183,15 @@ em {
position: absolute; position: absolute;
top: -0.45rem; top: -0.45rem;
inset-inline-end: -0.45rem; inset-inline-end: -0.45rem;
width: 1.55rem; width: 1.55rem !important;
height: 1.55rem; min-width: 1.55rem !important;
border-radius: 999px; height: 1.55rem !important;
border: 1px solid #fecaca; padding: 0 !important;
background: #fff; border-radius: 999px !important;
color: #b91c1c; border: 1px solid #fecaca !important;
display: grid; background: #fff !important;
color: #b91c1c !important;
display: grid !important;
place-items: center; place-items: center;
cursor: pointer; cursor: pointer;
opacity: 0; opacity: 0;
@@ -15,11 +15,28 @@ import {
type FollowUpMessageKind, type FollowUpMessageKind,
type SalesCopilotSessionDto, type SalesCopilotSessionDto,
} from '@mento/shared'; } from '@mento/shared';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
FormItem as AFormItem,
Input as AInput,
Row as ARow,
Select as ASelect,
Space as ASpace,
Tag as ATag,
Textarea as ATextarea,
Typography,
} from 'ant-design-vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali'; import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { UiButton } from '@/components/ui';
import SmsComposeModal from '@/components/SmsComposeModal.vue'; import SmsComposeModal from '@/components/SmsComposeModal.vue';
const { Text: ATypographyText, Title: ATypographyTitle, Paragraph: ATypographyParagraph } =
Typography;
const props = defineProps<{ const props = defineProps<{
personId?: string | null; personId?: string | null;
leadId?: string | null; leadId?: string | null;
@@ -50,6 +67,19 @@ const history = ref<SalesCopilotSessionDto[]>([]);
const smsOpen = ref(false); const smsOpen = ref(false);
const step = ref<'form' | 'result'>('form'); const step = ref<'form' | 'result'>('form');
const topicOptions = COPILOT_TOPICS.map((item) => ({
value: item,
label: COPILOT_TOPIC_LABELS[item],
}));
const goalOptions = COPILOT_GOALS.map((item) => ({
value: item,
label: COPILOT_GOAL_LABELS[item],
}));
const messageKindOptions = FOLLOW_UP_MESSAGE_KINDS.map((kind) => ({
value: kind,
label: FOLLOW_UP_MESSAGE_LABELS[kind],
}));
const facts = computed<CopilotFacts>(() => ({ const facts = computed<CopilotFacts>(() => ({
customerName: props.customerName, customerName: props.customerName,
stageName: props.stageName, stageName: props.stageName,
@@ -177,128 +207,182 @@ watch(
</script> </script>
<template> <template>
<section class="copilot"> <a-space direction="vertical" :style="{ width: '100%' }">
<p class="banner"> <a-alert
دستیار مربی فروش است. پیشنهادش تا وقتی تأیید نکنید در پرونده به‌عنوان واقعیت ذخیره نمی‌شود و پیام بیرونی هم بدون تأیید شما ارسال نمی‌شود. type="info"
</p> show-icon
<article class="card summary"> message="دستیار مربی فروش است. پیشنهادش تا وقتی تأیید نکنید در پرونده به‌عنوان واقعیت ذخیره نمی‌شود و پیام بیرونی هم بدون تأیید شما ارسال نمی‌شود."
<div> />
<strong>{{ customerName || 'مخاطب' }}</strong>
<span v-if="stageName">مرحله: {{ stageName }}</span>
</div>
<span v-if="discLabel" class="pill">DISC احتمالی {{ discLabel }}</span>
<span v-else class="muted">پروفایل DISC تازه و معتبر نیست</span>
</article>
<form v-show="step === 'form'" class="card" @submit.prevent="analyze"> <a-card size="small">
<label> <a-space wrap :style="{ width: '100%', justifyContent: 'space-between' }">
موضوع مکالمه <a-space direction="vertical" :size="0">
<select v-model="topic"> <a-typography-text strong>{{ customerName || 'مخاطب' }}</a-typography-text>
<option v-for="item in COPILOT_TOPICS" :key="item" :value="item">{{ COPILOT_TOPIC_LABELS[item] }}</option> <a-typography-text v-if="stageName" type="secondary">مرحله: {{ stageName }}</a-typography-text>
</select> </a-space>
</label> <a-tag v-if="discLabel" color="cyan">DISC احتمالی {{ discLabel }}</a-tag>
<label> <a-typography-text v-else type="secondary">پروفایل DISC تازه و معتبر نیست</a-typography-text>
هدف شما </a-space>
<select v-model="goal"> </a-card>
<option v-for="item in COPILOT_GOALS" :key="item" :value="item">{{ COPILOT_GOAL_LABELS[item] }}</option>
</select>
</label>
<label>
حرف مشتری
<textarea v-model="statement" rows="4" required placeholder="جملهٔ دقیق مشتری، اعتراض یا دغدغه‌اش" />
</label>
<label>
نشانه‌های رفتاری مشاهده‌شده
<textarea v-model="behaviorNotes" rows="2" placeholder="مثلاً عجله داشت، جزئیات خواست، یا خواست مشورت کند" />
</label>
<UiButton type="submit" variant="primary" :disabled="busy">تحلیل مکالمه و پیشنهاد راهکار</UiButton>
</form>
<div v-if="analysis && step === 'result'" class="stack"> <a-card v-show="step === 'form'" size="small">
<article class="card"> <a-row :gutter="[16, 0]">
<header class="head"> <a-col :xs="24" :md="12">
<h3>تحلیل</h3> <a-form-item label="موضوع مکالمه">
<button type="button" class="link" @click="step = 'form'">ویرایش ورودی</button> <a-select v-model:value="topic" :options="topicOptions" :style="{ width: '100%' }" />
</header> </a-form-item>
<p>{{ analysis.customer_statement_summary }}</p> </a-col>
<p v-if="analysis.objection_label"><b>دستهٔ احتمالی:</b> {{ analysis.objection_label }}</p> <a-col :xs="24" :md="12">
<a-form-item label="هدف شما">
<a-select v-model:value="goal" :options="goalOptions" :style="{ width: '100%' }" />
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="حرف مشتری" required>
<a-textarea
v-model:value="statement"
:rows="4"
placeholder="جملهٔ دقیق مشتری، اعتراض یا دغدغه‌اش"
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="نشانه‌های رفتاری مشاهده‌شده">
<a-textarea
v-model:value="behaviorNotes"
:rows="2"
placeholder="مثلاً عجله داشت، جزئیات خواست، یا خواست مشورت کند"
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-button type="primary" :loading="busy" :disabled="!statement.trim()" @click="analyze">
تحلیل مکالمه و پیشنهاد راهکار
</a-button>
</a-col>
</a-row>
</a-card>
<template v-if="analysis && step === 'result'">
<a-card size="small">
<template #title>تحلیل</template>
<template #extra>
<a-button type="link" @click="step = 'form'">ویرایش ورودی</a-button>
</template>
<a-typography-paragraph>{{ analysis.customer_statement_summary }}</a-typography-paragraph>
<a-typography-paragraph v-if="analysis.objection_label">
<a-typography-text strong>دستهٔ احتمالی:</a-typography-text>
{{ analysis.objection_label }}
</a-typography-paragraph>
<ul> <ul>
<li v-for="reason in analysis.possible_underlying_reasons" :key="reason">{{ reason }}</li> <li v-for="reason in analysis.possible_underlying_reasons" :key="reason">{{ reason }}</li>
</ul> </ul>
<p v-if="analysis.missing_information.length" class="warn"> <a-alert
اطلاعات ناموجود: {{ analysis.missing_information.join('؛ ') }} v-if="analysis.missing_information.length"
</p> type="warning"
<p class="muted">{{ analysis.confidence_note }}</p> show-icon
<p v-if="analysis.disc_context" class="muted">{{ analysis.disc_context.note }}</p> :message="`اطلاعات ناموجود: ${analysis.missing_information.join('؛ ')}`"
</article> :style="{ marginBottom: '8px' }"
<article class="card"> />
<h3>سؤال پیشنهادی</h3> <a-typography-text type="secondary">{{ analysis.confidence_note }}</a-typography-text>
<p>{{ analysis.recommended_question }}</p> <br v-if="analysis.disc_context" />
<button type="button" class="link" @click="copy(analysis.recommended_question)">کپی سؤال</button> <a-typography-text v-if="analysis.disc_context" type="secondary">
</article> {{ analysis.disc_context.note }}
<article class="card"> </a-typography-text>
<h3>پاسخ پیشنهادی</h3> </a-card>
<textarea v-model="responseText" rows="5" />
<div class="actions"> <a-card size="small" title="سؤال پیشنهادی">
<UiButton size="sm" variant="outline" type="button" @click="copy(responseText)">کپی پاسخ</UiButton> <a-typography-paragraph>{{ analysis.recommended_question }}</a-typography-paragraph>
<UiButton size="sm" variant="outline" type="button" :disabled="busy" @click="analyze">تولید پاسخ جدید</UiButton> <a-button type="link" @click="copy(analysis.recommended_question)">کپی سؤال</a-button>
</div> </a-card>
<p class="warn">خطای رایج: {{ analysis.common_mistake }}</p>
</article> <a-card size="small" title="پاسخ پیشنهادی">
<article class="card"> <a-textarea v-model:value="responseText" :rows="5" />
<h3>راهبرد</h3> <a-space :style="{ marginTop: '8px' }">
<a-button @click="copy(responseText)">کپی پاسخ</a-button>
<a-button :loading="busy" @click="analyze">تولید پاسخ جدید</a-button>
</a-space>
<a-alert
type="warning"
show-icon
:message="`خطای رایج: ${analysis.common_mistake}`"
:style="{ marginTop: '8px' }"
/>
</a-card>
<a-card size="small" title="راهبرد">
<ul> <ul>
<li v-for="line in analysis.sales_strategy" :key="line">{{ line }}</li> <li v-for="line in analysis.sales_strategy" :key="line">{{ line }}</li>
</ul> </ul>
<h3>اقدام بعدی</h3> <a-typography-title :level="5">اقدام بعدی</a-typography-title>
<p>{{ analysis.next_best_action }}</p> <a-typography-paragraph>{{ analysis.next_best_action }}</a-typography-paragraph>
<label> <a-row :gutter="[16, 0]">
تاریخ پیگیری <a-col :xs="24" :md="12">
<input v-model="followUpAt" type="date" /> <a-form-item label="تاریخ پیگیری">
</label> <JalaliDateInput v-model="followUpAt" />
<label> </a-form-item>
نتیجهٔ تماس </a-col>
<input v-model="callOutcome" type="text" maxlength="500" /> <a-col :xs="24" :md="12">
</label> <a-form-item label="نتیجهٔ تماس">
<label> <a-input v-model:value="callOutcome" :maxlength="500" />
یادداشت کارشناس </a-form-item>
<textarea v-model="agentNote" rows="2" /> </a-col>
</label> <a-col :span="24">
</article> <a-form-item label="یادداشت کارشناس">
<article class="card"> <a-textarea v-model:value="agentNote" :rows="2" />
<h3>متن پیگیری</h3> </a-form-item>
<select v-model="messageKind"> </a-col>
<option v-for="kind in FOLLOW_UP_MESSAGE_KINDS" :key="kind" :value="kind">{{ FOLLOW_UP_MESSAGE_LABELS[kind] }}</option> </a-row>
</select> </a-card>
<textarea v-model="messageText" rows="4" />
<div class="actions"> <a-card size="small" title="متن پیگیری">
<UiButton size="sm" variant="outline" type="button" @click="copy(messageText)">کپی متن</UiButton> <a-form-item label="نوع پیام">
<UiButton v-if="smsEndpoint && phone" size="sm" variant="outline" type="button" @click="smsOpen = true"> <a-select
v-model:value="messageKind"
:options="messageKindOptions"
:style="{ width: '100%' }"
/>
</a-form-item>
<a-textarea v-model:value="messageText" :rows="4" />
<a-space :style="{ marginTop: '8px' }">
<a-button @click="copy(messageText)">کپی متن</a-button>
<a-button v-if="smsEndpoint && phone" @click="smsOpen = true">
ارسال پیامک با تأیید ارسال پیامک با تأیید
</UiButton> </a-button>
</div> </a-space>
</article> </a-card>
<div class="actions">
<UiButton variant="primary" type="button" :disabled="busy" @click="save('confirmed')">ثبت نتیجه</UiButton>
<UiButton variant="outline" type="button" :disabled="busy" @click="createTask">ایجاد وظیفه پیگیری</UiButton>
<UiButton variant="ghost" type="button" :disabled="busy" @click="save('dismissed')">رد پیشنهاد</UiButton>
</div>
</div>
<p v-if="error" class="error">{{ error }}</p> <a-space wrap>
<a-button type="primary" :loading="busy" @click="save('confirmed')">ثبت نتیجه</a-button>
<a-button :loading="busy" @click="createTask">ایجاد وظیفه پیگیری</a-button>
<a-button type="text" :loading="busy" @click="save('dismissed')">رد پیشنهاد</a-button>
</a-space>
</template>
<article v-if="history.length" class="card"> <a-alert v-if="error" type="error" show-icon :message="error" />
<h3>نتایج ثبت‌شده</h3>
<ul class="history"> <a-card v-if="history.length" size="small" title="نتایج ثبت‌شده">
<li v-for="item in history" :key="item.id"> <a-space direction="vertical" :style="{ width: '100%' }">
<strong>{{ item.status === 'confirmed' ? 'تأییدشده' : 'ردشده' }}</strong> <a-space
<span>{{ formatJalaliNumeric(new Date(item.createdAt)) }} · {{ item.userName }}</span> v-for="item in history"
<span>{{ item.analysis.objection_label || 'بدون دسته' }}</span> :key="item.id"
<span v-if="item.activityId">وظیفه ساخته شد</span> wrap
</li> :style="{ width: '100%', justifyContent: 'space-between' }"
</ul> >
<p class="muted">{{ toFaDigits(history.length) }} نتیجه در تاریخچه مانده است.</p> <a-typography-text strong>
</article> {{ item.status === 'confirmed' ? 'تأییدشده' : 'ردشده' }}
</a-typography-text>
<a-typography-text type="secondary">
{{ formatJalaliNumeric(new Date(item.createdAt)) }} · {{ item.userName }}
</a-typography-text>
<a-typography-text>{{ item.analysis.objection_label || 'بدون دسته' }}</a-typography-text>
<a-tag v-if="item.activityId" color="success">وظیفه ساخته شد</a-tag>
</a-space>
</a-space>
<a-typography-text type="secondary" :style="{ display: 'block', marginTop: '8px' }">
{{ toFaDigits(history.length) }} نتیجه در تاریخچه مانده است.
</a-typography-text>
</a-card>
<SmsComposeModal <SmsComposeModal
v-if="smsEndpoint && phone" v-if="smsEndpoint && phone"
@@ -311,22 +395,5 @@ watch(
title="ارسال پیامک پیگیری" title="ارسال پیامک پیگیری"
@close="smsOpen = false" @close="smsOpen = false"
/> />
</section> </a-space>
</template> </template>
<style scoped>
.copilot, .stack { display: flex; flex-direction: column; gap: 0.75rem; }
.banner, .card { background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 0.9rem 1rem; }
.banner { background: #f8fafc; color: #475569; font-size: 0.86rem; }
.summary, .head, .actions, .history li { display: flex; justify-content: space-between; gap: 0.6rem; align-items: center; flex-wrap: wrap; }
label { display: flex; flex-direction: column; gap: 0.3rem; margin-bottom: 0.55rem; font-weight: 700; }
textarea, select, input { font: inherit; font-weight: 400; border: 1px solid #cbd5e1; border-radius: 10px; padding: 0.5rem; width: 100%; }
.pill { background: #ecfeff; color: #0f766e; border-radius: 999px; padding: 0.1rem 0.55rem; font-size: 0.78rem; font-weight: 800; }
.muted { color: #64748b; font-size: 0.82rem; font-weight: 400; }
.warn { color: #9a3412; }
.error { color: #b91c1c; }
.link { border: 0; background: transparent; color: #0f766e; cursor: pointer; }
.history { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 0.4rem; }
h3 { margin: 0 0 0.4rem; }
ul { margin: 0.3rem 0 0; padding-inline-start: 1.1rem; }
</style>
+141 -272
View File
@@ -2,12 +2,28 @@
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted, ref } from 'vue';
import type { GamificationRedemptionDto, GamificationRewardDto } from '@mento/shared'; import type { GamificationRedemptionDto, GamificationRewardDto } from '@mento/shared';
import { GAMIFICATION_REDEMPTION_LABELS } from '@mento/shared'; import { GAMIFICATION_REDEMPTION_LABELS } from '@mento/shared';
import UiIcon from '@/components/UiIcon.vue'; import {
import { UiButton, UiModal, UiTextarea } from '@/components/ui'; Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
FormItem as AFormItem,
Modal as AModal,
Progress as AProgress,
Row as ARow,
Space as ASpace,
Tag as ATag,
Textarea as ATextarea,
Typography,
} from 'ant-design-vue';
import { DollarOutlined } from '@/icons/ant-bridge';
import VsIcon from '@/components/VsIcon.vue';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { apiError, faNum, formatDateTime } from '@/lib/gamification'; import { apiError, faNum, formatDateTime } from '@/lib/gamification';
import { useClub } from './club-context'; import { useClub } from './club-context';
const { Text: ATypographyText, Title: ATypographyTitle } = Typography;
const { me, reload } = useClub(); const { me, reload } = useClub();
const rewards = ref<GamificationRewardDto[]>([]); const rewards = ref<GamificationRewardDto[]>([]);
const mine = ref<GamificationRedemptionDto[]>([]); const mine = ref<GamificationRedemptionDto[]>([]);
@@ -40,7 +56,7 @@ function open(r: GamificationRewardDto) {
picked.value = r; picked.value = r;
} }
async function confirm() { async function confirmRedeem() {
if (!picked.value) return; if (!picked.value) return;
busy.value = true; busy.value = true;
try { try {
@@ -62,292 +78,145 @@ async function confirm() {
} }
} }
function redemptionColor(status: GamificationRedemptionDto['status']) {
if (status === 'pending') return 'warning';
if (status === 'rejected') return 'error';
return 'success';
}
onMounted(load); onMounted(load);
</script> </script>
<template> <template>
<section class="store"> <a-row :gutter="[16, 16]">
<div class="wallet"> <a-col :span="24">
<UiIcon name="dollar" :size="20" /> <a-card size="small">
<span>موجودی شما: <b>{{ faNum(coins) }}</b> سکه</span> <a-space>
<small>سکه را با انجام فعالیت‌ها، نشان‌ها و بونوس‌ها جمع کن.</small> <DollarOutlined />
</div> <a-typography-text>
موجودی شما:
<a-typography-text strong>{{ faNum(coins) }}</a-typography-text>
سکه
</a-typography-text>
<a-typography-text type="secondary">
سکه را با انجام فعالیت‌ها، نشان‌ها و بونوس‌ها جمع کن.
</a-typography-text>
</a-space>
</a-card>
</a-col>
<p v-if="ok" class="ok">{{ ok }}</p> <a-col v-if="ok" :span="24">
<p v-if="error" class="err">{{ error }}</p> <a-alert type="success" show-icon :message="ok" />
</a-col>
<a-col v-if="error" :span="24">
<a-alert type="error" show-icon :message="error" />
</a-col>
<div class="grid"> <a-col :span="24">
<article <a-row :gutter="[16, 16]">
<a-col
v-for="r in rewards" v-for="r in rewards"
:key="r.id" :key="r.id"
class="reward" :xs="24"
:style="{ '--c': r.color }" :sm="12"
:class="{ locked: coins < r.cost }" :md="8"
:lg="6"
> >
<span class="ic"><UiIcon :name="r.icon as never" :size="26" /></span> <a-card size="small" :style="{ borderTop: `3px solid ${r.color}` }">
<h4>{{ r.name }}</h4> <a-space direction="vertical" :style="{ width: '100%' }">
<p v-if="r.description">{{ r.description }}</p> <VsIcon :name="String(r.icon)" map="ui" :size="26" :style="{ color: r.color }" />
<div class="price"> <a-typography-title :level="5" :style="{ margin: 0 }">{{ r.name }}</a-typography-title>
<b>{{ faNum(r.cost) }}</b> <a-typography-text v-if="r.description" type="secondary">{{ r.description }}</a-typography-text>
<small>سکه</small> <a-typography-text strong :style="{ color: '#b45309' }">
</div> {{ faNum(r.cost) }}
<div class="bar"><i :style="{ width: `${Math.min(100, Math.round((coins / r.cost) * 100))}%` }" /></div> <a-typography-text type="secondary">سکه</a-typography-text>
<small v-if="r.stock != null" class="stock">موجودی: {{ faNum(r.stock) }}</small> </a-typography-text>
<UiButton <a-progress
size="sm" :percent="Math.min(100, Math.round((coins / r.cost) * 100))"
:show-info="false"
:stroke-color="r.color"
/>
<a-typography-text v-if="r.stock != null" type="secondary">
موجودی: {{ faNum(r.stock) }}
</a-typography-text>
<a-button
block block
:variant="coins >= r.cost ? 'primary' : 'outline'" :type="coins >= r.cost ? 'primary' : 'default'"
:disabled="coins < r.cost || r.stock === 0" :disabled="coins < r.cost || r.stock === 0"
@click="open(r)" @click="open(r)"
> >
{{ coins >= r.cost ? 'دریافت پاداش' : `${faNum(r.cost - coins)} سکه دیگر` }} {{ coins >= r.cost ? 'دریافت پاداش' : `${faNum(r.cost - coins)} سکه دیگر` }}
</UiButton> </a-button>
</article> </a-space>
<p v-if="!rewards.length" class="empty">هنوز پاداشی تعریف نشده است.</p> </a-card>
</div> </a-col>
<a-col v-if="!rewards.length" :span="24">
<a-typography-text type="secondary">هنوز پاداشی تعریف نشده است.</a-typography-text>
</a-col>
</a-row>
</a-col>
<section v-if="mine.length" class="mine"> <a-col v-if="mine.length" :span="24">
<h3>درخواست‌های من</h3> <a-card size="small" title="درخواست‌های من">
<ul> <a-space direction="vertical" :style="{ width: '100%' }">
<li v-for="m in mine" :key="m.id"> <a-space
<UiIcon :name="m.rewardIcon as never" :size="16" /> v-for="m in mine"
<span class="m-body"> :key="m.id"
<b>{{ m.rewardName }}</b> wrap
<small>{{ formatDateTime(m.createdAt) }}<template v-if="m.decisionNote"> · {{ m.decisionNote }}</template></small> :style="{ width: '100%', justifyContent: 'space-between' }"
>
<a-space>
<VsIcon :name="String(m.rewardIcon)" map="ui" :size="16" />
<span>
<a-typography-text strong>{{ m.rewardName }}</a-typography-text>
<br />
<a-typography-text type="secondary">
{{ formatDateTime(m.createdAt) }}
<template v-if="m.decisionNote"> · {{ m.decisionNote }}</template>
</a-typography-text>
</span> </span>
<span class="cost">{{ faNum(m.cost) }} سکه</span> </a-space>
<span class="st" :class="m.status">{{ GAMIFICATION_REDEMPTION_LABELS[m.status] }}</span> <a-space>
</li> <a-typography-text type="warning">{{ faNum(m.cost) }} سکه</a-typography-text>
</ul> <a-tag :color="redemptionColor(m.status)">
</section> {{ GAMIFICATION_REDEMPTION_LABELS[m.status] }}
</a-tag>
</a-space>
</a-space>
</a-space>
</a-card>
</a-col>
<UiModal :open="!!picked" title="تأیید دریافت پاداش" @close="picked = null"> <a-modal
<div v-if="picked" class="confirm"> :open="!!picked"
<p> title="تأیید دریافت پاداش"
برای دریافت <b>«{{ picked.name }}»</b> مبلغ <b>{{ faNum(picked.cost) }}</b> سکه از موجودی شما کسر می‌شود. :confirm-loading="busy"
</p> ok-text="تأیید و دریافت"
<p class="muted"> cancel-text="انصراف"
destroy-on-close
@ok="confirmRedeem"
@cancel="picked = null"
>
<template v-if="picked">
<a-typography-text>
برای دریافت <a-typography-text strong>«{{ picked.name }}»</a-typography-text>
مبلغ <a-typography-text strong>{{ faNum(picked.cost) }}</a-typography-text>
سکه از موجودی شما کسر می‌شود.
</a-typography-text>
<a-typography-text type="secondary" :style="{ display: 'block', marginTop: '8px' }">
موجودی پس از دریافت: {{ faNum(coins - picked.cost) }} سکه موجودی پس از دریافت: {{ faNum(coins - picked.cost) }} سکه
<template v-if="picked.requiresApproval"> — این درخواست پس از تأیید مدیر نهایی می‌شود و در صورت رد، سکه‌ها برمی‌گردد.</template> <template v-if="picked.requiresApproval">
</p> — این درخواست پس از تأیید مدیر نهایی می‌شود و در صورت رد، سکه‌ها برمی‌گردد.
<UiTextarea v-model="note" placeholder="توضیح (اختیاری) — مثلاً زمان یا مدل دلخواه" :rows="2" />
</div>
<template #footer>
<UiButton variant="ghost" @click="picked = null">انصراف</UiButton>
<UiButton :loading="busy" @click="confirm">تأیید و دریافت</UiButton>
</template> </template>
</UiModal> </a-typography-text>
</section> <a-form-item label="توضیح" :style="{ marginTop: '12px', marginBottom: 0 }">
<a-textarea
v-model:value="note"
:rows="2"
placeholder="توضیح (اختیاری) — مثلاً زمان یا مدل دلخواه"
/>
</a-form-item>
</template>
</a-modal>
</a-row>
</template> </template>
<style scoped>
.store {
display: grid;
gap: var(--sp-4);
min-width: 0;
}
.wallet {
display: flex;
align-items: center;
gap: var(--sp-2);
flex-wrap: wrap;
padding: var(--sp-3) var(--sp-4);
border-radius: calc(var(--radius) + 4px);
background: linear-gradient(135deg, #fffbeb, #fef3c7);
border: 1px solid #fde68a;
color: #92400e;
}
.wallet b {
font-size: 1.2rem;
}
.wallet small {
color: #b45309;
margin-inline-start: auto;
}
.ok {
margin: 0;
color: var(--success-deep);
background: var(--success-soft);
padding: var(--sp-2) var(--sp-3);
border-radius: var(--radius);
}
.err {
margin: 0;
color: var(--danger);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
gap: var(--sp-3);
}
.reward {
--c: var(--accent);
display: grid;
gap: var(--sp-2);
align-content: start;
padding: var(--sp-4);
border-radius: calc(var(--radius) + 4px);
background: var(--surface);
border: 1px solid var(--line);
border-top: 3px solid var(--c);
box-shadow: var(--shadow-xs);
min-width: 0;
}
.ic {
width: 52px;
height: 52px;
border-radius: 14px;
display: grid;
place-items: center;
color: var(--c);
background: color-mix(in srgb, var(--c) 14%, transparent);
}
.reward h4 {
margin: 0;
font-size: var(--fs-md);
color: var(--ink);
}
.reward p {
margin: 0;
font-size: var(--fs-sm);
color: var(--muted);
}
.price {
display: flex;
align-items: baseline;
gap: 4px;
color: #b45309;
}
.price b {
font-size: 1.3rem;
font-weight: 800;
}
.bar {
height: 6px;
border-radius: 999px;
background: var(--line-light);
overflow: hidden;
}
.bar i {
display: block;
height: 100%;
background: var(--c);
}
.stock {
font-size: var(--fs-xs);
color: var(--muted);
}
.empty {
color: var(--muted);
}
.mine {
background: var(--surface);
border: 1px solid var(--line);
border-radius: calc(var(--radius) + 4px);
padding: var(--sp-4);
display: grid;
gap: var(--sp-2);
}
.mine h3 {
margin: 0;
font-size: var(--fs-md);
}
.mine ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
}
.mine li {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) 0;
border-bottom: 1px solid var(--line-light);
flex-wrap: wrap;
}
.mine li:last-child {
border-bottom: 0;
}
.m-body {
flex: 1;
min-width: 0;
display: grid;
}
.m-body b {
font-size: var(--fs-sm);
}
.m-body small {
font-size: var(--fs-xs);
color: var(--muted);
}
.cost {
font-size: var(--fs-xs);
color: #b45309;
font-weight: 700;
}
.st {
font-size: 0.7rem;
font-weight: 700;
padding: 2px 8px;
border-radius: 999px;
background: var(--surface-subtle);
color: var(--ink-secondary);
}
.st.pending {
background: var(--warning-soft);
color: var(--warning-deep);
}
.st.approved,
.st.delivered {
background: var(--success-soft);
color: var(--success-deep);
}
.st.rejected {
background: var(--danger-soft);
color: var(--danger);
}
.confirm {
display: grid;
gap: var(--sp-3);
}
.confirm p {
margin: 0;
}
.muted {
color: var(--muted);
font-size: var(--fs-sm);
}
</style>
@@ -0,0 +1,365 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import {
AutoComplete as AAutoComplete,
Button as AButton,
Flex as AFlex,
Input as AInput,
InputNumber as AInputNumber,
Table as ATable,
Typography,
theme,
} from 'ant-design-vue';
import { DeleteOutlined, PlusOutlined } from '@/icons/ant-bridge';
import { matchesSearch } from '@/lib/search';
import {
blockNonNumericKeydown,
formatMoney,
groupedNumberFormatter,
groupedNumberParser,
sanitizeNumericClipboard,
} from '@/lib/money';
import type { InvoiceGridColKey } from './types';
import { toFaDigits } from '@/lib/jalali';
import type { ProductDto } from '@mento/shared';
import {
computeGridLineTotal,
emptyInvoiceGridLine,
type InvoiceGridLine,
} from './types';
import { useGridKeyboard } from './useGridKeyboard';
const props = defineProps<{
products: ProductDto[];
currency: string;
}>();
const lines = defineModel<InvoiceGridLine[]>('lines', { required: true });
const emit = defineEmits<{
'request-focus-first': [];
}>();
const { token } = theme.useToken();
const { Text: ATypographyText } = Typography;
const cellRefs = ref<Record<string, HTMLElement | null>>({});
const productOpenRow = ref<number | null>(null);
const productSearch = ref('');
const {
registerCell,
focusCell,
moveNext,
onCellKeydown,
ensureTrailingEmpty,
} = useGridKeyboard({ lines, cellRefs });
onMounted(() => {
if (!lines.value.length) lines.value = [emptyInvoiceGridLine()];
else ensureTrailingEmpty();
});
watch(
() => lines.value.length,
() => ensureTrailingEmpty(),
);
const productOptions = computed(() => {
const q = productSearch.value.trim();
const list = !q
? props.products
: props.products.filter((p) =>
matchesSearch(q, [p.name, p.sku, p.description, p.category, p.unit]),
);
return list.slice(0, 40).map((p) => ({
value: p.id,
label: p.sku ? `${p.name} · ${p.sku}` : p.name,
}));
});
function productLabel(line: InvoiceGridLine) {
if (line.name) return line.name;
const product = props.products.find((p) => p.id === line.productId);
return product?.name ?? '';
}
function pickProduct(row: number, productId: string) {
const line = lines.value[row];
if (!line) return;
const product = props.products.find((p) => p.id === productId);
if (!product) {
line.productId = '';
line.name = productId;
return;
}
line.productId = product.id;
line.name = product.name;
line.description = product.description ?? line.description;
line.unit = product.unit ?? line.unit ?? 'عدد';
if (product.unitPrice != null) line.unitPrice = Number(product.unitPrice);
productOpenRow.value = null;
void moveNext(row, 'product');
}
function onProductSearch(value: string, row: number) {
productSearch.value = value;
const line = lines.value[row];
if (!line) return;
line.name = value;
if (line.productId) {
const current = props.products.find((p) => p.id === line.productId);
if (!current || current.name !== value) line.productId = '';
}
}
function onProductSelect(value: string, row: number) {
pickProduct(row, value);
}
function addRow() {
lines.value.push(emptyInvoiceGridLine());
void focusCell(lines.value.length - 1, 'product');
}
function removeRow(row: number) {
if (lines.value.length <= 1) {
lines.value[0] = emptyInvoiceGridLine();
void focusCell(0, 'product');
return;
}
lines.value.splice(row, 1);
ensureTrailingEmpty();
}
function money(n: number) {
return formatMoney(n, props.currency);
}
function onNumberKeydown(
event: KeyboardEvent,
row: number,
col: InvoiceGridColKey,
decimals: number,
) {
blockNonNumericKeydown(event, {
allowDecimal: decimals > 0,
allowMinus: false,
});
if (event.defaultPrevented) return;
onCellKeydown(event, row, col);
}
function onNumberPaste(event: ClipboardEvent, decimals: number) {
const pasted = event.clipboardData?.getData('text') ?? '';
if (!pasted) return;
const cleaned = sanitizeNumericClipboard(pasted, {
allowDecimal: decimals > 0,
allowMinus: false,
});
if (cleaned === pasted) return;
event.preventDefault();
const input = event.target;
if (!(input instanceof HTMLInputElement)) return;
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? input.value.length;
const next = `${input.value.slice(0, start)}${cleaned}${input.value.slice(end)}`;
input.value = next;
input.dispatchEvent(new Event('input', { bubbles: true }));
}
defineExpose({
focusFirst: () => focusCell(0, 'product'),
ensureTrailingEmpty,
});
emit('request-focus-first');
/**
* ستون‌های بدون width (کالا/شرح) فضای اضافه را می‌گیرند.
* اگر به همه width بدهیم، Ant عرض را پخش می‌کند و ستون # کش می‌آید.
*/
const columns = [
{
key: 'index',
title: '#',
width: 48,
align: 'center' as const,
customHeaderCell: () => ({ style: { paddingInline: '4px' } }),
customCell: () => ({ style: { paddingInline: '4px' } }),
},
{ key: 'product', title: 'کالا / خدمت', ellipsis: true },
{ key: 'description', title: 'شرح', ellipsis: true },
{ key: 'quantity', title: 'تعداد', width: 110 },
{ key: 'unit', title: 'واحد', width: 90 },
{ key: 'unitPrice', title: 'فی', width: 130 },
{ key: 'discount', title: 'تخفیف', width: 120 },
{ key: 'tax', title: 'مالیات٪', width: 100 },
{ key: 'total', title: 'جمع', width: 130 },
{
key: 'actions',
title: '',
width: 40,
align: 'center' as const,
customHeaderCell: () => ({ style: { paddingInline: '2px' } }),
customCell: () => ({ style: { paddingInline: '2px' } }),
},
];
</script>
<template>
<a-flex vertical :gap="token.marginSM" :style="{ minWidth: 0, width: '100%' }">
<a-table
:columns="columns"
:data-source="lines"
:pagination="false"
:row-key="(row: InvoiceGridLine) => row.key"
bordered
:scroll="{ x: 1100 }"
>
<template #headerCell="{ column }">
<span>{{ column.title }}</span>
</template>
<template #bodyCell="{ column, index }">
<template v-if="column.key === 'index'">
<a-typography-text type="secondary">{{ toFaDigits(index + 1) }}</a-typography-text>
</template>
<template v-else-if="column.key === 'product'">
<div :ref="(el) => registerCell(index, 'product', el)">
<a-auto-complete
:value="productLabel(lines[index]!)"
:options="productOptions"
:open="productOpenRow === index"
style="width: 100%"
placeholder="نام یا کد کالا"
@search="(v: string) => onProductSearch(v, index)"
@select="(v: string | number | object) => onProductSelect(String(v), index)"
@focus="productOpenRow = index"
@blur="productOpenRow = null"
@keydown="
(e: KeyboardEvent) =>
onCellKeydown(e, index, 'product', {
dropdownOpen: productOpenRow === index,
})
"
/>
</div>
</template>
<template v-else-if="column.key === 'description'">
<div :ref="(el) => registerCell(index, 'description', el)">
<a-input
v-model:value="lines[index]!.description"
placeholder="شرح"
@keydown="(e: KeyboardEvent) => onCellKeydown(e, index, 'description')"
/>
</div>
</template>
<template v-else-if="column.key === 'quantity'">
<div :ref="(el) => registerCell(index, 'quantity', el)">
<a-input-number
v-model:value="lines[index]!.quantity"
:min="0"
:controls="false"
:formatter="groupedNumberFormatter(2)"
:parser="groupedNumberParser(2)"
style="width: 100%"
@keydown="(e: KeyboardEvent) => onNumberKeydown(e, index, 'quantity', 2)"
@paste="(e: ClipboardEvent) => onNumberPaste(e, 2)"
/>
</div>
</template>
<template v-else-if="column.key === 'unit'">
<div :ref="(el) => registerCell(index, 'unit', el)">
<a-input
v-model:value="lines[index]!.unit"
placeholder="واحد"
@keydown="(e: KeyboardEvent) => onCellKeydown(e, index, 'unit')"
/>
</div>
</template>
<template v-else-if="column.key === 'unitPrice'">
<div :ref="(el) => registerCell(index, 'unitPrice', el)">
<a-input-number
v-model:value="lines[index]!.unitPrice"
:min="0"
:controls="false"
:formatter="groupedNumberFormatter(0)"
:parser="groupedNumberParser(0)"
style="width: 100%"
@keydown="(e: KeyboardEvent) => onNumberKeydown(e, index, 'unitPrice', 0)"
@paste="(e: ClipboardEvent) => onNumberPaste(e, 0)"
/>
</div>
</template>
<template v-else-if="column.key === 'discount'">
<div :ref="(el) => registerCell(index, 'discount', el)">
<a-input-number
v-model:value="lines[index]!.discountAmount"
:min="0"
:controls="false"
:formatter="groupedNumberFormatter(0)"
:parser="groupedNumberParser(0)"
style="width: 100%"
@keydown="(e: KeyboardEvent) => onNumberKeydown(e, index, 'discount', 0)"
@paste="(e: ClipboardEvent) => onNumberPaste(e, 0)"
/>
</div>
</template>
<template v-else-if="column.key === 'tax'">
<div :ref="(el) => registerCell(index, 'tax', el)">
<a-input-number
v-model:value="lines[index]!.taxPercent"
:min="0"
:max="100"
:controls="false"
:formatter="groupedNumberFormatter(2)"
:parser="groupedNumberParser(2)"
style="width: 100%"
@keydown="(e: KeyboardEvent) => onNumberKeydown(e, index, 'tax', 2)"
@paste="(e: ClipboardEvent) => onNumberPaste(e, 2)"
/>
</div>
</template>
<template v-else-if="column.key === 'total'">
<a-typography-text :style="{ direction: 'ltr', display: 'inline-block' }">
{{ money(computeGridLineTotal(lines[index]!)) }}
</a-typography-text>
</template>
<template v-else-if="column.key === 'actions'">
<a-button
type="text"
danger
aria-label="حذف ردیف"
title="حذف ردیف"
:style="{
width: '28px',
height: '28px',
minWidth: '28px',
padding: 0,
marginInline: 'auto',
}"
@click="removeRow(index)"
>
<template #icon><DeleteOutlined /></template>
</a-button>
</template>
</template>
</a-table>
<a-flex>
<a-button type="dashed" @click="addRow">
<template #icon><PlusOutlined /></template>
ردیف جدید
</a-button>
</a-flex>
</a-flex>
</template>
@@ -0,0 +1,58 @@
export type InvoiceGridColKey =
| 'product'
| 'description'
| 'quantity'
| 'unit'
| 'unitPrice'
| 'discount'
| 'tax'
| 'total';
export const INVOICE_GRID_EDITABLE_COLS: InvoiceGridColKey[] = [
'product',
'description',
'quantity',
'unit',
'unitPrice',
'discount',
'tax',
];
export type InvoiceGridLine = {
key: string;
productId: string;
name: string;
description: string;
quantity: number | undefined;
unit: string;
unitPrice: number | undefined;
discountAmount: number | undefined;
taxPercent: number | undefined;
};
export function emptyInvoiceGridLine(): InvoiceGridLine {
return {
key: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
productId: '',
name: '',
description: '',
quantity: 1,
unit: 'عدد',
unitPrice: undefined,
discountAmount: 0,
taxPercent: 0,
};
}
export function computeGridLineTotal(line: InvoiceGridLine): number {
const qty = Number(line.quantity) || 0;
const price = Number(line.unitPrice) || 0;
const discount = Math.max(0, Number(line.discountAmount) || 0);
const tax = Math.max(0, Number(line.taxPercent) || 0);
const net = Math.max(0, qty * price - discount);
return Math.round((net * (1 + tax / 100) + Number.EPSILON) * 100) / 100;
}
export function isLineFilled(line: InvoiceGridLine): boolean {
return Boolean(line.name.trim()) && line.quantity != null && line.unitPrice !== undefined;
}
@@ -0,0 +1,159 @@
import { nextTick, type Ref } from 'vue';
import {
INVOICE_GRID_EDITABLE_COLS,
type InvoiceGridColKey,
type InvoiceGridLine,
emptyInvoiceGridLine,
} from './types';
export type CellFocus = { row: number; col: InvoiceGridColKey };
function focusableEl(root: HTMLElement | null | undefined): HTMLElement | null {
if (!root) return null;
if (
root instanceof HTMLInputElement ||
root instanceof HTMLTextAreaElement ||
root instanceof HTMLButtonElement
) {
return root;
}
return root.querySelector<HTMLElement>(
'input, textarea, button, .ant-select-selection-search-input, .ant-input-number-input',
);
}
export function useGridKeyboard(opts: {
lines: Ref<InvoiceGridLine[]>;
cellRefs: Ref<Record<string, HTMLElement | null>>;
ensureTrailingEmpty?: boolean;
}) {
const { lines, cellRefs } = opts;
function cellKey(row: number, col: InvoiceGridColKey) {
return `${row}:${col}`;
}
function registerCell(row: number, col: InvoiceGridColKey, el: unknown) {
const key = cellKey(row, col);
if (!el) {
delete cellRefs.value[key];
return;
}
cellRefs.value[key] = el as HTMLElement;
}
function ensureTrailingEmpty() {
if (opts.ensureTrailingEmpty === false) return;
const last = lines.value[lines.value.length - 1];
if (!last || last.name.trim() || last.productId || last.unitPrice !== undefined) {
lines.value.push(emptyInvoiceGridLine());
}
}
async function focusCell(row: number, col: InvoiceGridColKey) {
await nextTick();
const el = focusableEl(cellRefs.value[cellKey(row, col)]);
if (!el) return;
el.focus();
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
el.select();
}
}
function colIndex(col: InvoiceGridColKey) {
return INVOICE_GRID_EDITABLE_COLS.indexOf(col);
}
async function moveNext(row: number, col: InvoiceGridColKey) {
const idx = colIndex(col);
if (idx < 0) return;
if (idx < INVOICE_GRID_EDITABLE_COLS.length - 1) {
await focusCell(row, INVOICE_GRID_EDITABLE_COLS[idx + 1]!);
return;
}
const nextRow = row + 1;
if (nextRow >= lines.value.length) {
lines.value.push(emptyInvoiceGridLine());
}
await focusCell(nextRow, INVOICE_GRID_EDITABLE_COLS[0]!);
}
async function movePrev(row: number, col: InvoiceGridColKey) {
const idx = colIndex(col);
if (idx < 0) return;
if (idx > 0) {
await focusCell(row, INVOICE_GRID_EDITABLE_COLS[idx - 1]!);
return;
}
if (row <= 0) return;
await focusCell(row - 1, INVOICE_GRID_EDITABLE_COLS[INVOICE_GRID_EDITABLE_COLS.length - 1]!);
}
async function moveVertical(row: number, col: InvoiceGridColKey, delta: number) {
const target = row + delta;
if (target < 0) return;
if (target >= lines.value.length) {
if (delta > 0) {
lines.value.push(emptyInvoiceGridLine());
} else {
return;
}
}
await focusCell(target, col);
}
function onCellKeydown(
event: KeyboardEvent,
row: number,
col: InvoiceGridColKey,
options?: { dropdownOpen?: boolean },
) {
if (options?.dropdownOpen && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
return;
}
if (event.key === 'Enter') {
event.preventDefault();
if (event.shiftKey) void movePrev(row, col);
else void moveNext(row, col);
return;
}
if (event.key === 'ArrowDown') {
event.preventDefault();
void moveVertical(row, col, 1);
return;
}
if (event.key === 'ArrowUp') {
event.preventDefault();
void moveVertical(row, col, -1);
return;
}
if (event.key === 'Insert' && !event.ctrlKey && !event.altKey) {
event.preventDefault();
lines.value.splice(row + 1, 0, emptyInvoiceGridLine());
void focusCell(row + 1, 'product');
return;
}
if (event.key === 'Delete' && event.ctrlKey) {
event.preventDefault();
if (lines.value.length <= 1) {
lines.value[0] = emptyInvoiceGridLine();
void focusCell(0, 'product');
return;
}
lines.value.splice(row, 1);
ensureTrailingEmpty();
void focusCell(Math.min(row, lines.value.length - 1), col);
}
}
return {
cellKey,
registerCell,
focusCell,
moveNext,
movePrev,
moveVertical,
onCellKeydown,
ensureTrailingEmpty,
};
}
@@ -0,0 +1,56 @@
export type InvoicePreviewTemplate =
| 'emerald'
| 'noir'
| 'pearl'
| 'sand'
| 'slate'
| 'bronze';
export type PaperSize = 'A4' | 'A5';
export type PaperOrientation = 'portrait' | 'landscape';
export const TEMPLATE_OPTIONS: { value: InvoicePreviewTemplate; label: string }[] = [
{ value: 'bronze', label: 'پایه' },
{ value: 'emerald', label: 'زمردی' },
{ value: 'noir', label: 'اجرایی' },
{ value: 'pearl', label: 'مرواریدی' },
{ value: 'sand', label: 'شنی' },
{ value: 'slate', label: 'اسلیت' },
];
export const PAPER_SIZE_OPTIONS: { value: PaperSize; label: string }[] = [
{ value: 'A4', label: 'A4' },
{ value: 'A5', label: 'A5' },
];
export const PAPER_ORIENTATION_OPTIONS: { value: PaperOrientation; label: string }[] = [
{ value: 'portrait', label: 'عمودی' },
{ value: 'landscape', label: 'افقی' },
];
/** Brand primary from antdTheme (`#10897d`) — base invoice template. */
export const DEFAULT_TEMPLATE: InvoicePreviewTemplate = 'bronze';
export const INVOICE_PRIMARY = '#10897d';
export const INVOICE_PRIMARY_DARK = '#0d6f66';
export const INVOICE_PRIMARY_SOFT = '#eef8f7';
export const INVOICE_PRIMARY_BORDER = '#b7ddd8';
/** Preview sheet width in px (approx. print aspect). */
export function previewPaperWidth(size: PaperSize, orientation: PaperOrientation): number {
if (size === 'A4') return orientation === 'landscape' ? 960 : 720;
return orientation === 'landscape' ? 720 : 520;
}
/** Optional min-height so the sheet reads as a paper page. */
export function previewPaperMinHeight(size: PaperSize, orientation: PaperOrientation): number {
const w = previewPaperWidth(size, orientation);
if (size === 'A4') {
return orientation === 'landscape'
? Math.round((w * 210) / 297)
: Math.round((w * 297) / 210);
}
return orientation === 'landscape'
? Math.round((w * 148) / 210)
: Math.round((w * 210) / 148);
}
@@ -272,6 +272,7 @@ function goBack() {
</script> </script>
<template> <template>
<div class="page-header-shell">
<!-- overflow: خط و ink-bar تب‌ها از گوشه‌های گرد کارت بیرون نزنند --> <!-- overflow: خط و ink-bar تب‌ها از گوشه‌های گرد کارت بیرون نزنند -->
<a-card :bordered="true" :body-style="{ padding: 0 }" :style="{ overflow: 'hidden' }" dir="rtl"> <a-card :bordered="true" :body-style="{ padding: 0 }" :style="{ overflow: 'hidden' }" dir="rtl">
<!-- ۱ · عنوان و اکشن‌ها --> <!-- ۱ · عنوان و اکشن‌ها -->
@@ -486,4 +487,12 @@ function goBack() {
</a-typography-text> </a-typography-text>
</a-flex> </a-flex>
</a-card> </a-card>
</div>
</template> </template>
<style scoped>
/* هدر در موبایل فعلاً فیکس/چسبان نیست و همراه محتوا اسکرول می‌شود */
.page-header-shell {
position: static;
}
</style>
@@ -7,7 +7,7 @@ import {
FlagFilled, FlagFilled,
LeftOutlined, LeftOutlined,
MoreOutlined, MoreOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import { import {
Avatar as AAvatar, Avatar as AAvatar,
Button as AButton, Button as AButton,
@@ -127,6 +127,7 @@ const chevronBtnStyle = computed(() => ({
boxSizing: 'border-box' as const, boxSizing: 'border-box' as const,
width: '22px', width: '22px',
height: '22px', height: '22px',
minWidth: '22px',
margin: 0, margin: 0,
padding: 0, padding: 0,
border: `1.5px solid ${dueToneColor.value}`, border: `1.5px solid ${dueToneColor.value}`,
@@ -316,9 +317,9 @@ const cardStyle = computed(() => ({
{{ money.unit }} {{ money.unit }}
</a-typography-text> </a-typography-text>
</a-typography-text> </a-typography-text>
<button <a-button
v-if="copy.quickView && !selectMode" v-if="copy.quickView && !selectMode"
type="button" type="text"
class="deal-card-peek" class="deal-card-peek"
:aria-label="previewing ? 'بستن پیش‌نمایش' : 'پیش‌نمایش فعالیت'" :aria-label="previewing ? 'بستن پیش‌نمایش' : 'پیش‌نمایش فعالیت'"
:aria-expanded="previewing" :aria-expanded="previewing"
@@ -326,7 +327,7 @@ const cardStyle = computed(() => ({
@click.stop="emit('open', deal.id)" @click.stop="emit('open', deal.id)"
> >
<LeftOutlined :style="chevronIconStyle" /> <LeftOutlined :style="chevronIconStyle" />
</button> </a-button>
<a-tooltip v-else-if="priorityFlag" :title="`اولویت: ${priorityFlag.label}`"> <a-tooltip v-else-if="priorityFlag" :title="`اولویت: ${priorityFlag.label}`">
<span :style="{ display: 'inline-flex', flexShrink: 0, lineHeight: 1 }"> <span :style="{ display: 'inline-flex', flexShrink: 0, lineHeight: 1 }">
<FlagFilled :style="{ color: priorityFlag.color, fontSize: '16px' }" /> <FlagFilled :style="{ color: priorityFlag.color, fontSize: '16px' }" />
@@ -24,7 +24,7 @@ import {
CloseOutlined, CloseOutlined,
FormOutlined, FormOutlined,
PlusOutlined, PlusOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import type { import type {
ActivityDto, ActivityDto,
ActivityType, ActivityType,
@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, ref } from 'vue'; import { nextTick, ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue'; import { PlusOutlined } from '@/icons/ant-bridge';
import { import {
Button as AButton, Button as AButton,
Card as ACard, Card as ACard,
@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, ref } from 'vue'; import { computed, nextTick, ref } from 'vue';
import { HolderOutlined, MoreOutlined } from '@ant-design/icons-vue'; import { HolderOutlined, MoreOutlined } from '@/icons/ant-bridge';
import { import {
Button as AButton, Button as AButton,
Dropdown as ADropdown, Dropdown as ADropdown,
@@ -5,7 +5,7 @@ import {
CheckOutlined, CheckOutlined,
DeleteOutlined, DeleteOutlined,
MoreOutlined, MoreOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import { import {
Avatar as AAvatar, Avatar as AAvatar,
Button as AButton, Button as AButton,
@@ -19,7 +19,7 @@ import {
FlagOutlined, FlagOutlined,
MoreOutlined, MoreOutlined,
WarningOutlined, WarningOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
const AMenuItem = AMenu.Item; const AMenuItem = AMenu.Item;
import UserAvatar from '@/components/UserAvatar.vue'; import UserAvatar from '@/components/UserAvatar.vue';
@@ -2,7 +2,7 @@
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { Button as AButton, Upload as AUpload, message } from 'ant-design-vue'; import { Button as AButton, Upload as AUpload, message } from 'ant-design-vue';
import type { UploadFile, UploadProps } from 'ant-design-vue'; import type { UploadFile, UploadProps } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue'; import { UploadOutlined } from '@/icons/ant-bridge';
import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress'; import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress';
import type { TreasuryPendingPhoto } from '@/lib/treasury-doc-photos'; import type { TreasuryPendingPhoto } from '@/lib/treasury-doc-photos';
@@ -3,6 +3,7 @@ import { computed, defineComponent, onMounted, ref } from 'vue';
import axios from 'axios'; import axios from 'axios';
import { import {
Button as AButton, Button as AButton,
Drawer as ADrawer,
Flex as AFlex, Flex as AFlex,
Select as ASelect, Select as ASelect,
Typography, Typography,
@@ -11,7 +12,6 @@ import {
import type { CompanyDto, FinancialPartyKind, PersonDto, TreasuryPartySearchDto } from '@mento/shared'; import type { CompanyDto, FinancialPartyKind, PersonDto, TreasuryPartySearchDto } from '@mento/shared';
import { UserOutlined } from '@/icons/ant-bridge'; import { UserOutlined } from '@/icons/ant-bridge';
import SelectWithIcon from '@/components/treasury/SelectWithIcon.vue'; import SelectWithIcon from '@/components/treasury/SelectWithIcon.vue';
import { UiModal } from '@/components/ui';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import CompanyFormView from '@/views/CompanyFormView.vue'; import CompanyFormView from '@/views/CompanyFormView.vue';
import PersonFormView from '@/views/PersonFormView.vue'; import PersonFormView from '@/views/PersonFormView.vue';
@@ -214,21 +214,37 @@ onMounted(() => {
</a-typography-text> </a-typography-text>
</a-flex> </a-flex>
<UiModal :open="personOpen" title="شخص جدید" @close="personOpen = false"> <a-drawer
v-model:open="personOpen"
title="شخص جدید"
placement="right"
:width="720"
:footer="null"
destroy-on-close
@close="personOpen = false"
>
<PersonFormView <PersonFormView
v-if="personOpen" v-if="personOpen"
embedded embedded
@saved="onPersonCreated" @saved="onPersonCreated"
@cancel="personOpen = false" @cancel="personOpen = false"
/> />
</UiModal> </a-drawer>
<UiModal :open="companyOpen" title="شرکت جدید" @close="companyOpen = false"> <a-drawer
v-model:open="companyOpen"
title="شرکت جدید"
placement="right"
:width="720"
:footer="null"
destroy-on-close
@close="companyOpen = false"
>
<CompanyFormView <CompanyFormView
v-if="companyOpen" v-if="companyOpen"
embedded embedded
@saved="onCompanyCreated" @saved="onCompanyCreated"
@cancel="companyOpen = false" @cancel="companyOpen = false"
/> />
</UiModal> </a-drawer>
</template> </template>
+2
View File
@@ -86,6 +86,7 @@ export const DownOutlined = icons.DownOutlined;
export const DownloadOutlined = icons.DownloadOutlined; export const DownloadOutlined = icons.DownloadOutlined;
export const DragOutlined = icons.DragOutlined; export const DragOutlined = icons.DragOutlined;
export const EditOutlined = icons.EditOutlined; export const EditOutlined = icons.EditOutlined;
export const EllipsisOutlined = icons.EllipsisOutlined;
export const EnvironmentOutlined = icons.EnvironmentOutlined; export const EnvironmentOutlined = icons.EnvironmentOutlined;
export const ExclamationCircleOutlined = icons.ExclamationCircleOutlined; export const ExclamationCircleOutlined = icons.ExclamationCircleOutlined;
export const ExpandOutlined = icons.ExpandOutlined; export const ExpandOutlined = icons.ExpandOutlined;
@@ -100,6 +101,7 @@ export const FilterOutlined = icons.FilterOutlined;
export const FireOutlined = icons.FireOutlined; export const FireOutlined = icons.FireOutlined;
export const FlagFilled = icons.FlagFilled; export const FlagFilled = icons.FlagFilled;
export const FlagOutlined = icons.FlagOutlined; export const FlagOutlined = icons.FlagOutlined;
export const FormOutlined = icons.FormOutlined;
export const FullscreenExitOutlined = icons.FullscreenExitOutlined; export const FullscreenExitOutlined = icons.FullscreenExitOutlined;
export const FullscreenOutlined = icons.FullscreenOutlined; export const FullscreenOutlined = icons.FullscreenOutlined;
export const FundOutlined = icons.FundOutlined; export const FundOutlined = icons.FundOutlined;
+2
View File
@@ -121,6 +121,7 @@ export const ANT_ICON_TO_VUESAX: Record<string, string> = {
DownloadOutlined: 'document-download', DownloadOutlined: 'document-download',
DragOutlined: 'element-equal', DragOutlined: 'element-equal',
EditOutlined: 'edit-2', EditOutlined: 'edit-2',
EllipsisOutlined: 'more',
EnvironmentOutlined: 'location', EnvironmentOutlined: 'location',
ExclamationCircleOutlined: 'warning-2', ExclamationCircleOutlined: 'warning-2',
ExpandOutlined: 'maximize-4', ExpandOutlined: 'maximize-4',
@@ -135,6 +136,7 @@ export const ANT_ICON_TO_VUESAX: Record<string, string> = {
FireOutlined: 'flash', FireOutlined: 'flash',
FlagFilled: 'flag', FlagFilled: 'flag',
FlagOutlined: 'flag', FlagOutlined: 'flag',
FormOutlined: 'edit',
FullscreenExitOutlined: 'maximize-3', FullscreenExitOutlined: 'maximize-3',
FullscreenOutlined: 'maximize-4', FullscreenOutlined: 'maximize-4',
FundOutlined: 'chart', FundOutlined: 'chart',
+24 -9
View File
@@ -31,7 +31,7 @@ import {
import { refreshUnreadTotal, useOrgChat } from '@/lib/useOrgChat'; import { refreshUnreadTotal, useOrgChat } from '@/lib/useOrgChat';
import { useWorkspaceTabs } from '@/lib/workspace-tabs'; import { useWorkspaceTabs } from '@/lib/workspace-tabs';
import { TabPane, Tabs } from 'ant-design-vue'; import { TabPane, Tabs } from 'ant-design-vue';
import { EllipsisOutlined } from '@ant-design/icons-vue'; import { EllipsisOutlined } from '@/icons/ant-bridge';
const auth = useAuthStore(); const auth = useAuthStore();
const router = useRouter(); const router = useRouter();
@@ -812,13 +812,13 @@ onUnmounted(() => {
<button <button
class="nav-item nav-fold-btn" class="nav-item nav-fold-btn"
type="button" type="button"
title="کارها" title="فعالیت‌ها"
:class="{ 'router-link-active': activitiesActive || openHubKey === 'activities', 'hub-on': openHubKey === 'activities' }" :class="{ 'router-link-active': activitiesActive || openHubKey === 'activities', 'hub-on': openHubKey === 'activities' }"
:aria-expanded="openHubKey === 'activities'" :aria-expanded="openHubKey === 'activities'"
@click="onHubClick('activities')" @click="onHubClick('activities')"
> >
<UiIcon name="check" :size="collapsed ? 20 : 18" /> <UiIcon name="check" :size="collapsed ? 20 : 18" />
<span>کارها</span> <span>فعالیت‌ها</span>
<span v-if="activityBadge" class="nav-badge">{{ toFaDigits(activityBadge) }}</span> <span v-if="activityBadge" class="nav-badge">{{ toFaDigits(activityBadge) }}</span>
<i class="chev" aria-hidden="true" /> <i class="chev" aria-hidden="true" />
</button> </button>
@@ -1498,6 +1498,8 @@ onUnmounted(() => {
} }
.workspace { .workspace {
--mobile-app-topbar-h: 0px;
--mobile-page-header-offset: 0px;
min-width: 0; min-width: 0;
min-height: 0; min-height: 0;
height: 100%; height: 100%;
@@ -2226,8 +2228,10 @@ onUnmounted(() => {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 0.35rem; gap: 0.35rem;
padding: 0.35rem 0.7rem; height: var(--control-h);
border-radius: 999px; box-sizing: border-box;
padding: 0 0.75rem;
border-radius: 10px;
background: var(--accent-subtle); background: var(--accent-subtle);
color: var(--accent-deep); color: var(--accent-deep);
font-size: 0.78rem; font-size: 0.78rem;
@@ -2276,7 +2280,7 @@ onUnmounted(() => {
.notif-layer { .notif-layer {
position: fixed; position: fixed;
inset: 0; inset: 0;
z-index: 40; z-index: 70;
display: grid; display: grid;
place-items: start end; place-items: start end;
padding: 5rem 1rem 1rem; padding: 5rem 1rem 1rem;
@@ -2363,6 +2367,11 @@ onUnmounted(() => {
} }
.content { .content {
/* .content زیر تاپ‌بار موبایل و خودش scroll container است؛ آفست تاپ‌بار هدر را روی محتوا هل می‌داد */
--page-header-sticky-top: 0px;
/* هم‌اندازهٔ padding بالای .content (بلوک موبایل پایین‌تر override می‌کند) */
--page-header-bleed: 16px;
--page-header-bg: var(--bg);
flex: 1 1 auto; flex: 1 1 auto;
min-height: 0; min-height: 0;
min-width: 0; min-width: 0;
@@ -2438,11 +2447,12 @@ onUnmounted(() => {
justify-content: space-between; justify-content: space-between;
gap: 0.75rem; gap: 0.75rem;
padding: 0.75rem 0.9rem; padding: 0.75rem 0.9rem;
min-height: var(--mobile-app-topbar-h);
background: #fff; background: #fff;
border-bottom: 1px solid #e8eef3; border-bottom: 1px solid #e8eef3;
position: sticky; position: sticky;
top: 0; top: 0;
z-index: 30; z-index: 50;
} }
.top-brand { .top-brand {
@@ -2477,6 +2487,11 @@ onUnmounted(() => {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
} }
.workspace {
--mobile-app-topbar-h: calc(60px + env(safe-area-inset-top, 0px));
--mobile-page-header-offset: var(--mobile-app-topbar-h);
}
.desktop-only { .desktop-only {
display: none !important; display: none !important;
} }
@@ -2520,7 +2535,7 @@ onUnmounted(() => {
} }
.notif-layer { .notif-layer {
padding: 4.25rem 0.65rem calc(1rem + var(--mobile-tabbar-h)); padding: calc(var(--mobile-app-topbar-h) + 0.5rem) 0.65rem calc(1rem + var(--mobile-tabbar-h));
place-items: start stretch; place-items: start stretch;
} }
@@ -2616,7 +2631,7 @@ onUnmounted(() => {
.more-layer { .more-layer {
position: fixed; position: fixed;
inset: 0 0 var(--mobile-tabbar-h) 0; inset: 0 0 var(--mobile-tabbar-h) 0;
z-index: 40; z-index: 75;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
background: #fff; background: #fff;
+69
View File
@@ -62,6 +62,75 @@ export function formatGroupedInput(value: number, maxFractionDigits = 2): string
}).format(value); }).format(value);
} }
/** formatter برای a-input-number با جداکنندهٔ هزارگان فارسی */
export function groupedNumberFormatter(maxFractionDigits = 2) {
return (value: string | number) => {
if (value === '' || value == null) return '';
const n = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(n)) return String(value);
return formatGroupedInput(n, maxFractionDigits);
};
}
/** parser برای a-input-number؛ ارقام فارسی و جداکننده‌ها را می‌پذیرد */
export function groupedNumberParser(maxFractionDigits = 2) {
return (display?: string) => {
if (display == null || display === '') return '';
const n = parseMoneyNumber(display, maxFractionDigits);
return n == null ? '' : n;
};
}
/**
* فقط رقم (و در صورت نیاز اعشار/منفی) را هنگام تایپ می‌پذیرد.
* میانبرها (Ctrl/Meta) و کلیدهای کنترلی (Backspace، Enter، …) آزاد می‌مانند.
*/
export function blockNonNumericKeydown(
event: KeyboardEvent,
opts: { allowDecimal?: boolean; allowMinus?: boolean } = {},
) {
const { allowDecimal = true, allowMinus = false } = opts;
if (event.ctrlKey || event.metaKey || event.altKey) return;
if (event.isComposing) return;
if (event.key.length !== 1) return;
if (/[0-9۰-۹٠-٩]/.test(event.key)) return;
if (
allowDecimal &&
(event.key === '.' ||
event.key === ',' ||
event.key === '٫' ||
event.key === '،')
) {
return;
}
if (allowMinus && event.key === '-') return;
event.preventDefault();
}
/** متن پیست‌شده را به کاراکترهای مجاز عددی محدود می‌کند */
export function sanitizeNumericClipboard(
raw: string,
opts: { allowDecimal?: boolean; allowMinus?: boolean } = {},
): string {
const { allowDecimal = true, allowMinus = false } = opts;
let out = '';
for (const ch of raw) {
if (/[0-9۰-۹٠-٩]/.test(ch)) {
out += ch;
continue;
}
if (allowDecimal && (ch === '.' || ch === ',' || ch === '٫' || ch === '،')) {
out += ch;
continue;
}
if (allowMinus && ch === '-' && !out.includes('-')) {
out += ch;
}
}
return out;
}
/** /**
* پارس متن ورودی مبلغ/قیمت. * پارس متن ورودی مبلغ/قیمت.
* جداکننده‌ها و ارقام فارسی را می‌پذیرد و مقدار عددی برمی‌گرداند. * جداکننده‌ها و ارقام فارسی را می‌پذیرد و مقدار عددی برمی‌گرداند.
+1
View File
@@ -159,6 +159,7 @@ export const NAV_HUBS: NavHubDef[] = [
shortcuts: [ shortcuts: [
{ to: '/deals/new', title: 'معامله جدید', icon: 'plus', module: 'pipeline' }, { to: '/deals/new', title: 'معامله جدید', icon: 'plus', module: 'pipeline' },
{ to: '/quotes/new', title: 'پیش‌فاکتور جدید', icon: 'document', module: 'quotes' }, { to: '/quotes/new', title: 'پیش‌فاکتور جدید', icon: 'document', module: 'quotes' },
{ to: '/invoices/quick', title: 'فاکتور سریع', icon: 'plus', module: 'invoices' },
], ],
cards: [ cards: [
{ {
+2
View File
@@ -45,6 +45,8 @@ const ROUTE_TITLES: Record<string, string> = {
'quote-detail': 'جزئیات پیش‌فاکتور', 'quote-detail': 'جزئیات پیش‌فاکتور',
invoices: 'فاکتورها', invoices: 'فاکتورها',
'invoice-new': 'فاکتور جدید', 'invoice-new': 'فاکتور جدید',
'invoice-quick': 'فاکتور سریع',
'invoice-quick-detail': 'فاکتور سریع',
'invoice-detail': 'جزئیات فاکتور', 'invoice-detail': 'جزئیات فاکتور',
inventory: 'انبار', inventory: 'انبار',
cheques: 'چک‌ها', cheques: 'چک‌ها',
+10
View File
@@ -244,6 +244,16 @@ export const router = createRouter({
name: 'invoice-new', name: 'invoice-new',
component: () => import('@/views/InvoiceFormView.vue'), component: () => import('@/views/InvoiceFormView.vue'),
}, },
{
path: 'invoices/quick',
name: 'invoice-quick',
component: () => import('@/views/InvoiceBuilderView.vue'),
},
{
path: 'invoices/quick/:id',
name: 'invoice-quick-detail',
component: () => import('@/views/InvoiceBuilderView.vue'),
},
{ {
path: 'invoices/:id', path: 'invoices/:id',
name: 'invoice-detail', name: 'invoice-detail',
+7 -3
View File
@@ -63,7 +63,7 @@ import { useAuthStore } from '@/stores/auth';
import { canMutateActivity } from '@/lib/activity-access'; import { canMutateActivity } from '@/lib/activity-access';
import { canManageSettings, canViewAllRecords } from '@/lib/roles'; import { canManageSettings, canViewAllRecords } from '@/lib/roles';
import { apiError } from '@/lib/routines'; import { apiError } from '@/lib/routines';
import { message } from 'ant-design-vue'; import { Drawer as ADrawer, message } from 'ant-design-vue';
import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize'; import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize';
import { registerTableColumns, useTableColumns } from '@/lib/tableColumns'; import { registerTableColumns, useTableColumns } from '@/lib/tableColumns';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue'; import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
@@ -1856,9 +1856,13 @@ onUnmounted(() => {
</div> </div>
</Teleport> </Teleport>
<UiModal <a-drawer
:open="Boolean(activityModal)" :open="Boolean(activityModal)"
title="فعالیت جدید" title="فعالیت جدید"
placement="right"
:width="720"
:footer="null"
destroy-on-close
@close="activityModal = null" @close="activityModal = null"
> >
<ActivityFormView <ActivityFormView
@@ -1871,7 +1875,7 @@ onUnmounted(() => {
@saved="onActivitySaved" @saved="onActivitySaved"
@cancel="activityModal = null" @cancel="activityModal = null"
/> />
</UiModal> </a-drawer>
<UiModal <UiModal
:open="deleteActivityIds.length > 0" :open="deleteActivityIds.length > 0"
File diff suppressed because it is too large Load Diff
+6 -4
View File
@@ -16,7 +16,7 @@ import {
ListItem as AListItem, ListItem as AListItem,
Menu as AMenu, Menu as AMenu,
MenuItem as AMenuItem, MenuItem as AMenuItem,
Modal as AModal, Drawer as ADrawer,
Pagination as APagination, Pagination as APagination,
Select as ASelect, Select as ASelect,
Space as ASpace, Space as ASpace,
@@ -1378,11 +1378,13 @@ function peopleCustomRow(record: PersonDto) {
</a-spin> </a-spin>
</a-flex> </a-flex>
<a-modal <a-drawer
v-model:open="contactModalOpen" v-model:open="contactModalOpen"
:title="contactModal === 'company' ? 'شرکت جدید' : 'شخص جدید'" :title="contactModal === 'company' ? 'شرکت جدید' : 'شخص جدید'"
placement="right"
:width="720"
:footer="null" :footer="null"
:width="960" destroy-on-close
> >
<PersonFormView <PersonFormView
v-if="contactModal === 'person'" v-if="contactModal === 'person'"
@@ -1396,7 +1398,7 @@ function peopleCustomRow(record: PersonDto) {
@saved="contactModal = null; void load()" @saved="contactModal = null; void load()"
@cancel="contactModal = null" @cancel="contactModal = null"
/> />
</a-modal> </a-drawer>
</template> </template>
<style scoped> <style scoped>
+14 -106
View File
@@ -17,7 +17,6 @@ import {
Input as AInput, Input as AInput,
InputNumber as AInputNumber, InputNumber as AInputNumber,
Modal, Modal,
Modal as AModal,
Row as ARow, Row as ARow,
Segmented as ASegmented, Segmented as ASegmented,
Select as ASelect, Select as ASelect,
@@ -28,12 +27,14 @@ import {
Typography, Typography,
} from 'ant-design-vue'; } from 'ant-design-vue';
import { import {
BulbOutlined,
CheckOutlined, CheckOutlined,
DeleteOutlined, DeleteOutlined,
FileOutlined,
FileTextOutlined, FileTextOutlined,
FundOutlined,
PlusOutlined, PlusOutlined,
UserAddOutlined, } from '@/icons/ant-bridge';
} from '@ant-design/icons-vue';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useFeedback } from '@/composables/useFeedback'; import { useFeedback } from '@/composables/useFeedback';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
@@ -43,13 +44,13 @@ import { toFaDigits } from '@/lib/jalali';
import { currencySuffix, formatMoney } from '@/lib/money'; import { currencySuffix, formatMoney } from '@/lib/money';
import CustomFieldsSection from '@/components/CustomFieldsSection.vue'; import CustomFieldsSection from '@/components/CustomFieldsSection.vue';
import EntityTimeline from '@/components/EntityTimeline.vue'; import EntityTimeline from '@/components/EntityTimeline.vue';
import PersonPicker from '@/components/PersonPicker.vue';
import RelatedActivitiesPanel from '@/components/activities/RelatedActivitiesPanel.vue'; import RelatedActivitiesPanel from '@/components/activities/RelatedActivitiesPanel.vue';
import RelatedTasksPanel from '@/components/routines/RelatedTasksPanel.vue'; import RelatedTasksPanel from '@/components/routines/RelatedTasksPanel.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue'; import MoneyInput from '@/components/MoneyInput.vue';
import StagePathStrip from '@/components/StagePathStrip.vue'; import StagePathStrip from '@/components/StagePathStrip.vue';
import UserMultiSelect from '@/components/UserMultiSelect.vue'; import UserMultiSelect from '@/components/UserMultiSelect.vue';
import PersonFormView from '@/views/PersonFormView.vue';
import type { import type {
CompanyDto, CompanyDto,
CreateDealRequest, CreateDealRequest,
@@ -57,14 +58,12 @@ import type {
DealLineItemInput, DealLineItemInput,
OrganizationDto, OrganizationDto,
OrgUserDto, OrgUserDto,
PaginatedResponse,
PersonDto, PersonDto,
PipelineBoardDto, PipelineBoardDto,
PipelineDto, PipelineDto,
ProductDto, ProductDto,
} from '@mento/shared'; } from '@mento/shared';
import { PageHeader } from '@/components/page'; import { PageHeader } from '@/components/page';
import { FundOutlined, FileOutlined, BulbOutlined } from '@/icons/ant-bridge';
import type { PageHeaderMenuItem } from '@/components/page'; import type { PageHeaderMenuItem } from '@/components/page';
const { Text: ATypographyText } = Typography; const { Text: ATypographyText } = Typography;
@@ -115,12 +114,6 @@ const showOthers = ref(true);
const othersKeys = ref<string[]>(['others']); const othersKeys = ref<string[]>(['others']);
const productsOpen = ref(false); const productsOpen = ref(false);
const contactKind = ref<ContactKind>('person'); const contactKind = ref<ContactKind>('person');
const personQuery = ref('');
const personResults = ref<PersonDto[] | null>(null);
const personSearching = ref(false);
const newPersonOpen = ref(false);
let personSearchTimer: ReturnType<typeof setTimeout> | undefined;
let personSearchSeq = 0;
const people = ref<PersonDto[]>([]); const people = ref<PersonDto[]>([]);
const companies = ref<CompanyDto[]>([]); const companies = ref<CompanyDto[]>([]);
@@ -173,17 +166,10 @@ const nextDuration = ref(30);
const selectedPerson = computed(() => people.value.find((p) => p.id === personId.value) ?? null); const selectedPerson = computed(() => people.value.find((p) => p.id === personId.value) ?? null);
const selectedCompany = computed(() => companies.value.find((c) => c.id === companyId.value) ?? null); const selectedCompany = computed(() => companies.value.find((c) => c.id === companyId.value) ?? null);
const selectedOwner = computed(() => users.value.find((u) => u.id === ownerId.value) ?? null); const selectedOwner = computed(() => users.value.find((u) => u.id === ownerId.value) ?? null);
const personOptions = computed(() => personResults.value ?? people.value);
const contactKindOptions = [ const contactKindOptions = [
{ value: 'person' as const, label: 'شخص' }, { value: 'person' as const, label: 'شخص' },
{ value: 'company' as const, label: 'شرکت' }, { value: 'company' as const, label: 'شرکت' },
]; ];
const personSelectOptions = computed(() =>
personOptions.value.map((p) => ({
value: p.id,
label: p.company?.name ? `${p.fullName} · ${p.company.name}` : p.fullName,
})),
);
const companySelectOptions = computed(() => const companySelectOptions = computed(() =>
companies.value.map((c) => ({ value: c.id, label: c.name })), companies.value.map((c) => ({ value: c.id, label: c.name })),
); );
@@ -267,68 +253,17 @@ async function ensurePersonLoaded(pid: string) {
} }
} }
function pickPerson(p: PersonDto) { function onPersonPickerChange(p: PersonDto | null) {
if (!p) return;
rememberPerson(p); rememberPerson(p);
personId.value = p.id;
if (p.company?.id) companyId.value = p.company.id; if (p.company?.id) companyId.value = p.company.id;
} }
function clearPerson() { function onPersonPickerCreated(p: PersonDto) {
personId.value = '';
}
function openNewPerson() {
newPersonOpen.value = true;
}
function onPersonSearch(q: string) {
personQuery.value = q;
}
function onPersonSelect(value: unknown) {
const pid = typeof value === 'string' ? value : '';
if (!pid) {
clearPerson();
return;
}
const p = personOptions.value.find((x) => x.id === pid);
if (p) pickPerson(p);
else personId.value = pid;
}
function onPersonCreated(p?: PersonDto) {
newPersonOpen.value = false;
if (!p) return;
personQuery.value = '';
personResults.value = null;
contactKind.value = 'person'; contactKind.value = 'person';
pickPerson(p); onPersonPickerChange(p);
} }
watch(personQuery, (raw) => {
if (personSearchTimer) clearTimeout(personSearchTimer);
const q = raw.trim();
if (!q) {
personResults.value = null;
personSearching.value = false;
return;
}
personSearching.value = true;
const seq = ++personSearchSeq;
personSearchTimer = setTimeout(async () => {
try {
const { data } = await api.get<PaginatedResponse<PersonDto>>('/people', {
params: { q, limit: 30 },
});
if (seq === personSearchSeq) personResults.value = data.items;
} catch {
if (seq === personSearchSeq) personResults.value = [];
} finally {
if (seq === personSearchSeq) personSearching.value = false;
}
}, 300);
});
const linesTotal = computed(() => const linesTotal = computed(() =>
lines.value.reduce((sum, line) => { lines.value.reduce((sum, line) => {
const q = Number(line.quantity); const q = Number(line.quantity);
@@ -712,24 +647,13 @@ function onDealMenu(key: string) {
</a-col> </a-col>
<a-col v-show="contactKind === 'person'" :xs="24" :md="12"> <a-col v-show="contactKind === 'person'" :xs="24" :md="12">
<a-form-item label="شخص مرتبط" required> <a-form-item label="شخص مرتبط" required>
<a-space direction="vertical" :style="{ width: '100%' }" :size="8"> <PersonPicker
<a-select v-model="personId"
:value="personId || undefined" :seed-people="people"
show-search
allow-clear
:filter-option="false"
:options="personSelectOptions"
:loading="personSearching"
placeholder="جستجو و انتخاب شخص" placeholder="جستجو و انتخاب شخص"
style="width: 100%" @change="onPersonPickerChange"
@search="onPersonSearch" @created="onPersonPickerCreated"
@update:value="onPersonSelect"
/> />
<a-button type="link" @click="openNewPerson">
<template #icon><UserAddOutlined /></template>
افزودن شخص جدید
</a-button>
</a-space>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-show="contactKind === 'company'" :xs="24" :md="12"> <a-col v-show="contactKind === 'company'" :xs="24" :md="12">
@@ -1067,21 +991,5 @@ function onDealMenu(key: string) {
</a-form> </a-form>
</a-spin> </a-spin>
<a-modal
v-model:open="newPersonOpen"
title="شخص جدید"
:footer="null"
destroy-on-close
width="720px"
@cancel="newPersonOpen = false"
>
<PersonFormView
v-if="newPersonOpen"
embedded
:initial-query="personQuery"
@saved="onPersonCreated"
@cancel="newPersonOpen = false"
/>
</a-modal>
</div> </div>
</template> </template>
+676
View File
@@ -0,0 +1,676 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
Alert as AAlert,
Button as AButton,
Card as ACard,
Col as ACol,
Divider as ADivider,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
Row as ARow,
Segmented as ASegmented,
Select as ASelect,
Textarea as ATextarea,
Typography,
theme,
} from 'ant-design-vue';
import {
PrinterOutlined,
SaveOutlined,
ThunderboltOutlined,
} from '@/icons/ant-bridge';
import { PageHeader } from '@/components/page';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import PersonPicker from '@/components/PersonPicker.vue';
import InvoiceDocPreview from '@/components/InvoiceDocPreview.vue';
import InvoiceEntryGrid from '@/components/invoice-builder/InvoiceEntryGrid.vue';
import {
computeGridLineTotal,
emptyInvoiceGridLine,
isLineFilled,
type InvoiceGridLine,
} from '@/components/invoice-builder/types';
import { api } from '@/lib/api';
import { useFeedback } from '@/composables/useFeedback';
import { CURRENCY_OPTIONS, formatMoney } from '@/lib/money';
import { formatLocalDateInput } from '@/lib/jalali';
import { useAuthStore } from '@/stores/auth';
import type {
CreateInvoiceRequest,
InvoiceDto,
InvoiceLineItemInput,
InvoiceStatus,
OrganizationDto,
PersonDto,
ProductDto,
UpdateInvoiceRequest,
} from '@mento/shared';
const route = useRoute();
const router = useRouter();
const feedback = useFeedback();
const auth = useAuthStore();
const { token } = theme.useToken();
const { Text: ATypographyText } = Typography;
const id = computed(() =>
typeof route.params.id === 'string' ? route.params.id : '',
);
const isNew = computed(() => !id.value);
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const products = ref<ProductDto[]>([]);
const people = ref<PersonDto[]>([]);
const orgName = ref('');
const previewOpen = ref(false);
const gridRef = ref<InstanceType<typeof InvoiceEntryGrid> | null>(null);
const number = ref('');
const title = ref('فاکتور سریع');
const kind = ref<'invoice' | 'credit'>('invoice');
const status = ref<InvoiceStatus | string>('draft');
const notes = ref('');
const address = ref('');
const issuedAt = ref(formatLocalDateInput(new Date()));
const dueDate = ref('');
const currency = ref('IRR');
const discountAmount = ref(0);
const taxPercent = ref(0);
const personId = ref('');
const companyId = ref('');
const lines = ref<InvoiceGridLine[]>([emptyInvoiceGridLine()]);
const kindOptions = [
{ value: 'invoice', label: 'فاکتور' },
{ value: 'credit', label: 'برگشتی' },
];
const statusOptions = [
{ value: 'draft', label: 'پیش‌نویس' },
{ value: 'issued', label: 'صادر شده' },
];
const currencyOptions = CURRENCY_OPTIONS.map((c) => ({
value: c.code,
label: c.suffix,
}));
const filledLines = computed(() => lines.value.filter(isLineFilled));
const linesGross = computed(() =>
filledLines.value.reduce(
(sum, line) => sum + (Number(line.quantity) || 0) * (Number(line.unitPrice) || 0),
0,
),
);
const linesDiscount = computed(() =>
filledLines.value.reduce(
(sum, line) => sum + Math.max(0, Number(line.discountAmount) || 0),
0,
),
);
const linesTax = computed(() =>
filledLines.value.reduce((sum, line) => {
const gross = (Number(line.quantity) || 0) * (Number(line.unitPrice) || 0);
const discount = Math.max(0, Number(line.discountAmount) || 0);
const net = Math.max(0, gross - discount);
const tax = Math.max(0, Number(line.taxPercent) || 0);
return sum + (net * tax) / 100;
}, 0),
);
const linesSubtotal = computed(() =>
filledLines.value.reduce((sum, line) => sum + computeGridLineTotal(line), 0),
);
const invoiceDiscount = computed(() => Math.max(0, Number(discountAmount.value) || 0));
const invoiceTaxAmount = computed(() => {
const base = Math.max(0, linesSubtotal.value - invoiceDiscount.value);
return Math.round(((base * (Number(taxPercent.value) || 0)) / 100 + Number.EPSILON) * 100) / 100;
});
const payableSigned = computed(() =>
Math.round(
(linesSubtotal.value - invoiceDiscount.value + invoiceTaxAmount.value + Number.EPSILON) * 100,
) / 100,
);
const payableAmount = computed(() =>
kind.value === 'credit' ? -payableSigned.value : payableSigned.value,
);
function money(n: number) {
return formatMoney(n, currency.value);
}
function onPersonChange(person: PersonDto | null) {
if (person && !people.value.some((p) => p.id === person.id)) {
people.value = [person, ...people.value];
}
companyId.value = person?.company?.id ?? '';
if (!address.value.trim()) {
const fromPerson = (person?.addresses ?? []).map((a) => a.trim()).find(Boolean);
if (fromPerson) address.value = fromPerson;
}
}
function toLineInputs(): InvoiceLineItemInput[] {
return filledLines.value.map((line) => ({
productId: line.productId || null,
name: line.name.trim(),
unit: line.unit.trim() || null,
description: line.description.trim() || null,
quantity: Number(line.quantity) || 0,
unitPrice: Number(line.unitPrice) || 0,
discountAmount: Number(line.discountAmount) || 0,
taxPercent: Number(line.taxPercent) || 0,
currency: currency.value || 'IRR',
}));
}
function mapFromInvoice(data: InvoiceDto) {
number.value = data.number;
title.value = data.title || 'فاکتور سریع';
kind.value = data.kind === 'credit' ? 'credit' : 'invoice';
status.value = data.status;
notes.value = data.notes ?? '';
address.value = data.address ?? '';
issuedAt.value = data.issuedAt
? formatLocalDateInput(new Date(data.issuedAt))
: formatLocalDateInput(new Date());
dueDate.value = data.dueDate ? formatLocalDateInput(new Date(data.dueDate)) : '';
currency.value = data.currency || 'IRR';
discountAmount.value = data.discountAmount ?? 0;
taxPercent.value = data.taxPercent ?? 0;
personId.value = data.person?.id ?? '';
companyId.value = data.company?.id ?? '';
if (data.person) {
const seed = {
id: data.person.id,
fullName: data.person.fullName,
firstName: data.person.fullName.split(' ')[0] ?? '',
lastName: data.person.fullName.split(' ').slice(1).join(' '),
company: data.company
? { id: data.company.id, name: data.company.name }
: null,
addresses: [],
} as PersonDto;
people.value = [seed, ...people.value.filter((p) => p.id !== data.person!.id)];
}
lines.value = (data.lineItems ?? []).map((item) => ({
key: item.id,
productId: item.productId ?? '',
name: item.name,
description: item.description ?? '',
quantity: item.quantity,
unit: item.unit ?? 'عدد',
unitPrice: item.unitPrice,
discountAmount: item.discountAmount ?? 0,
taxPercent: item.taxPercent ?? 0,
}));
if (!lines.value.length) lines.value = [emptyInvoiceGridLine()];
else lines.value.push(emptyInvoiceGridLine());
}
function buildPayload(): CreateInvoiceRequest {
return {
title: title.value.trim() || 'فاکتور سریع',
status: status.value,
kind: kind.value,
currency: currency.value || 'IRR',
notes: notes.value.trim() || undefined,
address: address.value.trim() || undefined,
discountAmount: invoiceDiscount.value,
taxPercent: Number(taxPercent.value) || 0,
issuedAt: issuedAt.value ? new Date(issuedAt.value).toISOString() : null,
dueDate: dueDate.value ? new Date(dueDate.value).toISOString() : null,
personId: personId.value || null,
companyId: companyId.value || null,
lineItems: toLineInputs(),
};
}
async function save(andNew = false) {
error.value = '';
const payload = buildPayload();
if (!payload.lineItems?.length) {
error.value = 'حداقل یک ردیف کالا وارد کنید.';
return;
}
saving.value = true;
try {
let saved: InvoiceDto;
if (isNew.value) {
const { data } = await api.post<InvoiceDto>('/invoices', payload);
saved = data;
} else {
const update: UpdateInvoiceRequest = {
...payload,
address: address.value.trim() || null,
};
const { data } = await api.patch<InvoiceDto>(`/invoices/${id.value}`, update);
saved = data;
}
feedback.success(andNew ? 'فاکتور ذخیره شد؛ فاکتور جدید آماده است.' : 'فاکتور ذخیره شد.');
if (andNew) {
await router.replace({ name: 'invoice-quick' });
resetForm();
return;
}
if (isNew.value) {
await router.replace({ name: 'invoice-quick-detail', params: { id: saved.id } });
}
mapFromInvoice(saved);
} catch (err) {
error.value =
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
'ذخیره فاکتور ناموفق بود.';
} finally {
saving.value = false;
}
}
function resetForm() {
number.value = '';
title.value = 'فاکتور سریع';
kind.value = 'invoice';
status.value = 'draft';
notes.value = '';
address.value = '';
issuedAt.value = formatLocalDateInput(new Date());
dueDate.value = '';
currency.value = 'IRR';
discountAmount.value = 0;
taxPercent.value = 0;
personId.value = '';
companyId.value = '';
lines.value = [emptyInvoiceGridLine()];
error.value = '';
}
const statusLabel = computed(() => {
if (status.value === 'issued') return 'صادر شده';
if (status.value === 'paid') return 'پرداخت شده';
if (status.value === 'partially_paid') return 'پرداخت جزئی';
if (status.value === 'canceled') return 'لغو شده';
return 'پیش‌نویس';
});
const previewLines = computed(() =>
filledLines.value.map((line) => {
const product = products.value.find((p) => p.id === line.productId);
return {
name: line.name,
description: line.description?.trim() || undefined,
sku: product?.sku || undefined,
unit: line.unit?.trim() || undefined,
quantity: Number(line.quantity) || 0,
unitPrice: Number(line.unitPrice) || 0,
discount: Number(line.discountAmount) || 0,
taxPercent: Number(line.taxPercent) || 0,
total: computeGridLineTotal(line),
};
}),
);
const customerName = computed(() => {
const person = people.value.find((p) => p.id === personId.value);
return person?.fullName || '';
});
const customerSub = computed(() => {
const person = people.value.find((p) => p.id === personId.value);
return person?.company?.name || '';
});
const customerPhone = computed(() => {
const person = people.value.find((p) => p.id === personId.value);
return person?.mobile?.trim() || person?.phone?.trim() || '';
});
function openPreview() {
previewOpen.value = true;
}
function onGlobalKeydown(event: KeyboardEvent) {
if (event.ctrlKey && event.key.toLowerCase() === 's') {
event.preventDefault();
void save(false);
}
if (event.ctrlKey && event.key.toLowerCase() === 'p') {
event.preventDefault();
openPreview();
}
}
async function load() {
loading.value = true;
error.value = '';
try {
const [productsRes, orgRes] = await Promise.all([
api.get<ProductDto[]>('/products', { params: { activeOnly: true } }),
api.get<OrganizationDto>('/organizations/current').catch(() => null),
]);
products.value = productsRes.data;
orgName.value =
orgRes?.data?.name ||
auth.user?.organizationName ||
'';
if (!isNew.value) {
const { data } = await api.get<InvoiceDto>(`/invoices/${id.value}`);
mapFromInvoice(data);
}
} catch (err) {
error.value =
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
'بارگذاری فاکتور ناموفق بود.';
} finally {
loading.value = false;
}
}
onMounted(() => {
void load();
window.addEventListener('keydown', onGlobalKeydown);
});
onUnmounted(() => {
window.removeEventListener('keydown', onGlobalKeydown);
});
</script>
<template>
<div>
<PageHeader
title="فاکتور سریع"
subtitle="ورود جدولی سریع، شبیه نرم‌افزارهای حسابداری"
:icon="ThunderboltOutlined"
:back-to="{ name: 'invoices' }"
:style="{ marginBottom: `${token.margin}px` }"
>
<template #actions>
<a-button :disabled="saving || loading" @click="openPreview">
<template #icon><PrinterOutlined /></template>
چاپ / PDF
</a-button>
<a-button :loading="saving" :disabled="loading" @click="save(true)">
ذخیره و جدید
</a-button>
</template>
<template #primary>
<a-button type="primary" :loading="saving" :disabled="loading" @click="save(false)">
<template #icon><SaveOutlined /></template>
ذخیره (Ctrl+S)
</a-button>
</template>
</PageHeader>
<a-alert
v-if="error"
type="error"
show-icon
:message="error"
:style="{ marginBottom: `${token.margin}px` }"
closable
@close="error = ''"
/>
<a-card
:bordered="true"
:body-style="{ padding: `${token.paddingSM}px ${token.padding}px` }"
:style="{ marginBottom: `${token.margin}px` }"
>
<a-form layout="vertical" class="invoice-quick-head">
<a-row :gutter="[12, 8]">
<a-col :xs="24" :sm="12" :md="8" :lg="5" :xl="5">
<a-form-item label="مشتری" :style="{ marginBottom: 0 }">
<PersonPicker
v-model="personId"
:seed-people="people"
@change="onPersonChange"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8" :lg="5" :xl="5">
<a-form-item label="عنوان" :style="{ marginBottom: 0 }">
<a-input v-model:value="title" placeholder="عنوان فاکتور" />
</a-form-item>
</a-col>
<a-col :xs="12" :sm="8" :md="4" :lg="3" :xl="3">
<a-form-item label="نوع" :style="{ marginBottom: 0 }">
<a-segmented v-model:value="kind" :options="kindOptions" block />
</a-form-item>
</a-col>
<a-col :xs="12" :sm="8" :md="4" :lg="3" :xl="3">
<a-form-item label="وضعیت" :style="{ marginBottom: 0 }">
<a-select v-model:value="status" :options="statusOptions" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="12" :sm="8" :md="5" :lg="3" :xl="3">
<a-form-item label="تاریخ صدور" :style="{ marginBottom: 0 }">
<JalaliDateInput v-model="issuedAt" />
</a-form-item>
</a-col>
<a-col :xs="12" :sm="8" :md="5" :lg="3" :xl="3">
<a-form-item label="سررسید" :style="{ marginBottom: 0 }">
<JalaliDateInput v-model="dueDate" />
</a-form-item>
</a-col>
<a-col :xs="12" :sm="8" :md="4" :lg="2" :xl="2">
<a-form-item label="ارز" :style="{ marginBottom: 0 }">
<a-select
v-model:value="currency"
:options="currencyOptions"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="آدرس" :style="{ marginBottom: 0 }">
<a-textarea
v-model:value="address"
:rows="2"
placeholder="آدرس صورتحساب یا ارسال…"
allow-clear
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-card>
<a-card
title="ردیف‌های فاکتور"
:bordered="true"
:style="{ marginBottom: `${token.margin}px` }"
>
<template #extra>
<a-typography-text type="secondary">
Enter = سلول بعد · Insert = ردیف جدید · Ctrl+Delete = حذف ردیف
</a-typography-text>
</template>
<InvoiceEntryGrid
ref="gridRef"
v-model:lines="lines"
:products="products"
:currency="currency"
/>
</a-card>
<a-card
:bordered="true"
:body-style="{ padding: `${token.paddingSM}px ${token.padding}px` }"
>
<a-form layout="vertical">
<a-row :gutter="[16, 12]" align="top">
<a-col :xs="24" :md="10" :lg="8">
<a-row :gutter="[12, 8]">
<a-col :span="12">
<a-form-item label="تخفیف فاکتور" :style="{ marginBottom: 0 }">
<MoneyInput
v-model="discountAmount"
:decimals="0"
as-number
:show-prefix="false"
placeholder="۰"
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="مالیات فاکتور ٪" :style="{ marginBottom: 0 }">
<MoneyInput
v-model="taxPercent"
:decimals="2"
as-number
:show-prefix="false"
placeholder="۰"
addon-after="٪"
/>
</a-form-item>
</a-col>
</a-row>
</a-col>
<a-col :xs="24" :md="14" :lg="16">
<a-form-item label="خلاصه مبالغ" :style="{ marginBottom: 0 }">
<a-flex
align="center"
justify="space-between"
wrap="wrap"
:gap="token.marginXS"
:style="{
width: '100%',
minHeight: `${token.controlHeight}px`,
background: token.colorBgContainer,
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorder}`,
borderRadius: `${token.borderRadius}px`,
padding: `0 ${token.paddingSM}px`,
boxSizing: 'border-box',
}"
>
<a-flex align="center" :gap="token.marginXXS">
<a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }">
جمع ردیف‌ها:
</a-typography-text>
<a-typography-text :style="{ direction: 'ltr', fontVariantNumeric: 'tabular-nums' }">
{{ money(linesGross) }}
</a-typography-text>
</a-flex>
<a-divider type="vertical" :style="{ height: '18px', margin: 0 }" />
<a-flex align="center" :gap="token.marginXXS">
<a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }">
تخفیف:
</a-typography-text>
<a-typography-text :style="{ direction: 'ltr', fontVariantNumeric: 'tabular-nums' }">
{{ money(linesDiscount + invoiceDiscount) }}
</a-typography-text>
</a-flex>
<a-divider type="vertical" :style="{ height: '18px', margin: 0 }" />
<a-flex align="center" :gap="token.marginXXS">
<a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }">
مالیات:
</a-typography-text>
<a-typography-text :style="{ direction: 'ltr', fontVariantNumeric: 'tabular-nums' }">
{{ money(linesTax + invoiceTaxAmount) }}
</a-typography-text>
</a-flex>
<a-divider type="vertical" :style="{ height: '18px', margin: 0 }" />
<a-flex
align="center"
:gap="token.marginXS"
>
<a-typography-text
:style="{
color: token.colorPrimaryText,
fontWeight: 600,
fontSize: `${token.fontSizeSM}px`,
}"
>
قابل پرداخت:
</a-typography-text>
<a-typography-text
strong
:style="{
direction: 'ltr',
fontVariantNumeric: 'tabular-nums',
color: token.colorPrimary,
fontSize: `${token.fontSize}px`,
}"
>
{{ money(payableAmount) }}
</a-typography-text>
</a-flex>
</a-flex>
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="یادداشت" :style="{ marginBottom: 0 }">
<a-textarea
v-model:value="notes"
:rows="2"
placeholder="یادداشت فاکتور…"
allow-clear
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-card>
<InvoiceDocPreview
v-model:open="previewOpen"
:doc-mode="kind"
:org-name="orgName"
:number="number"
:title="title"
:status-label="statusLabel"
:issued-at="issuedAt"
:due-or-valid="dueDate"
due-or-valid-label="سررسید"
:customer-name="customerName"
:customer-sub="customerSub"
:customer-address="address"
:customer-phone="customerPhone"
:notes="notes"
:currency="currency"
:lines="previewLines"
:subtotal="linesSubtotal"
:discount="invoiceDiscount + linesDiscount"
:tax-amount="linesTax + invoiceTaxAmount"
:tax-percent="taxPercent"
:payable="payableAmount"
/>
</div>
</template>
<style>
.invoice-quick-head.ant-form-vertical .ant-form-item {
margin-bottom: 0 !important;
}
.invoice-quick-head .ant-form-item-additional,
.invoice-quick-head .ant-form-item-margin-offset {
display: none !important;
min-height: 0 !important;
height: 0 !important;
margin: 0 !important;
padding: 0 !important;
}
</style>
+76 -47
View File
@@ -40,19 +40,18 @@ import {
EyeOutlined, EyeOutlined,
FileTextOutlined, FileTextOutlined,
PlusOutlined, PlusOutlined,
UserAddOutlined,
} from '@/icons/ant-bridge'; } from '@/icons/ant-bridge';
import { CrmSkeleton, CrmSkeletonCard } from '@/components/skeleton'; import { CrmSkeleton, CrmSkeletonCard } from '@/components/skeleton';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue'; import MoneyInput from '@/components/MoneyInput.vue';
import InvoiceDocPreview from '@/components/InvoiceDocPreview.vue'; import InvoiceDocPreview from '@/components/InvoiceDocPreview.vue';
import PersonPicker from '@/components/PersonPicker.vue';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import type { import type {
CreateInvoiceRequest, CreateInvoiceRequest,
CreatePaymentRequest, CreatePaymentRequest,
CreateQuoteRequest, CreateQuoteRequest,
DealDto, DealDto,
DealLineItemInput,
FinancialAccountDto, FinancialAccountDto,
InvoiceDto, InvoiceDto,
InvoiceInstallmentInput, InvoiceInstallmentInput,
@@ -76,9 +75,12 @@ type LineDraft = {
name: string; name: string;
description: string; description: string;
sku: string; sku: string;
unit: string;
kind: 'product' | 'service' | ''; kind: 'product' | 'service' | '';
quantity: string; quantity: string;
unitPrice: string; unitPrice: string;
discountAmount: string;
taxPercent: string;
}; };
type InstallmentDraft = { type InstallmentDraft = {
@@ -138,6 +140,7 @@ const number = ref('');
const title = ref('فاکتور'); const title = ref('فاکتور');
const status = ref<string>('draft'); const status = ref<string>('draft');
const notes = ref(''); const notes = ref('');
const address = ref('');
const issuedAt = ref(formatLocalDateInput(new Date())); const issuedAt = ref(formatLocalDateInput(new Date()));
const dueDate = ref(''); const dueDate = ref('');
const validUntil = ref(''); const validUntil = ref('');
@@ -263,7 +266,10 @@ function roundMoney(value: number): number {
function lineTotal(line: LineDraft): number { function lineTotal(line: LineDraft): number {
const qty = Number(line.quantity) || 0; const qty = Number(line.quantity) || 0;
const price = Number(line.unitPrice) || 0; const price = Number(line.unitPrice) || 0;
return qty * price; const discount = Math.max(0, Number(line.discountAmount) || 0);
const tax = Math.max(0, Number(line.taxPercent) || 0);
const net = Math.max(0, qty * price - discount);
return roundMoney(net * (1 + tax / 100));
} }
const subtotal = computed(() => const subtotal = computed(() =>
@@ -308,9 +314,12 @@ function newLine(): LineDraft {
name: '', name: '',
description: '', description: '',
sku: '', sku: '',
unit: 'عدد',
kind: '', kind: '',
quantity: '1', quantity: '1',
unitPrice: '', unitPrice: '',
discountAmount: '0',
taxPercent: '0',
}; };
} }
@@ -336,6 +345,7 @@ function onPickProduct(line: LineDraft) {
line.name = product.name; line.name = product.name;
line.description = product.description ?? ''; line.description = product.description ?? '';
line.sku = product.sku ?? ''; line.sku = product.sku ?? '';
line.unit = product.unit ?? line.unit ?? 'عدد';
line.kind = product.kind; line.kind = product.kind;
if (product.unitPrice != null) line.unitPrice = String(product.unitPrice); if (product.unitPrice != null) line.unitPrice = String(product.unitPrice);
} }
@@ -345,14 +355,25 @@ function onPersonChange() {
companyId.value = person?.company?.id ?? ''; companyId.value = person?.company?.id ?? '';
} }
function toLineInputs(): DealLineItemInput[] { function onPersonPickerChange(p: PersonDto | null) {
if (p && !people.value.some((x) => x.id === p.id)) {
people.value = [p, ...people.value];
}
companyId.value = p?.company?.id ?? '';
}
function toLineInputs() {
return lines.value return lines.value
.filter((l) => l.name.trim() && l.quantity !== '' && l.unitPrice !== '') .filter((l) => l.name.trim() && l.quantity !== '' && l.unitPrice !== '')
.map((l) => ({ .map((l) => ({
productId: l.productId || null, productId: l.productId || null,
name: l.name.trim(), name: l.name.trim(),
unit: l.unit.trim() || null,
description: l.description.trim() || null,
quantity: Number(l.quantity), quantity: Number(l.quantity),
unitPrice: Number(l.unitPrice), unitPrice: Number(l.unitPrice),
discountAmount: Number(l.discountAmount) || 0,
taxPercent: Number(l.taxPercent) || 0,
currency: currency.value || 'IRR', currency: currency.value || 'IRR',
})); }));
} }
@@ -404,8 +425,12 @@ function mapLinesFromItems(
id?: string; id?: string;
productId?: string | null; productId?: string | null;
name: string; name: string;
unit?: string | null;
description?: string | null;
quantity: number; quantity: number;
unitPrice: number; unitPrice: number;
discountAmount?: number;
taxPercent?: number;
}>, }>,
): LineDraft[] { ): LineDraft[] {
return items.map((item, index) => { return items.map((item, index) => {
@@ -414,11 +439,14 @@ function mapLinesFromItems(
key: item.id || `line-${index}-${Date.now()}`, key: item.id || `line-${index}-${Date.now()}`,
productId: item.productId ?? '', productId: item.productId ?? '',
name: item.name, name: item.name,
description: product?.description ?? '', description: item.description ?? product?.description ?? '',
sku: product?.sku ?? '', sku: product?.sku ?? '',
unit: item.unit ?? product?.unit ?? 'عدد',
kind: product?.kind ?? '', kind: product?.kind ?? '',
quantity: String(item.quantity), quantity: String(item.quantity),
unitPrice: String(item.unitPrice), unitPrice: String(item.unitPrice),
discountAmount: String(item.discountAmount ?? 0),
taxPercent: String(item.taxPercent ?? 0),
}; };
}); });
} }
@@ -486,6 +514,7 @@ async function load() {
title.value = defaultTitle.value; title.value = defaultTitle.value;
status.value = 'draft'; status.value = 'draft';
notes.value = ''; notes.value = '';
address.value = '';
issuedAt.value = formatLocalDateInput(new Date()); issuedAt.value = formatLocalDateInput(new Date());
dueDate.value = ''; dueDate.value = '';
validUntil.value = ''; validUntil.value = '';
@@ -558,6 +587,7 @@ async function load() {
title.value = data.title; title.value = data.title;
status.value = data.status; status.value = data.status;
notes.value = data.notes ?? ''; notes.value = data.notes ?? '';
address.value = data.address ?? '';
currency.value = data.currency || currency.value; currency.value = data.currency || currency.value;
discountAmount.value = String(data.discountAmount ?? 0); discountAmount.value = String(data.discountAmount ?? 0);
taxPercent.value = String(data.taxPercent ?? 0); taxPercent.value = String(data.taxPercent ?? 0);
@@ -622,6 +652,7 @@ function invoicePayload(): CreateInvoiceRequest {
status: status.value, status: status.value,
kind: docMode.value === 'credit' ? 'credit' : 'invoice', kind: docMode.value === 'credit' ? 'credit' : 'invoice',
notes: notes.value || undefined, notes: notes.value || undefined,
address: address.value.trim() || undefined,
discountAmount: discountNum.value, discountAmount: discountNum.value,
taxPercent: taxPercentNum.value, taxPercent: taxPercentNum.value,
issuedAt: issuedAt.value ? new Date(issuedAt.value).toISOString() : null, issuedAt: issuedAt.value ? new Date(issuedAt.value).toISOString() : null,
@@ -856,6 +887,9 @@ const previewLines = computed(() =>
? unit ? unit
: Number(product?.unitPrice) || 0; : Number(product?.unitPrice) || 0;
const quantity = Number.isFinite(qty) && l.quantity !== '' ? qty : 1; const quantity = Number.isFinite(qty) && l.quantity !== '' ? qty : 1;
const discount = Math.max(0, Number(l.discountAmount) || 0);
const taxPct = Math.max(0, Number(l.taxPercent) || 0);
const net = Math.max(0, quantity * unitPrice - discount);
return { return {
name: name:
l.name.trim() || l.name.trim() ||
@@ -863,9 +897,12 @@ const previewLines = computed(() =>
(l.productId ? 'محصول انتخاب‌شده' : 'بدون نام'), (l.productId ? 'محصول انتخاب‌شده' : 'بدون نام'),
description: l.description?.trim() || product?.description || undefined, description: l.description?.trim() || product?.description || undefined,
sku: l.sku || product?.sku || undefined, sku: l.sku || product?.sku || undefined,
unit: l.unit || product?.unit || undefined,
quantity, quantity,
unitPrice, unitPrice,
total: quantity * unitPrice, discount,
taxPercent: taxPct,
total: Math.round((net * (1 + taxPct / 100) + Number.EPSILON) * 100) / 100,
}; };
}), }),
); );
@@ -889,11 +926,12 @@ const previewPayable = computed(() => {
const previewCustomer = computed(() => { const previewCustomer = computed(() => {
const p = people.value.find((x) => x.id === personId.value); const p = people.value.find((x) => x.id === personId.value);
if (!p) return { name: '—', sub: '' }; if (!p) return { name: '—', sub: '', phone: '' };
const full = p.fullName || `${p.firstName ?? ''} ${p.lastName ?? ''}`.trim(); const full = p.fullName || `${p.firstName ?? ''} ${p.lastName ?? ''}`.trim();
return { return {
name: p.company?.name || full || '—', name: full || '—',
sub: p.company?.name ? full : '', sub: p.company?.name || '',
phone: p.mobile?.trim() || p.phone?.trim() || '',
}; };
}); });
@@ -918,12 +956,6 @@ function onValidityDaysChange() {
applyValidityDays(validityDays.value); applyValidityDays(validityDays.value);
} }
function personLabel(p: PersonDto) {
return p.company?.name
? `${p.fullName} — ${p.company.name}`
: p.fullName;
}
const pendingInstallments = computed( const pendingInstallments = computed(
() => () =>
invoice.value?.installments.filter((i) => i.status === 'pending') ?? [], invoice.value?.installments.filter((i) => i.status === 'pending') ?? [],
@@ -943,10 +975,6 @@ watch(
const { Title: ATypographyTitle, Text: ATypographyText } = Typography; const { Title: ATypographyTitle, Text: ATypographyText } = Typography;
const personSelectOptions = computed(() =>
people.value.map((p) => ({ value: p.id, label: personLabel(p) })),
);
const statusSelectOptions = computed(() => const statusSelectOptions = computed(() =>
Object.entries(statusOptions.value).map(([value, label]) => ({ value, label })), Object.entries(statusOptions.value).map(([value, label]) => ({ value, label })),
); );
@@ -1075,21 +1103,13 @@ onMounted(load);
<a-row :gutter="[16, 0]"> <a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12"> <a-col :xs="24" :md="12">
<a-form-item label="مشتری" required> <a-form-item label="مشتری" required>
<a-select <PersonPicker
v-model:value="personId" v-model="personId"
show-search :seed-people="people"
option-filter-prop="label" add-label="افزودن مشتری جدید"
:options="personSelectOptions"
placeholder="انتخاب مشتری" placeholder="انتخاب مشتری"
style="width: 100%" @change="onPersonPickerChange"
@change="onPersonChange"
/> />
<RouterLink :to="{ name: 'person-new' }">
<a-button type="link" style="padding-inline: 0">
<template #icon><UserAddOutlined /></template>
افزودن مشتری جدید
</a-button>
</RouterLink>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="12"> <a-col :xs="24" :md="12">
@@ -1161,7 +1181,14 @@ onMounted(load);
<a-typography-text type="secondary">فیلدی برای تکمیل وجود ندارد.</a-typography-text> <a-typography-text type="secondary">فیلدی برای تکمیل وجود ندارد.</a-typography-text>
</a-collapse-panel> </a-collapse-panel>
<a-collapse-panel key="shipping" header="آدرس و ارسال"> <a-collapse-panel key="shipping" header="آدرس و ارسال">
<a-typography-text type="secondary">فیلدی برای تکمیل وجود ندارد.</a-typography-text> <a-form-item label="آدرس" :style="{ marginBottom: 0 }">
<a-textarea
v-model:value="address"
:rows="2"
placeholder="آدرس صورتحساب یا ارسال…"
allow-clear
/>
</a-form-item>
</a-collapse-panel> </a-collapse-panel>
</a-collapse> </a-collapse>
@@ -1277,14 +1304,14 @@ onMounted(load);
<a-divider orientation="right">مبالغ</a-divider> <a-divider orientation="right">مبالغ</a-divider>
<a-row :gutter="[16, 0]"> <a-row :gutter="[16, 12]">
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :lg="6">
<a-form-item label="تخفیف"> <a-form-item label="تخفیف" :style="{ marginBottom: 0 }">
<MoneyInput v-model="discountAmount" :decimals="0" placeholder="۰" /> <MoneyInput v-model="discountAmount" :decimals="0" placeholder="۰" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :lg="6">
<a-form-item label="مالیات (%)"> <a-form-item label="مالیات (%)" :style="{ marginBottom: 0 }">
<a-input-number <a-input-number
:value="Number(taxPercent) || 0" :value="Number(taxPercent) || 0"
:min="0" :min="0"
@@ -1294,8 +1321,8 @@ onMounted(load);
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="docMode === 'invoice'" :xs="24" :md="8"> <a-col v-if="docMode === 'invoice'" :xs="24" :sm="12" :lg="6">
<a-form-item label="نوع پورسانت"> <a-form-item label="نوع پورسانت" :style="{ marginBottom: 0 }">
<a-segmented <a-segmented
v-model:value="commissionMode" v-model:value="commissionMode"
block block
@@ -1306,9 +1333,13 @@ onMounted(load);
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="docMode === 'invoice' && commissionMode === 'percent'" :xs="24" :md="8"> <a-col v-if="docMode === 'invoice'" :xs="24" :sm="12" :lg="6">
<a-form-item label="پورسانت کارشناس (%)"> <a-form-item
:label="commissionMode === 'percent' ? 'پورسانت کارشناس (%)' : 'مبلغ پورسانت'"
:style="{ marginBottom: 0 }"
>
<a-input-number <a-input-number
v-if="commissionMode === 'percent'"
:value="commissionPercent === '' ? undefined : Number(commissionPercent)" :value="commissionPercent === '' ? undefined : Number(commissionPercent)"
:min="0" :min="0"
:max="100" :max="100"
@@ -1317,11 +1348,7 @@ onMounted(load);
style="width: 100%" style="width: 100%"
@update:value="(v) => (commissionPercent = v == null ? '' : String(v))" @update:value="(v) => (commissionPercent = v == null ? '' : String(v))"
/> />
</a-form-item> <MoneyInput v-else v-model="commissionFixedAmount" :decimals="0" />
</a-col>
<a-col v-else-if="docMode === 'invoice'" :xs="24" :md="8">
<a-form-item label="مبلغ پورسانت">
<MoneyInput v-model="commissionFixedAmount" :decimals="0" />
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
@@ -1576,6 +1603,8 @@ onMounted(load);
:due-or-valid-label="docMode === 'quote' ? 'اعتبار تا' : 'مهلت پرداخت'" :due-or-valid-label="docMode === 'quote' ? 'اعتبار تا' : 'مهلت پرداخت'"
:customer-name="previewCustomer.name" :customer-name="previewCustomer.name"
:customer-sub="previewCustomer.sub" :customer-sub="previewCustomer.sub"
:customer-address="address"
:customer-phone="previewCustomer.phone"
:notes="notes" :notes="notes"
:currency="currency" :currency="currency"
:lines="previewLines" :lines="previewLines"
+8 -1
View File
@@ -494,7 +494,13 @@ const columns = computed<TableColumnsType<BillingRow>>(() => {
}); });
function onAddMenu({ key }: { key: string | number }) { function onAddMenu({ key }: { key: string | number }) {
const kind = String(key) as 'invoice' | 'quote' | 'credit'; const k = String(key);
if (k === 'quick') {
addOpen.value = false;
void router.push({ name: 'invoice-quick' });
return;
}
const kind = k as 'invoice' | 'quote' | 'credit';
invoiceModal.value = { kind }; invoiceModal.value = { kind };
addOpen.value = false; addOpen.value = false;
} }
@@ -565,6 +571,7 @@ defineExpose({ toggleSelect, pageCount, statusIcon });
</a-button> </a-button>
<template #overlay> <template #overlay>
<a-menu @click="onAddMenu"> <a-menu @click="onAddMenu">
<a-menu-item key="quick">فاکتور سریع</a-menu-item>
<a-menu-item key="invoice">فاکتور جدید</a-menu-item> <a-menu-item key="invoice">فاکتور جدید</a-menu-item>
<a-menu-item key="quote">پیش فاکتور جدید</a-menu-item> <a-menu-item key="quote">پیش فاکتور جدید</a-menu-item>
<a-menu-item key="credit">فاکتور برگشتی</a-menu-item> <a-menu-item key="credit">فاکتور برگشتی</a-menu-item>
+1 -1
View File
@@ -42,7 +42,7 @@ import {
PhoneOutlined, PhoneOutlined,
PlusOutlined, PlusOutlined,
UserAddOutlined, UserAddOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { import {
isActivityExperienceAnswer, isActivityExperienceAnswer,
+10 -7
View File
@@ -9,6 +9,7 @@ import {
Card as ACard, Card as ACard,
Checkbox as ACheckbox, Checkbox as ACheckbox,
Col as ACol, Col as ACol,
Drawer as ADrawer,
Dropdown as ADropdown, Dropdown as ADropdown,
Empty as AEmpty, Empty as AEmpty,
Flex as AFlex, Flex as AFlex,
@@ -43,7 +44,7 @@ import {
SearchOutlined, SearchOutlined,
UnorderedListOutlined, UnorderedListOutlined,
UserAddOutlined, UserAddOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { import {
formatJalaliNumeric, formatJalaliNumeric,
@@ -2223,13 +2224,13 @@ onBeforeUnmount(() => {
</a-card> </a-card>
</a-col> </a-col>
<a-modal <a-drawer
v-model:open="createOpen" v-model:open="createOpen"
:title="createModalTitle" :title="createModalTitle"
:confirm-loading="createBusy" placement="right"
ok-text="ثبت" :width="520"
cancel-text="انصراف" destroy-on-close
@ok="submitCreate" @close="createOpen = false"
> >
<a-form layout="vertical" :model="createForm" @click.stop> <a-form layout="vertical" :model="createForm" @click.stop>
<a-row :gutter="[16, 0]"> <a-row :gutter="[16, 0]">
@@ -2425,6 +2426,7 @@ onBeforeUnmount(() => {
</a-modal> </a-modal>
<template #footer> <template #footer>
<a-space>
<a-button :disabled="createBusy" @click="createOpen = false">انصراف</a-button> <a-button :disabled="createBusy" @click="createOpen = false">انصراف</a-button>
<a-button type="primary" :disabled="createBusy" :loading="createBusy" @click="submitCreate"> <a-button type="primary" :disabled="createBusy" :loading="createBusy" @click="submitCreate">
{{ {{
@@ -2433,7 +2435,8 @@ onBeforeUnmount(() => {
: 'ثبت لید' : 'ثبت لید'
}} }}
</a-button> </a-button>
</a-space>
</template> </template>
</a-modal> </a-drawer>
</a-row> </a-row>
</template> </template>
+13 -13
View File
@@ -939,9 +939,9 @@ onBeforeUnmount(() => {
</a-flex> </a-flex>
<a-form layout="vertical"> <a-form layout="vertical">
<a-row :gutter="[16, 0]" align="bottom"> <a-row :gutter="[16, 12]" align="bottom">
<a-col :xs="24" :md="10"> <a-col :xs="24" :sm="12" :md="10" :xl="9">
<a-form-item label="جستجو"> <a-form-item label="جستجو" :style="{ marginBottom: 0 }">
<a-input <a-input
v-model:value="q" v-model:value="q"
allow-clear allow-clear
@@ -953,8 +953,8 @@ onBeforeUnmount(() => {
</a-input> </a-input>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :sm="12" :md="6"> <a-col :xs="24" :sm="12" :md="6" :xl="5">
<a-form-item label="سطح"> <a-form-item label="سطح" :style="{ marginBottom: 0 }">
<a-select <a-select
v-model:value="tierFilter" v-model:value="tierFilter"
:options="tierFilterOptions" :options="tierFilterOptions"
@@ -964,9 +964,12 @@ onBeforeUnmount(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :sm="12" :md="8"> <a-col :xs="24" :md="8" :xl="10">
<a-form-item label=" "> <a-form-item :colon="false" :style="{ marginBottom: 0 }">
<a-space wrap :size="8"> <template #label>
<span style="visibility: hidden">عملیات</span>
</template>
<a-flex justify="flex-end" wrap="wrap" :gap="8">
<a-button :disabled="saving" @click="exportExcel"> <a-button :disabled="saving" @click="exportExcel">
<template #icon><DownloadOutlined /></template> <template #icon><DownloadOutlined /></template>
خروجی Excel خروجی Excel
@@ -979,16 +982,13 @@ onBeforeUnmount(() => {
<template #icon><GiftOutlined /></template> <template #icon><GiftOutlined /></template>
امتیاز گروهی امتیاز گروهی
</a-button> </a-button>
</a-space> <TableColumnsMenu table-key="loyalty.members" align="end" />
</a-flex>
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
</a-form> </a-form>
<a-flex justify="flex-end">
<TableColumnsMenu table-key="loyalty.members" align="end" />
</a-flex>
<a-table <a-table
:columns="columns" :columns="columns"
:data-source="visibleMembers" :data-source="visibleMembers"
+2 -2
View File
@@ -31,7 +31,8 @@ import {
PhoneOutlined, PhoneOutlined,
PlusOutlined, PlusOutlined,
SearchOutlined, SearchOutlined,
} from '@ant-design/icons-vue'; UserOutlined,
} from '@/icons/ant-bridge';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useFeedback } from '@/composables/useFeedback'; import { useFeedback } from '@/composables/useFeedback';
import type { CompanyDto, CreatePersonRequest, PersonDto, PersonGender, PersonMood } from '@mento/shared'; import type { CompanyDto, CreatePersonRequest, PersonDto, PersonGender, PersonMood } from '@mento/shared';
@@ -58,7 +59,6 @@ import CustomerMoodFace from '@/components/CustomerMoodFace.vue';
import EntityTimeline from '@/components/EntityTimeline.vue'; import EntityTimeline from '@/components/EntityTimeline.vue';
import MentoMemoryPanel from '@/components/MentoMemoryPanel.vue'; import MentoMemoryPanel from '@/components/MentoMemoryPanel.vue';
import { PageHeader } from '@/components/page'; import { PageHeader } from '@/components/page';
import { UserOutlined } from '@/icons/ant-bridge';
const ASpaceCompact = Space.Compact; const ASpaceCompact = Space.Compact;
const { Text: ATypographyText, Paragraph: ATypographyParagraph } = const { Text: ATypographyText, Paragraph: ATypographyParagraph } =
+7 -5
View File
@@ -25,10 +25,11 @@ import {
DeleteOutlined, DeleteOutlined,
DownloadOutlined, DownloadOutlined,
UploadOutlined, UploadOutlined,
} from '@ant-design/icons-vue'; } from '@/icons/ant-bridge';
import { import {
Alert as AAlert, Alert as AAlert,
Button as AButton, Button as AButton,
Drawer as ADrawer,
Flex as AFlex, Flex as AFlex,
Form as AForm, Form as AForm,
FormItem as AFormItem, FormItem as AFormItem,
@@ -936,13 +937,14 @@ function onNewDeal() {
</a-form> </a-form>
</a-modal> </a-modal>
<a-modal <a-drawer
:open="Boolean(dealModal)" :open="Boolean(dealModal)"
:title="dealModal?.dealId ? 'ویرایش معامله' : 'ایجاد معامله جدید'" :title="dealModal?.dealId ? 'ویرایش معامله' : 'ایجاد معامله جدید'"
placement="right"
:width="720"
:footer="null" :footer="null"
destroy-on-close destroy-on-close
width="720px" @close="dealModal = null"
@cancel="dealModal = null"
> >
<DealFormView <DealFormView
v-if="dealModal" v-if="dealModal"
@@ -953,7 +955,7 @@ function onNewDeal() {
@saved="onDealSaved" @saved="onDealSaved"
@cancel="dealModal = null" @cancel="dealModal = null"
/> />
</a-modal> </a-drawer>
</div> </div>
</template> </template>
+36 -2
View File
@@ -13,7 +13,7 @@ import {
toFaDigits, toFaDigits,
} from '@/lib/jalali'; } from '@/lib/jalali';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { CHART_PALETTE, type UiChartOption } from '@/components/ui'; import { CHART_PALETTE, type UiChartOption } from '@/components/ui/UiChart.vue';
import type { import type {
OrganizationDto, OrganizationDto,
OrgUserDto, OrgUserDto,
@@ -39,21 +39,52 @@ import {
REPORTS_BUILDER_METRIC_LABELS, REPORTS_BUILDER_METRIC_LABELS,
REPORTS_BUILDER_METRICS, REPORTS_BUILDER_METRICS,
} from '@mento/shared'; } from '@mento/shared';
import { Empty as AEmpty, theme } from 'ant-design-vue'; import {
Alert as AAlert,
Avatar as AAvatar,
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,
Progress as AProgress,
Row as ARow,
Segmented as ASegmented,
Select as ASelect,
Space as ASpace,
Spin as ASpin,
Statistic as AStatistic,
Table as ATable,
TabPane as ATabPane,
Tabs as ATabs,
Tooltip as ATooltip,
Typography,
theme,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue'; import type { TableColumnsType } from 'ant-design-vue';
import { PageHeader } from '@/components/page'; import { PageHeader } from '@/components/page';
import { CrmSkeleton, CrmSkeletonCard, CrmSkeletonKpi } from '@/components/skeleton'; import { CrmSkeleton, CrmSkeletonCard, CrmSkeletonKpi } from '@/components/skeleton';
import { import {
BarChartOutlined, BarChartOutlined,
CalendarOutlined, CalendarOutlined,
CheckCircleOutlined,
DeleteOutlined, DeleteOutlined,
DollarOutlined, DollarOutlined,
FileExcelOutlined, FileExcelOutlined,
FileTextOutlined, FileTextOutlined,
LinkOutlined, LinkOutlined,
QuestionCircleOutlined,
RiseOutlined, RiseOutlined,
SaveOutlined, SaveOutlined,
TeamOutlined, TeamOutlined,
ThunderboltOutlined,
} from '@/icons/ant-bridge'; } from '@/icons/ant-bridge';
import { use } from 'echarts/core'; import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers'; import { CanvasRenderer } from 'echarts/renderers';
@@ -78,6 +109,9 @@ use([
]); ]);
const { token } = theme.useToken(); const { token } = theme.useToken();
const { Text: ATypographyText, Paragraph: ATypographyParagraph } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const emptySimple = AEmpty.PRESENTED_IMAGE_SIMPLE; const emptySimple = AEmpty.PRESENTED_IMAGE_SIMPLE;
const stretchColStyle = { display: 'flex' }; const stretchColStyle = { display: 'flex' };
@@ -1,10 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue'; import { computed, onMounted, ref } from 'vue';
import axios from 'axios'; import axios from 'axios';
import { import {
Alert as AAlert, Alert as AAlert,
Button as AButton, Button as AButton,
Card as ACard, Card as ACard,
Checkbox as ACheckbox,
Col as ACol, Col as ACol,
Divider as ADivider, Divider as ADivider,
Empty as AEmpty, Empty as AEmpty,
@@ -13,12 +14,21 @@ import {
FormItem as AFormItem, FormItem as AFormItem,
Input as AInput, Input as AInput,
List as AList, List as AList,
Modal as AModal,
Row as ARow, Row as ARow,
Select as ASelect, Select as ASelect,
Space as ASpace,
Switch as ASwitch,
Tag as ATag,
Typography, Typography,
message, message,
} from 'ant-design-vue'; } from 'ant-design-vue';
import { AppstoreOutlined, FileTextOutlined, ScheduleOutlined } from '@/icons/ant-bridge'; import {
AppstoreOutlined,
EditOutlined,
FileTextOutlined,
ScheduleOutlined,
} from '@/icons/ant-bridge';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import MoneyInput from '@/components/MoneyInput.vue'; import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
@@ -27,7 +37,7 @@ import TreasuryListPagination from '@/components/treasury/TreasuryListPagination
import { toman } from './treasury-format'; import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging'; import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile'; import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali'; import { formatJalaliNumeric, formatLocalDateInput, toFaDigits } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money'; import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography; const { Text: ATypographyText } = Typography;
@@ -42,13 +52,93 @@ type Row = {
kind: string; kind: string;
amount: string; amount: string;
interval: string; interval: string;
startDate: string;
nextDue: string; nextDue: string;
isActive: boolean; 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 rows = ref<Row[]>([]); const rows = ref<Row[]>([]);
const error = ref(''); const error = ref('');
const ok = ref(''); const ok = ref('');
const saving = ref(false); const saving = ref(false);
const editOpen = ref(false);
const editingId = ref<string | null>(null);
const form = ref(emptyForm());
const editForm = ref(emptyForm());
const { const {
page, page,
pageSize, pageSize,
@@ -58,17 +148,49 @@ const {
onPageSizeChange, onPageSizeChange,
showTotal, showTotal,
} = useTreasuryListPaging(() => rows.value, 'treasury.recurring'); } = useTreasuryListPaging(() => rows.value, 'treasury.recurring');
const form = ref({ title: '', kind: 'expense', amount: '', interval: 'monthly', startDate: '' });
const createReminderEnabled = computed(() => form.value.reminderDaysBefore !== '');
const editReminderEnabled = computed(() => editForm.value.reminderDaysBefore !== '');
const modalWidth = computed(() => (isMobile.value ? '100%' : 720));
async function load() { async function load() {
const { data } = await api.get<Row[]>('/treasury/recurring'); const { data } = await api.get<Row[]>('/treasury/recurring');
rows.value = data; rows.value = data;
} }
function reminderPayload(state: FormState) {
const days = reminderFromSelect(state.reminderDaysBefore);
return {
reminderDaysBefore: days,
reminderRepeatDaily: days == null ? true : freqFromSelect(state.reminderRepeatDaily),
reminderNotifyApp: days == null ? false : state.reminderNotifyApp,
reminderNotifySms: days == null ? false : state.reminderNotifySms,
};
}
function onFinishFailed() { function onFinishFailed() {
message.warning('لطفاً فیلدهای الزامی را کامل کنید.'); message.warning('لطفاً فیلدهای الزامی را کامل کنید.');
} }
function openEdit(item: Row) {
error.value = '';
ok.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;
}
async function createItem() { async function createItem() {
error.value = ''; error.value = '';
ok.value = ''; ok.value = '';
@@ -80,11 +202,14 @@ async function createItem() {
return; return;
} }
await api.post('/treasury/recurring', { await api.post('/treasury/recurring', {
...form.value, title: form.value.title,
kind: form.value.kind,
amount, amount,
startDate: form.value.startDate || undefined, interval: form.value.interval,
startDate: form.value.dueDate || undefined,
...reminderPayload(form.value),
}); });
form.value = { title: '', kind: 'expense', amount: '', interval: 'monthly', startDate: '' }; form.value = emptyForm();
ok.value = 'الگو ثبت شد. در سررسید فقط سند باز ساخته می‌شود.'; ok.value = 'الگو ثبت شد. در سررسید فقط سند باز ساخته می‌شود.';
await load(); await load();
} catch (e) { } catch (e) {
@@ -96,6 +221,45 @@ async function createItem() {
} }
} }
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;
}
}
onMounted(() => { onMounted(() => {
void load(); void load();
}); });
@@ -103,7 +267,7 @@ onMounted(() => {
<template> <template>
<a-flex vertical :gap="16"> <a-flex vertical :gap="16">
<a-alert v-if="error" type="error" show-icon :message="error" /> <a-alert v-if="error && !editOpen" type="error" show-icon :message="error" />
<a-alert v-if="ok" type="success" show-icon :message="ok" /> <a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false"> <a-card :bordered="false">
@@ -119,7 +283,9 @@ onMounted(() => {
<a-form-item <a-form-item
name="title" name="title"
:rules="[{ required: true, message: 'عنوان الزامی است' }]" :rules="[{ required: true, message: 'عنوان الزامی است' }]"
label="عنوان"><a-input v-model:value="form.title"> label="عنوان"
>
<a-input v-model:value="form.title">
<template #prefix><FileTextOutlined /></template> <template #prefix><FileTextOutlined /></template>
</a-input> </a-input>
</a-form-item> </a-form-item>
@@ -138,7 +304,9 @@ onMounted(() => {
<a-form-item <a-form-item
name="amount" name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]" :rules="[{ required: true, message: 'مبلغ الزامی است' }]"
label="مبلغ"><MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" /> label="مبلغ"
>
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :md="8">
@@ -153,11 +321,47 @@ onMounted(() => {
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :md="8">
<a-form-item name="startDate" label="شروع"><JalaliDateInput v-model="form.startDate" /> <a-form-item name="dueDate" label="شروع / سررسید بعدی">
<JalaliDateInput v-model="form.dueDate" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="زمان یادآور">
<SelectWithIcon :icon="ScheduleOutlined">
<a-select
v-model:value="form.reminderDaysBefore"
style="width: 100%"
:options="REMINDER_DAY_OPTIONS"
/>
</SelectWithIcon>
</a-form-item>
</a-col>
<a-col v-if="createReminderEnabled" :xs="24" :md="8">
<a-form-item label="تکرار یادآور">
<SelectWithIcon :icon="ScheduleOutlined">
<a-select
v-model:value="form.reminderRepeatDaily"
style="width: 100%"
:options="REMINDER_FREQ_OPTIONS"
/>
</SelectWithIcon>
</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="form.reminderNotifyApp">ناتیفیکیشن</a-checkbox>
<a-checkbox v-model:checked="form.reminderNotifySms">پیامک</a-checkbox>
</a-space>
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
<a-flex vertical :gap="12" align="flex-start">
<a-typography-text type="secondary">
مثلاً «۲ روز قبل · فقط یک‌بار»: یک پیام در همان روز؛ «۳ روز قبل · هر روز»: هر روز تا سررسید برای مالک.
</a-typography-text>
<a-button type="primary" html-type="submit" :loading="saving">ثبت الگو</a-button> <a-button type="primary" html-type="submit" :loading="saving">ثبت الگو</a-button>
</a-flex>
</a-form> </a-form>
<a-divider orientation="right">فهرست الگوها</a-divider> <a-divider orientation="right">فهرست الگوها</a-divider>
@@ -166,14 +370,41 @@ onMounted(() => {
<template #renderItem="{ item }"> <template #renderItem="{ item }">
<a-list-item> <a-list-item>
<template #actions> <template #actions>
<a-button type="link" @click="openEdit(item)">
<template #icon><EditOutlined /></template>
ویرایش
</a-button>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text> <a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template> </template>
<a-list-item-meta> <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> <template #description>
<a-flex vertical :gap="4">
<a-typography-text type="secondary">
{{ item.kind === 'income' ? 'درآمد' : 'هزینه' }} {{ item.kind === 'income' ? 'درآمد' : 'هزینه' }}
· {{ item.interval }} · {{ INTERVAL_LABEL[item.interval] || item.interval }}
· بعدی {{ formatJalaliNumeric(new Date(item.nextDue)) }} · بعدی {{ 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> </template>
</a-list-item-meta> </a-list-item-meta>
</a-list-item> </a-list-item>
@@ -188,5 +419,98 @@ onMounted(() => {
@update:page-size="onPageSizeChange" @update:page-size="onPageSizeChange"
/> />
</a-card> </a-card>
<a-modal
v-model:open="editOpen"
title="ویرایش الگو"
ok-text="ذخیره"
cancel-text="انصراف"
:confirm-loading="saving"
:width="modalWidth"
:centered="isMobile"
destroy-on-close
@ok="saveEdit"
>
<a-flex vertical :gap="12">
<a-alert v-if="error && editOpen" type="error" show-icon :message="error" />
<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">
<template #prefix><FileTextOutlined /></template>
</a-input>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="نوع" name="kind" :rules="[{ required: true }]">
<SelectWithIcon :icon="AppstoreOutlined">
<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>
</SelectWithIcon>
</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="editForm.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="دوره" name="interval" :rules="[{ required: true }]">
<SelectWithIcon :icon="ScheduleOutlined">
<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>
</SelectWithIcon>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="سررسید بعدی" name="dueDate">
<JalaliDateInput v-model="editForm.dueDate" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="زمان یادآور">
<SelectWithIcon :icon="ScheduleOutlined">
<a-select
v-model:value="editForm.reminderDaysBefore"
style="width: 100%"
:options="REMINDER_DAY_OPTIONS"
/>
</SelectWithIcon>
</a-form-item>
</a-col>
<a-col v-if="editReminderEnabled" :xs="24" :md="8">
<a-form-item label="تکرار یادآور">
<SelectWithIcon :icon="ScheduleOutlined">
<a-select
v-model:value="editForm.reminderRepeatDaily"
style="width: 100%"
:options="REMINDER_FREQ_OPTIONS"
/>
</SelectWithIcon>
</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-flex>
</a-modal>
</a-flex> </a-flex>
</template> </template>
@@ -5,23 +5,38 @@ import {
Alert as AAlert, Alert as AAlert,
Button as AButton, Button as AButton,
Card as ACard, Card as ACard,
Col as ACol,
Divider as ADivider, Divider as ADivider,
Empty as AEmpty, Empty as AEmpty,
Flex as AFlex, Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
List as AList, List as AList,
Descriptions as ADescriptions, Descriptions as ADescriptions,
DescriptionsItem as ADescriptionsItem, DescriptionsItem as ADescriptionsItem,
Row as ARow,
Space as ASpace,
Table as ATable, Table as ATable,
Tabs as ATabs, Tabs as ATabs,
Typography, Typography,
message,
} from 'ant-design-vue'; } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue'; import type { TableColumnsType } from 'ant-design-vue';
import { DownloadOutlined } from '@/icons/ant-bridge'; import { DownloadOutlined, SearchOutlined } from '@/icons/ant-bridge';
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import type { TreasuryPartyBalanceDto } from '@mento/shared'; import type { TreasuryPartyBalanceDto } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue'; import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue'; import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import {
dateToJalali,
formatJalaliNumeric,
formatLocalDateInput,
jalaliMonthName,
jalaliToDate,
toFaDigits,
} from '@/lib/jalali';
import { toman } from './treasury-format'; import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging'; import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile'; import { useTreasuryMobile } from './useTreasuryMobile';
@@ -51,13 +66,23 @@ type MetricRow = {
previous: string; previous: string;
}; };
type PayableMonth = { month: string; label?: string; amount: string };
const todayJalali = dateToJalali(new Date());
const fromDate = ref(formatLocalDateInput(jalaliToDate(todayJalali.jy, todayJalali.jm, 1)));
const toDate = ref(formatLocalDateInput(new Date()));
const rangeFrom = ref('');
const rangeTo = ref('');
const previousFrom = ref('');
const previousTo = ref('');
const current = ref<Period | null>(null); const current = ref<Period | null>(null);
const previous = ref<Period | null>(null); const previous = ref<Period | null>(null);
const payablesByMonth = ref<Array<{ month: string; amount: string }>>([]); const payablesByMonth = ref<PayableMonth[]>([]);
const receivablesByParty = ref<Array<{ name: string; amount: string }>>([]); const receivablesByParty = ref<Array<{ name: string; amount: string }>>([]);
const debtors = ref<TreasuryPartyBalanceDto[]>([]); const debtors = ref<TreasuryPartyBalanceDto[]>([]);
const creditors = ref<TreasuryPartyBalanceDto[]>([]); const creditors = ref<TreasuryPartyBalanceDto[]>([]);
const reportTab = ref('periods'); const reportTab = ref('periods');
const loading = ref(false);
const error = ref(''); const error = ref('');
const balanceError = ref(''); const balanceError = ref('');
@@ -78,6 +103,17 @@ const lines = [
['خالص جریان نقدی', 'cashNet'], ['خالص جریان نقدی', 'cashNet'],
] as const; ] as const;
const currentRangeLabel = computed(() =>
rangeFrom.value && rangeTo.value
? `${formatJalaliNumeric(new Date(rangeFrom.value))} تا ${formatJalaliNumeric(new Date(rangeTo.value))}`
: '—',
);
const previousRangeLabel = computed(() =>
previousFrom.value && previousTo.value
? `${formatJalaliNumeric(new Date(previousFrom.value))} تا ${formatJalaliNumeric(new Date(previousTo.value))}`
: '—',
);
const metricColumns: TableColumnsType<MetricRow> = [ const metricColumns: TableColumnsType<MetricRow> = [
{ title: 'شاخص', dataIndex: 'label', key: 'label' }, { title: 'شاخص', dataIndex: 'label', key: 'label' },
{ title: 'این دوره', dataIndex: 'current', key: 'current' }, { title: 'این دوره', dataIndex: 'current', key: 'current' },
@@ -127,17 +163,84 @@ const {
'treasury.reports-expense-cats', 'treasury.reports-expense-cats',
); );
function monthTitle(item: PayableMonth) {
if (item.label) return item.label;
const match = /^(\d{4})-(\d{2})$/.exec(item.month);
if (!match) return item.month;
const year = Number(match[1]);
const month = Number(match[2]);
if (year > 1700) {
const j = dateToJalali(new Date(year, month - 1, 15));
return `${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`;
}
return `${jalaliMonthName(month)} ${toFaDigits(year)}`;
}
async function load() { async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<{ const { data } = await api.get<{
from?: string;
to?: string;
previousFrom?: string;
previousTo?: string;
current: Period; current: Period;
previous: Period; previous: Period;
payablesByMonth: Array<{ month: string; amount: string }>; payablesByMonth: PayableMonth[];
receivablesByParty: Array<{ name: string; amount: string }>; receivablesByParty: Array<{ name: string; amount: string }>;
}>('/treasury/reports'); }>('/treasury/reports', {
params: {
from: fromDate.value || undefined,
to: toDate.value || undefined,
},
});
const fromIso = data.from || `${fromDate.value}T00:00:00`;
const toIso = data.to || `${toDate.value}T23:59:59`;
const fromJ = dateToJalali(new Date(fromIso));
const prevMonth = {
jy: fromJ.jm === 1 ? fromJ.jy - 1 : fromJ.jy,
jm: fromJ.jm === 1 ? 12 : fromJ.jm - 1,
};
const fallbackPrevFrom = jalaliToDate(prevMonth.jy, prevMonth.jm, 1);
const nextOfPrev = jalaliToDate(
prevMonth.jm === 12 ? prevMonth.jy + 1 : prevMonth.jy,
prevMonth.jm === 12 ? 1 : prevMonth.jm + 1,
1,
);
const fallbackPrevTo = new Date(nextOfPrev.getTime() - 1);
rangeFrom.value = fromIso;
rangeTo.value = toIso;
previousFrom.value = data.previousFrom || fallbackPrevFrom.toISOString();
previousTo.value = data.previousTo || fallbackPrevTo.toISOString();
current.value = data.current; current.value = data.current;
previous.value = data.previous; previous.value = data.previous;
payablesByMonth.value = data.payablesByMonth; payablesByMonth.value = data.payablesByMonth;
receivablesByParty.value = data.receivablesByParty; receivablesByParty.value = data.receivablesByParty;
} catch {
error.value = 'گزارش بارگذاری نشد.';
} finally {
loading.value = false;
}
}
function applyRange() {
if (!fromDate.value || !toDate.value) {
message.warning('از تاریخ و تا تاریخ را مشخص کنید.');
return;
}
if (fromDate.value > toDate.value) {
message.warning('بازهٔ تاریخ نامعتبر است.');
return;
}
void load();
}
function resetToCurrentJalaliMonth() {
const today = dateToJalali(new Date());
fromDate.value = formatLocalDateInput(jalaliToDate(today.jy, today.jm, 1));
toDate.value = formatLocalDateInput(new Date());
void load();
} }
function sumRemaining(rows: TreasuryPartyBalanceDto[]) { function sumRemaining(rows: TreasuryPartyBalanceDto[]) {
@@ -185,7 +288,13 @@ async function loadBalances() {
} }
async function download() { async function download() {
const { data } = await api.get<Blob>('/treasury/reports/export', { responseType: 'blob' }); const { data } = await api.get<Blob>('/treasury/reports/export', {
responseType: 'blob',
params: {
from: fromDate.value || undefined,
to: toDate.value || undefined,
},
});
const url = URL.createObjectURL(data); const url = URL.createObjectURL(data);
const link = document.createElement('a'); const link = document.createElement('a');
link.href = url; link.href = url;
@@ -195,9 +304,7 @@ async function download() {
} }
onMounted(() => { onMounted(() => {
void load().catch(() => { void load();
error.value = 'گزارش بارگذاری نشد.';
});
void loadBalances().catch((e: unknown) => { void loadBalances().catch((e: unknown) => {
if (axios.isAxiosError(e) && (e.response?.status === 404 || e.response?.status === 403)) { if (axios.isAxiosError(e) && (e.response?.status === 404 || e.response?.status === 403)) {
debtors.value = []; debtors.value = [];
@@ -211,12 +318,42 @@ onMounted(() => {
<template> <template>
<a-flex vertical :gap="16"> <a-flex vertical :gap="16">
<a-flex justify="flex-end"> <a-card :bordered="false">
<a-button @click="download"> <a-form layout="vertical" @finish="applyRange">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="از تاریخ">
<JalaliDateInput v-model="fromDate" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تا تاریخ">
<JalaliDateInput v-model="toDate" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label=" ">
<a-space :size="8" wrap>
<a-button type="primary" html-type="submit" :loading="loading">
<template #icon><SearchOutlined /></template>
اعمال بازه
</a-button>
<a-button :disabled="loading" @click="resetToCurrentJalaliMonth">
ماه جاری شمسی
</a-button>
<a-button :disabled="loading" @click="download">
<template #icon><DownloadOutlined /></template> <template #icon><DownloadOutlined /></template>
خروجی اکسل خروجی اکسل
</a-button> </a-button>
</a-flex> </a-space>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-typography-text type="secondary">
پیش‌فرض: از اول ماه شمسی جاری تا امروز. «دوره قبل» همیشه ماه شمسی کاملِ قبل (اول تا آخر ماه) است.
</a-typography-text>
</a-card>
<a-alert v-if="error" type="error" show-icon :message="error" /> <a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="balanceError" type="error" show-icon :message="balanceError" /> <a-alert v-if="balanceError" type="error" show-icon :message="balanceError" />
@@ -225,14 +362,25 @@ onMounted(() => {
<a-tabs v-model:activeKey="reportTab"> <a-tabs v-model:activeKey="reportTab">
<a-tab-pane key="periods" tab="مقایسه دوره‌ها"> <a-tab-pane key="periods" tab="مقایسه دوره‌ها">
<a-flex vertical :gap="16"> <a-flex vertical :gap="16">
<a-descriptions bordered :column="isMobile ? 1 : 2">
<a-descriptions-item label="این دوره">{{ currentRangeLabel }}</a-descriptions-item>
<a-descriptions-item label="دوره قبل">{{ previousRangeLabel }}</a-descriptions-item>
</a-descriptions>
<a-list v-if="isMobile && metricRows.length" :data-source="metricRows"> <a-list v-if="isMobile && metricRows.length" :data-source="metricRows">
<template #renderItem="{ item }"> <template #renderItem="{ item }">
<a-list-item> <a-list-item>
<a-card :title="item.label" style="width: 100%"> <a-card :title="item.label" style="width: 100%">
<a-descriptions :column="1" bordered> <a-flex vertical :gap="8">
<a-descriptions-item label="این دوره">{{ item.current }}</a-descriptions-item> <a-flex justify="space-between" align="center" :gap="8">
<a-descriptions-item label="دوره قبل">{{ item.previous }}</a-descriptions-item> <a-typography-text type="secondary">این دوره</a-typography-text>
</a-descriptions> <a-typography-text strong>{{ item.current }}</a-typography-text>
</a-flex>
<a-flex justify="space-between" align="center" :gap="8">
<a-typography-text type="secondary">دوره قبل</a-typography-text>
<a-typography-text>{{ item.previous }}</a-typography-text>
</a-flex>
</a-flex>
</a-card> </a-card>
</a-list-item> </a-list-item>
</template> </template>
@@ -242,6 +390,7 @@ onMounted(() => {
:columns="metricColumns" :columns="metricColumns"
:data-source="metricRows" :data-source="metricRows"
:pagination="false" :pagination="false"
:loading="loading"
row-key="key" row-key="key"
/> />
<a-empty v-else description="داده‌ای برای نمایش نیست." /> <a-empty v-else description="داده‌ای برای نمایش نیست." />
@@ -269,7 +418,7 @@ onMounted(() => {
@update:page-size="onPartyPageSizeChange" @update:page-size="onPartyPageSizeChange"
/> />
<a-divider orientation="right">تعهدات به تفکیک ماه</a-divider> <a-divider orientation="right">تعهدات به تفکیک ماه شمسی</a-divider>
<a-empty v-if="!payablesByMonth.length" description="تعهد بازی نیست." /> <a-empty v-if="!payablesByMonth.length" description="تعهد بازی نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedMonthRows"> <a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedMonthRows">
<template #renderItem="{ item }"> <template #renderItem="{ item }">
@@ -278,7 +427,7 @@ onMounted(() => {
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text> <a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</template> </template>
<a-list-item-meta> <a-list-item-meta>
<template #title>{{ item.month }}</template> <template #title>{{ monthTitle(item) }}</template>
</a-list-item-meta> </a-list-item-meta>
</a-list-item> </a-list-item>
</template> </template>
@@ -293,7 +442,7 @@ onMounted(() => {
/> />
<template v-if="current"> <template v-if="current">
<a-divider orientation="right">سهم هزینه‌ها</a-divider> <a-divider orientation="right">سهم هزینه‌ها (این دوره)</a-divider>
<a-empty v-if="!current.expenseCategories.length" description="دسته‌ای نیست." /> <a-empty v-if="!current.expenseCategories.length" description="دسته‌ای نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedExpenseCats"> <a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedExpenseCats">
<template #renderItem="{ item }"> <template #renderItem="{ item }">
@@ -0,0 +1,60 @@
# PersonPicker Implementation Plan
> **For agentic workers:** This plan was written after the code landed (per user request: build first, document after). Tasks below reflect what was done and how to verify.
**Goal:** Shared Ant Design Vue `PersonPicker` (select + server search + dropdown «add person» + create modal), used in Activity, Deal, and Invoice forms.
**Architecture:** One component owns search, options, dropdown footer CTA, and `PersonFormView` modal. Parents pass `v-model` + `seedPeople` and handle side effects via `@change` / `@created`.
**Tech stack:** Vue 3, Ant Design Vue 4, `@mento/web`, existing `/people` API.
---
## File map
| File | Role |
|---|---|
| `apps/web/src/components/PersonPicker.vue` | New shared picker |
| `apps/web/src/views/ActivityFormView.vue` | Consume picker; remove local search/modal |
| `apps/web/src/views/DealFormView.vue` | Same |
| `apps/web/src/views/InvoiceFormView.vue` | Same; label «افزودن مشتری جدید» |
| `docs/superpowers/specs/2026-11-29-person-picker-design.md` | Design spec |
---
### Task 1: PersonPicker component
**Status:** Done
- `a-select` + `filter-option=false` + debounce search `GET /people?q=&limit=30`
- `dropdownRender` footer: divider + link button with `UserAddOutlined`
- `a-modal` + embedded `PersonFormView`; on save select person and emit `created` + `change`
- Props: `modelValue`, `placeholder`, `allowClear`, `disabled`, `addLabel`, `seedPeople`
### Task 2: ActivityFormView
**Status:** Done
- Replace select + link + `UiModal` with `<PersonPicker v-model="personId" :seed-people="people" @change="onPersonPickerChange" />`
- Keep `rememberPerson` / `ensurePersonLoaded` for load paths
### Task 3: DealFormView
**Status:** Done
- Same wiring; `@created` sets `contactKind = 'person'` and fills company from person
### Task 4: InvoiceFormView
**Status:** Done
- Replace select + `RouterLink` with PersonPicker (`add-label="افزودن مشتری جدید"`)
- Server search instead of client-only filter; seed from loaded `people`
### Task 5: Verify
```bash
npm run build -w @mento/web
```
Manual smoke: open Activity / Deal / Invoice → search person → add via dropdown footer → save form still binds personId.
@@ -0,0 +1,101 @@
# PersonPicker — Design Spec
**Date:** 2026-11-29
**Status:** Approved in conversation (layout A, scope 2, create-via-modal)
## Problem
«افزودن شخص جدید» alongside person select is duplicated and visually awkward (link button under select). Activity and Deal copy the same search + modal logic; Invoice uses a different label and navigates away instead of creating inline.
## Goals
1. One Ant Design Vue component for person select + create.
2. Cleaner UX: create action lives in the select dropdown footer.
3. Create always opens embedded `PersonFormView` in a modal; after save, select that person without leaving the parent form.
4. Wire into Activity form, Deal form, and Invoice form. Treasury stays out of scope.
## Non-goals
- Refactoring `TreasuryPartySelect` (multi-kind party: person/company/user/other).
- Migrating unrelated form chrome or legacy `Ui*` kits beyond what this component needs for its own modal.
- Shared company picker.
## Approach
**Full `PersonPicker` component** that owns:
- `a-select` with server search (`GET /people?q=&limit=30`, 300ms debounce)
- Dropdown footer: divider + link button (`UserAddOutlined` + configurable label)
- Modal with embedded `PersonFormView`
- Optional seed list so parents can keep already-loaded people visible
Parents keep only `v-model` (person id) and optional side effects on `created` / `change`.
## API
**File:** `apps/web/src/components/PersonPicker.vue`
| Prop / model | Type | Default | Notes |
|---|---|---|---|
| `modelValue` (`v-model`) | `string` | `''` | Selected person id |
| `placeholder` | `string` | `'جستجو و انتخاب شخص'` | |
| `allowClear` | `boolean` | `true` | |
| `disabled` | `boolean` | `false` | |
| `addLabel` | `string` | `'افزودن شخص جدید'` | Invoice may pass `'افزودن مشتری جدید'` |
| `seedPeople` | `PersonDto[]` | `[]` | Initial / remembered options |
| `modalNest` | `boolean` | `false` | Forward `nest` to modal when parent is already nested |
| Emit | Payload | When |
|---|---|---|
| `update:modelValue` | `string` | Selection cleared or changed |
| `change` | `PersonDto \| null` | Resolved person object when known; `null` on clear |
| `created` | `PersonDto` | After successful create in modal (also selects that person) |
## UI / design rules
- Ant-only controls; no raw HTML buttons/inputs; no new scoped look CSS.
- No manual `size` on Ant controls (theme `controlHeight: 36`).
- Dropdown footer: `a-divider` + `a-button type="link"` with icon; stop mousedown so select does not steal focus/close incorrectly (same pattern as `TreasuryPartySelect`).
- Modal: prefer `a-modal` if the surrounding page is Ant-migrated and does not already depend on `UiModal` for this flow; if nesting/`UiModal` is required for Activity’s existing nest behavior, match current Activity/Deal nesting so z-index/stacking does not regress.
- Pass `:initial-query` from the current search string into `PersonFormView` when opening create.
## Parent integration
### ActivityFormView
- Replace select + link + person-search watchers + create modal with `<PersonPicker v-model="personId" :seed-people="people" @change="…" @created="…" />`.
- On `change`/`created`, call existing `rememberPerson` / deal-link side effects as today.
- Remove duplicated `personQuery` / `personResults` / `newPersonOpen` / modal block when fully owned by the picker (seed via `people` ref still updated from `change`).
### DealFormView
- Same as Activity.
- On `created` / person pick: keep `contactKind = 'person'` and company auto-fill from `person.company` (existing `pickPerson` behavior).
### InvoiceFormView
- Replace select + `RouterLink` «افزودن مشتری جدید» with `PersonPicker` (`add-label` optional).
- Switch from client-only filter over loaded `people` to server search inside the picker; pass current `people` as `seedPeople`.
- On create/select, ensure parent `people` list still has the chosen person for any labels/downstream logic.
## Behavior details
- Empty query: show seed / remembered options (not a forced empty list).
- Clear: emit `''` and `change(null)`.
- Create cancel: close modal only.
- Create save: close modal, merge person into internal options, set `modelValue`, emit `created` then selection updates.
- Loading: select `loading` while search in flight.
- Errors: failed search → empty options for that query (silent or message consistent with Activity today).
## Governance
- Shared component under `apps/web/src/components/` (not `components/ui`).
- Touch only the three views listed for replacement; no drive-by refactors.
- Ant strict rules: no new chrome CSS, no `size` props.
## Success criteria
- One shared component used in Activity, Deal, Invoice.
- No standalone «افزودن شخص جدید» link under the select in those three views.
- Create stays in-modal; Invoice no longer navigates away to create.
- `npm run build -w @mento/web` passes.
@@ -0,0 +1,89 @@
# Invoice Preview Templates — Design Spec
**Date:** 2026-11-30
**Status:** Approved in conversation (preview-only selection; approach C; 5 distinct moods)
## Problem
Current `InvoiceDocPreview` looks cluttered: repeated doc-type labels, a dense 6-field metadata grid, weak hierarchy, and a generic “wireframe” look. Users need multiple luxurious, professional invoice looks they can switch in preview/print.
## Goals
1. Five visually distinct invoice templates available in the preview modal.
2. Template choice applies to both on-screen preview and print HTML.
3. Reduce clutter: fewer competing labels, clearer hierarchy, calmer table/totals.
4. Keep Ant Design Vue governance for modal chrome (segmented, buttons); sheet itself is print-oriented HTML/CSS.
## Non-goals
- Org-level default template persistence (settings / API) — later.
- Per-invoice template stored on Invoice model — later.
- Changing invoice data model, builder grid, or totals logic.
- Migrating other pages or legacy print paths outside `InvoiceDocPreview`.
## Approach
**Shared skeleton + distinct layouts/themes (approach C):**
- One data/render pipeline (props → line rows → totals).
- Three layout families reused across five moods:
- Wide colored header band
- Dark sidebar + light body
- Minimal / editorial / modern header variants
- Five named themes with different color, typography weight, and chrome — not five fully forked HTML trees.
## Templates
| Id | Label (FA) | Mood | Accent | Layout family |
|----|------------|------|--------|---------------|
| `emerald` | کلاسیک زمردی | Brand / professional | Emerald green | Wide header band |
| `noir` | اجرایی تیره | Luxury corporate | Navy + soft gold | Dark sidebar |
| `pearl` | مرواریدی | Luxury minimal | Near-black on white | Minimal lines only |
| `sand` | ادیتوریال شنی | Editorial / magazine | Warm beige + brown | Soft top wash + asymmetric meta |
| `slate` | مدرن اسلیت | Modern technical | Slate + teal accent | Two-column header + chip meta |
**Default:** `emerald`
### Shared content rules (all templates)
- Show doc type **once** (no duplicate “فاکتور فروش” in header corners).
- Primary meta in header: customer, issue date, due/valid, title (max 4). Status and currency move to compact chips or footer strip — not a 6-cell dense grid.
- Table: calm header, generous row padding, amount column emphasized; optional unit/discount/tax columns only when data needs them (existing logic).
- Totals: one clear block (bottom-start in RTL); notes opposite side when present.
- Paper sizes A4 / A5 remain; template scales typography slightly for A5.
### Per-template chrome (summary)
1. **Emerald:** thin emerald top bar; soft emerald table header; totals box with emerald payable.
2. **Noir:** ~18% navy sidebar (org + doc type); navy table header / white text; gold payable; notes with thin gold rule.
3. **Pearl:** oversized org name; no color bars; thick rule under column headers; totals as typography only (no bordered card).
4. **Sand:** soft beige top third; editorial title; muted brown labels; warm beige totals column.
5. **Slate:** aligned two-column header; meta as chips; slate table header; payable in teal strip / soft card.
## UX (preview modal)
- Header/footer chrome stays Ant: `a-segmented` for **template** (5 short FA labels) + existing A4/A5 segmented + print/close.
- Selected template drives both preview sheet and `printSheet()` CSS/HTML.
- No persistence beyond the open modal session (reset to `emerald` when modal opens is acceptable; optionally remember last choice in `sessionStorage` — nice-to-have, not required).
## Implementation touchpoints
| Area | Change |
|------|--------|
| `apps/web/src/components/InvoiceDocPreview.vue` | Template state, preview markup per layout/theme, print HTML/CSS parity |
| Call sites | No prop API change required unless we later expose `defaultTemplate` |
Prefer extracting shared helpers (escape, money, row HTML, col visibility) inside the same file or a small colocated module if the SFC grows too large — avoid premature split.
## Success criteria
- User can switch among 5 looks in preview without leaving the modal.
- Print matches the selected look (colors with `print-color-adjust: exact`).
- Preview feels less cluttered than current (no duplicate titles; meta ≤ 4 primary fields).
- `npm run build -w @mento/web` passes; Ant control rules on modal chrome unchanged (no manual `size`).
## Out of scope follow-ups
- Org setting “default invoice template”
- Persist template on invoice record
- PDF generation service (server-side)
+21 -2
View File
@@ -3262,13 +3262,29 @@ export interface InvoiceLineItemDto {
id: string; id: string;
productId: string | null; productId: string | null;
name: string; name: string;
unit: string | null;
description: string | null;
quantity: number; quantity: number;
unitPrice: number; unitPrice: number;
discountAmount: number;
taxPercent: number;
currency: string; currency: string;
position: number; position: number;
lineTotal: number; lineTotal: number;
} }
export interface InvoiceLineItemInput {
productId?: string | null;
name: string;
unit?: string | null;
description?: string | null;
quantity: number;
unitPrice: number;
discountAmount?: number;
taxPercent?: number;
currency?: string;
}
export type ChequeStatus = "pending" | "cleared" | "bounced"; export type ChequeStatus = "pending" | "cleared" | "bounced";
export type ChequeDirection = "in" | "out"; export type ChequeDirection = "in" | "out";
@@ -3368,6 +3384,7 @@ export interface InvoiceDto {
kind?: "invoice" | "credit"; kind?: "invoice" | "credit";
currency: string; currency: string;
notes: string | null; notes: string | null;
address?: string | null;
discountAmount?: number; discountAmount?: number;
taxPercent?: number; taxPercent?: number;
issuedAt: string | null; issuedAt: string | null;
@@ -3409,6 +3426,7 @@ export interface CreateInvoiceRequest {
kind?: "invoice" | "credit"; kind?: "invoice" | "credit";
currency?: string; currency?: string;
notes?: string; notes?: string;
address?: string;
discountAmount?: number; discountAmount?: number;
taxPercent?: number; taxPercent?: number;
issuedAt?: string | null; issuedAt?: string | null;
@@ -3419,7 +3437,7 @@ export interface CreateInvoiceRequest {
quoteId?: string | null; quoteId?: string | null;
fromDealId?: string | null; fromDealId?: string | null;
fromQuoteId?: string | null; fromQuoteId?: string | null;
lineItems?: DealLineItemInput[]; lineItems?: InvoiceLineItemInput[];
installments?: InvoiceInstallmentInput[]; installments?: InvoiceInstallmentInput[];
commissionPercent?: number | null; commissionPercent?: number | null;
commissionFixedAmount?: number | null; commissionFixedAmount?: number | null;
@@ -3431,6 +3449,7 @@ export interface UpdateInvoiceRequest {
kind?: "invoice" | "credit"; kind?: "invoice" | "credit";
currency?: string; currency?: string;
notes?: string | null; notes?: string | null;
address?: string | null;
discountAmount?: number; discountAmount?: number;
taxPercent?: number; taxPercent?: number;
issuedAt?: string | null; issuedAt?: string | null;
@@ -3439,7 +3458,7 @@ export interface UpdateInvoiceRequest {
companyId?: string | null; companyId?: string | null;
dealId?: string | null; dealId?: string | null;
quoteId?: string | null; quoteId?: string | null;
lineItems?: DealLineItemInput[]; lineItems?: InvoiceLineItemInput[];
installments?: InvoiceInstallmentInput[]; installments?: InvoiceInstallmentInput[];
commissionPercent?: number | null; commissionPercent?: number | null;
commissionFixedAmount?: number | null; commissionFixedAmount?: number | null;