update saleinvoice single and create return from sale form, update agent.md file,

This commit is contained in:
2026-06-01 13:53:42 +03:30
parent c271a36f7e
commit d44004d555
25 changed files with 562 additions and 199 deletions
@@ -1,5 +1,13 @@
import { ToastService } from '@/core/services/toast.service';
import { Component, EventEmitter, inject, Input, Output, signal } from '@angular/core';
import {
Component,
EventEmitter,
inject,
Input,
Output,
signal,
SimpleChanges,
} from '@angular/core';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { finalize, Observable } from 'rxjs';
@@ -43,7 +51,7 @@ export abstract class AbstractForm<
// });
}
ngOnChanges() {
ngOnChanges(changes: SimpleChanges) {
this.form.patchValue(this.initialValues ?? this.defaultValues);
}
@@ -1,7 +1,7 @@
<p-confirmdialog #cd>
<ng-template #headless let-message let-onAccept="onAccept" let-onReject="onReject">
@if (message) {
<div class="bg-surface-0 dark:bg-surface-900 flex flex-col items-center rounded p-8">
<div class="bg-surface-card flex flex-col items-center rounded p-8">
<div
class="bg-primary text-primary-contrast -mt-20 inline-flex h-24 w-24 items-center justify-center rounded-full">
<i class="pi pi-question text-5xl!"></i>
@@ -9,11 +9,19 @@
<span class="mt-6 mb-2 block text-2xl font-bold">{{ message.header }}</span>
<p class="mb-0">{{ message.message }}</p>
<div class="mt-6 flex items-center gap-2">
<p-button [label]="message.acceptLabel" type="button" (onClick)="onAccept()" styleClass="w-32"></p-button>
<p-button
[label]="message.acceptLabel"
type="button"
[loading]="!!message.acceptLoading"
[disabled]="!!message.acceptLoading"
[severity]="message.acceptButtonProps?.severity"
(onClick)="onAccept()"
styleClass="w-32"></p-button>
<p-button
[label]="message.rejectLabel"
type="button"
[outlined]="true"
[disabled]="!!message.acceptLoading"
(onClick)="onReject()"
styleClass="w-32"></p-button>
</div>
@@ -1,13 +1,9 @@
import { Injectable, inject } from '@angular/core';
import { Confirmation, ConfirmationService } from 'primeng/api';
export interface AppConfirmOptions {
header: string;
message: string;
acceptLabel?: string;
rejectLabel?: string;
accept?: () => void;
reject?: () => void;
export interface AppConfirmOptions extends Confirmation {
variant?: 'warn' | 'danger' | 'default';
acceptLoading?: boolean;
}
@Injectable({
@@ -16,16 +12,38 @@ export interface AppConfirmOptions {
export class AppConfirmationService {
private confirmationService = inject(ConfirmationService);
ask(options: Confirmation): Promise<boolean> {
ask(options: AppConfirmOptions): Promise<boolean> {
const { variant = 'default', ...confirmationOptions } = options;
switch (variant) {
case 'danger':
options.acceptButtonProps.severity = 'danger';
break;
case 'warn':
options.acceptButtonProps.severity = 'warn';
break;
}
return new Promise((resolve) => {
this.confirmationService.confirm({
position: 'bottom',
acceptLabel: 'تایید',
rejectLabel: 'لغو',
...options,
closeOnEscape: true,
accept: () => options.accept?.() || resolve(true),
reject: () => resolve(false),
...confirmationOptions,
accept: async () => {
try {
options.acceptLoading = true;
await confirmationOptions.accept?.();
resolve(true);
} finally {
options.acceptLoading = false;
}
},
reject: () => {
if (options.acceptLoading) return;
resolve(false);
},
});
});
}
@@ -0,0 +1,31 @@
import { DatepickerComponent } from '@/uikit';
import { formatGregorian, gregorianAddUnit } from '@/utils';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'field-invoice-date',
template: `
<app-datepicker
label="تاریخ صورت‌حساب‌"
[alignment]="alignment"
[min]="invoiceMinDate"
[max]="invoiceMaxDate"
[control]="control"
(valueChange)="changeDate($event)"
/>
`,
imports: [DatepickerComponent],
})
export class FieldInvoiceDateComponent {
@Input() alignment: 'horizontal' | 'vertical' = 'vertical';
@Input({ required: true }) control!: FormControl<string | null>;
@Output() onChangeDate = new EventEmitter<string>();
invoiceMinDate = formatGregorian(gregorianAddUnit(new Date(), -7, 'days'));
invoiceMaxDate = formatGregorian(new Date());
changeDate(date: string) {
this.onChangeDate.emit(date);
}
}
@@ -62,7 +62,9 @@
@if (suffixTemp) {
<ng-container [ngTemplateOutlet]="suffixTemp" />
} @else if (preparedSuffix()) {
<p-inputgroup-addon>{{ preparedSuffix() }}</p-inputgroup-addon>
<p-inputgroup-addon [ngClass]="{ 'border-red-400!': (control.touched || control.dirty) && control.invalid }">{{
preparedSuffix()
}}</p-inputgroup-addon>
}
</p-inputgroup>
}
@@ -0,0 +1,18 @@
<form [formGroup]="form" (ngSubmit)="submit()">
<p-message severity="info" icon="pi pi-info-circle">
در برگشت از فروش صورتحساب شما میتوانید صرفا تعداد محصولات و خدمات خود را کم و حذف کنید و حداقل مقدار محصولات و خدمات
شما ۱ می باشد.
</p-message>
<field-invoice-date [control]="form.controls.invoice_date" />
@for (item of items.controls; track (goodItems()[$index]?.good_snapshot!.id || '') + ($index + '')) {
<div class="py-2">
<shared-return-form-item
[control]="item.controls.quantity"
[good]="goodItems()[$index]!.good_snapshot"
[index]="$index" />
</div>
}
<app-form-footer-actions />
</form>
@@ -0,0 +1,108 @@
import { Maybe } from '@/core';
import { AbstractForm } from '@/shared/abstractClasses';
import { formatDate, GREGORIAN_DATE_FORMATS } from '@/utils';
import { Component, computed, Input, signal, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Message } from 'primeng/message';
import { FieldInvoiceDateComponent } from '../../fields/invoice_date.component';
import { FormFooterActionsComponent } from '../../formFooterActions/form-footer-actions.component';
import { IInvoiceItem } from '../sale-invoice-full-response.model';
import { SharedReturnFormItemComponent } from './item-form.component';
type ItemForm = FormGroup<{
quantity: FormControl<number | null>;
}>;
type BackFromSaleFormValue = {
items: {
id: string;
quantity: number;
maxQuantity: number;
}[];
};
@Component({
selector: 'shared-return-form',
templateUrl: 'form.component.html',
imports: [
Message,
FormFooterActionsComponent,
ReactiveFormsModule,
FieldInvoiceDateComponent,
SharedReturnFormItemComponent,
],
})
export class SharedReturnFormComponent extends AbstractForm<
BackFromSaleFormValue,
any,
IInvoiceItem[]
> {
@Input({ required: true }) invoiceDate!: string;
form = this.fb.group({
invoice_date: [this.invoiceDate],
items: this.fb.array<ItemForm>([], {
// validators: [atLeastOneQuantityValidator],
}),
});
goodItems = computed(() => this.initialValues!);
get items() {
return this.form.controls.items;
}
preparedCalculation = signal<Maybe<any>>(null);
init() {
this.initForm();
this.prepareCalculation();
}
prepareCalculation() {
const calculated = [];
this.initialValues?.forEach((item) => {});
}
initForm() {
this.items.clear();
this.form.controls.invoice_date.setValue(
formatDate(this.invoiceDate, 'gregory', 'en', GREGORIAN_DATE_FORMATS.FULL)
);
this.initialValues?.forEach((item: any) => {
this.items.push(
this.fb.group({
quantity: [
Number(item.quantity),
[Validators.required, Validators.min(0), Validators.max(Number(item.quantity))],
],
})
);
});
}
override ngOnInit(): void {
this.init();
}
override ngOnChanges(changes: SimpleChanges) {
if (changes['initialValues']) {
this.init();
}
}
override submitForm() {
const payload = this.items.controls.map((control) => ({
id: control.get('id')?.value,
quantity: control.get('quantity')?.value,
}));
if (!payload.some((item) => item.quantity)) {
this.toastService.warn({
text: 'حداقل مقدار یکی از کالاها/خدمات باید بیشتر از ۰ باشد.',
});
return;
}
}
}
@@ -0,0 +1,13 @@
<div>
<p-divider align="right">
{{ index + 1 }}- <b>{{ good.name }}</b>
</p-divider>
<app-input
[control]="control"
name="quantity"
[label]="good.measure_unit.name"
type="number"
[suffix]="good.measure_unit.name"
[max]="control.defaultValue || undefined"
[min]="0" />
</div>
@@ -0,0 +1,45 @@
import { Maybe } from '@/core';
import { Component, Input, signal, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { InputComponent } from '../../input/input.component';
import { Goodsnapshot } from '../sale-invoice-full-response.model';
type ItemForm = FormGroup<{
quantity: FormControl<number | null>;
}>;
type BackFromSaleFormValue = {
items: {
id: string;
quantity: number;
maxQuantity: number;
}[];
};
@Component({
selector: 'shared-return-form-item',
templateUrl: './item-form.component.html',
imports: [InputComponent, ReactiveFormsModule, Divider],
})
export class SharedReturnFormItemComponent {
@Input({ required: true }) control!: FormControl<number | null>;
@Input({ required: true }) good!: Goodsnapshot;
@Input({ required: true }) index!: number;
preparedCalculation = signal<Maybe<any>>(null);
prepareCalculation() {
const calculated = [];
}
ngOnInit(): void {
this.prepareCalculation();
}
ngOnChanges(changes: SimpleChanges) {
if (changes['initialValues']) {
this.prepareCalculation();
}
}
}
@@ -14,7 +14,7 @@ export interface ISaleInvoiceFullRawResponse {
consumer_account: ConsumerAccount;
pos: Pos;
payments: Payment[];
items: Item[];
items: IInvoiceItem[];
invoice_number: number;
type: IEnumTranslate<InvoiceTypes>;
created_at: string;
@@ -30,7 +30,7 @@ export interface ISaleInvoiceFullRawResponse {
export interface ISaleInvoiceFullResponse extends ISaleInvoiceFullRawResponse {}
interface Item {
export interface IInvoiceItem {
id: string;
good_id: string;
service_id: null;
@@ -64,9 +64,7 @@ interface Category {
updated_at: string;
}
interface Goodsnapshot {
good: Good;
}
export interface Goodsnapshot extends Good {}
interface Good {
id: string;
@@ -20,6 +20,7 @@
<div class="flex flex-col gap-4">
<div class="listKeyValue">
<app-key-value label="شماره صورت‌حساب" [value]="invoice.invoice_number" />
<app-key-value label="شماره منحصر به فرد مالیاتی" [value]="invoice.tax_id" />
<app-key-value label="تاریخ صورت‌حساب‌" [value]="invoice.invoice_date" type="date" />
<app-key-value label="تاریخ ایجاد صورت‌حساب‌" [value]="invoice.created_at" type="dateTime" />
<app-key-value label="نوع صورت‌حساب">
@@ -109,4 +110,8 @@
</app-page-data-list>
</app-card-data>
</div>
<shared-light-bottomsheet [(visible)]="showBackFromSaleForm" header=" برگشت از فروش">
<shared-return-form [initialValues]="invoice.items" [invoiceDate]="invoice.invoice_date" />
</shared-light-bottomsheet>
}
@@ -43,6 +43,7 @@ import { ProgressSpinner } from 'primeng/progressspinner';
import { TableModule } from 'primeng/table';
import { Observable } from 'rxjs';
import { AppConfirmationService } from '../confirmationDialog/confirmation-dialog.service';
import { SharedReturnFormComponent } from './returnForm/form.component';
export type TSaleInvoiceSingleViewVariant = 'full' | 'customer' | 'pos';
@@ -65,6 +66,7 @@ export type TSaleInvoiceSingleViewVariant = 'full' | 'customer' | 'pos';
CatalogInvoiceSettlementTypeTagComponent,
SharedLightBottomsheetComponent,
ProgressSpinner,
SharedReturnFormComponent,
],
})
export class SharedSaleInvoiceSingleViewComponent {
@@ -90,6 +92,8 @@ export class SharedSaleInvoiceSingleViewComponent {
@ViewChild('totalAmount', { static: false }) totalAmount!: TemplateRef<any>;
moreActionMenuItems = signal<MenuItem[]>([]);
showCorrectionForm = signal(false);
showBackFromSaleForm = signal(false);
constructor() {
this.showErrors = this.showErrors.bind(this);
@@ -112,16 +116,17 @@ export class SharedSaleInvoiceSingleViewComponent {
send() {
this.onSendToTsp.emit();
}
showRevokeConfirmation() {
this.confirmationService.ask({
async showRevokeConfirmation() {
await this.confirmationService.ask({
header: `ابطال صورت‌حساب‌ شماره ${this.invoice!.invoice_number}`,
message: `در صورت تایید ابطال صورت‌حساب‌ شماره ${this.invoice!.invoice_number} بر روی دکمه‌ی ابطال کلیک کنید.`,
acceptLabel: 'ابطال',
acceptButtonProps: {
severity: 'dangerdock',
},
variant: 'danger',
accept: () => {
accept: async () => {
// this.deferredInstallPrompt.prompt();
// this.deferredInstallPrompt.userChoice.finally(() => {
// this.deferredInstallPrompt = null;
@@ -133,7 +138,9 @@ export class SharedSaleInvoiceSingleViewComponent {
});
}
showCorrection() {}
showBackFromSale() {}
showBackFromSale() {
this.showBackFromSaleForm.set(true);
}
ngOnChanges(changes: SimpleChanges) {
if (changes['invoice'] && this.invoice) {
@@ -320,21 +327,18 @@ export class SharedSaleInvoiceSingleViewComponent {
{
label: 'اجرت',
value: formatWithCurrency(item.payload.wages),
show:
mustPrintConfig.items?.wage && item.good_snapshot.good.pricing_model === 'GOLD',
show: mustPrintConfig.items?.wage && item.good_snapshot.pricing_model === 'GOLD',
},
{
label: 'سود',
value: formatWithCurrency(item.payload.wages),
show:
mustPrintConfig.items?.profit && item.good_snapshot.good.pricing_model === 'GOLD',
show: mustPrintConfig.items?.profit && item.good_snapshot.pricing_model === 'GOLD',
},
{
label: 'حق‌العمل',
value: formatWithCurrency(item.payload.commission),
show:
mustPrintConfig.items?.commission &&
item.good_snapshot.good.pricing_model === 'GOLD',
mustPrintConfig.items?.commission && item.good_snapshot.pricing_model === 'GOLD',
},
{
label: 'مالیات بر ارزش افزوده',
@@ -1,3 +1,4 @@
import { Maybe } from '@/core';
import { formatDurationToText, formatJalali, JALALI_DATE_FORMATS } from '@/utils';
import priceMaskUtils from '@/utils/price-mask.utils';
import { CommonModule } from '@angular/common';
@@ -16,7 +17,7 @@ import { TDataType } from '../pageDataList/page-data-list.component';
})
export class KeyValueComponent {
@Input() label!: string;
@Input() value?: string | boolean | number;
@Input() value?: Maybe<string | boolean | number>;
@Input() hint?: string;
@Input() alignment?: 'start' | 'center' | 'end' = 'start';
@Input() type: TDataType = 'simple';
@@ -0,0 +1,46 @@
import { IPosOrderItem } from '@/domains/pos/modules/shop/models';
import { goldDiscountType, TGoldDiscountType } from '@/shared/localEnum/constants/goldDiscountType';
import { IGoldPayload } from '@/shared/models';
export interface IGoldAmountCalculationPayload {
commission: string;
wages: string;
discount_amount: string;
profit: string;
unit_price: string;
quantity: string;
discount_type: TGoldDiscountType;
}
export default (payload: Partial<IPosOrderItem<IGoldPayload>>) => {
const commissionAmount = Number(payload.payload?.commission ?? '0');
const wageAmount = Number(payload.payload?.wages ?? '0');
const discountAmount = Number(payload.discount_amount ?? '0');
const profitAmount = Number(payload.payload?.profit ?? '0');
const unitPrice = Number(payload.unit_price ?? '0');
const quantity = Number(payload.quantity ?? '0');
const discountType = payload.payload?.discount_type;
const unitWithQuantity = unitPrice * quantity;
const totalAmountBeforeProfit = unitWithQuantity + wageAmount + commissionAmount;
const baseTotalAmount = totalAmountBeforeProfit + profitAmount;
const baseAmountForDiscountCalculation =
discountType === goldDiscountType.PROFIT ? profitAmount : unitWithQuantity;
const taxAmount =
(profitAmount +
commissionAmount +
wageAmount -
(discountType === goldDiscountType.PROFIT ? discountAmount : 0)) *
0.1;
const totalAmount = baseTotalAmount - discountAmount + taxAmount;
return {
unitWithQuantity,
totalAmountBeforeProfit,
baseTotalAmount,
taxAmount,
totalAmount,
baseAmountForDiscountCalculation,
};
};
@@ -42,10 +42,10 @@
<ng-template #labelSuffix>
<p-selectButton
[options]="discountTypeItems"
[(ngModel)]="discountType"
[(ngModel)]="form.controls.payload.controls.discount_type.value"
[allowEmpty]="false"
optionLabel="label"
optionValue="value"
optionLabel="name"
optionValue="id"
(onChange)="changeDiscountCalculation($event)" />
</ng-template>
</app-amount-percentage-input>
@@ -8,6 +8,8 @@ import {
CalculatedAmountCardComponent,
InputComponent,
} from '@/shared/components';
import { LOCAL_ENUMS } from '@/shared/localEnum/constants';
import { goldDiscountType } from '@/shared/localEnum/constants/goldDiscountType';
import { TGoldKarat } from '@/shared/localEnum/constants/goldKarat';
import { IGoldPayload } from '@/shared/models';
import { Component, computed, EventEmitter, inject, Input, Output, signal } from '@angular/core';
@@ -15,6 +17,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { ButtonDirective } from 'primeng/button';
import { SelectButton, SelectButtonChangeEvent } from 'primeng/selectbutton';
import goldAmountCalculationUtil from './gold-amount-calculation.util';
@Component({
selector: 'shared-gold-payload-form',
@@ -54,18 +57,8 @@ export class SharedGoldPayloadFormComponent extends AbstractForm<
private readonly posGoldConfig = inject(PosConfigGoldPriceService);
readonly discountTypeItems = [
{
label: 'از سود',
value: 1,
},
{
label: 'از کل',
value: 2,
},
];
readonly discountTypeItems = LOCAL_ENUMS.goldDiscountTypes.items;
discountType = signal<number>(1);
unitWithQuantity = signal<number>(0);
totalAmountBeforeProfit = signal<number>(0);
baseTotalAmount = signal<number>(0);
@@ -105,6 +98,7 @@ export class SharedGoldPayloadFormComponent extends AbstractForm<
profit: [this.initialValues?.payload?.profit || 0, [Validators.required]],
profit_percentage: [0, [Validators.required, Validators.max(100), Validators.min(0)]],
karat: [this.initialValues?.payload?.karat || '', [Validators.required]],
discount_type: [this.initialValues?.payload?.discount_type || goldDiscountType.PROFIT],
}),
});
@@ -140,31 +134,21 @@ export class SharedGoldPayloadFormComponent extends AbstractForm<
karat: this.form.controls.payload.controls.karat.value as TGoldKarat,
profit: this.form.controls.payload.controls.profit.value || 0,
wages: this.form.controls.payload.controls.wages.value || 0,
discount_type:
this.form.controls.payload.controls.discount_type.value || goldDiscountType.PROFIT,
},
});
}
updateCalculateAmount(payload: Partial<IPosOrderItem<any>>) {
const commissionAmount = Number(payload.payload?.commission ?? '0');
const wageAmount = Number(payload.payload?.wages ?? '0');
const discountAmount = Number(payload.discount_amount ?? '0');
const profitAmount = Number(payload.payload?.profit ?? '0');
const unitPrice = Number(payload.unit_price ?? '0');
const quantity = Number(payload.quantity ?? '0');
const unitWithQuantity = unitPrice * quantity;
const totalAmountBeforeProfit = unitWithQuantity + wageAmount + commissionAmount;
const baseTotalAmount = totalAmountBeforeProfit + profitAmount;
const baseAmountForDiscountCalculation =
this.discountType() === 1 ? profitAmount : unitWithQuantity;
const taxAmount =
(profitAmount +
commissionAmount +
wageAmount -
(this.discountType() === 1 ? discountAmount : 0)) *
0.1;
const totalAmount = baseTotalAmount - discountAmount + taxAmount;
updateCalculateAmount(payload: Partial<IPosOrderItem<IGoldPayload>>) {
const {
unitWithQuantity,
totalAmountBeforeProfit,
baseTotalAmount,
taxAmount,
totalAmount,
baseAmountForDiscountCalculation,
} = goldAmountCalculationUtil(payload);
this.unitWithQuantity.set(unitWithQuantity);
this.totalAmountBeforeProfit.set(totalAmountBeforeProfit);
@@ -177,8 +161,7 @@ export class SharedGoldPayloadFormComponent extends AbstractForm<
}
changeDiscountCalculation($event: SelectButtonChangeEvent) {
this.discountType.set($event.value);
this.form.controls.payload.controls.discount_type.setValue($event.value);
this.updateCalculateAmount(this.form.value as any);
}
}
@@ -1,2 +1,3 @@
export * from './gold-amount-calculation.util';
export * from './gold-form.component';
export * from './standard-form.component';
@@ -0,0 +1,19 @@
import { ISelectItem } from '@/shared/abstractClasses';
export const goldDiscountType = {
PROFIT: 'PROFIT',
TOTAL: 'TOTAL',
} as const;
export type TGoldDiscountType = (typeof goldDiscountType)[keyof typeof goldDiscountType];
const translates: Record<TGoldDiscountType, string> = {
TOTAL: 'از کل',
PROFIT: 'از سود',
};
export const goldDiscountTypeSelect: ISelectItem[] = Object.keys(goldDiscountType).map((key) => ({
id: key,
name: translates[key as TGoldDiscountType],
}));
export const goldDiscountTypeLabel = 'نوع تخفیف';
@@ -1,3 +1,4 @@
import { goldDiscountTypeLabel, goldDiscountTypeSelect } from './goldDiscountType';
import { goldKaratLabel, goldKaratSelect } from './goldKarat';
import { licenseStatusLabel, licenseStatusSelect } from './licenseStatus';
@@ -11,4 +12,9 @@ export const LOCAL_ENUMS = {
label: licenseStatusLabel,
items: licenseStatusSelect,
},
goldDiscountTypes: {
label: goldDiscountTypeLabel,
items: goldDiscountTypeSelect,
},
};
@@ -1,6 +1,8 @@
import { TGoldKarat } from '@/shared/localEnum/constants/goldKarat';
import { TGoldDiscountType } from '../localEnum/constants/goldDiscountType';
export interface IGoldPayload {
discount_type: TGoldDiscountType;
karat: TGoldKarat;
wages: number;
profit: number;