Compare commits
10
Commits
5480398a93
...
d91dcf197b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d91dcf197b | ||
|
|
7bb5c2e00f | ||
|
|
2d74f53d0a | ||
|
|
fbe4f38e06 | ||
|
|
fbe7b98ada | ||
|
|
699657e483 | ||
|
|
4b7b2473fc | ||
|
|
1c850216e9 | ||
|
|
fb25b2251b | ||
|
|
5d386bf752 |
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<!--
|
||||
Legacy's city picker (henza_admin mixins/citiesModel.js): the cities as a
|
||||
tree — country > province > city > district — with the top level a heading
|
||||
that cannot be picked. A top-level row with nothing under it stays pickable,
|
||||
so a city entered without a parent is never unreachable.
|
||||
`parentPicker` is the «والد» field of the city form: every row is pickable
|
||||
there except the city being edited and its own descendants.
|
||||
-->
|
||||
<a-tree-select
|
||||
:value="value ?? undefined"
|
||||
:tree-data="treeData"
|
||||
show-search
|
||||
allow-clear
|
||||
tree-default-expand-all
|
||||
tree-node-filter-prop="title"
|
||||
:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
|
||||
:placeholder="placeholder ?? 'شهر را انتخاب کنید'"
|
||||
class="w-full"
|
||||
@update:value="onChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
|
||||
export interface CityRow {
|
||||
id: string;
|
||||
title: string;
|
||||
parent?: string | null;
|
||||
}
|
||||
|
||||
interface Node {
|
||||
value: string;
|
||||
key: string;
|
||||
title: string;
|
||||
disabled?: boolean;
|
||||
children?: Node[];
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
value?: string | null;
|
||||
cities: CityRow[];
|
||||
parentPicker?: boolean;
|
||||
/** parentPicker: the city being edited — it and its subtree are not offered. */
|
||||
excludeId?: string;
|
||||
placeholder?: string;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:value', v: string | undefined): void;
|
||||
(e: 'change', v: string | undefined): void;
|
||||
}>();
|
||||
|
||||
const treeData = computed<Node[]>(() => {
|
||||
const ids = new Set(props.cities.map((c) => c.id));
|
||||
const kids = new Map<string | null, CityRow[]>();
|
||||
for (const c of props.cities) {
|
||||
const p = c.parent && ids.has(c.parent) && c.parent !== c.id ? c.parent : null;
|
||||
if (!kids.has(p)) kids.set(p, []);
|
||||
kids.get(p)!.push(c);
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
const build = (parent: string | null, depth: number): Node[] =>
|
||||
(kids.get(parent) ?? [])
|
||||
.filter((c) => !seen.has(c.id) && !(props.parentPicker && c.id === props.excludeId))
|
||||
.map((c) => {
|
||||
seen.add(c.id);
|
||||
const children = build(c.id, depth + 1);
|
||||
const node: Node = { value: c.id, key: c.id, title: c.title };
|
||||
if (children.length) node.children = children;
|
||||
if (!props.parentPicker && depth === 0 && children.length) node.disabled = true;
|
||||
return node;
|
||||
});
|
||||
return build(null, 0);
|
||||
});
|
||||
|
||||
function onChange(v: string | undefined) {
|
||||
emit('update:value', v ?? undefined);
|
||||
emit('change', v ?? undefined);
|
||||
}
|
||||
</script>
|
||||
@@ -471,6 +471,14 @@ export const adminMenu: NavMenuNode[] = [
|
||||
i18n: 'اتصال حسابداری',
|
||||
permissionId:"config.accounting"
|
||||
},
|
||||
// MON-08 — the making-charge formula.
|
||||
{
|
||||
url: '/config/manage/wage',
|
||||
name: 'wage Formula',
|
||||
slug: 'manage-wage',
|
||||
i18n: 'اجرت',
|
||||
permissionId:"config.wage"
|
||||
},
|
||||
// Moved under "پیکر بندی" per request — same node shape as before
|
||||
// (own submenu / plain leaf), just relocated in the tree.
|
||||
{
|
||||
|
||||
@@ -122,6 +122,28 @@ export const adminRoute: RouteRecordRaw[] = [
|
||||
no_scroll: true
|
||||
}
|
||||
},
|
||||
// MON-08 — the making-charge formula (owner ruling 2026-10-08).
|
||||
{
|
||||
path: '/config/manage/wage',
|
||||
component: () => import('../views/manage/wage.vue'),
|
||||
meta: {
|
||||
breadcrumb: [
|
||||
{
|
||||
title: 'خانه',
|
||||
url: '/'
|
||||
},
|
||||
{
|
||||
title: 'اجرت',
|
||||
active: true
|
||||
}
|
||||
],
|
||||
pageTitle: 'اجرت',
|
||||
rule: 'editor',
|
||||
role: 'config.wage',
|
||||
parent: 'manage',
|
||||
no_scroll: true
|
||||
}
|
||||
},
|
||||
{
|
||||
path: '/config/manage/report',
|
||||
component: () => import('../views/manage/report.vue'),
|
||||
|
||||
@@ -72,13 +72,10 @@
|
||||
«شهر» also drives the commission autofill (ReagentCustomer.vue:111,215-228).
|
||||
-->
|
||||
<a-form-item label="شهر">
|
||||
<a-select
|
||||
<CityTreeSelect
|
||||
:value="form.city_id"
|
||||
show-search
|
||||
allow-clear
|
||||
option-filter-prop="label"
|
||||
:cities="cities"
|
||||
placeholder="شهر را انتخاب نمایید"
|
||||
:options="cities.map((c) => ({ value: c.id, label: c.title }))"
|
||||
@change="onCityChange"
|
||||
/>
|
||||
</a-form-item>
|
||||
@@ -117,6 +114,7 @@ import { onMounted, reactive, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { message } from 'ant-design-vue';
|
||||
import api from '../../../api/client';
|
||||
import CityTreeSelect from '../../../components/common/CityTreeSelect.vue';
|
||||
import ImageUploadInput from '../../../components/upload/ImageUploadInput.vue';
|
||||
|
||||
const route = useRoute();
|
||||
@@ -147,7 +145,7 @@ const form = reactive<Record<string, any>>({
|
||||
});
|
||||
|
||||
/** Cities for the «شهر» select and the commission autofill. */
|
||||
const cities = ref<Array<{ id: string; title: string; percent?: number | null }>>([]);
|
||||
const cities = ref<Array<{ id: string; title: string; parent?: string | null; percent?: number | null }>>([]);
|
||||
const err = reactive<Record<string, string>>({});
|
||||
|
||||
/** Snapshot of the server's record, captured after the edit form is populated. */
|
||||
@@ -180,7 +178,7 @@ function onAvatar(file: Record<string, unknown>) {
|
||||
* `if (!percent)`, so a city percent of 0 also falls through to the aux
|
||||
* lookup. Replicated rather than "fixed" (D4).
|
||||
*/
|
||||
async function onCityChange(value: string) {
|
||||
async function onCityChange(value: string | undefined) {
|
||||
form.city_id = value;
|
||||
if (!value) return;
|
||||
|
||||
@@ -246,6 +244,7 @@ onMounted(async () => {
|
||||
cities.value = (data.rows ?? []).map((c: any) => ({
|
||||
id: c.id,
|
||||
title: c.title ?? c.name,
|
||||
parent: c.parent ?? null,
|
||||
percent: c.percent === null || c.percent === undefined ? null : Number(c.percent),
|
||||
}));
|
||||
} catch (e) {
|
||||
|
||||
@@ -10,8 +10,9 @@
|
||||
render this component directly as a route-based fallback, but OmdeList.vue
|
||||
now opens it as a modal via open/id props.
|
||||
|
||||
Dropped: the MyUpload avatar widget and the Jalali DateInput, which belong to
|
||||
fields the redesigned Customer schema has no column for. Flagged in
|
||||
«تاریخ تولد» (legacy's Jalali DateInput, birth_date) is back since the
|
||||
Customer schema has birthDate (PERS-03). Dropped: the MyUpload avatar widget,
|
||||
which belongs to a field the redesigned Customer schema has no column for. Flagged in
|
||||
docs/ADMIN-PORT-PLAN.md rather than faked.
|
||||
|
||||
The نوع کاربری selector is live again now that Customer.type exists; its four
|
||||
@@ -79,6 +80,11 @@
|
||||
<a-form-item label="کد مشتری">
|
||||
<a-input v-model:value="form.mcode" />
|
||||
</a-form-item>
|
||||
<DateInput
|
||||
:model-value="form.birth_date || undefined"
|
||||
label="تاریخ تولد"
|
||||
@update:model-value="(v) => (form.birth_date = v ?? '')"
|
||||
/>
|
||||
<a-form-item label="کارشناس فروش">
|
||||
<a-select v-model:value="form.reagent_id" allow-clear placeholder="انتخاب کنید">
|
||||
<a-select-option v-for="r in reagent" :key="r.id" :value="r.id">
|
||||
@@ -98,17 +104,7 @@
|
||||
<a-card title="اطلاعات تکمیلی" class="mb-base">
|
||||
<div class="grid-2">
|
||||
<a-form-item label="شهر">
|
||||
<a-select
|
||||
v-model:value="form.city_id"
|
||||
show-search
|
||||
allow-clear
|
||||
placeholder="انتخاب کنید"
|
||||
:filter-option="filterCity"
|
||||
>
|
||||
<a-select-option v-for="c in cities" :key="c.id" :value="c.id">
|
||||
{{ c.title }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
<CityTreeSelect v-model:value="form.city_id" :cities="cities" @change="onCityChange" />
|
||||
</a-form-item>
|
||||
<a-form-item label="آدرس">
|
||||
<a-textarea v-model:value="form.address" :auto-size="{ minRows: 2, maxRows: 4 }" />
|
||||
@@ -192,6 +188,11 @@
|
||||
<a-form-item label="کد مشتری">
|
||||
<a-input v-model:value="form.mcode" />
|
||||
</a-form-item>
|
||||
<DateInput
|
||||
:model-value="form.birth_date || undefined"
|
||||
label="تاریخ تولد"
|
||||
@update:model-value="(v) => (form.birth_date = v ?? '')"
|
||||
/>
|
||||
<a-form-item label="کارشناس فروش">
|
||||
<a-select v-model:value="form.reagent_id" allow-clear placeholder="انتخاب کنید">
|
||||
<a-select-option v-for="r in reagent" :key="r.id" :value="r.id">
|
||||
@@ -211,17 +212,7 @@
|
||||
<a-card title="اطلاعات تکمیلی" class="mb-base">
|
||||
<div class="grid-2">
|
||||
<a-form-item label="شهر">
|
||||
<a-select
|
||||
v-model:value="form.city_id"
|
||||
show-search
|
||||
allow-clear
|
||||
placeholder="انتخاب کنید"
|
||||
:filter-option="filterCity"
|
||||
>
|
||||
<a-select-option v-for="c in cities" :key="c.id" :value="c.id">
|
||||
{{ c.title }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
<CityTreeSelect v-model:value="form.city_id" :cities="cities" @change="onCityChange" />
|
||||
</a-form-item>
|
||||
<a-form-item label="آدرس">
|
||||
<a-textarea v-model:value="form.address" :auto-size="{ minRows: 2, maxRows: 4 }" />
|
||||
@@ -269,6 +260,8 @@ import { message } from 'ant-design-vue';
|
||||
import BaseFormModal from '../../../components/common/BaseFormModal.vue';
|
||||
import ImageUploadInput from '../../../components/upload/ImageUploadInput.vue';
|
||||
import api from '../../../api/client';
|
||||
import CityTreeSelect from '../../../components/common/CityTreeSelect.vue';
|
||||
import DateInput from '../../../components/input/DateInput.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open?: boolean;
|
||||
@@ -299,7 +292,7 @@ const router = useRouter();
|
||||
|
||||
const id = asModal ? props.id : (route.params.id as string | undefined);
|
||||
const loading = ref(false);
|
||||
const cities = ref<{ id: string; title: string }[]>([]);
|
||||
const cities = ref<{ id: string; title: string; parent?: string | null; percent?: unknown }[]>([]);
|
||||
const reagent = ref<{ id: string; name: string }[]>([]);
|
||||
|
||||
const form = reactive<Record<string, any>>({
|
||||
@@ -313,6 +306,7 @@ const form = reactive<Record<string, any>>({
|
||||
pasazh_name: '',
|
||||
city_id: undefined,
|
||||
mcode: '',
|
||||
birth_date: '',
|
||||
address: '',
|
||||
// legacy defaulted to no selection; 2 (مغازه دار اپلیکیشن) is what the
|
||||
// backend falls back to when the field is absent.
|
||||
@@ -369,8 +363,24 @@ function diffFromInitial(): Record<string, any> {
|
||||
return out;
|
||||
}
|
||||
|
||||
function filterCity(input: string, option: any) {
|
||||
return String(option?.children?.[0]?.children ?? '').includes(input);
|
||||
/**
|
||||
* Legacy getPercent (henza_admin bulkCustomer.vue:260-272): picking a city fills
|
||||
* «درصد» with the city's own percent, else its commission percent — which, as
|
||||
* legacy's _getP, a city without one takes from its parent.
|
||||
*/
|
||||
async function onCityChange(value: string | undefined) {
|
||||
if (!value) return;
|
||||
let percent: unknown = cities.value.find((c) => c.id === value)?.percent;
|
||||
if (!Number(percent)) {
|
||||
try {
|
||||
const { data } = await api.get(`cities/get-percent-aux/${value}`);
|
||||
percent = data;
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
form.percent = percent === null || percent === undefined ? undefined : Number(percent);
|
||||
}
|
||||
|
||||
function validate(): boolean {
|
||||
@@ -468,6 +478,7 @@ onMounted(async () => {
|
||||
store_name: data.store_name ?? '',
|
||||
pasazh_name: data.pasazh_name ?? '',
|
||||
mcode: data.mcode ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
type: data.type ?? undefined,
|
||||
// Same reason as the five above: omitted here, they would be sent back
|
||||
|
||||
@@ -32,18 +32,13 @@
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item label="شهر">
|
||||
<a-select
|
||||
v-model:value="form.city_id"
|
||||
show-search
|
||||
allow-clear
|
||||
placeholder="انتخاب کنید"
|
||||
:filter-option="filterOption"
|
||||
>
|
||||
<a-select-option v-for="c in cities" :key="c.id" :value="c.id">
|
||||
{{ c.title }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
<CityTreeSelect v-model:value="form.city_id" :cities="cities" />
|
||||
</a-form-item>
|
||||
<DateInput
|
||||
:model-value="form.birth_day || undefined"
|
||||
label="تاریخ تولد"
|
||||
@update:model-value="(v) => (form.birth_day = v ?? '')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<a-button type="primary" @click="handleSubmit">ثبت اطلاعات</a-button>
|
||||
@@ -57,27 +52,26 @@ import { onMounted, reactive, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { message } from 'ant-design-vue';
|
||||
import api from '../../../api/client';
|
||||
import CityTreeSelect from '../../../components/common/CityTreeSelect.vue';
|
||||
import DateInput from '../../../components/input/DateInput.vue';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const id = route.params.id as string | undefined;
|
||||
const loading = ref(false);
|
||||
const cities = ref<{ id: string; title: string }[]>([]);
|
||||
const cities = ref<{ id: string; title: string; parent?: string | null }[]>([]);
|
||||
|
||||
const form = reactive<Record<string, any>>({
|
||||
fname: '',
|
||||
lname: '',
|
||||
phone: '',
|
||||
city_id: undefined,
|
||||
birth_day: '',
|
||||
});
|
||||
const err = reactive<Record<string, string>>({});
|
||||
const REQUIRED = 'لطفا مقدار را وارد کنید';
|
||||
|
||||
function filterOption(input: string, option: any) {
|
||||
return String(option?.children?.[0]?.children ?? '').includes(input);
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
Object.keys(err).forEach((k) => delete err[k]);
|
||||
if (!form.fname) err.fname = REQUIRED;
|
||||
@@ -128,6 +122,7 @@ onMounted(async () => {
|
||||
lname: data.lname ?? '',
|
||||
phone: data.mobile ?? '',
|
||||
city_id: data.city_id ?? undefined,
|
||||
birth_day: data.birth_day ?? '',
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// Ported from legacy henza_admin/src/views/city/CityListModel.js
|
||||
//
|
||||
// Note the 'level' column: legacy declares it but the cities payload has no such
|
||||
// field, so the cell always rendered blank. Preserved — see the port plan.
|
||||
// Legacy's 'level' column always rendered blank (the payload had no such
|
||||
// field); it is the parent city here, now that cities are a tree (PERS-02).
|
||||
import XTbl, { Xtc } from '../../components/x-table/model';
|
||||
|
||||
export function buildCityListModel(): XTbl {
|
||||
const tbl = new XTbl('admin/misc/cities/list', 'لیست شهر ها');
|
||||
tbl.add(new Xtc('title', 'نام شهر').filterKey('name').filterText());
|
||||
tbl.add(new Xtc('level', 'سطح').filterNumber().noSort());
|
||||
tbl.add(new Xtc('parent_title', 'والد').renderSlot('parent_title').noSort());
|
||||
tbl.add(new Xtc('percent', 'درصد مشتری عمده').renderSlot('percent').noSort());
|
||||
tbl.add(new Xtc('percent_aux', 'درصد کارشناس فروش').renderSlot('percent_aux').noSort());
|
||||
tbl.add(new Xtc('opt', 'عملیات').noSort().renderSlot('opt'));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<template>
|
||||
<!--
|
||||
Ported from legacy henza_admin/src/views/city/cityList.vue.
|
||||
The two percent columns are edited in a modal that legacy loads through two
|
||||
separate GETs (get-percent / get-percent-aux) before opening.
|
||||
The edit modal shows the city's OWN percents. Legacy filled it from
|
||||
get-percent / get-percent-aux, which return the parent's percent when the
|
||||
city has none — so saving silently copied the parent's onto the child.
|
||||
-->
|
||||
<div id="page-user-list">
|
||||
<a-card title="لیست شهر ها">
|
||||
@@ -11,6 +12,10 @@
|
||||
<ListPageHeader rid="cities.create" add-label="افزودن شهر" @add="addOpen = true" />
|
||||
</template>
|
||||
|
||||
<template #parent_title="{ text }">
|
||||
{{ text ?? '—' }}
|
||||
</template>
|
||||
|
||||
<template #percent="{ text }">
|
||||
{{ text ?? '-' }}
|
||||
</template>
|
||||
@@ -43,6 +48,15 @@
|
||||
<a-form-item label="نام شهر">
|
||||
<a-input v-model:value="form.title" />
|
||||
</a-form-item>
|
||||
<a-form-item label="والد" help="خالی = سرشاخه، مثل کشور">
|
||||
<CityTreeSelect
|
||||
v-model:value="form.parent"
|
||||
:cities="cities"
|
||||
parent-picker
|
||||
:exclude-id="tempRow?.id"
|
||||
placeholder="والد را انتخاب کنید"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="درصد مشتری عمده">
|
||||
<a-input-number v-model:value="form.percent" class="w-full" :step="0.1" />
|
||||
</a-form-item>
|
||||
@@ -68,6 +82,7 @@ import { buildCityListModel } from './CityListModel';
|
||||
import { useUsersStore } from '../../stores/users';
|
||||
import { useDeleteHandler } from '../../composables/useDeleteHandler';
|
||||
import api from '../../api/client';
|
||||
import CityTreeSelect from '../../components/common/CityTreeSelect.vue';
|
||||
|
||||
const users = useUsersStore();
|
||||
const hasPermission = (rid: string) => Boolean(users.hasPermission(rid));
|
||||
@@ -77,26 +92,20 @@ const citiesTable = ref<{ fetch: () => Promise<void> } | null>(null);
|
||||
const addOpen = ref(false);
|
||||
const visible = ref(false);
|
||||
const tempRow = ref<Record<string, any> | undefined>(undefined);
|
||||
const form = reactive<Record<string, any>>({ title: '', percent: null, percent_aux: null });
|
||||
const form = reactive<Record<string, any>>({ title: '', parent: undefined, percent: null, percent_aux: null });
|
||||
const cities = ref<{ id: string; title: string; parent?: string | null }[]>([]);
|
||||
|
||||
/**
|
||||
* legacy edit(): fetches the two percents separately before opening the modal.
|
||||
* Both are already on the row here, but the legacy calls are kept so the two
|
||||
* endpoints stay exercised and the values are always current.
|
||||
*/
|
||||
async function edit(row: Record<string, any>) {
|
||||
tempRow.value = row;
|
||||
form.title = row.title ?? '';
|
||||
form.parent = row.parent ?? undefined;
|
||||
form.percent = row.percent === null || row.percent === undefined ? null : Number(row.percent);
|
||||
form.percent_aux = row.percent_aux === null || row.percent_aux === undefined ? null : Number(row.percent_aux);
|
||||
try {
|
||||
const [p, pa] = await Promise.all([
|
||||
api.get(`cities/get-percent/${row.id}`),
|
||||
api.get(`cities/get-percent-aux/${row.id}`),
|
||||
]);
|
||||
form.percent = p.data === null ? null : Number(p.data);
|
||||
form.percent_aux = pa.data === null ? null : Number(pa.data);
|
||||
const { data } = await api.post('cities/list');
|
||||
cities.value = data.rows ?? [];
|
||||
} catch (e) {
|
||||
form.percent = row.percent === null ? null : Number(row.percent);
|
||||
form.percent_aux = row.percent_aux === null ? null : Number(row.percent_aux);
|
||||
console.log(e);
|
||||
}
|
||||
visible.value = true;
|
||||
}
|
||||
@@ -105,6 +114,7 @@ async function save() {
|
||||
try {
|
||||
await api.put(`cities/${tempRow.value?.id}`, {
|
||||
title: form.title,
|
||||
parent: form.parent ?? null,
|
||||
percent: form.percent,
|
||||
percent_aux: form.percent_aux,
|
||||
});
|
||||
|
||||
@@ -22,8 +22,14 @@
|
||||
<a-form-item label="نام شهر" :validate-status="err.title ? 'error' : ''" :help="err.title">
|
||||
<a-input v-model:value="form.title" />
|
||||
</a-form-item>
|
||||
<a-form-item label="استان">
|
||||
<a-input v-model:value="form.province" />
|
||||
<a-form-item label="والد" help="خالی = سرشاخه، مثل کشور">
|
||||
<CityTreeSelect v-model:value="form.parent" :cities="cities" parent-picker placeholder="والد را انتخاب کنید" />
|
||||
</a-form-item>
|
||||
<a-form-item label="درصد مشتری عمده">
|
||||
<a-input-number v-model:value="form.percent" class="w-full" :min="0" :max="100" :step="0.1" />
|
||||
</a-form-item>
|
||||
<a-form-item label="درصد کارشناس فروش">
|
||||
<a-input-number v-model:value="form.percent_aux" class="w-full" :min="0" :max="100" :step="0.1" />
|
||||
</a-form-item>
|
||||
</div>
|
||||
</BaseFormModal>
|
||||
@@ -36,8 +42,14 @@
|
||||
<a-form-item label="نام شهر" :validate-status="err.title ? 'error' : ''" :help="err.title">
|
||||
<a-input v-model:value="form.title" />
|
||||
</a-form-item>
|
||||
<a-form-item label="استان">
|
||||
<a-input v-model:value="form.province" />
|
||||
<a-form-item label="والد" help="خالی = سرشاخه، مثل کشور">
|
||||
<CityTreeSelect v-model:value="form.parent" :cities="cities" parent-picker placeholder="والد را انتخاب کنید" />
|
||||
</a-form-item>
|
||||
<a-form-item label="درصد مشتری عمده">
|
||||
<a-input-number v-model:value="form.percent" class="w-full" :min="0" :max="100" :step="0.1" />
|
||||
</a-form-item>
|
||||
<a-form-item label="درصد کارشناس فروش">
|
||||
<a-input-number v-model:value="form.percent_aux" class="w-full" :min="0" :max="100" :step="0.1" />
|
||||
</a-form-item>
|
||||
</div>
|
||||
<a-button type="primary" @click="handleSubmit">ثبت اطلاعات</a-button>
|
||||
@@ -47,11 +59,12 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue';
|
||||
import { onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { message } from 'ant-design-vue';
|
||||
import BaseFormModal from '../../components/common/BaseFormModal.vue';
|
||||
import api from '../../api/client';
|
||||
import CityTreeSelect from '../../components/common/CityTreeSelect.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
/** Present -> rendered as a modal by the parent list page. */
|
||||
@@ -71,7 +84,20 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const loading = ref(false);
|
||||
const form = reactive<Record<string, any>>({ title: '', province: '' });
|
||||
const form = reactive<Record<string, any>>({ title: '', parent: undefined, percent: null, percent_aux: null });
|
||||
const cities = ref<{ id: string; title: string; parent?: string | null }[]>([]);
|
||||
|
||||
async function loadCities() {
|
||||
try {
|
||||
const { data } = await api.post('cities/list');
|
||||
cities.value = data.rows ?? [];
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
// Fresh each time the modal opens, so a city added a moment ago can be a parent.
|
||||
if (asModal) watch(() => props.open, (o) => o && loadCities(), { immediate: true });
|
||||
else onMounted(loadCities);
|
||||
const err = reactive<Record<string, string>>({});
|
||||
|
||||
async function handleSubmit() {
|
||||
@@ -82,9 +108,11 @@ async function handleSubmit() {
|
||||
}
|
||||
try {
|
||||
loading.value = true;
|
||||
await api.post('cities', form);
|
||||
await api.post('cities', { ...form, parent: form.parent ?? null });
|
||||
message.info('اطلاعات با موفقیت به ثبت رسید.');
|
||||
if (asModal) {
|
||||
// Keep the parent: cities are usually added several under the same one.
|
||||
Object.assign(form, { title: '', percent: null, percent_aux: null });
|
||||
emit('success');
|
||||
emit('update:open', false);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
<template>
|
||||
<!--
|
||||
«اجرت» — the making-charge formula every app order is priced with
|
||||
(owner ruling 2026-10-08, MON-08). The server computes everything shown
|
||||
here (POST admin/pricing/wage-formula/preview), so the sample is exactly
|
||||
what an order would be charged — this page never does the arithmetic.
|
||||
|
||||
Flow: change the formula → the sample shows the formula in force and the
|
||||
draft side by side → the admin confirms the sample is right → «تأیید و
|
||||
ثبت». The approved sample is kept with the formula as its reference.
|
||||
-->
|
||||
<div v-if="hasPermission('config.wage')" class="wage">
|
||||
<a-spin :spinning="loading">
|
||||
<!-- ── status ─────────────────────────────────────────── -->
|
||||
<a-card class="mb-4" :bordered="false">
|
||||
<div class="status">
|
||||
<div>
|
||||
<div class="status__title">فرمول اجرت سفارشهای اپلیکیشن</div>
|
||||
<div class="hint">
|
||||
اجرتی که مشتری در اپ میبیند و اجرتی که روی فاکتور میآید، هر دو با همین فرمول در سرور حساب میشوند.
|
||||
اجرتی که اپراتور در پنل برای یک سفارش دستی وارد میکند، دست نمیخورد.
|
||||
</div>
|
||||
</div>
|
||||
<a-tag v-if="config?.isLegacyDefault" color="blue">فرمول سیستم قدیم (پیشفرض)</a-tag>
|
||||
<a-tag v-else-if="config" color="green">
|
||||
تأییدشده در {{ jdate(config.approvedAt) }} — {{ config.approvedBy?.name }}
|
||||
</a-tag>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-row :gutter="[16, 16]">
|
||||
<!-- ── the formula ──────────────────────────────────── -->
|
||||
<a-col :xs="24" :xl="12">
|
||||
<a-card title="ساختار فرمول">
|
||||
<template #extra>
|
||||
<a-button size="small" :disabled="isLegacy(draft)" @click="resetToLegacy">بازگشت به فرمول سیستم قدیم</a-button>
|
||||
</template>
|
||||
|
||||
<div class="formula" aria-live="polite">
|
||||
<span class="formula__lhs">اجرت نهایی =</span>
|
||||
<template v-for="(t, i) in formulaTerms" :key="t.key">
|
||||
<span v-if="i > 0 || t.sign === '−'" class="formula__op">{{ t.sign }}</span>
|
||||
<span class="chip" :class="`chip--${t.key}`">{{ t.text }}</span>
|
||||
</template>
|
||||
<span v-if="!formulaTerms.length" class="chip chip--zero">۰</span>
|
||||
<div v-if="limitsText" class="formula__limits">{{ limitsText }}</div>
|
||||
</div>
|
||||
|
||||
<div class="term" v-for="t in termRows" :key="t.key">
|
||||
<div class="term__head">
|
||||
<a-switch v-model:checked="t.enabled.value" size="small" />
|
||||
<span class="term__label">{{ t.label }}</span>
|
||||
<span class="chip chip--sm" :class="`chip--${t.key}`">{{ t.sign }}</span>
|
||||
</div>
|
||||
<div class="hint">{{ t.help }}</div>
|
||||
<div v-if="t.enabled.value" class="term__body">
|
||||
<span>ضریب</span>
|
||||
<a-input-number v-model:value="t.coef.value" :step="0.1" :min="-10" :max="10" class="num" />
|
||||
<template v-if="t.key === 'promotion'">
|
||||
<a-radio-group v-model:value="draft.promotionPick" size="small" button-style="solid">
|
||||
<a-radio-button value="max">بیشترین تخفیف</a-radio-button>
|
||||
<a-radio-button value="sum">جمع تخفیفها</a-radio-button>
|
||||
</a-radio-group>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="term">
|
||||
<div class="term__head">
|
||||
<span class="term__label">مقدار ثابت (درصد)</span>
|
||||
<span class="chip chip--sm chip--constant">±</span>
|
||||
</div>
|
||||
<div class="hint">به همهی اجرتها اضافه میشود؛ عدد منفی کم میکند. صفر یعنی بیاثر.</div>
|
||||
<div class="term__body">
|
||||
<a-input-number v-model:value="constantNum" :step="0.1" :min="-100" :max="100" class="num" addon-after="٪" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a-divider orientation="right" class="divider">محدودیت و گرد کردن</a-divider>
|
||||
<div class="limits">
|
||||
<div class="limit">
|
||||
<a-checkbox v-model:checked="minOn">حداقل اجرت</a-checkbox>
|
||||
<a-input-number v-model:value="minNum" :disabled="!minOn" :step="0.5" class="num" addon-after="٪" />
|
||||
</div>
|
||||
<div class="limit">
|
||||
<a-checkbox v-model:checked="maxOn">حداکثر اجرت</a-checkbox>
|
||||
<a-input-number v-model:value="maxNum" :disabled="!maxOn" :step="0.5" class="num" addon-after="٪" />
|
||||
</div>
|
||||
<div class="limit">
|
||||
<a-checkbox v-model:checked="roundOn">گرد کردن</a-checkbox>
|
||||
<a-input-number v-model:value="decimalsNum" :disabled="!roundOn" :min="0" :max="4" :precision="0" class="num" addon-after="رقم اعشار" />
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
</a-col>
|
||||
|
||||
<!-- ── the sample ───────────────────────────────────── -->
|
||||
<a-col :xs="24" :xl="12">
|
||||
<a-card title="نمونه — نتیجه را قبل از ثبت ببینید">
|
||||
<template #extra>
|
||||
<a-button size="small" type="link" :disabled="!config" @click="loadSavedSample">نمونهی ثبتشده</a-button>
|
||||
</template>
|
||||
|
||||
<div class="sample">
|
||||
<label>وزن خام<a-input-number v-model:value="sample.rashWeightGrams" :min="0" :step="0.1" class="num" addon-after="گرم" /></label>
|
||||
<label>تعداد<a-input-number v-model:value="sample.quantity" :min="1" :max="1000" :precision="0" class="num" /></label>
|
||||
<label>اجرت مدل<a-input-number v-model:value="sample.variantPercent" :step="0.5" class="num" addon-after="٪" /></label>
|
||||
<label>درصد مشتری<a-input-number v-model:value="sample.customerPercent" :step="0.5" class="num" addon-after="٪" /></label>
|
||||
<label>تخفیف فعال<a-input-number v-model:value="sample.promotionPercent" :min="0" :max="100" :step="0.5" class="num" addon-after="٪" /></label>
|
||||
</div>
|
||||
|
||||
<a-alert v-if="previewError" type="error" show-icon class="mb-4" :message="previewError" />
|
||||
|
||||
<table class="cmp" v-if="preview">
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>فرمول فعلی</th>
|
||||
<th :class="{ changed: dirty }">{{ dirty ? 'پیشنویس شما' : 'پیشنویس (بدون تغییر)' }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="r in cmpRows" :key="r.key" :class="{ strong: r.strong }">
|
||||
<td>{{ r.label }}</td>
|
||||
<td>{{ r.fmt(preview.current) }}</td>
|
||||
<td :class="{ diff: r.fmt(preview.current) !== r.fmt(preview.draft) }">{{ r.fmt(preview.draft) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-if="preview?.draft.limitedBy" class="hint warn">
|
||||
در پیشنویس، {{ preview.draft.limitedBy === 'min' ? 'حداقل' : 'حداکثر' }} اجرت روی نتیجه اثر گذاشت.
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<!-- ── approve ──────────────────────────────────────── -->
|
||||
<a-card class="mt-4" title="تأیید و ثبت">
|
||||
<a-alert
|
||||
v-if="!dirty"
|
||||
type="info"
|
||||
show-icon
|
||||
message="تغییری نسبت به فرمول فعلی ندادهاید."
|
||||
class="mb-4"
|
||||
/>
|
||||
<template v-else>
|
||||
<a-alert
|
||||
type="warning"
|
||||
show-icon
|
||||
class="mb-4"
|
||||
message="تا «تأیید و ثبت» نزنید هیچ چیزی عوض نمیشود."
|
||||
description="بعد از ثبت، همهی سفارشهای جدید اپ و اجرتی که اپ نشان میدهد با فرمول جدید حساب میشوند. سفارشهای ثبتشدهی قبلی تغییری نمیکنند."
|
||||
/>
|
||||
<a-checkbox v-model:checked="sampleChecked" class="mb-4">
|
||||
نتیجهی نمونه را بررسی کردم و درست است.
|
||||
</a-checkbox>
|
||||
<div>
|
||||
<a-popconfirm
|
||||
title="فرمول جدید از همین حالا برای سفارشهای اپ اعمال شود؟"
|
||||
ok-text="بله، ثبت شود"
|
||||
cancel-text="انصراف"
|
||||
:disabled="!canApprove"
|
||||
@confirm="approve"
|
||||
>
|
||||
<a-button type="primary" :disabled="!canApprove" :loading="saving">تأیید و ثبت فرمول</a-button>
|
||||
</a-popconfirm>
|
||||
<a-button class="ms" @click="discard">لغو تغییرات</a-button>
|
||||
</div>
|
||||
</template>
|
||||
</a-card>
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<!-- ── the approved reference sample + history ─────────── -->
|
||||
<a-card class="mt-4" title="نمونهی مرجعِ فرمول فعلی" v-if="config">
|
||||
<div class="hint mb-4">
|
||||
این نمونه همراه فرمول فعلی ثبت شده است؛ هر کس فرمول را ببیند میداند با چه عددی بررسی و تأیید شده.
|
||||
</div>
|
||||
<a-descriptions size="small" bordered :column="{ xs: 1, md: 3 }">
|
||||
<a-descriptions-item label="فرمول">{{ formulaText(config.formula) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="نمونه">{{ sampleText(config.sample) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="نتیجه">
|
||||
اجرت {{ pct(config.result.finalPercent) }} — {{ g(config.result.wageGrams) }} اجرت، {{ g(config.result.totalGrams) }} وزن کل
|
||||
</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
|
||||
<a-collapse v-if="config.history.length" ghost class="mt-4">
|
||||
<a-collapse-panel key="h" :header="`نسخههای قبلی (${config.history.length})`">
|
||||
<div v-for="(h, i) in config.history" :key="i" class="hist">
|
||||
<div class="hist__meta">{{ jdate(h.approvedAt) }} — {{ h.approvedBy?.name }}</div>
|
||||
<div>{{ formulaText(h.formula) }}</div>
|
||||
<div class="hint">{{ sampleText(h.sample) }} ← اجرت {{ pct(h.result.finalPercent) }}، وزن کل {{ g(h.result.totalGrams) }}</div>
|
||||
</div>
|
||||
</a-collapse-panel>
|
||||
</a-collapse>
|
||||
</a-card>
|
||||
</a-spin>
|
||||
</div>
|
||||
<a-result v-else status="403" title="دسترسی ندارید" sub-title="این صفحه دسترسی «اجرت» میخواهد." />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { message } from 'ant-design-vue';
|
||||
import moment from 'moment-jalaali';
|
||||
import { useUsersStore } from '../../stores/users';
|
||||
import api from '../../api/client';
|
||||
|
||||
type Pick = 'max' | 'sum';
|
||||
interface Formula {
|
||||
version: 1;
|
||||
variantCoef: string;
|
||||
customerCoef: string;
|
||||
promotionCoef: string;
|
||||
promotionPick: Pick;
|
||||
constant: string;
|
||||
min: string | null;
|
||||
max: string | null;
|
||||
decimals: number | null;
|
||||
}
|
||||
interface Sample {
|
||||
rashWeightGrams: number;
|
||||
quantity: number;
|
||||
variantPercent: number;
|
||||
customerPercent: number;
|
||||
promotionPercent: number;
|
||||
}
|
||||
interface Result {
|
||||
variantTerm: string;
|
||||
customerTerm: string;
|
||||
promotionPercent: string;
|
||||
promotionTerm: string;
|
||||
constant: string;
|
||||
beforeLimits: string;
|
||||
limitedBy: 'min' | 'max' | null;
|
||||
finalPercent: string;
|
||||
wageGrams: string;
|
||||
totalGrams: string;
|
||||
rashTotalGrams: string;
|
||||
}
|
||||
interface Approval { formula: Formula; sample: Sample; approvedAt: string; approvedBy: { id: string; name: string }; result: Result }
|
||||
interface Config extends Approval {
|
||||
approvedAt: string;
|
||||
isLegacyDefault: boolean;
|
||||
legacy: Formula;
|
||||
history: Approval[];
|
||||
}
|
||||
|
||||
const users = useUsersStore();
|
||||
const hasPermission = (rid: string) => Boolean(users.hasPermission(rid));
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const config = ref<Config | null>(null);
|
||||
const draft = reactive<Formula>({
|
||||
version: 1, variantCoef: '1', customerCoef: '1', promotionCoef: '1', promotionPick: 'max', constant: '0', min: null, max: null, decimals: null,
|
||||
});
|
||||
const sample = reactive<Sample>({ rashWeightGrams: 10, quantity: 1, variantPercent: 7, customerPercent: 3, promotionPercent: 0 });
|
||||
const preview = ref<{ current: Result; draft: Result } | null>(null);
|
||||
const previewError = ref('');
|
||||
const sampleChecked = ref(false);
|
||||
|
||||
const errMsg = (e: any, fallback: string) => {
|
||||
const m = e?.response?.data?.message;
|
||||
return Array.isArray(m) ? m.join('، ') : (m ?? fallback);
|
||||
};
|
||||
|
||||
/* ───────── numbers ⇄ the string-valued formula ───────── */
|
||||
|
||||
const n = (s: string | null) => (s === null ? null : Number(s));
|
||||
const s = (v: number | null | undefined) => (v === null || v === undefined || Number.isNaN(v) ? '0' : String(v));
|
||||
|
||||
// Each term remembers its coefficient while switched off, so turning it back
|
||||
// on restores the number instead of resetting it to 1.
|
||||
const remembered = reactive({ variant: 1, customer: 1, promotion: 1 });
|
||||
function termModel(key: 'variant' | 'customer' | 'promotion') {
|
||||
const field = `${key}Coef` as const;
|
||||
const enabled = computed({
|
||||
get: () => Number(draft[field]) !== 0,
|
||||
set: (on: boolean) => {
|
||||
if (!on) remembered[key] = Number(draft[field]) || 1;
|
||||
draft[field] = on ? String(remembered[key] || 1) : '0';
|
||||
},
|
||||
});
|
||||
const coef = computed({
|
||||
get: () => Number(draft[field]),
|
||||
set: (v: number | null) => (draft[field] = s(v)),
|
||||
});
|
||||
return { enabled, coef };
|
||||
}
|
||||
const termRows = [
|
||||
{ key: 'variant', label: 'اجرت مدل', sign: '+', help: 'اجرتی که روی هر مدل (واریانت) کالا ثبت شده است.', ...termModel('variant') },
|
||||
{ key: 'customer', label: 'درصد اختصاصی مشتری', sign: '+', help: 'درصدی که روی پروندهی هر مشتری ثبت شده (معمولاً ۳).', ...termModel('customer') },
|
||||
{ key: 'promotion', label: 'تخفیف فعال', sign: '−', help: 'تخفیفهای فعالِ مربوط به همان کالا، دستهبندی یا برند. سیستم قدیم فقط بیشترین را کم میکرد.', ...termModel('promotion') },
|
||||
] as const;
|
||||
|
||||
const constantNum = computed({ get: () => Number(draft.constant), set: (v: number | null) => (draft.constant = s(v)) });
|
||||
const minOn = computed({ get: () => draft.min !== null, set: (on: boolean) => (draft.min = on ? draft.min ?? '0' : null) });
|
||||
const maxOn = computed({ get: () => draft.max !== null, set: (on: boolean) => (draft.max = on ? draft.max ?? '20' : null) });
|
||||
const roundOn = computed({ get: () => draft.decimals !== null, set: (on: boolean) => (draft.decimals = on ? draft.decimals ?? 2 : null) });
|
||||
const minNum = computed({ get: () => n(draft.min), set: (v: number | null) => (draft.min = s(v)) });
|
||||
const maxNum = computed({ get: () => n(draft.max), set: (v: number | null) => (draft.max = s(v)) });
|
||||
const decimalsNum = computed({ get: () => draft.decimals, set: (v: number | null) => (draft.decimals = v ?? 0) });
|
||||
|
||||
/* ───────── readable formula ───────── */
|
||||
|
||||
const fa = (v: string | number) => String(v).replace(/\d/g, (d) => '۰۱۲۳۴۵۶۷۸۹'[Number(d)]).replace('.', '٫');
|
||||
const coefText = (c: string) => (Number(c) === 1 ? '' : `${fa(c)} × `);
|
||||
|
||||
function termsOf(f: Formula) {
|
||||
const out: { key: string; sign: '+' | '−'; text: string }[] = [];
|
||||
if (Number(f.variantCoef)) out.push({ key: 'variant', sign: '+', text: `${coefText(f.variantCoef)}اجرت مدل` });
|
||||
if (Number(f.customerCoef)) out.push({ key: 'customer', sign: '+', text: `${coefText(f.customerCoef)}درصد مشتری` });
|
||||
if (Number(f.promotionCoef))
|
||||
out.push({ key: 'promotion', sign: '−', text: `${coefText(f.promotionCoef)}${f.promotionPick === 'max' ? 'بیشترین تخفیف' : 'جمع تخفیفها'}` });
|
||||
if (Number(f.constant)) out.push({ key: 'constant', sign: Number(f.constant) < 0 ? '−' : '+', text: `${fa(Math.abs(Number(f.constant)))}٪` });
|
||||
return out;
|
||||
}
|
||||
const formulaTerms = computed(() => termsOf(draft));
|
||||
function limitsOf(f: Formula) {
|
||||
const parts: string[] = [];
|
||||
if (f.min !== null) parts.push(`حداقل ${fa(f.min)}٪`);
|
||||
if (f.max !== null) parts.push(`حداکثر ${fa(f.max)}٪`);
|
||||
if (f.decimals !== null) parts.push(`گرد تا ${fa(f.decimals)} رقم اعشار`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
const limitsText = computed(() => limitsOf(draft));
|
||||
function formulaText(f: Formula) {
|
||||
const t = termsOf(f);
|
||||
const body = t.map((x, i) => `${i > 0 || x.sign === '−' ? ` ${x.sign} ` : ''}${x.text}`).join('') || '۰';
|
||||
const lim = limitsOf(f);
|
||||
return `اجرت نهایی = ${body}${lim ? ` (${lim})` : ''}`;
|
||||
}
|
||||
const sampleText = (x: Sample) =>
|
||||
`${fa(x.rashWeightGrams)} گرم × ${fa(x.quantity)}، اجرت مدل ${fa(x.variantPercent)}٪، مشتری ${fa(x.customerPercent)}٪، تخفیف ${fa(x.promotionPercent)}٪`;
|
||||
|
||||
const pct = (v: string) => `${fa(Number(v))}٪`;
|
||||
const g = (v: string) => `${fa(Number(v))} گرم`;
|
||||
const jdate = (v?: string | null) => (v ? fa(moment(v).format('jYYYY/jM/jD HH:mm')) : '');
|
||||
|
||||
const cmpRows = [
|
||||
{ key: 'v', label: 'سهم اجرت مدل', fmt: (r: Result) => pct(r.variantTerm) },
|
||||
{ key: 'c', label: 'سهم درصد مشتری', fmt: (r: Result) => pct(r.customerTerm) },
|
||||
{ key: 'p', label: 'سهم تخفیف (کم میشود)', fmt: (r: Result) => pct(r.promotionTerm) },
|
||||
{ key: 'k', label: 'مقدار ثابت', fmt: (r: Result) => pct(r.constant) },
|
||||
{ key: 'b', label: 'قبل از محدودیت', fmt: (r: Result) => pct(r.beforeLimits) },
|
||||
{ key: 'f', label: 'اجرت نهایی', fmt: (r: Result) => pct(r.finalPercent), strong: true },
|
||||
{ key: 'w', label: 'اجرت به گرم', fmt: (r: Result) => g(r.wageGrams) },
|
||||
{ key: 't', label: 'وزن کل فاکتور', fmt: (r: Result) => g(r.totalGrams), strong: true },
|
||||
];
|
||||
|
||||
/* ───────── state ───────── */
|
||||
|
||||
const sameFormula = (a: Formula, b: Formula) =>
|
||||
(['variantCoef', 'customerCoef', 'promotionCoef', 'constant', 'min', 'max'] as const).every(
|
||||
(k) => (a[k] === null ? null : Number(a[k])) === (b[k] === null ? null : Number(b[k])),
|
||||
) && a.promotionPick === b.promotionPick && a.decimals === b.decimals;
|
||||
|
||||
const dirty = computed(() => !!config.value && !sameFormula(draft, config.value.formula));
|
||||
const isLegacy = (f: Formula) => !!config.value && sameFormula(f, config.value.legacy);
|
||||
const canApprove = computed(() => dirty.value && sampleChecked.value && !previewError.value && !!preview.value);
|
||||
|
||||
function setDraft(f: Formula) {
|
||||
Object.assign(draft, { ...f });
|
||||
}
|
||||
function setSample(x: Sample) {
|
||||
Object.assign(sample, {
|
||||
rashWeightGrams: Number(x.rashWeightGrams),
|
||||
quantity: Number(x.quantity),
|
||||
variantPercent: Number(x.variantPercent),
|
||||
customerPercent: Number(x.customerPercent),
|
||||
promotionPercent: Number(x.promotionPercent),
|
||||
});
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await api.get('admin/pricing/wage-formula');
|
||||
config.value = data;
|
||||
setDraft(data.formula);
|
||||
setSample(data.sample);
|
||||
sampleChecked.value = false;
|
||||
} catch (e) {
|
||||
message.error(errMsg(e, 'خطا در دریافت فرمول اجرت'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
async function runPreview() {
|
||||
const mine = ++seq;
|
||||
try {
|
||||
const { data } = await api.post('admin/pricing/wage-formula/preview', { formula: { ...draft }, sample: { ...sample } });
|
||||
if (mine !== seq) return;
|
||||
preview.value = data;
|
||||
previewError.value = '';
|
||||
} catch (e) {
|
||||
if (mine !== seq) return;
|
||||
previewError.value = errMsg(e, 'محاسبهی نمونه انجام نشد');
|
||||
}
|
||||
}
|
||||
// Any change: recompute on the server, and ask for the sample to be checked again.
|
||||
watch(
|
||||
[() => ({ ...draft }), () => ({ ...sample })],
|
||||
() => {
|
||||
sampleChecked.value = false;
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(runPreview, 250);
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
function resetToLegacy() {
|
||||
if (config.value) setDraft(config.value.legacy);
|
||||
}
|
||||
function discard() {
|
||||
if (config.value) setDraft(config.value.formula);
|
||||
}
|
||||
function loadSavedSample() {
|
||||
if (config.value) setSample(config.value.sample);
|
||||
}
|
||||
|
||||
async function approve() {
|
||||
saving.value = true;
|
||||
try {
|
||||
const { data } = await api.put('admin/pricing/wage-formula', { formula: { ...draft }, sample: { ...sample } });
|
||||
config.value = data;
|
||||
setDraft(data.formula);
|
||||
setSample(data.sample);
|
||||
sampleChecked.value = false;
|
||||
message.success('فرمول اجرت ثبت شد و از همین حالا اعمال میشود');
|
||||
} catch (e) {
|
||||
message.error(errMsg(e, 'خطا در ثبت فرمول'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await load();
|
||||
await runPreview();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mb-4 { margin-bottom: 1rem; }
|
||||
.mt-4 { margin-top: 1rem; }
|
||||
.ms { margin-inline-start: 8px; }
|
||||
.hint { font-size: 12px; color: #888; margin-top: 4px; }
|
||||
.warn { color: #d4380d; }
|
||||
|
||||
.status { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
|
||||
.status__title { font-size: 16px; font-weight: 600; }
|
||||
|
||||
.formula {
|
||||
background: linear-gradient(135deg, rgba(212, 167, 44, 0.08), rgba(212, 167, 44, 0.02));
|
||||
border: 1px solid rgba(212, 167, 44, 0.35);
|
||||
border-radius: 10px;
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 15px;
|
||||
line-height: 2.2;
|
||||
}
|
||||
.formula__lhs { font-weight: 700; margin-inline-end: 8px; }
|
||||
.formula__op { margin: 0 6px; font-weight: 700; color: #555; }
|
||||
.formula__limits { font-size: 12px; color: #666; line-height: 1.6; }
|
||||
|
||||
.chip { display: inline-block; padding: 0 10px; border-radius: 999px; line-height: 26px; font-weight: 600; white-space: nowrap; }
|
||||
.chip--sm { line-height: 20px; padding: 0 8px; font-size: 12px; }
|
||||
.chip--variant { background: #e6f4ff; color: #0958d9; }
|
||||
.chip--customer { background: #f9f0ff; color: #531dab; }
|
||||
.chip--promotion { background: #fff1f0; color: #cf1322; }
|
||||
.chip--constant { background: #f6ffed; color: #389e0d; }
|
||||
.chip--zero { background: #f5f5f5; color: #888; }
|
||||
|
||||
.term { padding: 10px 0; border-top: 1px dashed #eee; }
|
||||
.term:first-of-type { border-top: none; }
|
||||
.term__head { display: flex; align-items: center; gap: 8px; }
|
||||
.term__label { font-weight: 600; flex: 1; }
|
||||
.term__body { display: flex; align-items: center; gap: 10px; margin-top: 8px; flex-wrap: wrap; }
|
||||
.num { width: 150px; }
|
||||
|
||||
.divider { font-size: 13px; }
|
||||
.limits { display: flex; flex-direction: column; gap: 10px; }
|
||||
.limit { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
.sample { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||
.sample label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: #555; }
|
||||
.sample .num { width: 100%; }
|
||||
|
||||
.cmp { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
.cmp th, .cmp td { padding: 7px 10px; border-bottom: 1px solid #f0f0f0; text-align: start; }
|
||||
.cmp th { background: #fafafa; font-weight: 600; }
|
||||
.cmp th.changed { color: #d48806; }
|
||||
.cmp tr.strong td { font-weight: 700; font-size: 14px; }
|
||||
.cmp td.diff { background: #fffbe6; color: #ad6800; }
|
||||
|
||||
.hist { padding: 8px 0; border-bottom: 1px solid #f5f5f5; }
|
||||
.hist__meta { font-size: 12px; color: #888; }
|
||||
</style>
|
||||
@@ -14,7 +14,11 @@
|
||||
<DateInput v-model="filters.start_date" label="از تاریخ" />
|
||||
<DateInput v-model="filters.end_date" label="تا تاریخ" />
|
||||
<a-form-item label=" ">
|
||||
<a-button type="primary" @click="load">اعمال</a-button>
|
||||
<a-space>
|
||||
<a-button type="primary" @click="load">اعمال</a-button>
|
||||
<!-- legacy's only output: «دریافت گزارش», the 32-column Excel file -->
|
||||
<a-button :loading="downloading" @click="downloadExcel">دریافت فایل اکسل</a-button>
|
||||
</a-space>
|
||||
</a-form-item>
|
||||
</div>
|
||||
</a-form>
|
||||
@@ -46,6 +50,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue';
|
||||
import { message } from 'ant-design-vue';
|
||||
import DateInput from '../../components/input/DateInput.vue';
|
||||
import { jdate } from '../../utils/filters';
|
||||
import api from '../../api/client';
|
||||
@@ -83,6 +88,27 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
const downloading = ref(false);
|
||||
|
||||
/** Legacy getReport: the order items + financial documents of the range as Excel. */
|
||||
async function downloadExcel() {
|
||||
try {
|
||||
downloading.value = true;
|
||||
const { data } = await api.get('admin/report/order-items', { params: filters, responseType: 'blob' });
|
||||
const url = URL.createObjectURL(data as Blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `report-${filters.start_date ?? 'all'}-${filters.end_date ?? 'all'}.xlsx`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
message.error('خطا در دریافت فایل');
|
||||
} finally {
|
||||
downloading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
|
||||
@@ -842,6 +842,10 @@ export const treeData: PermissionNode[] = [
|
||||
"title": "اتصال حسابداری",
|
||||
"key": "config.accounting",
|
||||
},
|
||||
{
|
||||
"title": "اجرت",
|
||||
"key": "config.wage",
|
||||
},
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -51,3 +51,16 @@ SMS_ADMIN_RECIPIENTS=
|
||||
ACCOUNTING_SECRET_KEY=
|
||||
# "off" keeps this instance out of the background sync.
|
||||
ACCOUNTING_WORKER=
|
||||
|
||||
# SEC-04 — browser origins allowed to call the API, comma-separated, exact
|
||||
# (e.g. https://adm.example.ir,https://app.example.ir). Blank = any origin
|
||||
# (development); in production a blank list prints a warning at boot.
|
||||
# In production (NODE_ENV=production) JWT_SECRET is REQUIRED: the API refuses
|
||||
# to start on the built-in development key.
|
||||
CORS_ORIGINS=
|
||||
|
||||
# SEC-05 — the seed runs once on a fresh database at boot. In production it
|
||||
# creates roles and permissions only; set "true" to force the demo data
|
||||
# (sample customers, orders, debt and known-password accounts). Never in a
|
||||
# real deployment.
|
||||
SEED_DEMO_DATA=
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"bcryptjs": "^3.0.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"exceljs": "^4.4.0",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
-- «اجرت» admin screen (owner ruling 2026-10-08): its permission for the
|
||||
-- seeded super-admin user type. A fresh seed grants every rid in ALL_RIDS;
|
||||
-- an existing database gets the new one here. Data only, idempotent.
|
||||
-- The formula itself needs no row: until an admin approves one, the server
|
||||
-- uses legacy's formula (pricing/wage-formula.ts LEGACY_WAGE_FORMULA).
|
||||
INSERT INTO "permission" ("rid", "userTypeId")
|
||||
SELECT 'config.wage', 85
|
||||
WHERE EXISTS (SELECT 1 FROM "user_type" WHERE "id" = 85)
|
||||
ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- PERM-01 (owner approval 2026-10-08): legacy's two dashboard permissions
|
||||
-- «آمار عمده فروشی» (dashboard.omde) and «آمار تک فروشی» (dashboard.tak), and
|
||||
-- their tree parent "dashboard", became the single "dashboard.view" when the two
|
||||
-- dashboards became one. A database seeded before that change still holds the
|
||||
-- old rows: nothing reads them and the permission screen cannot show or revoke
|
||||
-- them. Whoever held one keeps the dashboard through "dashboard.view", then the
|
||||
-- old rows go. Data only, idempotent.
|
||||
INSERT INTO "permission" ("rid", "userTypeId")
|
||||
SELECT DISTINCT 'dashboard.view', "userTypeId"
|
||||
FROM "permission"
|
||||
WHERE "rid" IN ('dashboard', 'dashboard.omde', 'dashboard.tak')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
DELETE FROM "permission" WHERE "rid" IN ('dashboard', 'dashboard.omde', 'dashboard.tak');
|
||||
@@ -0,0 +1,33 @@
|
||||
-- PERS-02 (owner approval 2026-10-08): cities become a tree again, as in legacy
|
||||
-- (country > province > city > district, henza `cities.parent`). The flat
|
||||
-- `province` label is turned into parent rows, nothing is lost, then dropped.
|
||||
|
||||
ALTER TABLE "City" ADD COLUMN "parentId" TEXT;
|
||||
|
||||
-- One province row per distinct label, named as legacy names them
|
||||
-- («استان تهران»), unless a city row already carries that name.
|
||||
INSERT INTO "City" ("id", "name")
|
||||
SELECT 'cprov' || substr(md5(p.pname), 1, 20), p.pname
|
||||
FROM (
|
||||
SELECT DISTINCT
|
||||
CASE WHEN btrim("province") LIKE 'استان%' THEN btrim("province") ELSE 'استان ' || btrim("province") END AS pname
|
||||
FROM "City"
|
||||
WHERE "province" IS NOT NULL AND btrim("province") <> ''
|
||||
) p
|
||||
WHERE NOT EXISTS (SELECT 1 FROM "City" c WHERE c."name" = p.pname);
|
||||
|
||||
UPDATE "City" c
|
||||
SET "parentId" = (
|
||||
SELECT p."id" FROM "City" p
|
||||
WHERE p."id" <> c."id"
|
||||
AND p."name" = CASE WHEN btrim(c."province") LIKE 'استان%' THEN btrim(c."province") ELSE 'استان ' || btrim(c."province") END
|
||||
ORDER BY p."id"
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE c."province" IS NOT NULL AND btrim(c."province") <> '';
|
||||
|
||||
ALTER TABLE "City" DROP COLUMN "province";
|
||||
|
||||
CREATE INDEX "City_parentId_idx" ON "City"("parentId");
|
||||
|
||||
ALTER TABLE "City" ADD CONSTRAINT "City_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "City"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -118,10 +118,15 @@ enum LedgerSourceType {
|
||||
// Identity
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Legacy `cities` is a tree (country > province > city > district) and so is
|
||||
/// this: a city hangs under its `parent`. In the admin pickers a top-level row
|
||||
/// (the country) is a heading, not selectable (henza_admin citiesModel.js:38).
|
||||
model City {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
province String?
|
||||
parentId String?
|
||||
parent City? @relation("CityTree", fields: [parentId], references: [id], onDelete: Restrict)
|
||||
children City[] @relation("CityTree")
|
||||
/// Legacy cities.percent / percent_aux — per-city wage surcharges the city
|
||||
/// screen edits through GET cities/get-percent/{id} and get-percent-aux/{id}.
|
||||
percent Decimal? @db.Decimal(6, 3)
|
||||
@@ -131,6 +136,8 @@ model City {
|
||||
branches Branch[]
|
||||
preOrders PreOrder[]
|
||||
salesExpertProfiles SalesExpertProfile[]
|
||||
|
||||
@@index([parentId])
|
||||
}
|
||||
|
||||
model AdminUser {
|
||||
|
||||
+65
-26
@@ -28,32 +28,12 @@ const DEV_TEST_PHONE_PASSWORD_HASH = bcrypt.hashSync(DEV_TEST_PHONE, 10);
|
||||
// Replace these rows with real photo URLs when product photography exists.
|
||||
const PLACEHOLDER_PRODUCT_IMAGE = '/img/no-items.png';
|
||||
|
||||
async function main() {
|
||||
// ── Cities ────────────────────────────────────────────────────────────
|
||||
const [tehran, mashhad, isfahan, tabriz] = await Promise.all([
|
||||
prisma.city.upsert({ where: { id: 'city-tehran' }, update: {}, create: { id: 'city-tehran', name: 'تهران', province: 'تهران' } }),
|
||||
prisma.city.upsert({ where: { id: 'city-mashhad' }, update: {}, create: { id: 'city-mashhad', name: 'مشهد', province: 'خراسان رضوی' } }),
|
||||
prisma.city.upsert({ where: { id: 'city-isfahan' }, update: {}, create: { id: 'city-isfahan', name: 'اصفهان', province: 'اصفهان' } }),
|
||||
prisma.city.upsert({ where: { id: 'city-tabriz' }, update: {}, create: { id: 'city-tabriz', name: 'تبریز', province: 'آذربایجان شرقی' } }),
|
||||
]);
|
||||
|
||||
// ── Branches & workshop ──────────────────────────────────────────────
|
||||
const branchTehran = await prisma.branch.upsert({
|
||||
where: { id: 'branch-tehran-bazaar' },
|
||||
update: {},
|
||||
create: { id: 'branch-tehran-bazaar', name: 'شعبه بازار بزرگ تهران', cityId: tehran.id },
|
||||
});
|
||||
const branchMashhad = await prisma.branch.upsert({
|
||||
where: { id: 'branch-mashhad-main' },
|
||||
update: {},
|
||||
create: { id: 'branch-mashhad-main', name: 'شعبه مرکزی مشهد', cityId: mashhad.id },
|
||||
});
|
||||
await prisma.workshop.upsert({
|
||||
where: { id: 'workshop-central' },
|
||||
update: {},
|
||||
create: { id: 'workshop-central', name: 'کارگاه مرکزی ساخت طلا' },
|
||||
});
|
||||
|
||||
/**
|
||||
* Role definitions and their permissions — the one part of this file a real
|
||||
* deployment needs (the admin screens and the legacy import map onto these
|
||||
* ids). Idempotent: upserts and skipDuplicates only.
|
||||
*/
|
||||
async function seedAccessControl() {
|
||||
// ── Admin user types + permissions (legacy `permission(rid, ut)`) ────
|
||||
//
|
||||
// In legacy these lived in the dynamic `config_static` lookup under the key
|
||||
@@ -108,6 +88,65 @@ async function main() {
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything below is DEMO data: sample cities, branches, accounts with known
|
||||
* passwords (one super admin whose password is its own phone number), sample
|
||||
* customers, products, orders and posted debt. The app runs this seed once on
|
||||
* a fresh database at boot (src/prisma/bootstrap.ts), so without this gate a
|
||||
* production first boot would mix fake customers, fake debt and open admin
|
||||
* accounts into the real data (SEC-05). Production never gets it unless
|
||||
* SEED_DEMO_DATA=true is set on purpose.
|
||||
*/
|
||||
function demoDataAllowed(): boolean {
|
||||
if (process.env.SEED_DEMO_DATA?.trim() === 'true') return true;
|
||||
return process.env.NODE_ENV !== 'production';
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await seedAccessControl();
|
||||
|
||||
if (!demoDataAllowed()) {
|
||||
console.log('seed: production — roles and permissions only; demo data skipped (set SEED_DEMO_DATA=true to force)');
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Cities ────────────────────────────────────────────────────────────
|
||||
// A tree, as legacy's: country > province > city. The country is a heading
|
||||
// in the admin pickers; provinces and cities are selectable.
|
||||
const city = (id: string, name: string, parentId: string | null) =>
|
||||
prisma.city.upsert({ where: { id }, update: {}, create: { id, name, parentId } });
|
||||
await city('city-iran', 'ایران', null);
|
||||
await Promise.all([
|
||||
city('city-prov-tehran', 'استان تهران', 'city-iran'),
|
||||
city('city-prov-khorasan-razavi', 'استان خراسان رضوی', 'city-iran'),
|
||||
city('city-prov-isfahan', 'استان اصفهان', 'city-iran'),
|
||||
city('city-prov-east-azarbaijan', 'استان آذربایجان شرقی', 'city-iran'),
|
||||
]);
|
||||
const [tehran, mashhad, isfahan, tabriz] = await Promise.all([
|
||||
city('city-tehran', 'تهران', 'city-prov-tehran'),
|
||||
city('city-mashhad', 'مشهد', 'city-prov-khorasan-razavi'),
|
||||
city('city-isfahan', 'اصفهان', 'city-prov-isfahan'),
|
||||
city('city-tabriz', 'تبریز', 'city-prov-east-azarbaijan'),
|
||||
]);
|
||||
|
||||
// ── Branches & workshop ──────────────────────────────────────────────
|
||||
const branchTehran = await prisma.branch.upsert({
|
||||
where: { id: 'branch-tehran-bazaar' },
|
||||
update: {},
|
||||
create: { id: 'branch-tehran-bazaar', name: 'شعبه بازار بزرگ تهران', cityId: tehran.id },
|
||||
});
|
||||
const branchMashhad = await prisma.branch.upsert({
|
||||
where: { id: 'branch-mashhad-main' },
|
||||
update: {},
|
||||
create: { id: 'branch-mashhad-main', name: 'شعبه مرکزی مشهد', cityId: mashhad.id },
|
||||
});
|
||||
await prisma.workshop.upsert({
|
||||
where: { id: 'workshop-central' },
|
||||
update: {},
|
||||
create: { id: 'workshop-central', name: 'کارگاه مرکزی ساخت طلا' },
|
||||
});
|
||||
|
||||
// ── Admin users (sales agents + one super admin) ────────────────────
|
||||
|
||||
|
||||
@@ -29,19 +29,9 @@ export async function cities(ctx: Ctx) {
|
||||
WHERE deleted_at IS NULL
|
||||
OR id IN (SELECT city_id FROM customers WHERE deleted_at IS NULL AND city_id IS NOT NULL)`,
|
||||
);
|
||||
const all = new Map((await ctx.q<Row>('SELECT id, title, parent, level FROM cities')).map((r) => [String(r.id), r]));
|
||||
|
||||
// Legacy is a tree (country > province > city > district); the target City is
|
||||
// flat with a `province` label, taken from the level-1 ancestor.
|
||||
const provinceOf = (r: Row): string | null => {
|
||||
let cur: Row | undefined = r;
|
||||
for (let guard = 0; cur && guard < 10; guard++) {
|
||||
if (int(cur.level) === 1) return cur === r ? null : text(cur.title);
|
||||
cur = all.get(String(cur.parent));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Legacy is a tree (country > province > city > district) and so is the
|
||||
// target (PERS-02): rows first, then each one's parent once all are mapped.
|
||||
const existing = await ctx.db.city.findMany();
|
||||
const byKey = new Map(existing.map((c) => [matchKey(c.name), c.id]));
|
||||
|
||||
@@ -53,7 +43,6 @@ export async function cities(ctx: Ctx) {
|
||||
}
|
||||
const data = {
|
||||
name,
|
||||
province: provinceOf(r),
|
||||
percent: r.percent === null ? null : percent(r.percent),
|
||||
percentAux: r.percent_aux === null ? null : percent(r.percent_aux),
|
||||
};
|
||||
@@ -77,6 +66,32 @@ export async function cities(ctx: Ctx) {
|
||||
ctx.report.count(S, res.isNew ? 'created' : res.how === 'matched' ? 'matched existing' : 'updated');
|
||||
byKey.set(matchKey(name), res.id);
|
||||
}
|
||||
|
||||
// Parents. A row the import created takes legacy's parent; a matched row
|
||||
// keeps the parent it already has (fill-empty, as every other field). A
|
||||
// parent that was not imported (deleted in legacy) leaves the row on top.
|
||||
const parentOf = new Map((await ctx.db.city.findMany({ select: { id: true, parentId: true } })).map((c) => [c.id, c.parentId]));
|
||||
for (const r of rows) {
|
||||
const id = ctx.map.get('city', r.id);
|
||||
const parentId = r.parent === null ? null : ctx.map.get('city', r.parent);
|
||||
if (!id || !parentId || parentId === id) continue;
|
||||
if (ctx.map.how('city', r.id) !== 'created' && parentOf.get(id)) continue;
|
||||
if (parentOf.get(id) === parentId) continue;
|
||||
// Never close a loop: `id` must not be an ancestor of its new parent.
|
||||
let cur: string | null | undefined = parentId;
|
||||
let loop = false;
|
||||
for (let guard = 0; cur && guard < 50; guard++) {
|
||||
if (cur === id) loop = true;
|
||||
cur = parentOf.get(cur);
|
||||
}
|
||||
if (loop) {
|
||||
ctx.report.note(S, `legacy city ${r.id}: parent ${r.parent} would make a loop — left as is`);
|
||||
continue;
|
||||
}
|
||||
await ctx.db.city.update({ where: { id }, data: { parentId } });
|
||||
parentOf.set(id, parentId);
|
||||
ctx.report.count(S, 'parent set');
|
||||
}
|
||||
}
|
||||
|
||||
/** Target City id for an exact (normalised) name match, or null. */
|
||||
@@ -98,6 +113,18 @@ async function cityByName(ctx: Ctx, name: string | null): Promise<string | null>
|
||||
*/
|
||||
const SAME_ROLE: ReadonlyMap<number, number> = new Map([[85, 85]]);
|
||||
|
||||
/**
|
||||
* Legacy rids the target renamed (PERM-01): the wholesale and retail dashboards
|
||||
* («آمار عمده فروشی» dashboard.omde, «آمار تک فروشی» dashboard.tak) and their
|
||||
* tree parent became the one dashboard behind "dashboard.view". Without this a
|
||||
* role that saw a dashboard in legacy would lose it.
|
||||
*/
|
||||
const RENAMED_RIDS: ReadonlyMap<string, string> = new Map([
|
||||
['dashboard', 'dashboard.view'],
|
||||
['dashboard.omde', 'dashboard.view'],
|
||||
['dashboard.tak', 'dashboard.view'],
|
||||
]);
|
||||
|
||||
/** AdminRole is a label only — every permission comes from the user type. */
|
||||
function adminRoleFor(legacyUt: number | null): AdminRole {
|
||||
if (legacyUt === 85 || legacyUt === 104 || legacyUt === 105) return AdminRole.SUPER_ADMIN; // مدیر · مدیر اصلی · مدیران
|
||||
@@ -146,7 +173,9 @@ export async function roles(ctx: Ctx) {
|
||||
created = true;
|
||||
}
|
||||
|
||||
const legacyRids = perms.filter((p) => Number(p.ut) === legacyId).map((p) => String(p.rid));
|
||||
const legacyRids = [
|
||||
...new Set(perms.filter((p) => Number(p.ut) === legacyId).map((p) => RENAMED_RIDS.get(String(p.rid)) ?? String(p.rid))),
|
||||
];
|
||||
if (created || ctx.map.how('ut', legacyId) === 'created') {
|
||||
// A role the import created gets legacy's permissions, limited to rids the
|
||||
// target ACL knows (the storefront's are out of scope, D13).
|
||||
@@ -468,11 +497,17 @@ export async function customers(ctx: Ctx) {
|
||||
shopImageUrl: await ctx.imageUrl(r.shop_image_id, S),
|
||||
avatarFileId: await ctx.uploadedFile(r.image_id, 'legacy-avatar', S),
|
||||
birthDate: birthday(r.birth_date, r.created_at),
|
||||
canPlaceOrders: int(r.sts) !== -1,
|
||||
// Owner ruling 2026-10-08 (MON-05, option 2): everyone may order after the
|
||||
// move. Legacy customers.sts was never read by any code — most of the 313
|
||||
// «عدم سفارش» rows are just the sign-up default (ApiMobileController.php:704)
|
||||
// — so carrying it over would suddenly block real customers once the new
|
||||
// system enforces the switch. Only a deliberate suspension after go-live counts.
|
||||
canPlaceOrders: true,
|
||||
isActive: int(r.active) !== -1,
|
||||
isArchived: int(r.is_archive) === 1,
|
||||
};
|
||||
if (r.reagent_id !== null && !owned.referredByAgentId) ctx.report.count(S, 'referrer not mapped (not a migrated expert)');
|
||||
if (int(r.sts) === -1) ctx.report.count(S, 'legacy «عدم سفارش» (never enforced) — set to allowed (owner, option 2)');
|
||||
if (r.birth_date !== null && !owned.birthDate) ctx.report.count(S, 'birth date dropped (sign-up default or impossible)');
|
||||
|
||||
const res = await upsert(ctx, 'customer', r.id, {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { CustomersModule } from './modules/customers/customers.module';
|
||||
import { CustomerAuthModule } from './modules/customer-auth/customer-auth.module';
|
||||
import { SalesExpertAppModule } from './modules/sales-expert-app/sales-expert-app.module';
|
||||
import { CustomerProfileModule } from './modules/customer-profile/customer-profile.module';
|
||||
import { CustomerFavoritesModule } from './modules/customer-favorites/customer-favorites.module';
|
||||
import { CustomerReportModule } from './modules/customer-report/customer-report.module';
|
||||
import { SmsModule } from './modules/sms/sms.module';
|
||||
import { OrdersModule } from './modules/orders/orders.module';
|
||||
@@ -31,6 +32,7 @@ import { AdminInvoicesModule } from './modules/admin-invoices/admin-invoices.mod
|
||||
import { AdminMiscModule } from './modules/admin-misc/admin-misc.module';
|
||||
import { AdminUploadsModule } from './modules/admin-uploads/admin-uploads.module';
|
||||
import { AdminDashboardModule } from './modules/admin-dashboard/admin-dashboard.module';
|
||||
import { AdminReportModule } from './modules/admin-report/admin-report.module';
|
||||
import { SalesAgentModule } from './modules/sales-agent/sales-agent.module';
|
||||
|
||||
@Module({
|
||||
@@ -57,12 +59,14 @@ import { SalesAgentModule } from './modules/sales-agent/sales-agent.module';
|
||||
AdminMiscModule,
|
||||
AdminUploadsModule,
|
||||
AdminDashboardModule,
|
||||
AdminReportModule,
|
||||
CatalogModule,
|
||||
CustomersModule,
|
||||
SmsModule,
|
||||
CustomerAuthModule,
|
||||
SalesExpertAppModule,
|
||||
CustomerProfileModule,
|
||||
CustomerFavoritesModule,
|
||||
CustomerReportModule,
|
||||
SalesAgentModule,
|
||||
OrdersModule,
|
||||
|
||||
+37
-1
@@ -18,7 +18,43 @@ const EXTRA_MIME_TYPES: Record<string, string> = {
|
||||
'.avif': 'image/avif',
|
||||
};
|
||||
|
||||
/**
|
||||
* SEC-04 — production must not run on the published development key. Both JWT
|
||||
* modules fall back to 'dev-only-insecure-secret' (a string anyone can read
|
||||
* in this repository), with which anyone could mint an admin token. Outside
|
||||
* production that fallback is kept, so a fresh checkout still runs.
|
||||
*/
|
||||
function assertProductionSecrets() {
|
||||
if (process.env.NODE_ENV !== 'production') return;
|
||||
if (!envOrNull('JWT_SECRET')) {
|
||||
throw new Error(
|
||||
'JWT_SECRET تنظیم نشده است — سرور در حالت production بدون آن اجرا نمیشود.\n' +
|
||||
'JWT_SECRET is not set: refusing to start in production on the public development key.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-04 — which sites may call the API from a browser. CORS_ORIGINS is a
|
||||
* comma-separated list of exact origins (e.g. https://adm.example.ir,https://app.example.ir).
|
||||
* Unset keeps the old allow-all, with a warning in production, so an existing
|
||||
* deployment keeps working until the list is filled in.
|
||||
*/
|
||||
function corsOrigins(): string[] | true {
|
||||
const list = (envOrNull('CORS_ORIGINS') ?? '')
|
||||
.split(',')
|
||||
.map((o) => o.trim().replace(/\/+$/, ''))
|
||||
.filter(Boolean);
|
||||
if (list.length) return list;
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
console.warn('⚠ CORS_ORIGINS تنظیم نشده — هر سایتی میتواند به API درخواست بفرستد. / CORS_ORIGINS is not set: any website may call this API.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
assertProductionSecrets();
|
||||
|
||||
// D20 — reports the SMS configuration and never throws. A missing credential
|
||||
// no longer stops the boot; messages are logged instead of sent.
|
||||
assertSmsConfigured();
|
||||
@@ -85,7 +121,7 @@ async function bootstrap() {
|
||||
app.setGlobalPrefix('api');
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||
app.useGlobalFilters(new PrismaExceptionFilter());
|
||||
app.enableCors();
|
||||
app.enableCors({ origin: corsOrigins() });
|
||||
// Uploaded files, mounted OUTSIDE the /api prefix so the URLs stored on
|
||||
// UploadedFile.url ("/uploads/<name>") resolve directly.
|
||||
app.useStaticAssets(envOr('UPLOAD_DIR', join(process.cwd(), 'storage', 'uploads')), {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { LedgerCurrency, LedgerDirection, OrderStatus, Prisma } from '@prisma/client';
|
||||
import { LedgerService } from './ledger.service';
|
||||
|
||||
/**
|
||||
* ACC-03 / MON-04 — an order's debt follows its status, exactly as legacy's
|
||||
* recomputed `Σ orders.input WHERE sts > 4`: owed once while delivered (to the
|
||||
* expert or the customer), nothing otherwise, never twice.
|
||||
*/
|
||||
describe('LedgerService.syncOrderDebt', () => {
|
||||
type Entry = { orderId: string; currency: LedgerCurrency; direction: LedgerDirection; amount: Prisma.Decimal; confirmed: boolean };
|
||||
|
||||
function build(order: { status: OrderStatus; totalGoldWeightGrams: string; flatRialCharge: string }) {
|
||||
const entries: Entry[] = [];
|
||||
const balance = { gold: new Prisma.Decimal(0), rial: new Prisma.Decimal(0) };
|
||||
const row = { id: 'o1', customerId: 'c1', ...order };
|
||||
const tx = {
|
||||
order: { findUnique: jest.fn(async () => row) },
|
||||
ledgerEntry: {
|
||||
create: jest.fn(async ({ data }: { data: Entry }) => {
|
||||
entries.push(data);
|
||||
return data;
|
||||
}),
|
||||
groupBy: jest.fn(async ({ where }: { where: { orderId: string; currency: LedgerCurrency } }) => {
|
||||
const out: { direction: LedgerDirection; _sum: { amount: Prisma.Decimal } }[] = [];
|
||||
for (const d of [LedgerDirection.DEBIT, LedgerDirection.CREDIT]) {
|
||||
const hit = entries.filter((e) => e.orderId === where.orderId && e.currency === where.currency && e.direction === d && e.confirmed);
|
||||
if (hit.length) out.push({ direction: d, _sum: { amount: hit.reduce((s, e) => s.add(e.amount), new Prisma.Decimal(0)) } });
|
||||
}
|
||||
return out;
|
||||
}),
|
||||
},
|
||||
customer: {
|
||||
update: jest.fn(async ({ data }: { data: { goldDebtGrams?: { increment: Prisma.Decimal }; fiatDebtRial?: { increment: Prisma.Decimal } } }) => {
|
||||
if (data.goldDebtGrams) balance.gold = balance.gold.add(data.goldDebtGrams.increment);
|
||||
if (data.fiatDebtRial) balance.rial = balance.rial.add(data.fiatDebtRial.increment);
|
||||
}),
|
||||
},
|
||||
};
|
||||
const service = new LedgerService(tx as never);
|
||||
const move = async (status: OrderStatus) => {
|
||||
row.status = status;
|
||||
await service.syncOrderDebt('o1', tx as never);
|
||||
};
|
||||
return { move, entries, balance };
|
||||
}
|
||||
|
||||
it('posts the gold and rial debt once on delivery to the expert', async () => {
|
||||
const t = build({ status: OrderStatus.PLACED, totalGoldWeightGrams: '10.5', flatRialCharge: '2000' });
|
||||
await t.move(OrderStatus.DELIVERED_TO_AGENT);
|
||||
expect(t.balance.gold.toString()).toBe('10.5');
|
||||
expect(t.balance.rial.toString()).toBe('2000');
|
||||
expect(t.entries).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('never posts twice when the order reaches delivered again (the ACC-03 bug)', async () => {
|
||||
const t = build({ status: OrderStatus.PLACED, totalGoldWeightGrams: '10.5', flatRialCharge: '0' });
|
||||
await t.move(OrderStatus.DELIVERED_TO_AGENT);
|
||||
await t.move(OrderStatus.DELIVERED_TO_AGENT);
|
||||
await t.move(OrderStatus.DELIVERED_TO_CUSTOMER);
|
||||
expect(t.balance.gold.toString()).toBe('10.5');
|
||||
expect(t.entries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('takes the debt off when the order goes back, and puts it back once', async () => {
|
||||
const t = build({ status: OrderStatus.PLACED, totalGoldWeightGrams: '10.5', flatRialCharge: '0' });
|
||||
await t.move(OrderStatus.DELIVERED_TO_AGENT);
|
||||
await t.move(OrderStatus.PREPARING);
|
||||
expect(t.balance.gold.toString()).toBe('0');
|
||||
expect(t.entries[1].direction).toBe(LedgerDirection.CREDIT);
|
||||
await t.move(OrderStatus.DELIVERED_TO_AGENT);
|
||||
expect(t.balance.gold.toString()).toBe('10.5');
|
||||
});
|
||||
|
||||
it('posts the debt when an order goes straight to delivered-to-customer', async () => {
|
||||
const t = build({ status: OrderStatus.PLACED, totalGoldWeightGrams: '3', flatRialCharge: '0' });
|
||||
await t.move(OrderStatus.DELIVERED_TO_CUSTOMER);
|
||||
expect(t.balance.gold.toString()).toBe('3');
|
||||
});
|
||||
|
||||
it('a cancelled delivered order owes nothing', async () => {
|
||||
const t = build({ status: OrderStatus.PLACED, totalGoldWeightGrams: '3', flatRialCharge: '500' });
|
||||
await t.move(OrderStatus.DELIVERED_TO_AGENT);
|
||||
await t.move(OrderStatus.CANCELLED);
|
||||
expect(t.balance.gold.toString()).toBe('0');
|
||||
expect(t.balance.rial.toString()).toBe('0');
|
||||
});
|
||||
|
||||
it('posts nothing for an order that was never delivered', async () => {
|
||||
const t = build({ status: OrderStatus.PLACED, totalGoldWeightGrams: '3', flatRialCharge: '500' });
|
||||
await t.move(OrderStatus.ADMIN_APPROVED);
|
||||
await t.move(OrderStatus.PREPARING);
|
||||
expect(t.entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,15 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { LedgerCurrency, LedgerDirection, LedgerSourceType, Prisma, PrismaClient } from '@prisma/client';
|
||||
import { LedgerCurrency, LedgerDirection, LedgerSourceType, OrderStatus, Prisma, PrismaClient } from '@prisma/client';
|
||||
import { GRAMS_PER_MESGHAL, STANDARD_KARAT_PER_MILLE } from '@gold-bank/shared-types';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
|
||||
type Tx = Prisma.TransactionClient | PrismaClient;
|
||||
|
||||
const ZERO = new Prisma.Decimal(0);
|
||||
|
||||
/** Legacy `sts > 4`: delivered to the expert (5) or to the customer (6). */
|
||||
const OWING_STATUSES: OrderStatus[] = [OrderStatus.DELIVERED_TO_AGENT, OrderStatus.DELIVERED_TO_CUSTOMER];
|
||||
|
||||
export interface PostEntryInput {
|
||||
customerId: string;
|
||||
currency: LedgerCurrency;
|
||||
@@ -103,42 +108,56 @@ export class LedgerService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts the dual-currency debt for a stock order once it reaches
|
||||
* DELIVERED_TO_AGENT: GOLD_GRAM debt = order.totalGoldWeightGrams, RIAL debt
|
||||
* = order.flatRialCharge. Both entries are self-confirming — the status
|
||||
* transition itself is the confirming event (mirrors legacy sts>4, which
|
||||
* first becomes true at sts=5 "تحویل مسئول فروش" / delivered to agent, not
|
||||
* sts=6 delivered to customer).
|
||||
* Brings an order's debt in line with its status — legacy's rule exactly.
|
||||
*
|
||||
* Legacy never "posted" order debt; it RECOMPUTED it
|
||||
* (CustomerController::updateRemain): Σ orders.input WHERE sts > 4, i.e. an
|
||||
* order owes its full weight (and its rial charge) while it is delivered —
|
||||
* to the expert (5) or to the customer (6) — and nothing otherwise. So:
|
||||
* - moving into a delivered status twice never counts twice (ACC-03 /
|
||||
* MON-04: the old guard on `deliveredAt` let a second DELIVERED_TO_AGENT
|
||||
* post the debt again);
|
||||
* - going straight to DELIVERED_TO_CUSTOMER still creates the debt (the
|
||||
* old trigger fired only on DELIVERED_TO_AGENT, so that order owed nothing);
|
||||
* - moving back below delivered, or cancelling, takes it off again.
|
||||
*
|
||||
* It compares what the order SHOULD owe with the confirmed ORDER_STOCK
|
||||
* entries already on it and posts only the difference, as a confirmed
|
||||
* DEBIT or CREDIT — so it is idempotent and nothing is ever edited or
|
||||
* deleted (the ledger stays append-only). Entries imported from legacy carry
|
||||
* their orderId, so imported orders reconcile the same way.
|
||||
*/
|
||||
async postOrderDebt(orderId: string, tx: Tx = this.prisma) {
|
||||
async syncOrderDebt(orderId: string, tx: Tx = this.prisma) {
|
||||
const order = await tx.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new NotFoundException('Order not found');
|
||||
|
||||
await this.postEntry(
|
||||
{
|
||||
customerId: order.customerId,
|
||||
currency: LedgerCurrency.GOLD_GRAM,
|
||||
direction: LedgerDirection.DEBIT,
|
||||
sourceType: LedgerSourceType.ORDER_STOCK,
|
||||
amount: order.totalGoldWeightGrams,
|
||||
orderId: order.id,
|
||||
confirmed: true,
|
||||
note: 'Gold-weight debt on delivery',
|
||||
},
|
||||
tx,
|
||||
);
|
||||
const owes = OWING_STATUSES.includes(order.status);
|
||||
const targets: [LedgerCurrency, Prisma.Decimal, string][] = [
|
||||
[LedgerCurrency.GOLD_GRAM, owes ? new Prisma.Decimal(order.totalGoldWeightGrams) : ZERO, 'Gold-weight debt'],
|
||||
[LedgerCurrency.RIAL, owes ? new Prisma.Decimal(order.flatRialCharge) : ZERO, 'Flat Rial charge (e.g. stones)'],
|
||||
];
|
||||
|
||||
for (const [currency, should, label] of targets) {
|
||||
const posted = await tx.ledgerEntry.groupBy({
|
||||
by: ['direction'],
|
||||
where: { orderId, currency, sourceType: LedgerSourceType.ORDER_STOCK, confirmed: true },
|
||||
_sum: { amount: true },
|
||||
});
|
||||
const sum = (d: LedgerDirection) => posted.find((p) => p.direction === d)?._sum.amount ?? ZERO;
|
||||
const current = new Prisma.Decimal(sum(LedgerDirection.DEBIT)).sub(sum(LedgerDirection.CREDIT));
|
||||
const diff = should.sub(current);
|
||||
if (diff.isZero()) continue;
|
||||
|
||||
if (new Prisma.Decimal(order.flatRialCharge).gt(0)) {
|
||||
await this.postEntry(
|
||||
{
|
||||
customerId: order.customerId,
|
||||
currency: LedgerCurrency.RIAL,
|
||||
direction: LedgerDirection.DEBIT,
|
||||
currency,
|
||||
direction: diff.gt(0) ? LedgerDirection.DEBIT : LedgerDirection.CREDIT,
|
||||
sourceType: LedgerSourceType.ORDER_STOCK,
|
||||
amount: order.flatRialCharge,
|
||||
amount: diff.abs(),
|
||||
orderId: order.id,
|
||||
confirmed: true,
|
||||
note: 'Flat Rial charge (e.g. stones) on delivery',
|
||||
note: owes ? `${label} — order delivered (${order.status})` : `${label} reversed — order moved to ${order.status}`,
|
||||
},
|
||||
tx,
|
||||
);
|
||||
|
||||
@@ -16,7 +16,16 @@ export class AdminCitiesController {
|
||||
@HttpCode(200)
|
||||
async list() {
|
||||
const cities = await this.prisma.city.findMany({ orderBy: { name: 'asc' } });
|
||||
// legacy shape: { id, title }
|
||||
return { rows: cities.map((c) => ({ id: c.id, title: c.name, province: c.province })) };
|
||||
// legacy shape: the cities row — { id, title, parent, percent, percent_aux }.
|
||||
// `parent` lets the admin pickers draw legacy's tree (PERS-02).
|
||||
return {
|
||||
rows: cities.map((c) => ({
|
||||
id: c.id,
|
||||
title: c.name,
|
||||
parent: c.parentId,
|
||||
percent: c.percent,
|
||||
percent_aux: c.percentAux,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,23 @@ export type OmdeScope = 'all' | 'banker' | 'shopkeeper' | 'non_verified' | 'arch
|
||||
* `sts_verify_step_one !== 2`, i.e. only an ACCEPTED first step unlocks them.
|
||||
* The new schema models one ordered enum, so these numbers are derived from it.
|
||||
*/
|
||||
/**
|
||||
* PERS-03: the birth date both customer forms collect (legacy bulkCustomer
|
||||
* `birth_date`, singleCustomer `birth_day`). DateInput sends the Gregorian
|
||||
* 'YYYY-MM-DD' of the Jalali date picked; stored at UTC midnight, as the
|
||||
* import stores legacy's. undefined = not sent (leave as is), '' = cleared.
|
||||
*/
|
||||
function birthDateOrNull(raw: unknown): Date | null | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
if (raw === null || String(raw).trim() === '') return null;
|
||||
const m = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(String(raw).trim());
|
||||
const d = m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])) : null;
|
||||
if (!d || d.getUTCMonth() !== +m![2] - 1 || d.getUTCFullYear() < 1900 || d > new Date()) {
|
||||
throw new BadRequestException('تاریخ تولد معتبر نیست');
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* A national code as the operator typed it, digits normalised; empty -> null.
|
||||
* The column is optional and unique (2026-10-07): an absent code is NULL,
|
||||
@@ -344,6 +361,9 @@ export class AdminCustomersService {
|
||||
zone: c.zone,
|
||||
pasazh_name: c.pasazhName,
|
||||
mcode: c.memberCode,
|
||||
// Both legacy names: bulkCustomer reads birth_date, singleCustomer birth_day.
|
||||
birth_date: c.birthDate ? c.birthDate.toISOString().slice(0, 10) : null,
|
||||
birth_day: c.birthDate ? c.birthDate.toISOString().slice(0, 10) : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -650,6 +670,7 @@ export class AdminCustomersService {
|
||||
nationalCode: null,
|
||||
passwordHash: OTP_ONLY_PASSWORD_HASH,
|
||||
cityId: (data.city_id as string) || null,
|
||||
birthDate: birthDateOrNull(data.birth_day ?? data.birth_date) ?? null,
|
||||
kind: CustomerKind.RETAIL,
|
||||
},
|
||||
});
|
||||
@@ -726,6 +747,7 @@ export class AdminCustomersService {
|
||||
pasazhName: (data.pasazh_name as string) ?? null,
|
||||
zone: (data.zone as string) ?? null,
|
||||
memberCode: (data.mcode as string) ?? null,
|
||||
birthDate: birthDateOrNull(data.birth_date ?? data.birth_day) ?? null,
|
||||
// legacy `image_id` from MyUpload's `ok` payload
|
||||
avatarFileId: (data.image_id as string) || null,
|
||||
// The three document photos the wholesale form collects. These were
|
||||
@@ -802,6 +824,8 @@ export class AdminCustomersService {
|
||||
if (data.pasazh_name !== undefined) patch.pasazhName = String(data.pasazh_name);
|
||||
if (data.zone !== undefined) patch.zone = String(data.zone);
|
||||
if (data.mcode !== undefined) patch.memberCode = String(data.mcode);
|
||||
const birthDate = birthDateOrNull(data.birth_date !== undefined ? data.birth_date : data.birth_day);
|
||||
if (birthDate !== undefined) patch.birthDate = birthDate;
|
||||
if (data.reagent_id !== undefined) {
|
||||
patch.referredByAgent = data.reagent_id
|
||||
? { connect: { id: String(data.reagent_id) } }
|
||||
|
||||
@@ -3,6 +3,7 @@ import { LedgerCurrency, LedgerDirection, LedgerSourceType, Prisma } from '@pris
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { TableService } from '../admin-table/table.service';
|
||||
import { LedgerService } from '../accounting/ledger.service';
|
||||
import { SmsService } from '../sms/sms.service';
|
||||
import type { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
|
||||
/**
|
||||
@@ -62,6 +63,7 @@ export class AdminDocumentsService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly table: TableService,
|
||||
private readonly ledger: LedgerService,
|
||||
private readonly sms: SmsService,
|
||||
) {}
|
||||
|
||||
private static readonly ALLOWED = [
|
||||
@@ -313,6 +315,7 @@ export class AdminDocumentsService {
|
||||
|
||||
if (!e.confirmed) {
|
||||
await this.ledger.confirmEntry(id, adminUserId);
|
||||
this.notifyDocumentConfirm(e.customerId, true);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
@@ -335,9 +338,24 @@ export class AdminDocumentsService {
|
||||
});
|
||||
});
|
||||
|
||||
this.notifyDocumentConfirm(e.customerId, false);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
// Legacy CashController::toggleConfiremCash sent an SMS on both outcomes.
|
||||
private notifyDocumentConfirm(customerId: string, confirmed: boolean) {
|
||||
const text = confirmed
|
||||
? 'هنزا گلد\nسند مالی شما توسط مدیر سیستم تایید شد.'
|
||||
: 'هنزا گلد\nسند مالی شما توسط مدیر سیستم رد شد.';
|
||||
|
||||
this.prisma.customer
|
||||
.findUnique({ where: { id: customerId }, select: { mobile: true } })
|
||||
.then((c) => {
|
||||
if (c) this.sms.send(c.mobile, text);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy `DELETE cash/{id}`.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { AdminMiscService } from './admin-misc.service';
|
||||
|
||||
/** Cities as a tree (PERS-02): legacy's percent inheritance and loop guard. */
|
||||
describe('AdminMiscService — city tree', () => {
|
||||
type Row = { id: string; parentId: string | null; percent: Prisma.Decimal | null; percentAux: Prisma.Decimal | null };
|
||||
const D = (v: number) => new Prisma.Decimal(v);
|
||||
let rows: Map<string, Row>;
|
||||
let service: AdminMiscService;
|
||||
let update: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
// ایران > استان تهران > تهران > تهران شمال
|
||||
rows = new Map(
|
||||
[
|
||||
{ id: 'iran', parentId: null, percent: null, percentAux: null },
|
||||
{ id: 'prov', parentId: 'iran', percent: D(10.12), percentAux: D(10.12) },
|
||||
{ id: 'teh', parentId: 'prov', percent: D(0), percentAux: D(8) },
|
||||
{ id: 'north', parentId: 'teh', percent: null, percentAux: null },
|
||||
].map((r) => [r.id, r]),
|
||||
);
|
||||
update = jest.fn(async ({ where, data }) => ({ ...rows.get(where.id), ...data }));
|
||||
const prisma = {
|
||||
city: {
|
||||
findUnique: jest.fn(async ({ where }) => rows.get(where.id) ?? null),
|
||||
update,
|
||||
},
|
||||
};
|
||||
service = new AdminMiscService(prisma as never, {} as never, {} as never);
|
||||
});
|
||||
|
||||
it('a city without its own percent takes the nearest ancestor’s (legacy _getP)', async () => {
|
||||
expect(String(await service.getCityPercent('north', true))).toBe('8');
|
||||
// 0 counts as "none", as legacy's `> 0`: تهران has 0, so استان تهران's.
|
||||
expect(String(await service.getCityPercent('north', false))).toBe('10.12');
|
||||
});
|
||||
|
||||
it('0 when no ancestor has one', async () => {
|
||||
expect(await service.getCityPercent('iran', false)).toBe(0);
|
||||
});
|
||||
|
||||
it('refuses to put a city under its own descendant', async () => {
|
||||
await expect(service.updateCity('teh', { parent: 'north' })).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(service.updateCity('teh', { parent: 'teh' })).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('moves a city and clears a parent', async () => {
|
||||
await service.updateCity('north', { parent: 'prov' });
|
||||
expect(update).toHaveBeenLastCalledWith({ where: { id: 'north' }, data: { parentId: 'prov' } });
|
||||
await service.updateCity('north', { parent: '' });
|
||||
expect(update).toHaveBeenLastCalledWith({ where: { id: 'north' }, data: { parentId: null } });
|
||||
});
|
||||
|
||||
it('refuses an unknown parent', async () => {
|
||||
await expect(service.updateCity('north', { parent: 'nope' })).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
import { CurrentAdmin, RequirePermission } from '../auth/guards';
|
||||
import type { AuthenticatedAdmin } from '../auth/jwt.strategy';
|
||||
import { isAccountingSettingKey } from '../accounting-sync/accounting-config';
|
||||
import { PRICING_SETTING_PREFIX } from '../pricing/wage.service';
|
||||
|
||||
/**
|
||||
* Cities, SMS, notifications, newsletter, activity log and settings — the
|
||||
@@ -34,7 +35,7 @@ export class AdminMiscController {
|
||||
@Post('cities')
|
||||
@HttpCode(200)
|
||||
@RequirePermission('cities.create')
|
||||
createCity(@Body() data: { title?: string; name?: string; province?: string }) {
|
||||
createCity(@Body() data: Record<string, never>) {
|
||||
return this.misc.createCity(data);
|
||||
}
|
||||
|
||||
@@ -228,7 +229,7 @@ export class AdminMiscController {
|
||||
// `custom.config.statics.slider`) simply by calling `const/mobile_main_slider`
|
||||
// directly, since the underlying Setting row is keyed the same either way.
|
||||
private assertNotSliderKey(key: string) {
|
||||
if (key === 'mobile_main_slider' || isAccountingSettingKey(key)) {
|
||||
if (key === 'mobile_main_slider' || isAccountingSettingKey(key) || key.trim().toLowerCase().startsWith(PRICING_SETTING_PREFIX)) {
|
||||
throw new ForbiddenException('این تنظیم فقط از مسیر اختصاصی خود قابل دسترسی است');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/comm
|
||||
import { MessageAudience, Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { TableService } from '../admin-table/table.service';
|
||||
import { SmsService } from '../sms/sms.service';
|
||||
import type { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
import { ACCOUNTING_SETTING_PREFIX } from '../accounting-sync/accounting-config';
|
||||
import { PRICING_SETTING_PREFIX } from '../pricing/wage.service';
|
||||
|
||||
/**
|
||||
* The remaining admin screens — legacy views/city, views/sms, views/notify,
|
||||
@@ -22,17 +24,21 @@ export class AdminMiscService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly table: TableService,
|
||||
private readonly sms: SmsService,
|
||||
) {}
|
||||
|
||||
// ── Cities ─────────────────────────────────────────────────────────
|
||||
//
|
||||
// Legacy cities are a tree (country > province > city > district) and so are
|
||||
// the target's again (PERS-02): each city may hang under a `parent`.
|
||||
|
||||
/** Legacy `POST cities/list` grid. */
|
||||
async listCities(query: TableQueryDto) {
|
||||
this.table.assertNotExport(query);
|
||||
|
||||
const { where, orderBy, skip, take, page, limit } = this.table.build(query, {
|
||||
searchable: ['name', 'province'],
|
||||
allowed: ['id', 'name', 'province', 'percent', 'percentAux'],
|
||||
searchable: ['name'],
|
||||
allowed: ['id', 'name', 'parentId', 'percent', 'percentAux'],
|
||||
defaultOrderBy: { name: 'asc' },
|
||||
});
|
||||
|
||||
@@ -42,7 +48,10 @@ export class AdminMiscService {
|
||||
orderBy: orderBy as Prisma.CityOrderByWithRelationInput,
|
||||
skip,
|
||||
take,
|
||||
include: { _count: { select: { customers: true, branches: true } } },
|
||||
include: {
|
||||
parent: { select: { id: true, name: true } },
|
||||
_count: { select: { customers: true, branches: true, children: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.city.count({ where: where as Prisma.CityWhereInput }),
|
||||
]);
|
||||
@@ -52,11 +61,13 @@ export class AdminMiscService {
|
||||
id: c.id,
|
||||
title: c.name,
|
||||
name: c.name,
|
||||
province: c.province,
|
||||
parent: c.parentId,
|
||||
parent_title: c.parent?.name ?? null,
|
||||
percent: c.percent,
|
||||
percent_aux: c.percentAux,
|
||||
customers_count: c._count.customers,
|
||||
branches_count: c._count.branches,
|
||||
children_count: c._count.children,
|
||||
})),
|
||||
total,
|
||||
query,
|
||||
@@ -65,33 +76,82 @@ export class AdminMiscService {
|
||||
);
|
||||
}
|
||||
|
||||
/** Legacy `POST cities`. */
|
||||
async createCity(data: { title?: string; name?: string; province?: string }) {
|
||||
const name = String(data.title ?? data.name ?? '').trim();
|
||||
if (!name) throw new BadRequestException('نام شهر الزامی است');
|
||||
return this.prisma.city.create({ data: { name, province: data.province ?? null } });
|
||||
/**
|
||||
* The parent a create/update asks for: `parent` (legacy's field name) or
|
||||
* `parent_id`; empty means top level. Refuses an unknown city, the city
|
||||
* itself, or one of its own descendants (that would make a loop).
|
||||
*/
|
||||
private async resolveCityParent(
|
||||
data: { parent?: unknown; parent_id?: unknown },
|
||||
selfId?: string,
|
||||
): Promise<string | null | undefined> {
|
||||
const raw = data.parent !== undefined ? data.parent : data.parent_id;
|
||||
if (raw === undefined) return undefined;
|
||||
if (raw === null || String(raw).trim() === '') return null;
|
||||
const parentId = String(raw).trim();
|
||||
|
||||
// Walk up from the requested parent; meeting selfId means a loop.
|
||||
let cur: string | null = parentId;
|
||||
for (let guard = 0; cur && guard < 50; guard++) {
|
||||
if (cur === selfId) throw new BadRequestException('شهر نمیتواند زیرمجموعهی خودش باشد.');
|
||||
const row: { parentId: string | null } | null = await this.prisma.city.findUnique({
|
||||
where: { id: cur },
|
||||
select: { parentId: true },
|
||||
});
|
||||
if (!row) {
|
||||
if (cur === parentId) throw new BadRequestException('والد انتخابشده پیدا نشد.');
|
||||
break;
|
||||
}
|
||||
cur = row.parentId;
|
||||
}
|
||||
return parentId;
|
||||
}
|
||||
|
||||
/** Legacy `PUT cities/{id}` — the grid's inline edit also sets the percents. */
|
||||
private static cityPercent(v: unknown): Prisma.Decimal | null | undefined {
|
||||
if (v === undefined) return undefined;
|
||||
if (v === null || String(v).trim() === '') return null;
|
||||
try {
|
||||
return new Prisma.Decimal(String(v));
|
||||
} catch {
|
||||
throw new BadRequestException('درصد باید عدد باشد.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Legacy `POST cities` — name, parent and the two percents. */
|
||||
async createCity(data: { title?: string; name?: string; parent?: unknown; parent_id?: unknown; percent?: unknown; percent_aux?: unknown }) {
|
||||
const name = String(data.title ?? data.name ?? '').trim();
|
||||
if (!name) throw new BadRequestException('نام شهر الزامی است');
|
||||
const parentId = await this.resolveCityParent(data);
|
||||
return this.prisma.city.create({
|
||||
data: {
|
||||
name,
|
||||
parentId: parentId ?? null,
|
||||
percent: AdminMiscService.cityPercent(data.percent) ?? null,
|
||||
percentAux: AdminMiscService.cityPercent(data.percent_aux) ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Legacy `PUT cities/{id}` — name, parent and the two percents. */
|
||||
async updateCity(
|
||||
id: string,
|
||||
data: { title?: string; name?: string; province?: string; percent?: unknown; percent_aux?: unknown },
|
||||
data: { title?: string; name?: string; parent?: unknown; parent_id?: unknown; percent?: unknown; percent_aux?: unknown },
|
||||
) {
|
||||
const existing = await this.prisma.city.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('شهر یافت نشد');
|
||||
|
||||
const patch: Prisma.CityUpdateInput = {};
|
||||
const patch: Prisma.CityUncheckedUpdateInput = {};
|
||||
if (data.title !== undefined || data.name !== undefined) {
|
||||
patch.name = String(data.title ?? data.name);
|
||||
}
|
||||
if (data.province !== undefined) patch.province = data.province ?? null;
|
||||
if (data.percent !== undefined) {
|
||||
patch.percent = data.percent === null ? null : new Prisma.Decimal(String(data.percent));
|
||||
}
|
||||
if (data.percent_aux !== undefined) {
|
||||
patch.percentAux =
|
||||
data.percent_aux === null ? null : new Prisma.Decimal(String(data.percent_aux));
|
||||
const name = String(data.title ?? data.name ?? '').trim();
|
||||
if (!name) throw new BadRequestException('نام شهر الزامی است');
|
||||
patch.name = name;
|
||||
}
|
||||
const parentId = await this.resolveCityParent(data, id);
|
||||
if (parentId !== undefined) patch.parentId = parentId;
|
||||
const percent = AdminMiscService.cityPercent(data.percent);
|
||||
if (percent !== undefined) patch.percent = percent;
|
||||
const percentAux = AdminMiscService.cityPercent(data.percent_aux);
|
||||
if (percentAux !== undefined) patch.percentAux = percentAux;
|
||||
|
||||
return this.prisma.city.update({ where: { id }, data: patch });
|
||||
}
|
||||
@@ -99,16 +159,19 @@ export class AdminMiscService {
|
||||
/**
|
||||
* Legacy `DELETE cities/{id}`.
|
||||
*
|
||||
* Refuses while customers or branches still point at the city — legacy deleted
|
||||
* regardless, orphaning those rows.
|
||||
* Refuses while customers, branches or child cities still point at the city —
|
||||
* legacy deleted regardless, orphaning those rows.
|
||||
*/
|
||||
async removeCity(id: string) {
|
||||
const c = await this.prisma.city.findUnique({
|
||||
where: { id },
|
||||
include: { _count: { select: { customers: true, branches: true, addresses: true } } },
|
||||
include: { _count: { select: { customers: true, branches: true, addresses: true, children: true } } },
|
||||
});
|
||||
if (!c) throw new NotFoundException('شهر یافت نشد');
|
||||
|
||||
if (c._count.children > 0) {
|
||||
throw new BadRequestException(`حذف این شهر ممکن نیست، چون ${c._count.children} شهر زیرمجموعهی آن است.`);
|
||||
}
|
||||
const refs = c._count.customers + c._count.branches + c._count.addresses;
|
||||
if (refs > 0) {
|
||||
throw new BadRequestException(
|
||||
@@ -119,11 +182,28 @@ export class AdminMiscService {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** Legacy `GET cities/get-percent/{id}` — returns the bare number. */
|
||||
/**
|
||||
* Legacy `GET cities/get-percent/{id}` — returns the bare number. As legacy's
|
||||
* CitiesController::_getP: a city without its own percent (null or 0) takes
|
||||
* its parent's, and so on up; 0 when no ancestor has one.
|
||||
*/
|
||||
async getCityPercent(id: string, aux: boolean) {
|
||||
const c = await this.prisma.city.findUnique({ where: { id } });
|
||||
if (!c) throw new NotFoundException('شهر یافت نشد');
|
||||
return aux ? c.percentAux : c.percent;
|
||||
let cur: string | null = id;
|
||||
for (let guard = 0; cur && guard < 50; guard++) {
|
||||
const c: { parentId: string | null; percent: Prisma.Decimal | null; percentAux: Prisma.Decimal | null } | null =
|
||||
await this.prisma.city.findUnique({
|
||||
where: { id: cur },
|
||||
select: { parentId: true, percent: true, percentAux: true },
|
||||
});
|
||||
if (!c) {
|
||||
if (cur === id) throw new NotFoundException('شهر یافت نشد');
|
||||
break;
|
||||
}
|
||||
const v = aux ? c.percentAux : c.percent;
|
||||
if (v !== null && v.gt(0)) return v;
|
||||
cur = c.parentId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ── SMS ────────────────────────────────────────────────────────────
|
||||
@@ -167,12 +247,9 @@ export class AdminMiscService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy `POST sms` — records the send.
|
||||
*
|
||||
* NOTE no SMS gateway is wired up: legacy handed the message to an external
|
||||
* provider, and this port has no credentials for one. The message is stored
|
||||
* with the audience it resolved to, so the log is accurate, but nothing is
|
||||
* actually transmitted. Flagged in docs/ADMIN-PORT-PLAN.md.
|
||||
* Legacy `POST sms` — resolves the audience, substitutes `%name` per
|
||||
* recipient (legacy SmsController::batch + replaceName), delivers via the
|
||||
* configured gateway (D26 relay), and records the send.
|
||||
*/
|
||||
async sendSms(
|
||||
data: { type?: string | number; mobile?: string; text?: string },
|
||||
@@ -184,6 +261,18 @@ export class AdminMiscService {
|
||||
const audience = this.resolveAudience(data.type);
|
||||
const recipients = await this.resolveRecipients(audience, data.mobile);
|
||||
|
||||
const needsNameSub = body.includes('%name');
|
||||
const customersByMobile = needsNameSub
|
||||
? await this.customerNamesByMobile(recipients)
|
||||
: new Map<string, string>();
|
||||
|
||||
for (const mobile of recipients) {
|
||||
const text = needsNameSub
|
||||
? body.replace(/%name/g, customersByMobile.get(mobile) ?? 'مشتری عزیز')
|
||||
: body;
|
||||
this.sms.send(mobile, text, { audience });
|
||||
}
|
||||
|
||||
return this.prisma.smsMessage.create({
|
||||
data: {
|
||||
audience,
|
||||
@@ -195,6 +284,18 @@ export class AdminMiscService {
|
||||
});
|
||||
}
|
||||
|
||||
private async customerNamesByMobile(mobiles: string[]): Promise<Map<string, string>> {
|
||||
const rows = await this.prisma.customer.findMany({
|
||||
where: { mobile: { in: mobiles } },
|
||||
select: { mobile: true, fullName: true },
|
||||
});
|
||||
const map = new Map<string, string>();
|
||||
for (const r of rows) {
|
||||
if (r.fullName) map.set(r.mobile, r.fullName + ' عزیز');
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy's numeric audience codes, read off views/sms/create.vue where each
|
||||
* option is gated by its own rid:
|
||||
@@ -482,7 +583,7 @@ export class AdminMiscService {
|
||||
// lease) have their own `config.accounting` screen and never appear here
|
||||
// (D27); the single-key routes refuse them in the controller.
|
||||
const rows = await this.prisma.setting.findMany({
|
||||
where: { NOT: { key: { startsWith: ACCOUNTING_SETTING_PREFIX } } },
|
||||
where: { AND: [{ NOT: { key: { startsWith: ACCOUNTING_SETTING_PREFIX } } }, { NOT: { key: { startsWith: PRICING_SETTING_PREFIX } } }] },
|
||||
orderBy: { key: 'asc' },
|
||||
});
|
||||
return rows.map((r) => ({ key: r.key, value: r.value, updated_at: r.updatedAt }));
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../prisma/prisma.module';
|
||||
import { OrdersModule } from '../orders/orders.module';
|
||||
import { AccountingModule } from '../accounting/accounting.module';
|
||||
import { AdminOrdersController } from './admin-orders.controller';
|
||||
import { AdminOrdersService } from './admin-orders.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, OrdersModule],
|
||||
imports: [PrismaModule, OrdersModule, AccountingModule],
|
||||
controllers: [AdminOrdersController],
|
||||
providers: [AdminOrdersService],
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { TableService } from '../admin-table/table.service';
|
||||
import type { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
import { AccountingHooksService } from '../accounting-sync/accounting-hooks.service';
|
||||
import { OrdersService } from '../orders/orders.service';
|
||||
import { LedgerService } from '../accounting/ledger.service';
|
||||
import type { UpdateOrderStatusDto } from './update-status.dto';
|
||||
|
||||
/**
|
||||
@@ -42,6 +43,7 @@ export class AdminOrdersService {
|
||||
private readonly table: TableService,
|
||||
private readonly orders: OrdersService,
|
||||
private readonly accounting: AccountingHooksService,
|
||||
private readonly ledger: LedgerService,
|
||||
) {}
|
||||
|
||||
/** Fields the XTable filter bar and sorter may reference. */
|
||||
@@ -371,8 +373,8 @@ export class AdminOrdersService {
|
||||
* Legacy `POST single/order-sts/edit` — advance or remove a status.
|
||||
*
|
||||
* Setting a status delegates to OrdersService.updateStatus rather than writing
|
||||
* the row here, because that method also posts the gold debt to the ledger at
|
||||
* DELIVERED_TO_AGENT. Duplicating the update would silently skip that.
|
||||
* the row here, because that method also keeps the order's debt in line with its status
|
||||
* (syncOrderDebt). Duplicating the update would silently skip that.
|
||||
*/
|
||||
async setStatus(dto: UpdateOrderStatusDto, actorAdminUserId: string) {
|
||||
if (dto.remove) {
|
||||
@@ -384,35 +386,33 @@ export class AdminOrdersService {
|
||||
/**
|
||||
* Legacy's `remove: true` branch: drop a recorded status event.
|
||||
*
|
||||
* Deliberately refuses to remove DELIVERED_TO_AGENT. In legacy, deleting that
|
||||
* row left the posted debt ledger entries behind, so the customer stayed in
|
||||
* debt for an order no longer marked delivered. Rather than reproduce a
|
||||
* data-corrupting path, this rejects and explains — recorded in
|
||||
* docs/ADMIN-PORT-PLAN.md.
|
||||
* Any status may be removed, as in legacy (MajorOrderController.php:180-203),
|
||||
* which stepped `sts` back and then RECOMPUTED the debt (updateRemain). The
|
||||
* rollback below does the same through syncOrderDebt, so taking an order
|
||||
* back below «تحویل به نماینده» takes its debt off, and nothing is left
|
||||
* behind. (This used to be refused, on the belief that legacy left the debt
|
||||
* in place; legacy recomputed it.)
|
||||
*/
|
||||
private async removeStatusEvent(orderId: string, status: OrderStatus) {
|
||||
if (status === OrderStatus.DELIVERED_TO_AGENT) {
|
||||
throw new BadRequestException(
|
||||
'حذف وضعیت «تحویل به نماینده» ممکن نیست، چون بدهی طلا در همین مرحله ثبت شده است.',
|
||||
);
|
||||
}
|
||||
|
||||
const event = await this.prisma.orderStatusEvent.findFirst({
|
||||
where: { orderId, toStatus: status },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
if (!event) throw new NotFoundException('وضعیت مورد نظر یافت نشد');
|
||||
|
||||
await this.prisma.orderStatusEvent.delete({ where: { id: event.id } });
|
||||
|
||||
// Roll the order back to whatever status is now the latest recorded one.
|
||||
const latest = await this.prisma.orderStatusEvent.findFirst({
|
||||
where: { orderId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const rolledBackTo = latest?.toStatus ?? OrderStatus.PLACED;
|
||||
// One transaction: the event, the status and the debt move together or not at all.
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.orderStatusEvent.delete({ where: { id: event.id } });
|
||||
|
||||
// Roll the order back to whatever status is now the latest recorded one.
|
||||
const latest = await tx.orderStatusEvent.findFirst({
|
||||
where: { orderId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const rolledBackTo = latest?.toStatus ?? OrderStatus.PLACED;
|
||||
const updated = await tx.order.update({ where: { id: orderId }, data: { status: rolledBackTo } });
|
||||
// Legacy updateRemain after the step back: the debt follows the status.
|
||||
await this.ledger.syncOrderDebt(orderId, tx);
|
||||
// D27 — rolled back below the document rule: the پیشفاکتور is withdrawn.
|
||||
await this.accounting.orderStatusReached(tx, orderId, rolledBackTo);
|
||||
return updated;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { AdminReportService } from './admin-report.service';
|
||||
import { RequirePermission } from '../auth/guards';
|
||||
|
||||
/**
|
||||
* Legacy `GET report/get-order-item-with-details` — a combined order-item +
|
||||
* financial-document Excel export with 32 Persian-header columns, date-filtered.
|
||||
*/
|
||||
@Controller('admin/report')
|
||||
export class AdminReportController {
|
||||
constructor(private readonly report: AdminReportService) {}
|
||||
|
||||
@Get('order-items')
|
||||
@RequirePermission('report.order.item')
|
||||
getOrderItemReport(
|
||||
@Query('start_date') startDate?: string,
|
||||
@Query('end_date') endDate?: string,
|
||||
) {
|
||||
return this.report.getOrderItemReport(startDate, endDate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../prisma/prisma.module';
|
||||
import { AdminReportController } from './admin-report.controller';
|
||||
import { AdminReportService } from './admin-report.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [AdminReportController],
|
||||
providers: [AdminReportService],
|
||||
})
|
||||
export class AdminReportModule {}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { BadRequestException, Injectable, StreamableFile } from '@nestjs/common';
|
||||
import { LedgerSourceType, Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { toJalali, formatJalali } from '../accounting-sync/jalali';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
|
||||
const TYPE_LABELS: Partial<Record<LedgerSourceType, string>> = {
|
||||
REPAYMENT_MELTED_GOLD: 'آب شده',
|
||||
REPAYMENT_TRANSFER: 'حواله',
|
||||
REPAYMENT_CHEQUE: 'چک',
|
||||
REPAYMENT_CASH: 'پولی',
|
||||
};
|
||||
|
||||
const REPAYMENT_TYPES: LedgerSourceType[] = [
|
||||
LedgerSourceType.REPAYMENT_MELTED_GOLD,
|
||||
LedgerSourceType.REPAYMENT_TRANSFER,
|
||||
LedgerSourceType.REPAYMENT_CHEQUE,
|
||||
LedgerSourceType.REPAYMENT_CASH,
|
||||
];
|
||||
|
||||
const HEADERS = [
|
||||
'کد آیتم',
|
||||
'نام محصول',
|
||||
'کد محصول',
|
||||
'عنوان تنوع',
|
||||
'وزن خام تحویل مشتری',
|
||||
'وزن نهایی با درصد',
|
||||
'تعداد',
|
||||
'درصد',
|
||||
'اجرت ریالی',
|
||||
'توضیحات',
|
||||
'شماره سفارش',
|
||||
'تاریخ ثبت',
|
||||
'تاریخ',
|
||||
'سال',
|
||||
'ماه',
|
||||
'روز',
|
||||
'ساعت',
|
||||
'شماره سند',
|
||||
'نوع سند',
|
||||
'میزان پول',
|
||||
'میزان گرم',
|
||||
'وضعیت سند',
|
||||
'نام مشتری',
|
||||
'نام خانوادگی مشتری',
|
||||
'نام و نام خانوادگی مشتری',
|
||||
'کارشناس فروش',
|
||||
'شماره موبایل مشتری',
|
||||
'آدرس',
|
||||
'تلفن مغازه',
|
||||
'بدهکار',
|
||||
'بستانکار',
|
||||
'بدهی ریالی',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminReportService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getOrderItemReport(startDate?: string, endDate?: string): Promise<StreamableFile> {
|
||||
const dateFilter: Prisma.DateTimeFilter = {};
|
||||
if (startDate) dateFilter.gte = parseDate(startDate, 'از تاریخ');
|
||||
if (endDate) {
|
||||
// The whole end day, as the on-screen report (admin-dashboard dateWhere).
|
||||
const end = parseDate(endDate, 'تا تاریخ');
|
||||
end.setHours(23, 59, 59, 999);
|
||||
dateFilter.lte = end;
|
||||
}
|
||||
const hasDateFilter = startDate || endDate;
|
||||
|
||||
const orderItems = await this.prisma.orderItem.findMany({
|
||||
where: hasDateFilter ? { order: { createdAt: dateFilter } } : undefined,
|
||||
orderBy: { id: 'desc' },
|
||||
include: {
|
||||
order: {
|
||||
include: {
|
||||
customer: true,
|
||||
salesAgent: true,
|
||||
},
|
||||
},
|
||||
productVariant: { include: { product: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const ledgerEntries = await this.prisma.ledgerEntry.findMany({
|
||||
where: {
|
||||
sourceType: { in: REPAYMENT_TYPES },
|
||||
...(hasDateFilter ? { createdAt: dateFilter } : {}),
|
||||
},
|
||||
include: { customer: true },
|
||||
});
|
||||
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet('گزارش', {
|
||||
views: [{ rightToLeft: true }],
|
||||
});
|
||||
|
||||
ws.columns = HEADERS.map((h) => ({ header: h, width: 18 }));
|
||||
|
||||
for (const item of orderItems) {
|
||||
const order = item.order;
|
||||
const customer = order.customer;
|
||||
const jalali = toJalali(order.createdAt);
|
||||
const jalaliStr = formatJalali(jalali, '/');
|
||||
const hour = new Date(order.createdAt.getTime() + 3.5 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(11, 16);
|
||||
|
||||
// computedWeightGrams is ONE unit's weight (OrdersService.createOrder
|
||||
// multiplies it by quantity for the order total), as legacy's order_items.w
|
||||
// is. Legacy's export divided it by qty again, so every multi-unit line
|
||||
// under-reported its weight; not repeated here.
|
||||
const perUnitWeight = Number(item.computedWeightGrams);
|
||||
// Legacy's «درصد» is the final percent: percent_pay − discount.
|
||||
const finalPercent = Number(item.wagePercentSnapshot.sub(item.discountPercentSnapshot));
|
||||
|
||||
for (let i = 0; i < item.quantity; i++) {
|
||||
ws.addRow([
|
||||
item.id,
|
||||
item.productVariant?.product?.title ?? '',
|
||||
item.productVariant?.product?.productCode ?? '',
|
||||
item.productVariant?.title ?? '',
|
||||
Number(item.rashWeightGramsSnapshot),
|
||||
round4(perUnitWeight),
|
||||
1,
|
||||
finalPercent,
|
||||
Number(item.flatRialCharge),
|
||||
'',
|
||||
order.orderNumber,
|
||||
jalaliStr,
|
||||
jalaliStr,
|
||||
jalali.jy,
|
||||
jalali.jm,
|
||||
jalali.jd,
|
||||
hour,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
customer.firstName ?? '',
|
||||
customer.lastName ?? '',
|
||||
customer.fullName,
|
||||
order.salesAgent?.fullName ?? '',
|
||||
customer.mobile,
|
||||
customer.address ?? '',
|
||||
customer.phone ?? '',
|
||||
round4(perUnitWeight),
|
||||
0,
|
||||
Number(item.flatRialCharge),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of ledgerEntries) {
|
||||
const customer = entry.customer;
|
||||
const jalali = toJalali(entry.createdAt);
|
||||
const jalaliStr = formatJalali(jalali, '/');
|
||||
const hour = new Date(entry.createdAt.getTime() + 3.5 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(11, 16);
|
||||
|
||||
const isCashOrCheque =
|
||||
entry.sourceType === LedgerSourceType.REPAYMENT_CASH ||
|
||||
entry.sourceType === LedgerSourceType.REPAYMENT_CHEQUE;
|
||||
const rialAmount = isCashOrCheque ? Number(entry.priceRial ?? 0) : 0;
|
||||
const gramAmount = !isCashOrCheque ? Number(entry.amount) : 0;
|
||||
|
||||
ws.addRow([
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
entry.orderId ?? '',
|
||||
jalaliStr,
|
||||
jalaliStr,
|
||||
jalali.jy,
|
||||
jalali.jm,
|
||||
jalali.jd,
|
||||
hour,
|
||||
entry.id,
|
||||
TYPE_LABELS[entry.sourceType] ?? '',
|
||||
rialAmount,
|
||||
gramAmount,
|
||||
entry.confirmed ? 'تایید شده' : 'تایید نشده',
|
||||
customer.firstName ?? '',
|
||||
customer.lastName ?? '',
|
||||
customer.fullName,
|
||||
null,
|
||||
customer.mobile,
|
||||
customer.address ?? '',
|
||||
customer.phone ?? '',
|
||||
0,
|
||||
gramAmount,
|
||||
0,
|
||||
]);
|
||||
}
|
||||
|
||||
const buffer = await wb.xlsx.writeBuffer();
|
||||
return new StreamableFile(Buffer.from(buffer), {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
disposition: 'attachment; filename="report.xlsx"',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function parseDate(v: string, field: string): Date {
|
||||
const d = new Date(v);
|
||||
if (Number.isNaN(d.getTime())) throw new BadRequestException(`${field}: تاریخ معتبر نیست`);
|
||||
return d;
|
||||
}
|
||||
|
||||
function round4(n: number): number {
|
||||
return Math.round(n * 10000) / 10000;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { AdminUsersService } from './admin-users.service';
|
||||
|
||||
/** SEC-07: a role's saved permissions are limited to rids the server knows. */
|
||||
describe('AdminUsersService.setRoles', () => {
|
||||
let createMany: jest.Mock;
|
||||
let service: AdminUsersService;
|
||||
|
||||
beforeEach(() => {
|
||||
createMany = jest.fn();
|
||||
const prisma = {
|
||||
userType: { findUnique: jest.fn(async () => ({ id: 90, permissions: [] })) },
|
||||
permission: { deleteMany: jest.fn(), createMany },
|
||||
$transaction: jest.fn(async () => []),
|
||||
};
|
||||
service = new AdminUsersService(prisma as never, {} as never, {} as never);
|
||||
});
|
||||
|
||||
it('keeps catalogue rids and their tree parents, drops anything else', async () => {
|
||||
await service.setRoles(90, [
|
||||
'order.list',
|
||||
'order', // tree parent of order.list
|
||||
'persons', // tree parent of persons.*
|
||||
'notify.create.single.customer', // legacy tree leaf no route checks
|
||||
'made.up.permission',
|
||||
'order.list', // duplicate
|
||||
'',
|
||||
]);
|
||||
const rows = createMany.mock.calls[0][0].data.map((d: { rid: string }) => d.rid);
|
||||
expect(rows.sort()).toEqual(['order', 'order.list', 'persons']);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { AdminRole, Prisma } from '@prisma/client';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
@@ -6,6 +6,18 @@ import { TableService } from '../admin-table/table.service';
|
||||
import { AdminSessionService } from '../sessions/admin-session.service';
|
||||
import type { TableQueryDto } from '../admin-table/table-query.dto';
|
||||
import { faToEn } from '../customer-auth/digits';
|
||||
import { ALL_RIDS } from '../auth/acl.constants';
|
||||
|
||||
/**
|
||||
* SEC-07: the rids a role may hold — every rid in the catalogue and each of
|
||||
* their tree parents ("persons", "order.omde", …), which the permission tree
|
||||
* posts when a whole branch is ticked.
|
||||
*/
|
||||
const STORABLE_RIDS: ReadonlySet<string> = new Set(
|
||||
(ALL_RIDS as readonly string[]).flatMap((rid) =>
|
||||
rid.split('.').map((_, i, parts) => parts.slice(0, i + 1).join('.')),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Admin users and the permission matrix — legacy views/user/*, served by
|
||||
@@ -22,6 +34,8 @@ import { faToEn } from '../customer-auth/digits';
|
||||
*/
|
||||
@Injectable()
|
||||
export class AdminUsersService {
|
||||
private readonly logger = new Logger(AdminUsersService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly table: TableService,
|
||||
@@ -449,7 +463,15 @@ export class AdminUsersService {
|
||||
const type = await this.prisma.userType.findUnique({ where: { id: userTypeId } });
|
||||
if (!type) throw new NotFoundException('سطح دسترسی یافت نشد');
|
||||
|
||||
const clean = [...new Set((rids ?? []).map((r) => String(r)).filter(Boolean))];
|
||||
const posted = [...new Set((rids ?? []).map((r) => String(r).trim()).filter(Boolean))];
|
||||
// SEC-07: only rids the server knows are stored. The rest grant nothing —
|
||||
// most are legacy tree leaves no route checks (e.g. notify.create.single.*)
|
||||
// — so they are dropped rather than failing the whole save.
|
||||
const clean = posted.filter((r) => STORABLE_RIDS.has(r));
|
||||
const dropped = posted.filter((r) => !STORABLE_RIDS.has(r));
|
||||
if (dropped.length) {
|
||||
this.logger.warn(`setRoles(${userTypeId}): ignored ${dropped.length} unknown rid(s): ${dropped.slice(0, 20).join(', ')}`);
|
||||
}
|
||||
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.permission.deleteMany({ where: { userTypeId } }),
|
||||
|
||||
@@ -34,6 +34,7 @@ export const ALL_RIDS = [
|
||||
'comment.view.edit',
|
||||
// D27 — «اتصال حسابداری» (Tahesab / Zarrin). Not a legacy rid.
|
||||
'config.accounting',
|
||||
'config.wage',
|
||||
'config.report',
|
||||
'config.statics',
|
||||
'config.statics.brand',
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Body, Controller, Get, HttpCode, Post } from '@nestjs/common';
|
||||
import { CurrentCustomer, CustomerAuth } from '../customer-auth/customer.guards';
|
||||
import type { AuthenticatedCustomer } from '../customer-auth/customer-jwt.strategy';
|
||||
import { CustomerFavoritesService } from './customer-favorites.service';
|
||||
import { ToggleFavoriteDto } from './dto/toggle-favorite.dto';
|
||||
|
||||
/**
|
||||
* Legacy endpoints (routes/api.php:84-85, customer guard):
|
||||
* POST add-to-fav -> POST customer/me/favorites/toggle
|
||||
* POST get-favorites -> GET customer/me/favorites
|
||||
* The customer always comes from the token (D21); for a sales expert that is
|
||||
* their trading account.
|
||||
*/
|
||||
@Controller('customer/me/favorites')
|
||||
export class CustomerFavoritesController {
|
||||
constructor(private readonly favorites: CustomerFavoritesService) {}
|
||||
|
||||
@CustomerAuth()
|
||||
@Get()
|
||||
list(@CurrentCustomer() me: AuthenticatedCustomer) {
|
||||
return this.favorites.list(me.id);
|
||||
}
|
||||
|
||||
@CustomerAuth()
|
||||
@Post('toggle')
|
||||
@HttpCode(200)
|
||||
toggle(@Body() dto: ToggleFavoriteDto, @CurrentCustomer() me: AuthenticatedCustomer) {
|
||||
return this.favorites.toggle(me.id, dto.productId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../../prisma/prisma.module';
|
||||
import { CustomerFavoritesController } from './customer-favorites.controller';
|
||||
import { CustomerFavoritesService } from './customer-favorites.service';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [CustomerFavoritesController],
|
||||
providers: [CustomerFavoritesService],
|
||||
})
|
||||
export class CustomerFavoritesModule {}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { CustomerFavoritesService } from './customer-favorites.service';
|
||||
|
||||
/** FAV-01 — favourites live on the server, toggled the way legacy did. */
|
||||
describe('CustomerFavoritesService', () => {
|
||||
function build(rows: { customerId: string; productId: string }[], products = ['p1', 'p2']) {
|
||||
const prisma = {
|
||||
customerFavorite: {
|
||||
findMany: jest.fn(async ({ where }: { where: { customerId: string } }) =>
|
||||
rows.filter((r) => r.customerId === where.customerId).map((r) => ({ productId: r.productId })),
|
||||
),
|
||||
deleteMany: jest.fn(async ({ where }: { where: { customerId: string; productId: string } }) => {
|
||||
const before = rows.length;
|
||||
rows.splice(0, rows.length, ...rows.filter((r) => !(r.customerId === where.customerId && r.productId === where.productId)));
|
||||
return { count: before - rows.length };
|
||||
}),
|
||||
upsert: jest.fn(async ({ create }: { create: { customerId: string; productId: string } }) => {
|
||||
rows.push(create);
|
||||
return create;
|
||||
}),
|
||||
},
|
||||
product: {
|
||||
findUnique: jest.fn(async ({ where }: { where: { id: string } }) => (products.includes(where.id) ? { id: where.id } : null)),
|
||||
},
|
||||
};
|
||||
return { service: new CustomerFavoritesService(prisma as never), rows };
|
||||
}
|
||||
|
||||
it('lists only the caller’s own favourites', async () => {
|
||||
const { service } = build([
|
||||
{ customerId: 'c1', productId: 'p1' },
|
||||
{ customerId: 'c2', productId: 'p2' },
|
||||
]);
|
||||
expect(await service.list('c1')).toEqual({ ids: ['p1'] });
|
||||
});
|
||||
|
||||
it('adds when absent and removes when present', async () => {
|
||||
const { service, rows } = build([]);
|
||||
expect(await service.toggle('c1', 'p1')).toEqual({ favorite: true });
|
||||
expect(rows).toEqual([{ customerId: 'c1', productId: 'p1' }]);
|
||||
expect(await service.toggle('c1', 'p1')).toEqual({ favorite: false });
|
||||
expect(rows).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses a product that does not exist', async () => {
|
||||
const { service } = build([]);
|
||||
await expect(service.toggle('c1', 'nope')).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
|
||||
/**
|
||||
* The customer's favourite products, kept on the server as legacy did
|
||||
* (`major_favorites`, ApiMobileController::toggleFavorite / getFavorites).
|
||||
* The apps used to keep them in memory only, so they vanished on reload and
|
||||
* the 874 favourites imported from legacy were never shown (FAV-01).
|
||||
*/
|
||||
@Injectable()
|
||||
export class CustomerFavoritesService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/**
|
||||
* Product ids, newest first (legacy: `orderBy('updated_at', 'DESC')`).
|
||||
* Legacy also hid inactive products; the apps render favourites from the
|
||||
* catalogue, which already lists only active ones, so ids are enough.
|
||||
*/
|
||||
async list(customerId: string) {
|
||||
const rows = await this.prisma.customerFavorite.findMany({
|
||||
where: { customerId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: { productId: true },
|
||||
});
|
||||
return { ids: rows.map((r) => r.productId) };
|
||||
}
|
||||
|
||||
/** Legacy toggle: delete if present, else add. Answers the new state. */
|
||||
async toggle(customerId: string, productId: string) {
|
||||
const key = { customerId_productId: { customerId, productId } };
|
||||
const removed = await this.prisma.customerFavorite.deleteMany({ where: { customerId, productId } });
|
||||
if (removed.count > 0) return { favorite: false };
|
||||
|
||||
const product = await this.prisma.product.findUnique({ where: { id: productId }, select: { id: true } });
|
||||
if (!product) throw new NotFoundException('محصول یافت نشد');
|
||||
// upsert, so a double tap racing itself cannot fail on the primary key.
|
||||
await this.prisma.customerFavorite.upsert({ where: key, create: { customerId, productId }, update: {} });
|
||||
return { favorite: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsNotEmpty, IsString, MaxLength } from 'class-validator';
|
||||
|
||||
/** Legacy `POST add-to-fav` sent `{ id }`; the product id here is explicit. */
|
||||
export class ToggleFavoriteDto {
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'شناسهی محصول الزامی است' })
|
||||
@MaxLength(64)
|
||||
productId!: string;
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export class OrdersController {
|
||||
@CustomerAuth()
|
||||
@Post()
|
||||
create(@Body() dto: CreateOrderDto, @CurrentCustomer() me: AuthenticatedCustomer) {
|
||||
return this.orders.createOrder(dto, me.id);
|
||||
return this.orders.createOrder(dto, me.id, { placedBy: 'customer' });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,9 +3,10 @@ import { OrdersService } from './orders.service';
|
||||
import { OrdersController } from './orders.controller';
|
||||
import { CatalogModule } from '../catalog/catalog.module';
|
||||
import { AccountingModule } from '../accounting/accounting.module';
|
||||
import { PricingModule } from '../pricing/pricing.module';
|
||||
|
||||
@Module({
|
||||
imports: [CatalogModule, AccountingModule],
|
||||
imports: [CatalogModule, AccountingModule, PricingModule],
|
||||
controllers: [OrdersController],
|
||||
providers: [OrdersService],
|
||||
exports: [OrdersService],
|
||||
|
||||
@@ -30,7 +30,8 @@ describe('OrdersService.createOrder — sales expert credit', () => {
|
||||
};
|
||||
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
|
||||
const accounting = { orderStatusReached: jest.fn() };
|
||||
const service = new OrdersService(prisma as never, catalog as never, {} as never, accounting as never);
|
||||
const wage = { quote: jest.fn() };
|
||||
const service = new OrdersService(prisma as never, catalog as never, {} as never, accounting as never, wage as never);
|
||||
return { service, created };
|
||||
}
|
||||
|
||||
@@ -48,3 +49,73 @@ describe('OrdersService.createOrder — sales expert credit', () => {
|
||||
expect(created[0].salesAgentId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/** A server quote of 10% for every variant. */
|
||||
const wageStub = {
|
||||
quote: jest.fn(async (_c: string, ids: string[]) => new Map(ids.map((id) => [id, { wagePercentSnapshot: '10', discountPercentSnapshot: '0' }]))),
|
||||
};
|
||||
|
||||
/** MON-05 (owner ruling 2026-10-08): «عدم سفارش» stops app orders only. */
|
||||
describe('OrdersService.createOrder — order ban', () => {
|
||||
function build(canPlaceOrders: boolean) {
|
||||
const tx = { order: { create: jest.fn(async ({ data }: { data: object }) => ({ id: 'o1', ...data })) } };
|
||||
const prisma = {
|
||||
customer: {
|
||||
findUnique: jest.fn(async () => ({
|
||||
id: 'c1',
|
||||
canPlaceOrders,
|
||||
referredByAgentId: null,
|
||||
goldDebtGrams: new Prisma.Decimal(0),
|
||||
goldCreditLimitGrams: new Prisma.Decimal(1000),
|
||||
})),
|
||||
},
|
||||
$transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)),
|
||||
};
|
||||
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
|
||||
return new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never);
|
||||
}
|
||||
const dto = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 3 }] } as never;
|
||||
|
||||
it('refuses a suspended customer ordering from the app', async () => {
|
||||
await expect(build(false).createOrder(dto, 'c1', { placedBy: 'customer' })).rejects.toThrow('غیرفعال');
|
||||
});
|
||||
|
||||
it('lets an operator place an order for a suspended customer', async () => {
|
||||
await expect(build(false).createOrder(dto, 'c1', { placedBy: 'operator' })).resolves.toMatchObject({ id: 'o1' });
|
||||
});
|
||||
|
||||
it('lets an allowed customer order from the app', async () => {
|
||||
await expect(build(true).createOrder(dto, 'c1', { placedBy: 'customer' })).resolves.toMatchObject({ id: 'o1' });
|
||||
});
|
||||
});
|
||||
|
||||
/** MON-08 (owner ruling 2026-10-08): an app order is priced by the server, never by the app. */
|
||||
describe('OrdersService.createOrder — server-side making charge', () => {
|
||||
function build() {
|
||||
const created: Record<string, any>[] = [];
|
||||
const tx = { order: { create: jest.fn(async ({ data }: { data: Record<string, any> }) => { created.push(data); return { id: 'o1', ...data }; }) } };
|
||||
const prisma = {
|
||||
customer: { findUnique: jest.fn(async () => ({ id: 'c1', canPlaceOrders: true, referredByAgentId: null, goldDebtGrams: new Prisma.Decimal(0), goldCreditLimitGrams: new Prisma.Decimal(1000) })) },
|
||||
$transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)),
|
||||
};
|
||||
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
|
||||
const service = new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never);
|
||||
return { service, created };
|
||||
}
|
||||
// A tampered request: zero making charge, a 50% discount and a rial charge.
|
||||
const tampered = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 0, discountPercent: 50, flatRialCharge: 999 }] } as never;
|
||||
|
||||
it('ignores what the app sends and uses the server quote', async () => {
|
||||
const { service, created } = build();
|
||||
await service.createOrder(tampered, 'c1', { placedBy: 'customer' });
|
||||
expect(created[0].totalGoldWeightGrams.toString()).toBe('11');
|
||||
expect(created[0].flatRialCharge.toString()).toBe('0');
|
||||
});
|
||||
|
||||
it('keeps the numbers an operator entered in the panel', async () => {
|
||||
const { service, created } = build();
|
||||
await service.createOrder(tampered, 'c1', { placedBy: 'operator' });
|
||||
expect(created[0].totalGoldWeightGrams.toString()).toBe('5');
|
||||
expect(created[0].flatRialCharge.toString()).toBe('999');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { ForbiddenException, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { OrderChannel, OrderStatus, Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { CatalogService } from '../catalog/catalog.service';
|
||||
import { LedgerService } from '../accounting/ledger.service';
|
||||
import { AccountingHooksService } from '../accounting-sync/accounting-hooks.service';
|
||||
import { CreateOrderDto } from './dto/create-order.dto';
|
||||
import { WageService } from '../pricing/wage.service';
|
||||
|
||||
interface ComputedItem {
|
||||
productVariantId: string;
|
||||
@@ -25,23 +26,37 @@ export class OrdersService {
|
||||
private readonly catalog: CatalogService,
|
||||
private readonly ledger: LedgerService,
|
||||
private readonly accounting: AccountingHooksService,
|
||||
private readonly wage: WageService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Places a stock order. Per line item:
|
||||
* w = rashWeightGrams * (1 + (wagePercent - discountPercent) / 100)
|
||||
* mirrors legacy ApiMobileController::setOrder. Debt is NOT posted here —
|
||||
* only once the order reaches DELIVERED_TO_AGENT (see updateStatus).
|
||||
* only while the order is delivered (see updateStatus / syncOrderDebt).
|
||||
*/
|
||||
/**
|
||||
* @param customerId taken from the caller's token by the controller, NEVER
|
||||
* from the request body. The body's `customerId` is ignored; see the note
|
||||
* on CreateOrderDto.
|
||||
*/
|
||||
async createOrder(dto: CreateOrderDto, customerId: string) {
|
||||
async createOrder(
|
||||
dto: CreateOrderDto,
|
||||
customerId: string,
|
||||
opts: { placedBy: 'customer' | 'operator' } = { placedBy: 'operator' },
|
||||
) {
|
||||
const customer = await this.prisma.customer.findUnique({ where: { id: customerId } });
|
||||
if (!customer) throw new NotFoundException(`Customer ${customerId} not found`);
|
||||
|
||||
// MON-05 (owner ruling 2026-10-08): «معلق کردن سفارش» stops the customer
|
||||
// ordering from the app. Legacy stored the switch (customers.sts) but no
|
||||
// code read it, so it stopped nothing. An operator placing an order FOR
|
||||
// the customer from the panel is not blocked — that is how a suspended
|
||||
// account is still served.
|
||||
if (opts.placedBy === 'customer' && !customer.canPlaceOrders) {
|
||||
throw new ForbiddenException('ثبت سفارش برای حساب شما فعلاً غیرفعال است. لطفاً با پشتیبانی تماس بگیرید.');
|
||||
}
|
||||
|
||||
// The apps still send customerId in the body (removed from them in Phase 2).
|
||||
// It is not used for anything; a mismatch means either a stale client or an
|
||||
// attempt to order on someone else's account, and both are worth seeing.
|
||||
@@ -52,12 +67,25 @@ export class OrdersService {
|
||||
);
|
||||
}
|
||||
|
||||
// MON-08 (owner ruling 2026-10-08): an app order is priced by the server's
|
||||
// making-charge formula (pricing/wage-formula.ts — legacy's by default), the
|
||||
// same figure the app showed. Whatever the app sends for wage, discount or
|
||||
// rial charge is ignored, so a tampered request cannot set its own price.
|
||||
// An operator ordering from the panel keeps the numbers they entered, as
|
||||
// legacy's order builder did.
|
||||
const quotes =
|
||||
opts.placedBy === 'customer'
|
||||
? await this.wage.quote(customerId, dto.items.map((i) => i.productVariantId))
|
||||
: null;
|
||||
|
||||
const computedItems: ComputedItem[] = await Promise.all(
|
||||
dto.items.map(async (item) => {
|
||||
const variant = await this.catalog.getVariantOrThrow(item.productVariantId);
|
||||
const rashWeight = new Prisma.Decimal(variant.rashWeightGrams);
|
||||
const wagePercent = new Prisma.Decimal(item.wagePercent);
|
||||
const discountPercent = new Prisma.Decimal(item.discountPercent ?? 0);
|
||||
const quote = quotes?.get(variant.id);
|
||||
if (quotes && !quote) throw new NotFoundException(`Variant ${variant.id} not found`);
|
||||
const wagePercent = new Prisma.Decimal(quote ? quote.wagePercentSnapshot : item.wagePercent);
|
||||
const discountPercent = new Prisma.Decimal(quote ? quote.discountPercentSnapshot : (item.discountPercent ?? 0));
|
||||
const netPercent = wagePercent.sub(discountPercent);
|
||||
const computedWeightGrams = rashWeight.mul(netPercent.div(100).add(1));
|
||||
|
||||
@@ -68,7 +96,8 @@ export class OrdersService {
|
||||
wagePercentSnapshot: wagePercent,
|
||||
discountPercentSnapshot: discountPercent,
|
||||
computedWeightGrams,
|
||||
flatRialCharge: new Prisma.Decimal(item.flatRialCharge ?? 0),
|
||||
// Legacy app: rial_pay is always 0 (cart.vue); only an operator sets one.
|
||||
flatRialCharge: new Prisma.Decimal(quotes ? 0 : (item.flatRialCharge ?? 0)),
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -152,14 +181,10 @@ export class OrdersService {
|
||||
data: { orderId, fromStatus: order.status, toStatus: newStatus, note, actorAdminUserId },
|
||||
});
|
||||
|
||||
// Debt recognition point — mirrors legacy sts>4, which first becomes true
|
||||
// at sts=5 ("تحویل مسئول فروش" / delivered to agent), not sts=6 (delivered
|
||||
// to customer). Only fires once: a second transition into this status
|
||||
// (e.g. a data-fix re-save) would double-post debt, so guard on the order
|
||||
// not already having deliveredAt.
|
||||
if (newStatus === OrderStatus.DELIVERED_TO_AGENT && !order.deliveredAt) {
|
||||
await this.ledger.postOrderDebt(orderId, tx);
|
||||
}
|
||||
// Debt follows the status, as legacy's recomputed `sts > 4` did: owed
|
||||
// while delivered (to the expert or the customer), not otherwise, never
|
||||
// twice. See LedgerService.syncOrderDebt (ACC-03 / MON-04).
|
||||
await this.ledger.syncOrderDebt(orderId, tx);
|
||||
|
||||
// D27 — the accounting document (پیشفاکتور) follows the owner's rule on
|
||||
// which status posts it, queued in this same transaction.
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PricingService } from './pricing.service';
|
||||
import { PricingController } from './pricing.controller';
|
||||
import { WageService } from './wage.service';
|
||||
import { WageAdminController, WageCustomerController } from './wage.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [PricingController],
|
||||
providers: [PricingService],
|
||||
exports: [PricingService],
|
||||
controllers: [PricingController, WageAdminController, WageCustomerController],
|
||||
providers: [PricingService, WageService],
|
||||
exports: [PricingService, WageService],
|
||||
})
|
||||
export class PricingModule {}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { computeSample, computeWage, LEGACY_WAGE_FORMULA, parseWageFormula, type WageFormula } from './wage-formula';
|
||||
|
||||
/**
|
||||
* The making-charge formula. The default must reproduce legacy exactly:
|
||||
* final % = variant % + customer % − largest active promotion
|
||||
* weight = rash × (1 + final/100) × qty
|
||||
*/
|
||||
describe('wage formula', () => {
|
||||
const legacy = LEGACY_WAGE_FORMULA;
|
||||
|
||||
it('legacy: variant + customer, no promotion', () => {
|
||||
const w = computeWage(legacy, { variantPercent: '7', customerPercent: '3', promotionPercents: [] });
|
||||
expect(w.finalPercent).toBe('10');
|
||||
expect(w.wagePercentSnapshot).toBe('10');
|
||||
expect(w.discountPercentSnapshot).toBe('0');
|
||||
});
|
||||
|
||||
it('legacy: the LARGEST promotion is subtracted, not the sum', () => {
|
||||
const w = computeWage(legacy, { variantPercent: '7', customerPercent: '3', promotionPercents: ['1', '2.5', '2'] });
|
||||
expect(w.promotionPercent).toBe('2.5');
|
||||
expect(w.finalPercent).toBe('7.5');
|
||||
// Stored so that wage − discount = final, which is what createOrder multiplies by.
|
||||
expect(w.wagePercentSnapshot).toBe('10');
|
||||
expect(w.discountPercentSnapshot).toBe('2.5');
|
||||
});
|
||||
|
||||
it('legacy sample weight matches setOrder: 10 g × (1 + 10%) = 11 g', () => {
|
||||
const r = computeSample(legacy, { rashWeightGrams: '10', quantity: 1, variantPercent: '7', customerPercent: '3', promotionPercent: '0' });
|
||||
expect(r.totalGrams).toBe('11');
|
||||
expect(r.wageGrams).toBe('1');
|
||||
});
|
||||
|
||||
it('a changed structure: no customer term, sum of promotions, +0.5, floor 5, 2 decimals', () => {
|
||||
const f: WageFormula = { ...legacy, customerCoef: '0', promotionPick: 'sum', constant: '0.5', min: '5', decimals: 2 };
|
||||
expect(computeWage(f, { variantPercent: '6', customerPercent: '3', promotionPercents: ['1', '1'] }).finalPercent).toBe('5');
|
||||
const w = computeWage(f, { variantPercent: '7.333', customerPercent: '3', promotionPercents: [] });
|
||||
expect(w.finalPercent).toBe('7.83');
|
||||
expect(w.limitedBy).toBeNull();
|
||||
});
|
||||
|
||||
it('the cap is reported when it bites', () => {
|
||||
const w = computeWage({ ...legacy, max: '8' }, { variantPercent: '7', customerPercent: '3', promotionPercents: [] });
|
||||
expect(w).toMatchObject({ finalPercent: '8', limitedBy: 'max', beforeLimits: '10' });
|
||||
});
|
||||
|
||||
it('rejects nonsense from the admin form', () => {
|
||||
expect(() => parseWageFormula({ ...legacy, variantCoef: 'abc' })).toThrow(BadRequestException);
|
||||
expect(() => parseWageFormula({ ...legacy, min: '9', max: '8' })).toThrow(BadRequestException);
|
||||
expect(() => parseWageFormula({ ...legacy, promotionPick: 'avg' })).toThrow(BadRequestException);
|
||||
expect(() => parseWageFormula({ ...legacy, decimals: 9 })).toThrow(BadRequestException);
|
||||
expect(parseWageFormula({ ...legacy })).toEqual(legacy);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
/**
|
||||
* The making-charge («اجرت») formula — one place, used to price every order
|
||||
* line placed from the app and to show the same figure in the app beforehand
|
||||
* (owner ruling 2026-10-08: the number shown must be the number charged, and
|
||||
* nothing the app sends is trusted).
|
||||
*
|
||||
* Legacy, reconstructed from henza_pwa + ApiMobileController::setOrder:
|
||||
* percent_pay = customer.percent + variant.percentage_pay (Mixins/product getWage)
|
||||
* discount = the LARGEST active promotion for the product,
|
||||
* its category or its brand (getPromotion; customer-type off)
|
||||
* final % = percent_pay − discount (setOrder :558)
|
||||
* weight = rash × (1 + final/100) × qty
|
||||
* rial charge = 0 (cart.vue: rial_pay: 0)
|
||||
*
|
||||
* The admin «اجرت» screen may change the numbers AND the structure: each term
|
||||
* has a coefficient (0 switches it off), the promotion can be the largest or
|
||||
* the sum, a constant can be added, and the result can be floored, capped and
|
||||
* rounded. LEGACY_WAGE_FORMULA reproduces legacy exactly.
|
||||
*/
|
||||
export interface WageFormula {
|
||||
version: 1;
|
||||
/** × the variant's own making charge (legacy percentage_pay). */
|
||||
variantCoef: string;
|
||||
/** × the customer's own percent (legacy customers.percent). */
|
||||
customerCoef: string;
|
||||
/** × the promotion discount, SUBTRACTED. */
|
||||
promotionCoef: string;
|
||||
/** Which promotion counts when several apply: legacy takes the largest. */
|
||||
promotionPick: 'max' | 'sum';
|
||||
/** Added as is, in percent. */
|
||||
constant: string;
|
||||
/** Floor / cap on the final percent; null = none (legacy has neither). */
|
||||
min: string | null;
|
||||
max: string | null;
|
||||
/** Round the final percent to this many decimals; null = none (legacy). */
|
||||
decimals: number | null;
|
||||
}
|
||||
|
||||
export const LEGACY_WAGE_FORMULA: WageFormula = Object.freeze({
|
||||
version: 1,
|
||||
variantCoef: '1',
|
||||
customerCoef: '1',
|
||||
promotionCoef: '1',
|
||||
promotionPick: 'max',
|
||||
constant: '0',
|
||||
min: null,
|
||||
max: null,
|
||||
decimals: null,
|
||||
});
|
||||
|
||||
export interface WageInputs {
|
||||
variantPercent: Prisma.Decimal.Value;
|
||||
customerPercent: Prisma.Decimal.Value;
|
||||
/** Every active promotion that applies, in percent. */
|
||||
promotionPercents: Prisma.Decimal.Value[];
|
||||
}
|
||||
|
||||
export interface WageBreakdown {
|
||||
variantTerm: string;
|
||||
customerTerm: string;
|
||||
/** The promotion percent picked (largest or sum) before its coefficient. */
|
||||
promotionPercent: string;
|
||||
promotionTerm: string;
|
||||
constant: string;
|
||||
beforeLimits: string;
|
||||
/** Which limit changed the result, if any. */
|
||||
limitedBy: 'min' | 'max' | null;
|
||||
finalPercent: string;
|
||||
/**
|
||||
* What the order line stores. OrdersService computes
|
||||
* weight = rash × (1 + (wage − discount)/100), so wage = final + discount term
|
||||
* and discount = discount term keeps that product equal to `finalPercent`.
|
||||
*/
|
||||
wagePercentSnapshot: string;
|
||||
discountPercentSnapshot: string;
|
||||
}
|
||||
|
||||
const D = (v: Prisma.Decimal.Value | null | undefined) => new Prisma.Decimal(v ?? 0);
|
||||
|
||||
export function computeWage(f: WageFormula, i: WageInputs): WageBreakdown {
|
||||
const promos = i.promotionPercents.map(D);
|
||||
const promo =
|
||||
promos.length === 0
|
||||
? D(0)
|
||||
: f.promotionPick === 'sum'
|
||||
? promos.reduce((s, p) => s.add(p), D(0))
|
||||
: promos.reduce((m, p) => (p.gt(m) ? p : m), promos[0]);
|
||||
|
||||
const variantTerm = D(f.variantCoef).mul(D(i.variantPercent));
|
||||
const customerTerm = D(f.customerCoef).mul(D(i.customerPercent));
|
||||
const promotionTerm = D(f.promotionCoef).mul(promo);
|
||||
const constant = D(f.constant);
|
||||
const before = variantTerm.add(customerTerm).sub(promotionTerm).add(constant);
|
||||
|
||||
let final = before;
|
||||
let limitedBy: WageBreakdown['limitedBy'] = null;
|
||||
if (f.min !== null && final.lt(D(f.min))) {
|
||||
final = D(f.min);
|
||||
limitedBy = 'min';
|
||||
}
|
||||
if (f.max !== null && final.gt(D(f.max))) {
|
||||
final = D(f.max);
|
||||
limitedBy = 'max';
|
||||
}
|
||||
if (f.decimals !== null) final = final.toDecimalPlaces(f.decimals, Prisma.Decimal.ROUND_HALF_UP);
|
||||
|
||||
return {
|
||||
variantTerm: variantTerm.toString(),
|
||||
customerTerm: customerTerm.toString(),
|
||||
promotionPercent: promo.toString(),
|
||||
promotionTerm: promotionTerm.toString(),
|
||||
constant: constant.toString(),
|
||||
beforeLimits: before.toString(),
|
||||
limitedBy,
|
||||
finalPercent: final.toString(),
|
||||
wagePercentSnapshot: final.add(promotionTerm).toString(),
|
||||
discountPercentSnapshot: promotionTerm.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** A worked example for the admin screen: the formula applied to one order line. */
|
||||
export interface WageSample {
|
||||
rashWeightGrams: string;
|
||||
quantity: number;
|
||||
variantPercent: string;
|
||||
customerPercent: string;
|
||||
promotionPercent: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_WAGE_SAMPLE: WageSample = Object.freeze({
|
||||
rashWeightGrams: '10',
|
||||
quantity: 1,
|
||||
variantPercent: '7',
|
||||
customerPercent: '3',
|
||||
promotionPercent: '0',
|
||||
});
|
||||
|
||||
export function computeSample(f: WageFormula, s: WageSample) {
|
||||
const wage = computeWage(f, {
|
||||
variantPercent: s.variantPercent,
|
||||
customerPercent: s.customerPercent,
|
||||
promotionPercents: D(s.promotionPercent).isZero() ? [] : [s.promotionPercent],
|
||||
});
|
||||
const rash = D(s.rashWeightGrams).mul(s.quantity);
|
||||
// Same formula as OrdersService.createOrder.
|
||||
const total = rash.mul(D(wage.finalPercent).div(100).add(1));
|
||||
return {
|
||||
...wage,
|
||||
rashTotalGrams: rash.toString(),
|
||||
wageGrams: total.sub(rash).toDecimalPlaces(4).toString(),
|
||||
totalGrams: total.toDecimalPlaces(4).toString(),
|
||||
};
|
||||
}
|
||||
|
||||
/* ───────────── validation (admin input) ───────────── */
|
||||
|
||||
function num(v: unknown, field: string, lo: number, hi: number): string {
|
||||
const s = String(v ?? '').trim();
|
||||
let d: Prisma.Decimal;
|
||||
try {
|
||||
d = new Prisma.Decimal(s);
|
||||
} catch {
|
||||
throw new BadRequestException(`${field}: عدد معتبر نیست`);
|
||||
}
|
||||
if (!d.isFinite() || d.lt(lo) || d.gt(hi)) throw new BadRequestException(`${field}: باید بین ${lo} و ${hi} باشد`);
|
||||
return d.toString();
|
||||
}
|
||||
|
||||
function optNum(v: unknown, field: string, lo: number, hi: number): string | null {
|
||||
return v === null || v === undefined || String(v).trim() === '' ? null : num(v, field, lo, hi);
|
||||
}
|
||||
|
||||
export function parseWageFormula(raw: unknown): WageFormula {
|
||||
const r = (raw ?? {}) as Record<string, unknown>;
|
||||
const pick = r.promotionPick === 'sum' ? 'sum' : r.promotionPick === 'max' ? 'max' : null;
|
||||
if (!pick) throw new BadRequestException('نحوهی انتخاب تخفیف باید «بیشترین» یا «جمع» باشد');
|
||||
const decimals =
|
||||
r.decimals === null || r.decimals === undefined || r.decimals === '' ? null : Number(num(r.decimals, 'تعداد رقم اعشار', 0, 4));
|
||||
if (decimals !== null && !Number.isInteger(decimals)) throw new BadRequestException('تعداد رقم اعشار باید عدد صحیح باشد');
|
||||
const f: WageFormula = {
|
||||
version: 1,
|
||||
variantCoef: num(r.variantCoef, 'ضریب اجرت مدل', -10, 10),
|
||||
customerCoef: num(r.customerCoef, 'ضریب درصد مشتری', -10, 10),
|
||||
promotionCoef: num(r.promotionCoef, 'ضریب تخفیف', -10, 10),
|
||||
promotionPick: pick,
|
||||
constant: num(r.constant, 'مقدار ثابت', -100, 100),
|
||||
min: optNum(r.min, 'حداقل اجرت', -100, 1000),
|
||||
max: optNum(r.max, 'حداکثر اجرت', -100, 1000),
|
||||
decimals,
|
||||
};
|
||||
if (f.min !== null && f.max !== null && D(f.min).gt(D(f.max))) {
|
||||
throw new BadRequestException('حداقل اجرت نمیتواند از حداکثر بیشتر باشد');
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
export function parseWageSample(raw: unknown): WageSample {
|
||||
const r = (raw ?? {}) as Record<string, unknown>;
|
||||
const qty = Number(r.quantity);
|
||||
if (!Number.isInteger(qty) || qty < 1 || qty > 1000) throw new BadRequestException('تعداد نمونه باید عدد صحیح بین ۱ و ۱۰۰۰ باشد');
|
||||
return {
|
||||
rashWeightGrams: num(r.rashWeightGrams, 'وزن خام نمونه', 0, 100000),
|
||||
quantity: qty,
|
||||
variantPercent: num(r.variantPercent, 'اجرت مدل نمونه', -100, 1000),
|
||||
customerPercent: num(r.customerPercent, 'درصد مشتری نمونه', -100, 1000),
|
||||
promotionPercent: num(r.promotionPercent, 'تخفیف نمونه', 0, 100),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Body, Controller, Get, HttpCode, Post, Put } from '@nestjs/common';
|
||||
import { ArrayMaxSize, IsArray, IsString } from 'class-validator';
|
||||
import { CurrentAdmin, RequirePermission } from '../auth/guards';
|
||||
import type { AuthenticatedAdmin } from '../auth/jwt.strategy';
|
||||
import { CurrentCustomer, CustomerAuth } from '../customer-auth/customer.guards';
|
||||
import type { AuthenticatedCustomer } from '../customer-auth/customer-jwt.strategy';
|
||||
import { WageService } from './wage.service';
|
||||
|
||||
/**
|
||||
* «اجرت» admin screen — the making-charge formula, a worked sample, and the
|
||||
* approval that puts a new formula in force. Behind its own rid.
|
||||
*/
|
||||
@Controller('admin/pricing/wage-formula')
|
||||
@RequirePermission('config.wage')
|
||||
export class WageAdminController {
|
||||
constructor(private readonly wage: WageService) {}
|
||||
|
||||
@Get()
|
||||
get() {
|
||||
return this.wage.getConfig();
|
||||
}
|
||||
|
||||
/** Nothing is saved: the draft and the formula in force on the same sample. */
|
||||
@Post('preview')
|
||||
@HttpCode(200)
|
||||
preview(@Body() body: { formula?: unknown; sample?: unknown }) {
|
||||
return this.wage.preview(body?.formula, body?.sample);
|
||||
}
|
||||
|
||||
/** Puts the formula in force, recorded with the sample it was checked on. */
|
||||
@Put()
|
||||
approve(@Body() body: { formula?: unknown; sample?: unknown }, @CurrentAdmin() admin: AuthenticatedAdmin) {
|
||||
return this.wage.approve(body?.formula, body?.sample, admin);
|
||||
}
|
||||
}
|
||||
|
||||
class WageQuoteDto {
|
||||
@IsArray()
|
||||
@ArrayMaxSize(200)
|
||||
@IsString({ each: true })
|
||||
variantIds!: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The making charge the app shows on a product and in the cart — computed by
|
||||
* the same code that prices the order, for the signed-in customer.
|
||||
*/
|
||||
@Controller('customer/me/wage-quote')
|
||||
export class WageCustomerController {
|
||||
constructor(private readonly wage: WageService) {}
|
||||
|
||||
@CustomerAuth()
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
async quote(@Body() dto: WageQuoteDto, @CurrentCustomer() me: AuthenticatedCustomer) {
|
||||
return [...(await this.wage.quote(me.id, dto.variantIds)).values()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma, PromotionScope } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import {
|
||||
computeSample,
|
||||
computeWage,
|
||||
DEFAULT_WAGE_SAMPLE,
|
||||
LEGACY_WAGE_FORMULA,
|
||||
parseWageFormula,
|
||||
parseWageSample,
|
||||
type WageBreakdown,
|
||||
type WageFormula,
|
||||
type WageSample,
|
||||
} from './wage-formula';
|
||||
|
||||
/** Setting row holding the formula; kept off the generic `const` routes (see admin-misc). */
|
||||
export const WAGE_FORMULA_SETTING_KEY = 'pricing.wageFormula';
|
||||
export const PRICING_SETTING_PREFIX = 'pricing.';
|
||||
|
||||
interface Approval {
|
||||
formula: WageFormula;
|
||||
sample: WageSample;
|
||||
approvedAt: string;
|
||||
approvedBy: { id: string; name: string };
|
||||
}
|
||||
|
||||
interface StoredWageFormula extends Approval {
|
||||
/** Earlier approved versions, newest first (last 20). */
|
||||
history: Approval[];
|
||||
}
|
||||
|
||||
type Tx = Prisma.TransactionClient | PrismaService;
|
||||
|
||||
/** One variant's making charge for one customer, as charged and as shown. */
|
||||
export interface WageQuote extends WageBreakdown {
|
||||
variantId: string;
|
||||
variantPercent: string;
|
||||
customerPercent: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class WageService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
private async stored(tx: Tx = this.prisma): Promise<StoredWageFormula | null> {
|
||||
const row = await tx.setting.findUnique({ where: { key: WAGE_FORMULA_SETTING_KEY } });
|
||||
return row ? (row.value as unknown as StoredWageFormula) : null;
|
||||
}
|
||||
|
||||
/** The formula in force; legacy's exactly until an admin approves another. */
|
||||
async formula(tx: Tx = this.prisma): Promise<WageFormula> {
|
||||
const s = await this.stored(tx);
|
||||
return s ? parseWageFormula(s.formula) : { ...LEGACY_WAGE_FORMULA };
|
||||
}
|
||||
|
||||
/* ───────────── admin screen ───────────── */
|
||||
|
||||
async getConfig() {
|
||||
const s = await this.stored();
|
||||
const formula = s ? parseWageFormula(s.formula) : { ...LEGACY_WAGE_FORMULA };
|
||||
const sample = s ? parseWageSample(s.sample) : { ...DEFAULT_WAGE_SAMPLE };
|
||||
return {
|
||||
formula,
|
||||
sample,
|
||||
result: computeSample(formula, sample),
|
||||
approvedAt: s?.approvedAt ?? null,
|
||||
approvedBy: s?.approvedBy ?? null,
|
||||
isLegacyDefault: !s,
|
||||
legacy: LEGACY_WAGE_FORMULA,
|
||||
history: (s?.history ?? []).map((h) => ({ ...h, result: computeSample(parseWageFormula(h.formula), parseWageSample(h.sample)) })),
|
||||
};
|
||||
}
|
||||
|
||||
/** The draft and the formula in force, side by side, on the same sample. */
|
||||
async preview(rawFormula: unknown, rawSample: unknown) {
|
||||
const draft = parseWageFormula(rawFormula);
|
||||
const sample = parseWageSample(rawSample);
|
||||
return {
|
||||
draft: computeSample(draft, sample),
|
||||
current: computeSample(await this.formula(), sample),
|
||||
};
|
||||
}
|
||||
|
||||
/** Approves a formula together with the sample it was checked on. */
|
||||
async approve(rawFormula: unknown, rawSample: unknown, admin: { id: string; fullName: string }) {
|
||||
const formula = parseWageFormula(rawFormula);
|
||||
const sample = parseWageSample(rawSample);
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
const prev = await this.stored(tx);
|
||||
const next: StoredWageFormula = {
|
||||
formula,
|
||||
sample,
|
||||
approvedAt: new Date().toISOString(),
|
||||
approvedBy: { id: admin.id, name: admin.fullName },
|
||||
history: prev
|
||||
? [{ formula: prev.formula, sample: prev.sample, approvedAt: prev.approvedAt, approvedBy: prev.approvedBy }, ...prev.history].slice(0, 20)
|
||||
: [],
|
||||
};
|
||||
const value = next as unknown as Prisma.InputJsonValue;
|
||||
await tx.setting.upsert({
|
||||
where: { key: WAGE_FORMULA_SETTING_KEY },
|
||||
update: { value },
|
||||
create: { key: WAGE_FORMULA_SETTING_KEY, value },
|
||||
});
|
||||
});
|
||||
return this.getConfig();
|
||||
}
|
||||
|
||||
/* ───────────── pricing a customer's lines ───────────── */
|
||||
|
||||
/**
|
||||
* The making charge of each variant for this customer — what the app shows
|
||||
* and what an app order is charged. The promotions considered are legacy's:
|
||||
* active, inside their dates, scoped to the product, its category or its
|
||||
* brand (customer-scoped promotions were switched off in the legacy app).
|
||||
*/
|
||||
async quote(customerId: string, variantIds: string[], tx: Tx = this.prisma): Promise<Map<string, WageQuote>> {
|
||||
const customer = await tx.customer.findUnique({
|
||||
where: { id: customerId },
|
||||
select: { makingChargeOffsetPercent: true },
|
||||
});
|
||||
if (!customer) throw new NotFoundException('مشتری یافت نشد');
|
||||
|
||||
const ids = [...new Set(variantIds)];
|
||||
const variants = await tx.productVariant.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, defaultWagePercent: true, product: { select: { id: true, categoryId: true, brandId: true } } },
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
const promotions = await tx.promotion.findMany({
|
||||
where: {
|
||||
isActive: true,
|
||||
scope: { in: [PromotionScope.PRODUCT, PromotionScope.CATEGORY, PromotionScope.BRAND] },
|
||||
AND: [
|
||||
{ OR: [{ startsAt: null }, { startsAt: { lte: now } }] },
|
||||
{ OR: [{ endsAt: null }, { endsAt: { gte: now } }] },
|
||||
],
|
||||
OR: [
|
||||
{ productId: { in: variants.map((v) => v.product.id) } },
|
||||
{ categoryId: { in: variants.map((v) => v.product.categoryId).filter((x): x is string => !!x) } },
|
||||
{ brandId: { in: variants.map((v) => v.product.brandId).filter((x): x is string => !!x) } },
|
||||
],
|
||||
},
|
||||
select: { scope: true, productId: true, categoryId: true, brandId: true, discountPercent: true },
|
||||
});
|
||||
|
||||
const formula = await this.formula(tx);
|
||||
const out = new Map<string, WageQuote>();
|
||||
for (const v of variants) {
|
||||
const applying = promotions.filter(
|
||||
(p) =>
|
||||
(p.scope === PromotionScope.PRODUCT && p.productId === v.product.id) ||
|
||||
(p.scope === PromotionScope.CATEGORY && !!v.product.categoryId && p.categoryId === v.product.categoryId) ||
|
||||
(p.scope === PromotionScope.BRAND && !!v.product.brandId && p.brandId === v.product.brandId),
|
||||
);
|
||||
const inputs = {
|
||||
variantPercent: v.defaultWagePercent,
|
||||
customerPercent: customer.makingChargeOffsetPercent,
|
||||
promotionPercents: applying.map((p) => p.discountPercent),
|
||||
};
|
||||
out.set(v.id, {
|
||||
variantId: v.id,
|
||||
variantPercent: new Prisma.Decimal(v.defaultWagePercent).toString(),
|
||||
customerPercent: new Prisma.Decimal(customer.makingChargeOffsetPercent).toString(),
|
||||
...computeWage(formula, inputs),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -8,19 +8,17 @@
|
||||
"lint": "eslint \"src/**/*.{ts,vue}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons-vue": "^6.1.0",
|
||||
"@gold-bank/shared-types": "workspace:*",
|
||||
"@lottiefiles/dotlottie-vue": "^0.4.15",
|
||||
"@vueuse/core": "^9.13.0",
|
||||
"ant-design-vue": "^3.2.20",
|
||||
"gsap": "^3.9.1",
|
||||
"moment-jalaali": "^0.10.0",
|
||||
"pinia": "^2.2.0",
|
||||
"swiper": "^7.4.1",
|
||||
"vant": "^4.0.3",
|
||||
"vue": "^3.5.0",
|
||||
"vue-router": "^4.4.0",
|
||||
"vue3-lazyload": "^0.2.5-beta",
|
||||
"@lottiefiles/dotlottie-vue": "^0.4.15"
|
||||
"vue3-lazyload": "^0.2.5-beta"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.1.0",
|
||||
@@ -30,8 +28,8 @@
|
||||
"tailwindcss": "3.0.18",
|
||||
"typescript": "^5.5.0",
|
||||
"vite": "^5.4.0",
|
||||
"vue-tsc": "^2.1.0",
|
||||
"vite-plugin-pwa": "^0.20.5",
|
||||
"vue-tsc": "^2.1.0",
|
||||
"workbox-precaching": "^7.1.0",
|
||||
"workbox-window": "^7.1.0"
|
||||
}
|
||||
|
||||
@@ -288,6 +288,15 @@ export interface AccountingBalance {
|
||||
provider: string | null
|
||||
}
|
||||
|
||||
/** POST /customer/me/wage-quote — one variant's making charge for the signed-in customer. */
|
||||
export interface WageQuote {
|
||||
variantId: string
|
||||
variantPercent: string
|
||||
customerPercent: string
|
||||
promotionPercent: string
|
||||
finalPercent: string
|
||||
}
|
||||
|
||||
export const api = {
|
||||
listProducts: () => request<ProductSummary[]>('/catalog/products'),
|
||||
/**
|
||||
@@ -320,6 +329,17 @@ export const api = {
|
||||
getAccountingBalance: () => request<AccountingBalance>('/customer/me/accounting-balance'),
|
||||
getMyOrders: () => request<OrderDetail[]>('/customer/me/orders'),
|
||||
getMyLedgerEntries: () => request<LedgerEntrySummary[]>('/customer/me/ledger-entries'),
|
||||
/** The making charge the server will charge for these variants (MON-08). */
|
||||
getWageQuotes: (variantIds: string[]) =>
|
||||
request<WageQuote[]>('/customer/me/wage-quote', { method: 'POST', body: JSON.stringify({ variantIds }) }),
|
||||
/** Favourite product ids, newest first — legacy get-favorites (FAV-01). */
|
||||
getFavorites: () => request<{ ids: string[] }>('/customer/me/favorites'),
|
||||
/** Legacy add-to-fav: adds or removes; answers the new state. */
|
||||
toggleFavorite: (productId: string) =>
|
||||
request<{ favorite: boolean }>('/customer/me/favorites/toggle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ productId }),
|
||||
}),
|
||||
createOrder: (dto: CreateOrderDto) => request<OrderSummary>('/orders', { method: 'POST', body: JSON.stringify(dto) }),
|
||||
getLatestGoldPrice: (karatPerMille = 750) => request<GoldPriceQuote>(`/pricing/latest?karatPerMille=${karatPerMille}`),
|
||||
/** GET /home/slider — public, no auth. Empty array when the admin hasn't
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
<!-- Ported from legacy henza_pwa/src/components/viewAll.vue.
|
||||
Legacy left `to` undeclared and relied on Vue's attribute fallthrough to
|
||||
land it on the root <router-link>; declared explicitly here only because
|
||||
vue-tsc's template type-checking (which legacy's own build never ran)
|
||||
requires router-link's `to` to be a known prop — same runtime value ends
|
||||
up bound either way, no behavior change. -->
|
||||
<template>
|
||||
<router-link :to="to" class="text-primary w-[280px] rounded-[10px] p-[8px] bg-light flex flex-col justify-center items-center">
|
||||
<Icon icon="vuesax-linear:arrow-left-1" class="cursor-pointer" size="25" />
|
||||
مشاهده همه
|
||||
</router-link>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { RouteLocationRaw } from 'vue-router'
|
||||
import Icon from './icon/Icon.vue'
|
||||
|
||||
defineProps<{ to: RouteLocationRaw }>()
|
||||
</script>
|
||||
@@ -1,229 +0,0 @@
|
||||
<!--
|
||||
The "حساب" block that sits BELOW the shop content on the home screen.
|
||||
|
||||
Two genuinely different states:
|
||||
- signed out: a quiet invitation, no fabricated numbers.
|
||||
- signed in: the customer's real gram position from GET /customers/:id
|
||||
(goldDebtGrams / fiatDebtRial), labelled بدهکار or بستانکار the same way
|
||||
DashboardView does, since the ledger stores debt as a signed figure.
|
||||
-->
|
||||
<template>
|
||||
<section class="acct">
|
||||
<template v-if="customer">
|
||||
<div class="acct__head">
|
||||
<div>
|
||||
<div class="acct__eyebrow">{{ positionLabel }}</div>
|
||||
<div class="acct__figure">
|
||||
{{ grams }}
|
||||
<span class="acct__unit">گرم</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="acct__seal" :class="isDebtor ? 'is-debtor' : 'is-creditor'">
|
||||
{{ isDebtor ? 'بدهکار' : 'بستانکار' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="acct__row">
|
||||
<span class="acct__rowLabel">بدهی ریالی</span>
|
||||
<span class="acct__rowValue">{{ price(fiat) }} <i>ریال</i></span>
|
||||
</div>
|
||||
|
||||
<div class="acct__actions">
|
||||
<button type="button" class="acct__action" @click="emit('go', 'ordersList')">
|
||||
<Icon icon="vuesax-linear:box" size="18" />
|
||||
سفارشها
|
||||
</button>
|
||||
<button type="button" class="acct__action" @click="emit('go', 'transactionsList')">
|
||||
<Icon icon="vuesax-linear:receipt-text" size="18" />
|
||||
اسناد
|
||||
</button>
|
||||
<button type="button" class="acct__action" @click="emit('go', 'profileData')">
|
||||
<Icon icon="vuesax-linear:user" size="18" />
|
||||
پروفایل
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="acct__invite">
|
||||
<div class="acct__inviteIcon" aria-hidden="true">
|
||||
<Icon icon="vuesax-linear:security-user" size="20" />
|
||||
</div>
|
||||
<div class="acct__inviteCopy">
|
||||
<h3>حساب گرمی شما</h3>
|
||||
<p>برای دیدن موجودی، سفارشها و اسناد خود وارد شوید.</p>
|
||||
</div>
|
||||
<button type="button" class="acct__inviteCta" @click="emit('login')">ورود / ثبتنام</button>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import Icon from '../icon/Icon.vue'
|
||||
import { price } from '../../utils/filters'
|
||||
import type { CustomerDetail } from '../../api/client'
|
||||
|
||||
const props = defineProps<{ customer: CustomerDetail | null }>()
|
||||
const emit = defineEmits<{ (e: 'go', route: string): void; (e: 'login'): void }>()
|
||||
|
||||
const isDebtor = computed(() => (props.customer ? parseFloat(props.customer.goldDebtGrams) > 0 : false))
|
||||
const positionLabel = computed(() => (isDebtor.value ? 'مانده بدهی گرمی' : 'مانده بستانکاری گرمی'))
|
||||
const grams = computed(() => (props.customer ? Math.abs(parseFloat(props.customer.goldDebtGrams)) : 0))
|
||||
const fiat = computed(() => (props.customer ? props.customer.fiatDebtRial.split('.')[0] : '0'))
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.acct {
|
||||
border-radius: 20px;
|
||||
padding: 18px;
|
||||
background: @ink;
|
||||
color: #fff;
|
||||
box-shadow: 0 22px 44px -32px rgba(20, 22, 26, 0.9);
|
||||
}
|
||||
|
||||
.acct__head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.acct__eyebrow {
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
padding-bottom: 7px;
|
||||
}
|
||||
|
||||
.acct__figure {
|
||||
font-size: 26px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.acct__unit {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
padding-inline-start: 3px;
|
||||
}
|
||||
|
||||
.acct__seal {
|
||||
font-size: 10.5px;
|
||||
font-weight: 700;
|
||||
padding: 5px 11px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.acct__seal.is-debtor {
|
||||
color: #fff;
|
||||
background: @wine;
|
||||
}
|
||||
.acct__seal.is-creditor {
|
||||
color: #fff;
|
||||
background: rgba(255, 255, 255, 0.13);
|
||||
}
|
||||
|
||||
.acct__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 16px;
|
||||
padding-top: 13px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.acct__rowLabel {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.acct__rowValue {
|
||||
font-weight: 700;
|
||||
}
|
||||
.acct__rowValue i {
|
||||
font-style: normal;
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.acct__actions {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.acct__action {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 11px 4px;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 13px;
|
||||
font-family: inherit;
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.88);
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
transition: background 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
.acct__action:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.acct__invite {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 13px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.acct__inviteIcon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 13px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
background: @wine;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.acct__inviteCopy {
|
||||
flex: 1 1 150px;
|
||||
}
|
||||
.acct__inviteCopy h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.acct__inviteCopy p {
|
||||
margin: 5px 0 0;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.8;
|
||||
color: rgba(255, 255, 255, 0.58);
|
||||
}
|
||||
|
||||
.acct__inviteCta {
|
||||
flex: 1 1 100%;
|
||||
margin-top: 4px;
|
||||
padding: 12px;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 13px;
|
||||
background: #fff;
|
||||
color: @ink;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
.acct__inviteCta:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
</style>
|
||||
@@ -1,94 +0,0 @@
|
||||
<!--
|
||||
Horizontal category rail. Categories are real, derived from the product
|
||||
catalogue by configStore (GET /catalog/products), so this renders nothing
|
||||
rather than placeholder tiles when the catalogue is empty.
|
||||
-->
|
||||
<template>
|
||||
<div class="rail no-scrollbar">
|
||||
<button
|
||||
v-for="cat in categories"
|
||||
:key="cat.id"
|
||||
type="button"
|
||||
class="rail__chip"
|
||||
:class="{ 'is-active': cat.id === activeId }"
|
||||
@click="emit('select', cat)"
|
||||
>
|
||||
<span class="rail__mark" aria-hidden="true">
|
||||
<img v-if="cat.icon?.image" :src="cat.icon.image" alt="" />
|
||||
</span>
|
||||
<span class="rail__title">{{ cat.title }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { HomeCategory } from '../../stores/configStore'
|
||||
|
||||
defineProps<{ categories: HomeCategory[]; activeId?: string | null }>()
|
||||
const emit = defineEmits<{ (e: 'select', cat: HomeCategory): void }>()
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rail {
|
||||
display: flex;
|
||||
gap: 9px;
|
||||
overflow-x: auto;
|
||||
padding: 2px 16px 2px;
|
||||
margin: 0 -16px;
|
||||
scroll-snap-type: x proximity;
|
||||
}
|
||||
|
||||
.rail__chip {
|
||||
scroll-snap-align: start;
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 14px 8px 10px;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
color: @inkSoft;
|
||||
background: @canvas;
|
||||
border: 1px solid @hairline;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.rail__chip:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.rail__chip.is-active {
|
||||
background: @ink;
|
||||
border-color: @ink;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.rail__mark {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
background: @hairlineSoft;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.rail__chip.is-active .rail__mark {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
|
||||
.rail__mark img {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
object-fit: contain;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.rail__title {
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -1,156 +0,0 @@
|
||||
<!--
|
||||
Product card for the redesigned home screen.
|
||||
|
||||
Shows only fields that genuinely exist on ProductSummary today: title, the
|
||||
cheapest variant's rash weight, its making-charge (اجرت) percent, and the
|
||||
catalogue image. No price is printed on the card, because a finished piece's
|
||||
rial price is a function of the live gold rate plus wage and is computed at
|
||||
order time, not stored on the product — printing one here would be invented.
|
||||
-->
|
||||
<template>
|
||||
<article class="card" :class="{ 'card--wide': wide }" data-product-origin @click="emit('open', value)">
|
||||
<div class="card__art">
|
||||
<img v-lazy="image" :alt="title" />
|
||||
<button type="button" class="card__fav" :class="{ 'is-on': favorites.isFavorite(id) }" @click.stop="favorites.toggle(id)">
|
||||
<Icon :icon="favorites.isFavorite(id) ? 'vuesax-linear:heart-fill' : 'vuesax-linear:heart'" size="17" />
|
||||
</button>
|
||||
<span v-if="badge" class="card__badge">{{ badge }}</span>
|
||||
</div>
|
||||
|
||||
<div class="card__body">
|
||||
<h3 class="card__title">{{ title }}</h3>
|
||||
<div class="card__meta">
|
||||
<span class="card__weight">{{ min_gram }} گرم</span>
|
||||
<span v-if="wage != null" class="card__wage">اجرت {{ wageLabel }}٪</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import Icon from '../icon/Icon.vue'
|
||||
import { useProduct } from '../../composables/useProduct'
|
||||
import { useFavoritesStore } from '../../stores/favoritesStore'
|
||||
import type { ProductSummary } from '../../api/client'
|
||||
|
||||
const props = defineProps<{ value: ProductSummary; wide?: boolean; badge?: string }>()
|
||||
const emit = defineEmits<{ (e: 'open', value: ProductSummary): void }>()
|
||||
|
||||
const favorites = useFavoritesStore()
|
||||
const { image, id, title, min_gram, wage } = useProduct(props.value)
|
||||
|
||||
const wageLabel = computed(() => {
|
||||
const w = wage.value
|
||||
if (w == null) return ''
|
||||
return w % 1 === 0 ? String(w) : w.toFixed(2)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.card {
|
||||
cursor: pointer;
|
||||
background: @canvas;
|
||||
border: 1px solid @hairline;
|
||||
border-radius: 18px;
|
||||
overflow: hidden;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.card:active {
|
||||
transform: scale(0.985);
|
||||
}
|
||||
|
||||
.card__art {
|
||||
position: relative;
|
||||
aspect-ratio: 1 / 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: @hairlineSoft;
|
||||
}
|
||||
|
||||
.card--wide .card__art {
|
||||
aspect-ratio: 4 / 3;
|
||||
}
|
||||
|
||||
.card__art img {
|
||||
width: 100%;
|
||||
max-width: 200px;
|
||||
height: 100%;
|
||||
max-height: 200px;
|
||||
object-fit: contain;
|
||||
object-position: center;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.card__fav {
|
||||
position: absolute;
|
||||
top: 9px;
|
||||
left: 9px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 50%;
|
||||
color: @inkMuted;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
backdrop-filter: blur(6px);
|
||||
transition: color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
.card__fav.is-on {
|
||||
color: @wine;
|
||||
}
|
||||
.card__fav:active {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
|
||||
.card__badge {
|
||||
position: absolute;
|
||||
top: 9px;
|
||||
right: 9px;
|
||||
padding: 4px 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
background: @wine;
|
||||
}
|
||||
|
||||
.card__body {
|
||||
padding: 11px 12px 13px;
|
||||
}
|
||||
|
||||
.card__title {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: @ink;
|
||||
line-height: 1.6;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.card__meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding-top: 7px;
|
||||
}
|
||||
|
||||
.card__weight {
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
color: @inkSoft;
|
||||
}
|
||||
|
||||
.card__wage {
|
||||
font-size: 10.5px;
|
||||
color: @inkFaint;
|
||||
padding-inline-start: 7px;
|
||||
border-inline-start: 1px solid @hairline;
|
||||
}
|
||||
</style>
|
||||
@@ -1,201 +0,0 @@
|
||||
<!--
|
||||
Editorial hero for the home screen. Replaces the legacy swiper banner with a
|
||||
self-contained, dependency-free slider: no swiper CSS to fight, no autoplay
|
||||
jitter, and it keeps working when a slide has no artwork.
|
||||
-->
|
||||
<template>
|
||||
<section class="showcase" v-if="slides.length">
|
||||
<div class="showcase__frame">
|
||||
<transition-group name="showcase-fade" tag="div" class="showcase__stage">
|
||||
<article v-for="(slide, i) in slides" :key="slide.key" v-show="i === index" class="showcase__slide">
|
||||
<img v-if="slide.image" :src="slide.image" alt="" class="showcase__art" />
|
||||
<div class="showcase__scrim" aria-hidden="true"></div>
|
||||
|
||||
<div class="showcase__copy">
|
||||
<span class="showcase__eyebrow">{{ slide.eyebrow }}</span>
|
||||
<h2 class="showcase__title">{{ slide.title }}</h2>
|
||||
<p class="showcase__sub">{{ slide.subtitle }}</p>
|
||||
<button type="button" class="showcase__cta" @click="emit('select', slide)">
|
||||
{{ slide.cta }}
|
||||
<Icon icon="vuesax-linear:arrow-left-2" size="17" />
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</transition-group>
|
||||
</div>
|
||||
|
||||
<div class="showcase__dots" v-if="slides.length > 1">
|
||||
<button
|
||||
v-for="(slide, i) in slides"
|
||||
:key="slide.key"
|
||||
type="button"
|
||||
class="showcase__dot"
|
||||
:class="{ 'is-active': i === index }"
|
||||
:aria-label="slide.title"
|
||||
@click="go(i)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import Icon from '../icon/Icon.vue'
|
||||
|
||||
export interface ShowcaseSlide {
|
||||
key: string
|
||||
eyebrow: string
|
||||
title: string
|
||||
subtitle: string
|
||||
cta: string
|
||||
image?: string
|
||||
categoryId?: string
|
||||
}
|
||||
|
||||
const props = defineProps<{ slides: ShowcaseSlide[] }>()
|
||||
const emit = defineEmits<{ (e: 'select', slide: ShowcaseSlide): void }>()
|
||||
|
||||
const index = ref(0)
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
function go(i: number) {
|
||||
index.value = i
|
||||
restart()
|
||||
}
|
||||
function restart() {
|
||||
if (timer) clearInterval(timer)
|
||||
if (props.slides.length > 1) {
|
||||
timer = setInterval(() => {
|
||||
index.value = (index.value + 1) % props.slides.length
|
||||
}, 6000)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(restart)
|
||||
onBeforeUnmount(() => {
|
||||
if (timer) clearInterval(timer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.showcase__frame {
|
||||
position: relative;
|
||||
border-radius: 22px;
|
||||
overflow: hidden;
|
||||
background: @ink;
|
||||
box-shadow: 0 26px 50px -34px rgba(20, 22, 26, 0.85);
|
||||
}
|
||||
|
||||
.showcase__stage {
|
||||
position: relative;
|
||||
display: block;
|
||||
aspect-ratio: 320 / 208;
|
||||
}
|
||||
|
||||
.showcase__slide {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
.showcase__art {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
opacity: 0.5;
|
||||
transform: scale(1.04);
|
||||
}
|
||||
|
||||
.showcase__scrim {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
linear-gradient(255deg, rgba(122, 27, 51, 0.55) 0%, rgba(122, 27, 51, 0) 52%),
|
||||
linear-gradient(to left, rgba(20, 22, 26, 0.2) 0%, rgba(20, 22, 26, 0.92) 72%);
|
||||
}
|
||||
|
||||
.showcase__copy {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
padding: 22px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.showcase__eyebrow {
|
||||
font-size: 10.5px;
|
||||
letter-spacing: 1.6px;
|
||||
color: rgba(255, 255, 255, 0.62);
|
||||
padding-bottom: 9px;
|
||||
}
|
||||
|
||||
.showcase__title {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
line-height: 1.35;
|
||||
color: #fff;
|
||||
margin: 0 0 7px;
|
||||
}
|
||||
|
||||
.showcase__sub {
|
||||
font-size: 12.5px;
|
||||
line-height: 1.85;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
margin: 0 0 16px;
|
||||
max-width: 30ch;
|
||||
}
|
||||
|
||||
.showcase__cta {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
padding: 9px 16px;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: @ink;
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
font-family: inherit;
|
||||
transition: transform 0.18s ease, background 0.18s ease;
|
||||
}
|
||||
.showcase__cta:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.showcase__dots {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.showcase__dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 999px;
|
||||
background: @hairline;
|
||||
transition: all 0.25s ease;
|
||||
}
|
||||
.showcase__dot.is-active {
|
||||
width: 20px;
|
||||
background: @wine;
|
||||
}
|
||||
|
||||
.showcase-fade-enter-active,
|
||||
.showcase-fade-leave-active {
|
||||
transition: opacity 0.55s ease;
|
||||
}
|
||||
.showcase-fade-enter-from,
|
||||
.showcase-fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,45 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/product/category.vue.
|
||||
Not yet wired to real data: the new API has no categories-with-icon endpoint
|
||||
(Prisma has a Category model, but no controller/route exposes it, and there
|
||||
are no per-category icon images). HomeView passes an empty list for now, so
|
||||
this renders nothing rather than fabricated placeholder tiles — see the
|
||||
"existing issue found" note in the report about the legacy `id === 45`
|
||||
special-case, preserved here for whenever real category data exists.
|
||||
-->
|
||||
<template>
|
||||
<router-link :to="{ name: 'search' }" @click="setCats" class="cursor-pointer h-full block">
|
||||
<div
|
||||
class="h-full w-full text-center flex flex-col items-center justify-between rounded-[4px]"
|
||||
:class="value.id === '45' ? 'bg-primary' : 'border border-1 border-secondary'"
|
||||
>
|
||||
<div class="flex justify-center mt-4 shrink-0">
|
||||
<img v-lazy="value.icon?.image" alt="category" class="w-[32px] h-[32px] text-center" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="mb-4 mt-4 py-1 px-1 font-semibold flex-1 flex items-center justify-center text-center min-h-[40px]"
|
||||
:class="value.id === '45' ? 'text-white' : 'text-primary'"
|
||||
>
|
||||
{{ value.title }}
|
||||
</div>
|
||||
</div>
|
||||
</router-link>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useFiltersStore } from '../../stores/filtersStore'
|
||||
|
||||
interface CategoryValue {
|
||||
id: string
|
||||
title: string
|
||||
icon?: { image: string }
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{ value: CategoryValue }>(), {})
|
||||
const filters = useFiltersStore()
|
||||
|
||||
const setCats = () => {
|
||||
filters.query.cats = [props.value.id]
|
||||
}
|
||||
</script>
|
||||
@@ -1,146 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/slider/homeSlider.vue.
|
||||
`$prefix` (legacy global property, always the compile-time-constant 'montzar'
|
||||
from themeConfig) is inlined directly here rather than re-registered as a
|
||||
global — same resolved value, no behavior change.
|
||||
-->
|
||||
<template>
|
||||
<div>
|
||||
<Swiper
|
||||
:grabCursor="true"
|
||||
:centeredSlides="true"
|
||||
:space-between="5"
|
||||
:loop="true"
|
||||
:slidesPerView="1.3"
|
||||
class="w-full home-slider"
|
||||
:autoplay="data.autoplay"
|
||||
:pagination="{ clickable: true }"
|
||||
>
|
||||
<SwiperSlide class="bg-center bg-cover h-auto" v-for="(item, index) in slides" :key="index">
|
||||
<img @click="clickHandler(item)" v-lazy="item.src" width="100%" class="block w-full rounded-[10px] object-cover" :style="`height:${height}`" />
|
||||
</SwiperSlide>
|
||||
</Swiper>
|
||||
<Drawer
|
||||
v-model:visible="data.show"
|
||||
placement="bottom"
|
||||
:closable="false"
|
||||
@close="setAutoPlay"
|
||||
height="60%"
|
||||
class="montzar-rounded-drawer rtl text-white bg-primaryLighten whitespace-pre-wrap text[13px]"
|
||||
>
|
||||
{{ data.slideContent.text }}
|
||||
</Drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Swiper, SwiperSlide } from 'swiper/vue'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/navigation'
|
||||
import 'swiper/css/pagination'
|
||||
import 'swiper/css/scrollbar'
|
||||
import SwiperCore, { Autoplay, Navigation, Pagination } from 'swiper'
|
||||
SwiperCore.use([Pagination, Navigation, Autoplay])
|
||||
import { reactive } from 'vue'
|
||||
import { Drawer } from 'ant-design-vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useFiltersStore } from '../../stores/filtersStore'
|
||||
|
||||
interface Slide {
|
||||
text: string | undefined
|
||||
type: string | undefined
|
||||
src: string | undefined
|
||||
link: string | undefined
|
||||
}
|
||||
|
||||
interface Data {
|
||||
show: boolean
|
||||
slideContent: Slide
|
||||
autoplay: { delay: number; disableOnInteraction: boolean } | boolean
|
||||
}
|
||||
|
||||
withDefaults(defineProps<{ slides: Slide[]; height: string }>(), {})
|
||||
|
||||
const data: Data = reactive({
|
||||
show: false,
|
||||
slideContent: { text: undefined, type: undefined, src: undefined, link: undefined },
|
||||
autoplay: { delay: 4000, disableOnInteraction: false },
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
const filters = useFiltersStore()
|
||||
|
||||
const clickHandler = async (item: Slide) => {
|
||||
if (item) {
|
||||
data.slideContent = item
|
||||
switch (item.type) {
|
||||
case 'popup':
|
||||
if (item && !(!item.text || item.text.length === 0)) data.show = true
|
||||
break
|
||||
case 'link':
|
||||
if (item && !(!item.link || item.link.length === 0)) window.open(item.link)?.focus()
|
||||
break
|
||||
case 'discount':
|
||||
if (!(!item.link || item.link.length === 0)) {
|
||||
// EXISTING ISSUE, ported as-is: legacy sets `query.value.discount`,
|
||||
// but the actual filter field is `has_discount` — this assignment
|
||||
// never affected search filtering in legacy either. Not "fixed"
|
||||
// here; flagged separately.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(filters.query as any).discount = true
|
||||
await router.push({ name: 'search' })
|
||||
}
|
||||
break
|
||||
default:
|
||||
// code block
|
||||
}
|
||||
data.autoplay = false
|
||||
}
|
||||
}
|
||||
const setAutoPlay = async () => {
|
||||
data.autoplay = { delay: 4000, disableOnInteraction: false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less">
|
||||
.home-slider {
|
||||
&.swiper {
|
||||
padding: 24px 0 24px 0;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet {
|
||||
transition: all 0.2s;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active,
|
||||
.swiper-pagination-bullet-active-main {
|
||||
width: 24px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.swiper-horizontal > .swiper-pagination-bullets,
|
||||
.swiper-pagination-bullets.swiper-pagination-horizontal,
|
||||
.swiper-pagination-custom,
|
||||
.swiper-pagination-fraction {
|
||||
bottom: 0 !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullets-dynamic * {
|
||||
transform: unset !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active {
|
||||
background: @primary;
|
||||
}
|
||||
|
||||
.swiper-slide {
|
||||
transition: all 0.6s;
|
||||
}
|
||||
|
||||
.swiper-slide:not(.swiper-slide-active) {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,139 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/slider/slider.vue.
|
||||
EXISTING ISSUE, ported as-is (not fixed): `showPopup` takes (src, index) but
|
||||
the template calls it with a single argument (`showPopup(item)`), and the
|
||||
v-for doesn't even destructure an index. `index` is therefore always
|
||||
undefined inside showPopup, so its "rotate the slides array to start at the
|
||||
tapped image" logic never runs — tapping any thumbnail always opens the
|
||||
full-screen zoom viewer starting from the first image, never the tapped one.
|
||||
-->
|
||||
<template>
|
||||
<div>
|
||||
<Swiper :grabCursor="true" :centeredSlides="true" :loop="false" :slidesPerView="1" class="w-full slider" :pagination="{ clickable: true }">
|
||||
<SwiperSlide class="bg-center bg-cover h-auto" v-for="item in slides" :key="item">
|
||||
<img @click="showPopup(item)" v-lazy="item" class="block w-auto object-cover z-0 pb-1" :style="`height:${height}`" />
|
||||
</SwiperSlide>
|
||||
<transition name="slideUp" mode="out-in">
|
||||
<svg alt="منتزر" class="absolute bottom-0 z-[2] m-auto pointer-events-none w-full h-[90px]" v-if="flagSvg">
|
||||
<path fill="#FFFFFF" class="w-full h-[90px]" :d="whiteShape" />
|
||||
<path fill="#3E5279" class="w-full h-[90px]" :d="curvedShape" />
|
||||
</svg>
|
||||
</transition>
|
||||
</Swiper>
|
||||
|
||||
<Drawer v-model:visible="show" placement="bottom" :closable="false" :bodyStyle="{ padding: 0 }" class="rtl whitespace-pre-wrap bg-white" height="100vh">
|
||||
<div @click="show = false" class="fixed top-[30px] right-[20px] z-[5] pb-2 pl-5">
|
||||
<Icon icon="vuesax-linear:arrow-right-1" @click="show = false" class="cursor-pointer text-white bg-secondary rounded-[5px] p-[2.5px]" size="28" />
|
||||
</div>
|
||||
|
||||
<Swiper :grabCursor="true" :zoom="{ maxRatio: 1.2 }" :modules="[Zoom]" :centeredSlides="true" :loop="false" :slidesPerView="1" class="w-full slider" :key="show">
|
||||
<SwiperSlide class="bg-center bg-cover h-auto" v-for="item in slides" :key="item">
|
||||
<div class="swiper-zoom-container">
|
||||
<img v-lazy="item" class="block object-contain w-[100vw] h-screen" />
|
||||
</div>
|
||||
</SwiperSlide>
|
||||
</Swiper>
|
||||
</Drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeMount, ref } from 'vue'
|
||||
import { Swiper, SwiperSlide } from 'swiper/vue'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/navigation'
|
||||
import 'swiper/css/pagination'
|
||||
import 'swiper/css/scrollbar'
|
||||
import 'swiper/css/zoom'
|
||||
import SwiperCore, { Navigation, Pagination, Zoom } from 'swiper'
|
||||
import { Drawer } from 'ant-design-vue'
|
||||
import Icon from '../icon/Icon.vue'
|
||||
import { useWindowDataStore } from '../../stores/windowDataStore'
|
||||
|
||||
SwiperCore.use([Pagination, Navigation])
|
||||
|
||||
const props = withDefaults(defineProps<{ slides: string[]; height: string; width?: string }>(), {})
|
||||
|
||||
const show = ref(false)
|
||||
const slides = ref<string[]>([...props.slides])
|
||||
|
||||
const showPopup = (src: string, index?: number) => {
|
||||
slides.value = [...props.slides]
|
||||
for (let i = 0; i < (index ?? 0); i++) {
|
||||
const helper = slides.value.shift()
|
||||
if (helper) slides.value.push(helper)
|
||||
}
|
||||
show.value = true
|
||||
}
|
||||
|
||||
const flagSvg = ref(false)
|
||||
onBeforeMount(() => {
|
||||
setTimeout(() => {
|
||||
flagSvg.value = true
|
||||
}, 100)
|
||||
})
|
||||
|
||||
const windowData = useWindowDataStore()
|
||||
const shapeHeight = 90
|
||||
const wcp1x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 21.8878249)
|
||||
const wcp2x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 2.37406336)
|
||||
const crcr1cp1x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 1.56947374)
|
||||
const crcr1cp2x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 5.47609844)
|
||||
const crcr2cp1x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 15.8024691)
|
||||
const crcr2cp2x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 2.2606383)
|
||||
const whiteShape = computed(() => `M0,${shapeHeight}H${Math.min(windowData.width, 768)}V0C${wcp1x.value},19.17,${wcp2x.value},119.08,0,49Z`)
|
||||
const curvedShape = computed(
|
||||
() => `M0,39.77C${crcr1cp1x.value},91.74,${crcr1cp2x.value},61.5,${Math.min(windowData.width, 768)},0,C${crcr2cp1x.value},29.34,${crcr2cp2x.value},112.54,0,57.1Z`,
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="less">
|
||||
.slider {
|
||||
.swiper-pagination-bullet {
|
||||
transition: all 0.2s;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active,
|
||||
.swiper-pagination-bullet-active-main {
|
||||
width: 24px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.swiper-horizontal > .swiper-pagination-bullets,
|
||||
.swiper-pagination-bullets.swiper-pagination-horizontal,
|
||||
.swiper-pagination-custom,
|
||||
.swiper-pagination-fraction {
|
||||
bottom: 40px !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullets-dynamic * {
|
||||
transform: unset !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active {
|
||||
background: @primary;
|
||||
}
|
||||
|
||||
.swiper-slide img {
|
||||
margin: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.slideUp-enter-active,
|
||||
.slideUp-leave-active {
|
||||
opacity: 1;
|
||||
transition: all @transition-duration ease @transition-delay;
|
||||
}
|
||||
|
||||
.slideUp-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(100%);
|
||||
}
|
||||
|
||||
.slideUp-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-100%);
|
||||
}
|
||||
</style>
|
||||
@@ -1,12 +0,0 @@
|
||||
<!-- Ported from legacy henza_pwa/src/components/content.vue -->
|
||||
<template>
|
||||
<main :style="{ marginTop: transition.transitionEnded ? `${transition.headerHeight}px` : 'unset' }">
|
||||
<slot />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useTransitionStore } from '../../stores/transitionStore'
|
||||
|
||||
const transition = useTransitionStore()
|
||||
</script>
|
||||
@@ -1,41 +0,0 @@
|
||||
<!-- Ported from legacy henza_pwa/src/components/ui/ScrollFetch.vue — the plain
|
||||
infinite-scroll container (default ant Empty, no custom illustration). -->
|
||||
<template>
|
||||
<main
|
||||
class="overflow-auto no-scrollbar w-[100vw] h-screen max-w-screen-md m-auto"
|
||||
:style="{ paddingTop: padding || transition.headerHeight + 'px' }"
|
||||
ref="scrollArea"
|
||||
>
|
||||
<slot></slot>
|
||||
<Spinner cls="my-[10px]" :spinning="loading" :indicator="true" tip="درحال دریافت اطلاعات" />
|
||||
<EmptyState v-if="flag" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useInfiniteScroll } from '@vueuse/core'
|
||||
import Spinner from '../Spinner.vue'
|
||||
import EmptyState from '../EmptyState.vue'
|
||||
import { useTransitionStore } from '../../stores/transitionStore'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
loading: boolean
|
||||
flag: boolean
|
||||
padding?: string
|
||||
}>(),
|
||||
{},
|
||||
)
|
||||
const emit = defineEmits<{ (e: 'fetch'): void }>()
|
||||
const transition = useTransitionStore()
|
||||
const scrollArea = ref(null)
|
||||
|
||||
useInfiniteScroll(
|
||||
scrollArea,
|
||||
() => {
|
||||
emit('fetch')
|
||||
},
|
||||
{ distance: 50 },
|
||||
)
|
||||
</script>
|
||||
@@ -1,48 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/ui/ScrollFetchAfterSearch.vue.
|
||||
Legacy imported emp_after_search.svg / emp_before_search.svg and an `isSearch`
|
||||
prop to pick between them, but the live template used neither — it rendered
|
||||
`ordersEmpty.svg` unconditionally. Ported as-is (unused imports dropped,
|
||||
`isSearch` kept since it is part of the component's declared prop contract).
|
||||
-->
|
||||
<template>
|
||||
<main
|
||||
class="overflow-auto no-scrollbar w-[100vw] h-screen max-w-screen-md m-auto"
|
||||
:style="{ paddingTop: padding || transition.headerHeight + 'px' }"
|
||||
ref="scrollArea"
|
||||
>
|
||||
<slot></slot>
|
||||
<Spinner cls="my-[10px]" :spinning="loading" :indicator="true" tip="درحال دریافت اطلاعات" />
|
||||
<EmptyState v-if="flag && !loading" :image="ordersEmpty" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useInfiniteScroll } from '@vueuse/core'
|
||||
import Spinner from '../Spinner.vue'
|
||||
import EmptyState from '../EmptyState.vue'
|
||||
import ordersEmpty from '../../assets/img/empty/ordersEmpty.svg'
|
||||
import { useTransitionStore } from '../../stores/transitionStore'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
loading: boolean
|
||||
flag: boolean
|
||||
padding?: string
|
||||
isSearch?: boolean
|
||||
}>(),
|
||||
{},
|
||||
)
|
||||
const emit = defineEmits<{ (e: 'fetch'): void }>()
|
||||
const transition = useTransitionStore()
|
||||
const scrollArea = ref(null)
|
||||
|
||||
useInfiniteScroll(
|
||||
scrollArea,
|
||||
() => {
|
||||
emit('fetch')
|
||||
},
|
||||
{ distance: 50 },
|
||||
)
|
||||
</script>
|
||||
@@ -12,14 +12,14 @@
|
||||
// data exists in the new API, so `hasDiscountWage` is always null here —
|
||||
// the discount badge and "before/after" price never render, which is
|
||||
// correct given there is genuinely nothing to show, not a bug.
|
||||
// - `wage`: legacy added the logged-in customer's own `percent` (a
|
||||
// commission/markup field on their account) on top of the variant's
|
||||
// making-charge %. No login exists in this port yet, so wage is just the
|
||||
// selected variant's defaultWagePercent on its own.
|
||||
// - `wage` now comes from the server (wageQuoteStore), which adds the
|
||||
// customer's own percent and the promotion exactly as legacy did.
|
||||
// - `is_exist` (stock) and `has_warranty`: no such fields exist on our
|
||||
// ProductVariant model yet — always true / false respectively.
|
||||
import { computed, ref, unref, type Ref } from 'vue'
|
||||
import type { ProductSummary, ProductVariantSummary } from '../api/client'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
import { useWageQuoteStore } from '../stores/wageQuoteStore'
|
||||
|
||||
/** A variant can be ordered when it has stock, or when it is flagged pre-order. */
|
||||
export function isVariantOrderable(v: ProductVariantSummary): boolean {
|
||||
@@ -47,7 +47,20 @@ export function useProduct(productItem: ProductSummary, initialVariant?: Product
|
||||
const variants = computed(() => product.value.variants)
|
||||
const selectedVariant: Ref<ProductVariantSummary | null> = ref(initialVariant ?? getCheapestVariant(unref(variants)))
|
||||
const min_gram = computed(() => selectedVariant.value ? parseFloat(selectedVariant.value.rashWeightGrams) : 0)
|
||||
const wage = computed(() => (selectedVariant.value ? parseFloat(selectedVariant.value.defaultWagePercent) : null))
|
||||
// The making charge the server will charge (MON-08): variant + the
|
||||
// customer's own percent − the best active promotion, by the formula the
|
||||
// admin «اجرت» screen controls. Signed in: the server's figure, hidden for
|
||||
// the moment it loads rather than flashing a different number. Signed out
|
||||
// (no customer, so no customer percent): the variant's own figure.
|
||||
const session = useSessionStore()
|
||||
const wageQuotes = useWageQuoteStore()
|
||||
const wage = computed(() => {
|
||||
const v = selectedVariant.value
|
||||
if (!v) return null
|
||||
if (!session.isLoggedIn) return parseFloat(v.defaultWagePercent)
|
||||
wageQuotes.request(v.id)
|
||||
return wageQuotes.finalPercent(v.id)
|
||||
})
|
||||
const hasDiscountWage = ref<number | null>(null) // no promotions backend yet — see file header
|
||||
// REAL stock: ProductVariant.qty / isPreOrder exist and are returned by
|
||||
// GET /catalog/products. A variant is orderable when it has stock, or when
|
||||
|
||||
@@ -1,22 +1,55 @@
|
||||
// Adapted from legacy henza_pwa/src/Mixins/favorite.ts + the `favorits` slice of
|
||||
// myDataStore. Legacy persisted favorites server-side via POST /add-to-fav; the
|
||||
// new API has no favorites endpoint yet, so this is local-only (Pinia state,
|
||||
// not persisted) until that backend support exists. Flagged — not a silent
|
||||
// behavior match, a deliberate stand-in.
|
||||
// myDataStore. Legacy kept favourites on the server (POST add-to-fav /
|
||||
// get-favorites, table major_favorites); so does this, through
|
||||
// /customer/me/favorites (FAV-01). It used to be memory-only, so favourites
|
||||
// vanished on reload and the ones imported from legacy were never shown.
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
import { api } from '../api/client'
|
||||
import { useSessionStore } from './session'
|
||||
|
||||
export const useFavoritesStore = defineStore('favorites', {
|
||||
state: () => ({
|
||||
ids: [] as string[],
|
||||
}),
|
||||
actions: {
|
||||
toggle(id: string) {
|
||||
const index = this.ids.indexOf(id)
|
||||
if (index === -1) this.ids.push(id)
|
||||
else this.ids.splice(index, 1)
|
||||
export const useFavoritesStore = defineStore('favorites', () => {
|
||||
const ids = ref<string[]>([])
|
||||
const session = useSessionStore()
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
ids.value = (await api.getFavorites()).ids
|
||||
} catch (e) {
|
||||
// Offline or a dead session (the client already handles 401): keep what we have.
|
||||
console.warn('favorites: load failed', e)
|
||||
}
|
||||
}
|
||||
|
||||
// Loaded for whoever is signed in, cleared on logout — never another user's list.
|
||||
watch(
|
||||
() => session.token,
|
||||
(token) => {
|
||||
ids.value = []
|
||||
if (token) void load()
|
||||
},
|
||||
isFavorite(id: string) {
|
||||
return this.ids.includes(id)
|
||||
},
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
/** Flips at once on screen, then confirms with the server (legacy toggled the same way). */
|
||||
async function toggle(id: string) {
|
||||
const was = ids.value.includes(id)
|
||||
ids.value = was ? ids.value.filter((x) => x !== id) : [id, ...ids.value]
|
||||
try {
|
||||
const { favorite } = await api.toggleFavorite(id)
|
||||
const has = ids.value.includes(id)
|
||||
if (favorite && !has) ids.value = [id, ...ids.value]
|
||||
if (!favorite && has) ids.value = ids.value.filter((x) => x !== id)
|
||||
} catch (e) {
|
||||
// Put it back so the heart never shows a state the server does not hold.
|
||||
ids.value = was ? [id, ...ids.value.filter((x) => x !== id)] : ids.value.filter((x) => x !== id)
|
||||
console.warn('favorites: toggle failed', e)
|
||||
}
|
||||
}
|
||||
|
||||
function isFavorite(id: string) {
|
||||
return ids.value.includes(id)
|
||||
}
|
||||
|
||||
return { ids, load, toggle, isFavorite }
|
||||
})
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// Ported from legacy henza_pwa/src/store/loadingStore.ts — a single global
|
||||
// loading flag, converted from the hand-rolled ref-class to Pinia.
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useLoadingStore = defineStore('loading', {
|
||||
state: () => ({
|
||||
loading: false,
|
||||
}),
|
||||
actions: {
|
||||
setLoading(loading: boolean) {
|
||||
this.loading = loading
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
// The making charge («اجرت») the server will charge this customer for each
|
||||
// variant — fetched from /customer/me/wage-quote, which runs the same formula
|
||||
// that prices the order (MON-08, owner ruling 2026-10-08). The app shows this
|
||||
// figure, never one it computes itself, so what is shown is what is charged.
|
||||
//
|
||||
// Requests are batched: many cards asking at once become one call.
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
import { api, type WageQuote } from '../api/client'
|
||||
import { useSessionStore } from './session'
|
||||
|
||||
export const useWageQuoteStore = defineStore('wageQuotes', () => {
|
||||
const session = useSessionStore()
|
||||
const quotes = ref<Record<string, WageQuote>>({})
|
||||
const pending = new Set<string>()
|
||||
const inFlight = new Set<string>()
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// A different customer has a different percent: never reuse another's quotes.
|
||||
watch(
|
||||
() => session.token,
|
||||
() => {
|
||||
quotes.value = {}
|
||||
pending.clear()
|
||||
inFlight.clear()
|
||||
},
|
||||
)
|
||||
|
||||
async function flush() {
|
||||
timer = null
|
||||
const ids = [...pending].slice(0, 200)
|
||||
ids.forEach((id) => {
|
||||
pending.delete(id)
|
||||
inFlight.add(id)
|
||||
})
|
||||
if (pending.size) timer = setTimeout(flush, 0)
|
||||
if (!ids.length) return
|
||||
try {
|
||||
const rows = await api.getWageQuotes(ids)
|
||||
const next = { ...quotes.value }
|
||||
for (const r of rows) next[r.variantId] = r
|
||||
quotes.value = next
|
||||
} catch (e) {
|
||||
console.warn('wage quote failed', e)
|
||||
} finally {
|
||||
ids.forEach((id) => inFlight.delete(id))
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks for a variant's quote (idempotent; safe to call from a computed). */
|
||||
function request(variantId: string) {
|
||||
if (!session.token || quotes.value[variantId] || pending.has(variantId) || inFlight.has(variantId)) return
|
||||
pending.add(variantId)
|
||||
if (!timer) timer = setTimeout(flush, 30)
|
||||
}
|
||||
|
||||
/** The charged percent, or null while it is still loading. */
|
||||
function finalPercent(variantId: string): number | null {
|
||||
const q = quotes.value[variantId]
|
||||
return q ? parseFloat(q.finalPercent) : null
|
||||
}
|
||||
|
||||
return { quotes, request, finalPercent }
|
||||
})
|
||||
@@ -11,20 +11,6 @@ export function price(val: number | string | undefined | null): string {
|
||||
return val as any
|
||||
}
|
||||
|
||||
export function priceUnit(val: number | string | undefined | null): string {
|
||||
if (['string', 'number'].includes(typeof val)) {
|
||||
return `${val!.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} تومان `
|
||||
}
|
||||
return val as any
|
||||
}
|
||||
|
||||
export function priceUnitRialLess(val: number | string | undefined | null): string {
|
||||
if (['string', 'number'].includes(typeof val)) {
|
||||
return `${val!.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} `
|
||||
}
|
||||
return val as any
|
||||
}
|
||||
|
||||
export function jdate(val: string | undefined | null): string {
|
||||
if (val) {
|
||||
// legacy parsed a fixed 'YYYY-MM-DD HH:mm:ss' Laravel timestamp format;
|
||||
|
||||
@@ -1,30 +1,9 @@
|
||||
// Ported from legacy henza_pwa/src/Mixins/validator/index.ts — same rules,
|
||||
// same messages, verbatim.
|
||||
// same messages, verbatim. Only the rules the app uses are kept (DEAD-01/02).
|
||||
export const message = (field: string) => ` مقدار ${field} نا معتبر است `
|
||||
|
||||
export const mobile = (field: string) => ({
|
||||
pattern: /^(\+98|0098|98|0)?9\d{9}$/g,
|
||||
message: message(field),
|
||||
})
|
||||
export const phone = (field: string) => ({
|
||||
pattern: /^((\+98|0098|98|0)\d1)?\d{8}$/g,
|
||||
message: message(field),
|
||||
})
|
||||
export const fa = (field: string) => ({
|
||||
pattern: /^([-ۿﮊپچگ ])+$/,
|
||||
message: ` مقدار ${field} باید فارسی باشد `,
|
||||
})
|
||||
export const mail = (field: string) => ({ type: 'email', message: message(field) })
|
||||
export const url = (field: string) => ({ type: 'url', message: message(field) })
|
||||
export const username = (field: string) => ({
|
||||
pattern: /^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/gim,
|
||||
message: ` مقدار ${field} باید شامل حروف و اعداد انگلیسی و _ باشد `,
|
||||
})
|
||||
export const required = (field: string) => ({ required: true, message: ` لطفا ${field} را وارد کنید ` })
|
||||
export const sheba = (field: string) => ({ pattern: /^IR\d{24}$/gim, message: message(field) })
|
||||
export const card = (field: string) => ({ pattern: /^\d{16}$/gim, message: message(field) })
|
||||
export const zip = (field: string) => ({ pattern: /^\d{10}$/gim, message: message(field) })
|
||||
export const num = (field: string) => ({ pattern: /^\d*$/gim, message: message(field) })
|
||||
export const len = (field: string, len: number) => ({ len, message: ` مقدار ${field} باید ${len} کارکتر باشد ` })
|
||||
export const max = (field: string, max: number) => ({ max, message: ` مقدار ${field} باید کمتر از ${max} کارکتر باشد ` })
|
||||
export const min = (field: string, min: number) => ({ min, message: ` مقدار ${field} باید بیشتر از ${min} کارکتر باشد ` })
|
||||
|
||||
@@ -222,6 +222,8 @@ const submitOrder = async () => {
|
||||
return {
|
||||
productVariantId: item.vid,
|
||||
quantity: item.qty,
|
||||
// Sent for older API builds only: the server prices app orders itself
|
||||
// (MON-08) and ignores this figure.
|
||||
wagePercent: variant ? parseFloat(variant.defaultWagePercent) : 0,
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -8,19 +8,17 @@
|
||||
"lint": "eslint \"src/**/*.{ts,vue}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons-vue": "^6.1.0",
|
||||
"@gold-bank/shared-types": "workspace:*",
|
||||
"@lottiefiles/dotlottie-vue": "^0.4.15",
|
||||
"@vueuse/core": "^9.13.0",
|
||||
"ant-design-vue": "^3.2.20",
|
||||
"gsap": "^3.9.1",
|
||||
"moment-jalaali": "^0.10.0",
|
||||
"pinia": "^2.2.0",
|
||||
"swiper": "^7.4.1",
|
||||
"vant": "^4.0.3",
|
||||
"vue": "^3.5.0",
|
||||
"vue-router": "^4.4.0",
|
||||
"vue3-lazyload": "^0.2.5-beta",
|
||||
"@lottiefiles/dotlottie-vue": "^0.4.15"
|
||||
"vue3-lazyload": "^0.2.5-beta"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.1.0",
|
||||
@@ -30,8 +28,8 @@
|
||||
"tailwindcss": "3.0.18",
|
||||
"typescript": "^5.5.0",
|
||||
"vite": "^5.4.0",
|
||||
"vue-tsc": "^2.1.0",
|
||||
"vite-plugin-pwa": "^0.20.5",
|
||||
"vue-tsc": "^2.1.0",
|
||||
"workbox-precaching": "^7.1.0",
|
||||
"workbox-window": "^7.1.0"
|
||||
}
|
||||
|
||||
@@ -303,6 +303,15 @@ export interface AccountingBalance {
|
||||
provider: string | null
|
||||
}
|
||||
|
||||
/** POST /customer/me/wage-quote — one variant's making charge for the signed-in customer. */
|
||||
export interface WageQuote {
|
||||
variantId: string
|
||||
variantPercent: string
|
||||
customerPercent: string
|
||||
promotionPercent: string
|
||||
finalPercent: string
|
||||
}
|
||||
|
||||
export const api = {
|
||||
listProducts: () => request<ProductSummary[]>('/catalog/products'),
|
||||
|
||||
@@ -336,6 +345,17 @@ export const api = {
|
||||
getAccountingBalance: () => request<AccountingBalance>('/customer/me/accounting-balance'),
|
||||
getMyOrders: () => request<OrderDetail[]>('/customer/me/orders'),
|
||||
getMyLedgerEntries: () => request<LedgerEntrySummary[]>('/customer/me/ledger-entries'),
|
||||
/** The making charge the server will charge for these variants (MON-08). */
|
||||
getWageQuotes: (variantIds: string[]) =>
|
||||
request<WageQuote[]>('/customer/me/wage-quote', { method: 'POST', body: JSON.stringify({ variantIds }) }),
|
||||
/** Favourite product ids, newest first — legacy get-favorites (FAV-01). */
|
||||
getFavorites: () => request<{ ids: string[] }>('/customer/me/favorites'),
|
||||
/** Legacy add-to-fav: adds or removes; answers the new state. */
|
||||
toggleFavorite: (productId: string) =>
|
||||
request<{ favorite: boolean }>('/customer/me/favorites/toggle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ productId }),
|
||||
}),
|
||||
|
||||
createOrder: (dto: CreateOrderDto) => request<OrderSummary>('/orders', { method: 'POST', body: JSON.stringify(dto) }),
|
||||
getLatestGoldPrice: (karatPerMille = 750) => request<GoldPriceQuote>(`/pricing/latest?karatPerMille=${karatPerMille}`),
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
<!-- Ported from legacy henza_pwa/src/components/viewAll.vue.
|
||||
Legacy left `to` undeclared and relied on Vue's attribute fallthrough to
|
||||
land it on the root <router-link>; declared explicitly here only because
|
||||
vue-tsc's template type-checking (which legacy's own build never ran)
|
||||
requires router-link's `to` to be a known prop — same runtime value ends
|
||||
up bound either way, no behavior change. -->
|
||||
<template>
|
||||
<router-link :to="to" class="text-primary w-[280px] rounded-[10px] p-[8px] bg-light flex flex-col justify-center items-center">
|
||||
<Icon icon="vuesax-linear:arrow-left-1" class="cursor-pointer" size="25" />
|
||||
مشاهده همه
|
||||
</router-link>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { RouteLocationRaw } from 'vue-router'
|
||||
import Icon from './icon/Icon.vue'
|
||||
|
||||
defineProps<{ to: RouteLocationRaw }>()
|
||||
</script>
|
||||
@@ -1,229 +0,0 @@
|
||||
<!--
|
||||
The "حساب" block that sits BELOW the shop content on the home screen.
|
||||
|
||||
Two genuinely different states:
|
||||
- signed out: a quiet invitation, no fabricated numbers.
|
||||
- signed in: the customer's real gram position from GET /customers/:id
|
||||
(goldDebtGrams / fiatDebtRial), labelled بدهکار or بستانکار the same way
|
||||
DashboardView does, since the ledger stores debt as a signed figure.
|
||||
-->
|
||||
<template>
|
||||
<section class="acct">
|
||||
<template v-if="customer">
|
||||
<div class="acct__head">
|
||||
<div>
|
||||
<div class="acct__eyebrow">{{ positionLabel }}</div>
|
||||
<div class="acct__figure">
|
||||
{{ grams }}
|
||||
<span class="acct__unit">گرم</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="acct__seal" :class="isDebtor ? 'is-debtor' : 'is-creditor'">
|
||||
{{ isDebtor ? 'بدهکار' : 'بستانکار' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="acct__row">
|
||||
<span class="acct__rowLabel">بدهی ریالی</span>
|
||||
<span class="acct__rowValue">{{ price(fiat) }} <i>ریال</i></span>
|
||||
</div>
|
||||
|
||||
<div class="acct__actions">
|
||||
<button type="button" class="acct__action" @click="emit('go', 'ordersList')">
|
||||
<Icon icon="vuesax-linear:box" size="18" />
|
||||
سفارشها
|
||||
</button>
|
||||
<button type="button" class="acct__action" @click="emit('go', 'transactionsList')">
|
||||
<Icon icon="vuesax-linear:receipt-text" size="18" />
|
||||
اسناد
|
||||
</button>
|
||||
<button type="button" class="acct__action" @click="emit('go', 'profileData')">
|
||||
<Icon icon="vuesax-linear:user" size="18" />
|
||||
پروفایل
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="acct__invite">
|
||||
<div class="acct__inviteIcon" aria-hidden="true">
|
||||
<Icon icon="vuesax-linear:security-user" size="20" />
|
||||
</div>
|
||||
<div class="acct__inviteCopy">
|
||||
<h3>حساب گرمی شما</h3>
|
||||
<p>برای دیدن موجودی، سفارشها و اسناد خود وارد شوید.</p>
|
||||
</div>
|
||||
<button type="button" class="acct__inviteCta" @click="emit('login')">ورود / ثبتنام</button>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import Icon from '../icon/Icon.vue'
|
||||
import { price } from '../../utils/filters'
|
||||
import type { CustomerDetail } from '../../api/client'
|
||||
|
||||
const props = defineProps<{ customer: CustomerDetail | null }>()
|
||||
const emit = defineEmits<{ (e: 'go', route: string): void; (e: 'login'): void }>()
|
||||
|
||||
const isDebtor = computed(() => (props.customer ? parseFloat(props.customer.goldDebtGrams) > 0 : false))
|
||||
const positionLabel = computed(() => (isDebtor.value ? 'مانده بدهی گرمی' : 'مانده بستانکاری گرمی'))
|
||||
const grams = computed(() => (props.customer ? Math.abs(parseFloat(props.customer.goldDebtGrams)) : 0))
|
||||
const fiat = computed(() => (props.customer ? props.customer.fiatDebtRial.split('.')[0] : '0'))
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.acct {
|
||||
border-radius: 20px;
|
||||
padding: 18px;
|
||||
background: @primary;
|
||||
color: #fff;
|
||||
box-shadow: 0 22px 44px -32px rgba(20, 22, 26, 0.9);
|
||||
}
|
||||
|
||||
.acct__head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.acct__eyebrow {
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
padding-bottom: 7px;
|
||||
}
|
||||
|
||||
.acct__figure {
|
||||
font-size: 26px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.acct__unit {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
padding-inline-start: 3px;
|
||||
}
|
||||
|
||||
.acct__seal {
|
||||
font-size: 10.5px;
|
||||
font-weight: 700;
|
||||
padding: 5px 11px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.acct__seal.is-debtor {
|
||||
color: #fff;
|
||||
background: @wine;
|
||||
}
|
||||
.acct__seal.is-creditor {
|
||||
color: #fff;
|
||||
background: rgba(255, 255, 255, 0.13);
|
||||
}
|
||||
|
||||
.acct__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 16px;
|
||||
padding-top: 13px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.acct__rowLabel {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.acct__rowValue {
|
||||
font-weight: 700;
|
||||
}
|
||||
.acct__rowValue i {
|
||||
font-style: normal;
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.acct__actions {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.acct__action {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 11px 4px;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 13px;
|
||||
font-family: inherit;
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.88);
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
transition: background 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
.acct__action:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.acct__invite {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 13px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.acct__inviteIcon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 13px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
background: @wine;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.acct__inviteCopy {
|
||||
flex: 1 1 150px;
|
||||
}
|
||||
.acct__inviteCopy h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.acct__inviteCopy p {
|
||||
margin: 5px 0 0;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.8;
|
||||
color: rgba(255, 255, 255, 0.58);
|
||||
}
|
||||
|
||||
.acct__inviteCta {
|
||||
flex: 1 1 100%;
|
||||
margin-top: 4px;
|
||||
padding: 12px;
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
border-radius: 13px;
|
||||
background: #fff;
|
||||
color: @ink;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
.acct__inviteCta:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
</style>
|
||||
@@ -1,45 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/product/category.vue.
|
||||
Not yet wired to real data: the new API has no categories-with-icon endpoint
|
||||
(Prisma has a Category model, but no controller/route exposes it, and there
|
||||
are no per-category icon images). HomeView passes an empty list for now, so
|
||||
this renders nothing rather than fabricated placeholder tiles — see the
|
||||
"existing issue found" note in the report about the legacy `id === 45`
|
||||
special-case, preserved here for whenever real category data exists.
|
||||
-->
|
||||
<template>
|
||||
<router-link :to="{ name: 'search' }" @click="setCats" class="cursor-pointer h-full block">
|
||||
<div
|
||||
class="h-full w-full text-center flex flex-col items-center justify-between rounded-[4px]"
|
||||
:class="value.id === '45' ? 'bg-primary' : 'border border-1 border-secondary'"
|
||||
>
|
||||
<div class="flex justify-center mt-4 shrink-0">
|
||||
<img v-lazy="value.icon?.image" alt="category" class="w-[32px] h-[32px] text-center" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="mb-4 mt-4 py-1 px-1 font-semibold flex-1 flex items-center justify-center text-center min-h-[40px]"
|
||||
:class="value.id === '45' ? 'text-white' : 'text-primary'"
|
||||
>
|
||||
{{ value.title }}
|
||||
</div>
|
||||
</div>
|
||||
</router-link>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useFiltersStore } from '../../stores/filtersStore'
|
||||
|
||||
interface CategoryValue {
|
||||
id: string
|
||||
title: string
|
||||
icon?: { image: string }
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{ value: CategoryValue }>(), {})
|
||||
const filters = useFiltersStore()
|
||||
|
||||
const setCats = () => {
|
||||
filters.query.cats = [props.value.id]
|
||||
}
|
||||
</script>
|
||||
@@ -1,146 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/slider/homeSlider.vue.
|
||||
`$prefix` (legacy global property, always the compile-time-constant 'montzar'
|
||||
from themeConfig) is inlined directly here rather than re-registered as a
|
||||
global — same resolved value, no behavior change.
|
||||
-->
|
||||
<template>
|
||||
<div>
|
||||
<Swiper
|
||||
:grabCursor="true"
|
||||
:centeredSlides="true"
|
||||
:space-between="5"
|
||||
:loop="true"
|
||||
:slidesPerView="1.3"
|
||||
class="w-full home-slider"
|
||||
:autoplay="data.autoplay"
|
||||
:pagination="{ clickable: true }"
|
||||
>
|
||||
<SwiperSlide class="bg-center bg-cover h-auto" v-for="(item, index) in slides" :key="index">
|
||||
<img @click="clickHandler(item)" v-lazy="item.src" width="100%" class="block w-full rounded-[10px] object-cover" :style="`height:${height}`" />
|
||||
</SwiperSlide>
|
||||
</Swiper>
|
||||
<Drawer
|
||||
v-model:visible="data.show"
|
||||
placement="bottom"
|
||||
:closable="false"
|
||||
@close="setAutoPlay"
|
||||
height="60%"
|
||||
class="montzar-rounded-drawer rtl text-white bg-primaryLighten whitespace-pre-wrap text[13px]"
|
||||
>
|
||||
{{ data.slideContent.text }}
|
||||
</Drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Swiper, SwiperSlide } from 'swiper/vue'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/navigation'
|
||||
import 'swiper/css/pagination'
|
||||
import 'swiper/css/scrollbar'
|
||||
import SwiperCore, { Autoplay, Navigation, Pagination } from 'swiper'
|
||||
SwiperCore.use([Pagination, Navigation, Autoplay])
|
||||
import { reactive } from 'vue'
|
||||
import { Drawer } from 'ant-design-vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useFiltersStore } from '../../stores/filtersStore'
|
||||
|
||||
interface Slide {
|
||||
text: string | undefined
|
||||
type: string | undefined
|
||||
src: string | undefined
|
||||
link: string | undefined
|
||||
}
|
||||
|
||||
interface Data {
|
||||
show: boolean
|
||||
slideContent: Slide
|
||||
autoplay: { delay: number; disableOnInteraction: boolean } | boolean
|
||||
}
|
||||
|
||||
withDefaults(defineProps<{ slides: Slide[]; height: string }>(), {})
|
||||
|
||||
const data: Data = reactive({
|
||||
show: false,
|
||||
slideContent: { text: undefined, type: undefined, src: undefined, link: undefined },
|
||||
autoplay: { delay: 4000, disableOnInteraction: false },
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
const filters = useFiltersStore()
|
||||
|
||||
const clickHandler = async (item: Slide) => {
|
||||
if (item) {
|
||||
data.slideContent = item
|
||||
switch (item.type) {
|
||||
case 'popup':
|
||||
if (item && !(!item.text || item.text.length === 0)) data.show = true
|
||||
break
|
||||
case 'link':
|
||||
if (item && !(!item.link || item.link.length === 0)) window.open(item.link)?.focus()
|
||||
break
|
||||
case 'discount':
|
||||
if (!(!item.link || item.link.length === 0)) {
|
||||
// EXISTING ISSUE, ported as-is: legacy sets `query.value.discount`,
|
||||
// but the actual filter field is `has_discount` — this assignment
|
||||
// never affected search filtering in legacy either. Not "fixed"
|
||||
// here; flagged separately.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(filters.query as any).discount = true
|
||||
await router.push({ name: 'search' })
|
||||
}
|
||||
break
|
||||
default:
|
||||
// code block
|
||||
}
|
||||
data.autoplay = false
|
||||
}
|
||||
}
|
||||
const setAutoPlay = async () => {
|
||||
data.autoplay = { delay: 4000, disableOnInteraction: false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less">
|
||||
.home-slider {
|
||||
&.swiper {
|
||||
padding: 24px 0 24px 0;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet {
|
||||
transition: all 0.2s;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active,
|
||||
.swiper-pagination-bullet-active-main {
|
||||
width: 24px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.swiper-horizontal > .swiper-pagination-bullets,
|
||||
.swiper-pagination-bullets.swiper-pagination-horizontal,
|
||||
.swiper-pagination-custom,
|
||||
.swiper-pagination-fraction {
|
||||
bottom: 0 !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullets-dynamic * {
|
||||
transform: unset !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active {
|
||||
background: @primary;
|
||||
}
|
||||
|
||||
.swiper-slide {
|
||||
transition: all 0.6s;
|
||||
}
|
||||
|
||||
.swiper-slide:not(.swiper-slide-active) {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,139 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/slider/slider.vue.
|
||||
EXISTING ISSUE, ported as-is (not fixed): `showPopup` takes (src, index) but
|
||||
the template calls it with a single argument (`showPopup(item)`), and the
|
||||
v-for doesn't even destructure an index. `index` is therefore always
|
||||
undefined inside showPopup, so its "rotate the slides array to start at the
|
||||
tapped image" logic never runs — tapping any thumbnail always opens the
|
||||
full-screen zoom viewer starting from the first image, never the tapped one.
|
||||
-->
|
||||
<template>
|
||||
<div>
|
||||
<Swiper :grabCursor="true" :centeredSlides="true" :loop="false" :slidesPerView="1" class="w-full slider" :pagination="{ clickable: true }">
|
||||
<SwiperSlide class="bg-center bg-cover h-auto" v-for="item in slides" :key="item">
|
||||
<img @click="showPopup(item)" v-lazy="item" class="block w-auto object-cover z-0 pb-1" :style="`height:${height}`" />
|
||||
</SwiperSlide>
|
||||
<transition name="slideUp" mode="out-in">
|
||||
<svg alt="منتزر" class="absolute bottom-0 z-[2] m-auto pointer-events-none w-full h-[90px]" v-if="flagSvg">
|
||||
<path fill="#FFFFFF" class="w-full h-[90px]" :d="whiteShape" />
|
||||
<path fill="#3E5279" class="w-full h-[90px]" :d="curvedShape" />
|
||||
</svg>
|
||||
</transition>
|
||||
</Swiper>
|
||||
|
||||
<Drawer v-model:visible="show" placement="bottom" :closable="false" :bodyStyle="{ padding: 0 }" class="rtl whitespace-pre-wrap bg-white" height="100vh">
|
||||
<div @click="show = false" class="fixed top-[30px] right-[20px] z-[5] pb-2 pl-5">
|
||||
<Icon icon="vuesax-linear:arrow-right-1" @click="show = false" class="cursor-pointer text-white bg-secondary rounded-[5px] p-[2.5px]" size="28" />
|
||||
</div>
|
||||
|
||||
<Swiper :grabCursor="true" :zoom="{ maxRatio: 1.2 }" :modules="[Zoom]" :centeredSlides="true" :loop="false" :slidesPerView="1" class="w-full slider" :key="show">
|
||||
<SwiperSlide class="bg-center bg-cover h-auto" v-for="item in slides" :key="item">
|
||||
<div class="swiper-zoom-container">
|
||||
<img v-lazy="item" class="block object-contain w-[100vw] h-screen" />
|
||||
</div>
|
||||
</SwiperSlide>
|
||||
</Swiper>
|
||||
</Drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeMount, ref } from 'vue'
|
||||
import { Swiper, SwiperSlide } from 'swiper/vue'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/navigation'
|
||||
import 'swiper/css/pagination'
|
||||
import 'swiper/css/scrollbar'
|
||||
import 'swiper/css/zoom'
|
||||
import SwiperCore, { Navigation, Pagination, Zoom } from 'swiper'
|
||||
import { Drawer } from 'ant-design-vue'
|
||||
import Icon from '../icon/Icon.vue'
|
||||
import { useWindowDataStore } from '../../stores/windowDataStore'
|
||||
|
||||
SwiperCore.use([Pagination, Navigation])
|
||||
|
||||
const props = withDefaults(defineProps<{ slides: string[]; height: string; width?: string }>(), {})
|
||||
|
||||
const show = ref(false)
|
||||
const slides = ref<string[]>([...props.slides])
|
||||
|
||||
const showPopup = (src: string, index?: number) => {
|
||||
slides.value = [...props.slides]
|
||||
for (let i = 0; i < (index ?? 0); i++) {
|
||||
const helper = slides.value.shift()
|
||||
if (helper) slides.value.push(helper)
|
||||
}
|
||||
show.value = true
|
||||
}
|
||||
|
||||
const flagSvg = ref(false)
|
||||
onBeforeMount(() => {
|
||||
setTimeout(() => {
|
||||
flagSvg.value = true
|
||||
}, 100)
|
||||
})
|
||||
|
||||
const windowData = useWindowDataStore()
|
||||
const shapeHeight = 90
|
||||
const wcp1x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 21.8878249)
|
||||
const wcp2x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 2.37406336)
|
||||
const crcr1cp1x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 1.56947374)
|
||||
const crcr1cp2x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 5.47609844)
|
||||
const crcr2cp1x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 15.8024691)
|
||||
const crcr2cp2x = computed(() => Math.min(windowData.width, 768) - Math.min(windowData.width, 768) / 2.2606383)
|
||||
const whiteShape = computed(() => `M0,${shapeHeight}H${Math.min(windowData.width, 768)}V0C${wcp1x.value},19.17,${wcp2x.value},119.08,0,49Z`)
|
||||
const curvedShape = computed(
|
||||
() => `M0,39.77C${crcr1cp1x.value},91.74,${crcr1cp2x.value},61.5,${Math.min(windowData.width, 768)},0,C${crcr2cp1x.value},29.34,${crcr2cp2x.value},112.54,0,57.1Z`,
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="less">
|
||||
.slider {
|
||||
.swiper-pagination-bullet {
|
||||
transition: all 0.2s;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active,
|
||||
.swiper-pagination-bullet-active-main {
|
||||
width: 24px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.swiper-horizontal > .swiper-pagination-bullets,
|
||||
.swiper-pagination-bullets.swiper-pagination-horizontal,
|
||||
.swiper-pagination-custom,
|
||||
.swiper-pagination-fraction {
|
||||
bottom: 40px !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullets-dynamic * {
|
||||
transform: unset !important;
|
||||
}
|
||||
|
||||
.swiper-pagination-bullet-active {
|
||||
background: @primary;
|
||||
}
|
||||
|
||||
.swiper-slide img {
|
||||
margin: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.slideUp-enter-active,
|
||||
.slideUp-leave-active {
|
||||
opacity: 1;
|
||||
transition: all @transition-duration ease @transition-delay;
|
||||
}
|
||||
|
||||
.slideUp-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(100%);
|
||||
}
|
||||
|
||||
.slideUp-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-100%);
|
||||
}
|
||||
</style>
|
||||
@@ -1,12 +0,0 @@
|
||||
<!-- Ported from legacy henza_pwa/src/components/content.vue -->
|
||||
<template>
|
||||
<main :style="{ marginTop: transition.transitionEnded ? `${transition.headerHeight}px` : 'unset' }">
|
||||
<slot />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useTransitionStore } from '../../stores/transitionStore'
|
||||
|
||||
const transition = useTransitionStore()
|
||||
</script>
|
||||
@@ -1,41 +0,0 @@
|
||||
<!-- Ported from legacy henza_pwa/src/components/ui/ScrollFetch.vue — the plain
|
||||
infinite-scroll container (default ant Empty, no custom illustration). -->
|
||||
<template>
|
||||
<main
|
||||
class="overflow-auto no-scrollbar w-[100vw] h-screen max-w-screen-md m-auto"
|
||||
:style="{ paddingTop: padding || transition.headerHeight + 'px' }"
|
||||
ref="scrollArea"
|
||||
>
|
||||
<slot></slot>
|
||||
<Spinner cls="my-[10px]" :spinning="loading" :indicator="true" tip="درحال دریافت اطلاعات" />
|
||||
<EmptyState v-if="flag" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useInfiniteScroll } from '@vueuse/core'
|
||||
import Spinner from '../Spinner.vue'
|
||||
import EmptyState from '../EmptyState.vue'
|
||||
import { useTransitionStore } from '../../stores/transitionStore'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
loading: boolean
|
||||
flag: boolean
|
||||
padding?: string
|
||||
}>(),
|
||||
{},
|
||||
)
|
||||
const emit = defineEmits<{ (e: 'fetch'): void }>()
|
||||
const transition = useTransitionStore()
|
||||
const scrollArea = ref(null)
|
||||
|
||||
useInfiniteScroll(
|
||||
scrollArea,
|
||||
() => {
|
||||
emit('fetch')
|
||||
},
|
||||
{ distance: 50 },
|
||||
)
|
||||
</script>
|
||||
@@ -1,48 +0,0 @@
|
||||
<!--
|
||||
Ported from legacy henza_pwa/src/components/ui/ScrollFetchAfterSearch.vue.
|
||||
Legacy imported emp_after_search.svg / emp_before_search.svg and an `isSearch`
|
||||
prop to pick between them, but the live template used neither — it rendered
|
||||
`ordersEmpty.svg` unconditionally. Ported as-is (unused imports dropped,
|
||||
`isSearch` kept since it is part of the component's declared prop contract).
|
||||
-->
|
||||
<template>
|
||||
<main
|
||||
class="overflow-auto no-scrollbar w-[100vw] h-screen max-w-screen-md m-auto"
|
||||
:style="{ paddingTop: padding || transition.headerHeight + 'px' }"
|
||||
ref="scrollArea"
|
||||
>
|
||||
<slot></slot>
|
||||
<Spinner cls="my-[10px]" :spinning="loading" :indicator="true" tip="درحال دریافت اطلاعات" />
|
||||
<EmptyState v-if="flag && !loading" :image="ordersEmpty" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useInfiniteScroll } from '@vueuse/core'
|
||||
import Spinner from '../Spinner.vue'
|
||||
import EmptyState from '../EmptyState.vue'
|
||||
import ordersEmpty from '../../assets/img/empty/ordersEmpty.svg'
|
||||
import { useTransitionStore } from '../../stores/transitionStore'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
loading: boolean
|
||||
flag: boolean
|
||||
padding?: string
|
||||
isSearch?: boolean
|
||||
}>(),
|
||||
{},
|
||||
)
|
||||
const emit = defineEmits<{ (e: 'fetch'): void }>()
|
||||
const transition = useTransitionStore()
|
||||
const scrollArea = ref(null)
|
||||
|
||||
useInfiniteScroll(
|
||||
scrollArea,
|
||||
() => {
|
||||
emit('fetch')
|
||||
},
|
||||
{ distance: 50 },
|
||||
)
|
||||
</script>
|
||||
@@ -12,14 +12,14 @@
|
||||
// data exists in the new API, so `hasDiscountWage` is always null here —
|
||||
// the discount badge and "before/after" price never render, which is
|
||||
// correct given there is genuinely nothing to show, not a bug.
|
||||
// - `wage`: legacy added the logged-in customer's own `percent` (a
|
||||
// commission/markup field on their account) on top of the variant's
|
||||
// making-charge %. No login exists in this port yet, so wage is just the
|
||||
// selected variant's defaultWagePercent on its own.
|
||||
// - `wage` now comes from the server (wageQuoteStore), which adds the
|
||||
// customer's own percent and the promotion exactly as legacy did.
|
||||
// - `is_exist` (stock) and `has_warranty`: no such fields exist on our
|
||||
// ProductVariant model yet — always true / false respectively.
|
||||
import { computed, ref, unref, type Ref } from 'vue'
|
||||
import type { ProductSummary, ProductVariantSummary } from '../api/client'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
import { useWageQuoteStore } from '../stores/wageQuoteStore'
|
||||
|
||||
/** A variant can be ordered when it has stock, or when it is flagged pre-order. */
|
||||
export function isVariantOrderable(v: ProductVariantSummary): boolean {
|
||||
@@ -52,7 +52,20 @@ export function useProduct(productItem: ProductSummary, initialVariant?: Product
|
||||
() => selectedVariant.value?.image?.url ?? product.value.images?.[0]?.url,
|
||||
)
|
||||
const min_gram = computed(() => selectedVariant.value ? parseFloat(selectedVariant.value.rashWeightGrams) : 0)
|
||||
const wage = computed(() => (selectedVariant.value ? parseFloat(selectedVariant.value.defaultWagePercent) : null))
|
||||
// The making charge the server will charge (MON-08): variant + the
|
||||
// customer's own percent − the best active promotion, by the formula the
|
||||
// admin «اجرت» screen controls. Signed in: the server's figure, hidden for
|
||||
// the moment it loads rather than flashing a different number. Signed out
|
||||
// (no customer, so no customer percent): the variant's own figure.
|
||||
const session = useSessionStore()
|
||||
const wageQuotes = useWageQuoteStore()
|
||||
const wage = computed(() => {
|
||||
const v = selectedVariant.value
|
||||
if (!v) return null
|
||||
if (!session.isLoggedIn) return parseFloat(v.defaultWagePercent)
|
||||
wageQuotes.request(v.id)
|
||||
return wageQuotes.finalPercent(v.id)
|
||||
})
|
||||
const hasDiscountWage = ref<number | null>(null) // no promotions backend yet — see file header
|
||||
// REAL stock: ProductVariant.qty / isPreOrder exist and are returned by
|
||||
// GET /catalog/products. A variant is orderable when it has stock, or when
|
||||
|
||||
@@ -1,22 +1,55 @@
|
||||
// Adapted from legacy henza_pwa/src/Mixins/favorite.ts + the `favorits` slice of
|
||||
// myDataStore. Legacy persisted favorites server-side via POST /add-to-fav; the
|
||||
// new API has no favorites endpoint yet, so this is local-only (Pinia state,
|
||||
// not persisted) until that backend support exists. Flagged — not a silent
|
||||
// behavior match, a deliberate stand-in.
|
||||
// myDataStore. Legacy kept favourites on the server (POST add-to-fav /
|
||||
// get-favorites, table major_favorites); so does this, through
|
||||
// /customer/me/favorites (FAV-01). It used to be memory-only, so favourites
|
||||
// vanished on reload and the ones imported from legacy were never shown.
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
import { api } from '../api/client'
|
||||
import { useSessionStore } from './session'
|
||||
|
||||
export const useFavoritesStore = defineStore('favorites', {
|
||||
state: () => ({
|
||||
ids: [] as string[],
|
||||
}),
|
||||
actions: {
|
||||
toggle(id: string) {
|
||||
const index = this.ids.indexOf(id)
|
||||
if (index === -1) this.ids.push(id)
|
||||
else this.ids.splice(index, 1)
|
||||
export const useFavoritesStore = defineStore('favorites', () => {
|
||||
const ids = ref<string[]>([])
|
||||
const session = useSessionStore()
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
ids.value = (await api.getFavorites()).ids
|
||||
} catch (e) {
|
||||
// Offline or a dead session (the client already handles 401): keep what we have.
|
||||
console.warn('favorites: load failed', e)
|
||||
}
|
||||
}
|
||||
|
||||
// Loaded for whoever is signed in, cleared on logout — never another user's list.
|
||||
watch(
|
||||
() => session.token,
|
||||
(token) => {
|
||||
ids.value = []
|
||||
if (token) void load()
|
||||
},
|
||||
isFavorite(id: string) {
|
||||
return this.ids.includes(id)
|
||||
},
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
/** Flips at once on screen, then confirms with the server (legacy toggled the same way). */
|
||||
async function toggle(id: string) {
|
||||
const was = ids.value.includes(id)
|
||||
ids.value = was ? ids.value.filter((x) => x !== id) : [id, ...ids.value]
|
||||
try {
|
||||
const { favorite } = await api.toggleFavorite(id)
|
||||
const has = ids.value.includes(id)
|
||||
if (favorite && !has) ids.value = [id, ...ids.value]
|
||||
if (!favorite && has) ids.value = ids.value.filter((x) => x !== id)
|
||||
} catch (e) {
|
||||
// Put it back so the heart never shows a state the server does not hold.
|
||||
ids.value = was ? [id, ...ids.value.filter((x) => x !== id)] : ids.value.filter((x) => x !== id)
|
||||
console.warn('favorites: toggle failed', e)
|
||||
}
|
||||
}
|
||||
|
||||
function isFavorite(id: string) {
|
||||
return ids.value.includes(id)
|
||||
}
|
||||
|
||||
return { ids, load, toggle, isFavorite }
|
||||
})
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// Ported from legacy henza_pwa/src/store/loadingStore.ts — a single global
|
||||
// loading flag, converted from the hand-rolled ref-class to Pinia.
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useLoadingStore = defineStore('loading', {
|
||||
state: () => ({
|
||||
loading: false,
|
||||
}),
|
||||
actions: {
|
||||
setLoading(loading: boolean) {
|
||||
this.loading = loading
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
// The making charge («اجرت») the server will charge this customer for each
|
||||
// variant — fetched from /customer/me/wage-quote, which runs the same formula
|
||||
// that prices the order (MON-08, owner ruling 2026-10-08). The app shows this
|
||||
// figure, never one it computes itself, so what is shown is what is charged.
|
||||
//
|
||||
// Requests are batched: many cards asking at once become one call.
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
import { api, type WageQuote } from '../api/client'
|
||||
import { useSessionStore } from './session'
|
||||
|
||||
export const useWageQuoteStore = defineStore('wageQuotes', () => {
|
||||
const session = useSessionStore()
|
||||
const quotes = ref<Record<string, WageQuote>>({})
|
||||
const pending = new Set<string>()
|
||||
const inFlight = new Set<string>()
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// A different customer has a different percent: never reuse another's quotes.
|
||||
watch(
|
||||
() => session.token,
|
||||
() => {
|
||||
quotes.value = {}
|
||||
pending.clear()
|
||||
inFlight.clear()
|
||||
},
|
||||
)
|
||||
|
||||
async function flush() {
|
||||
timer = null
|
||||
const ids = [...pending].slice(0, 200)
|
||||
ids.forEach((id) => {
|
||||
pending.delete(id)
|
||||
inFlight.add(id)
|
||||
})
|
||||
if (pending.size) timer = setTimeout(flush, 0)
|
||||
if (!ids.length) return
|
||||
try {
|
||||
const rows = await api.getWageQuotes(ids)
|
||||
const next = { ...quotes.value }
|
||||
for (const r of rows) next[r.variantId] = r
|
||||
quotes.value = next
|
||||
} catch (e) {
|
||||
console.warn('wage quote failed', e)
|
||||
} finally {
|
||||
ids.forEach((id) => inFlight.delete(id))
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks for a variant's quote (idempotent; safe to call from a computed). */
|
||||
function request(variantId: string) {
|
||||
if (!session.token || quotes.value[variantId] || pending.has(variantId) || inFlight.has(variantId)) return
|
||||
pending.add(variantId)
|
||||
if (!timer) timer = setTimeout(flush, 30)
|
||||
}
|
||||
|
||||
/** The charged percent, or null while it is still loading. */
|
||||
function finalPercent(variantId: string): number | null {
|
||||
const q = quotes.value[variantId]
|
||||
return q ? parseFloat(q.finalPercent) : null
|
||||
}
|
||||
|
||||
return { quotes, request, finalPercent }
|
||||
})
|
||||
@@ -11,20 +11,6 @@ export function price(val: number | string | undefined | null): string {
|
||||
return val as any
|
||||
}
|
||||
|
||||
export function priceUnit(val: number | string | undefined | null): string {
|
||||
if (['string', 'number'].includes(typeof val)) {
|
||||
return `${val!.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} تومان `
|
||||
}
|
||||
return val as any
|
||||
}
|
||||
|
||||
export function priceUnitRialLess(val: number | string | undefined | null): string {
|
||||
if (['string', 'number'].includes(typeof val)) {
|
||||
return `${val!.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} `
|
||||
}
|
||||
return val as any
|
||||
}
|
||||
|
||||
export function jdate(val: string | undefined | null): string {
|
||||
if (val) {
|
||||
// legacy parsed a fixed 'YYYY-MM-DD HH:mm:ss' Laravel timestamp format;
|
||||
|
||||
@@ -1,30 +1,9 @@
|
||||
// Ported from legacy henza_pwa/src/Mixins/validator/index.ts — same rules,
|
||||
// same messages, verbatim.
|
||||
// same messages, verbatim. Only the rules the app uses are kept (DEAD-01/02).
|
||||
export const message = (field: string) => ` مقدار ${field} نا معتبر است `
|
||||
|
||||
export const mobile = (field: string) => ({
|
||||
pattern: /^(\+98|0098|98|0)?9\d{9}$/g,
|
||||
message: message(field),
|
||||
})
|
||||
export const phone = (field: string) => ({
|
||||
pattern: /^((\+98|0098|98|0)\d1)?\d{8}$/g,
|
||||
message: message(field),
|
||||
})
|
||||
export const fa = (field: string) => ({
|
||||
pattern: /^([-ۿﮊپچگ ])+$/,
|
||||
message: ` مقدار ${field} باید فارسی باشد `,
|
||||
})
|
||||
export const mail = (field: string) => ({ type: 'email', message: message(field) })
|
||||
export const url = (field: string) => ({ type: 'url', message: message(field) })
|
||||
export const username = (field: string) => ({
|
||||
pattern: /^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/gim,
|
||||
message: ` مقدار ${field} باید شامل حروف و اعداد انگلیسی و _ باشد `,
|
||||
})
|
||||
export const required = (field: string) => ({ required: true, message: ` لطفا ${field} را وارد کنید ` })
|
||||
export const sheba = (field: string) => ({ pattern: /^IR\d{24}$/gim, message: message(field) })
|
||||
export const card = (field: string) => ({ pattern: /^\d{16}$/gim, message: message(field) })
|
||||
export const zip = (field: string) => ({ pattern: /^\d{10}$/gim, message: message(field) })
|
||||
export const num = (field: string) => ({ pattern: /^\d*$/gim, message: message(field) })
|
||||
export const len = (field: string, len: number) => ({ len, message: ` مقدار ${field} باید ${len} کارکتر باشد ` })
|
||||
export const max = (field: string, max: number) => ({ max, message: ` مقدار ${field} باید کمتر از ${max} کارکتر باشد ` })
|
||||
export const min = (field: string, min: number) => ({ min, message: ` مقدار ${field} باید بیشتر از ${min} کارکتر باشد ` })
|
||||
|
||||
@@ -213,6 +213,8 @@ const submitOrder = async () => {
|
||||
return {
|
||||
productVariantId: item.vid,
|
||||
quantity: item.qty,
|
||||
// Sent for older API builds only: the server prices app orders itself
|
||||
// (MON-08) and ignores this figure.
|
||||
wagePercent: variant ? parseFloat(variant.defaultWagePercent) : 0,
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -37,6 +37,11 @@ services:
|
||||
- JWT_EXPIRES_IN=${JWT_EXPIRES_IN:-}
|
||||
- JWT_CUSTOMER_SECRET=${JWT_CUSTOMER_SECRET:-}
|
||||
- JWT_CUSTOMER_EXPIRES_IN=${JWT_CUSTOMER_EXPIRES_IN:-}
|
||||
# SEC-04: comma-separated browser origins allowed to call the API
|
||||
# (e.g. https://adm.example.ir,https://app.example.ir). Blank = any.
|
||||
- CORS_ORIGINS=${CORS_ORIGINS:-}
|
||||
# SEC-05: demo seed data is never created in production unless "true".
|
||||
- SEED_DEMO_DATA=${SEED_DEMO_DATA:-}
|
||||
# ⚠ DELIVERY ONLY — a fixed OTP that signs in ANY active customer.
|
||||
# Empty/unset disables it, which is the correct state for production.
|
||||
# See ISSUES REL-01. Must be exactly 4 digits to be typable in the apps.
|
||||
|
||||
@@ -149,15 +149,13 @@ target's rid, grouped by the module of `apps/api/src/modules/`:
|
||||
|
||||
## §3+ — Field-by-field sections
|
||||
|
||||
To be filled, in the fix order given in the Phase 1 summary:
|
||||
|
||||
- §3 Price formula and product/variant
|
||||
- §4 Orders and the `gram_level` limit
|
||||
- §5 Financial documents (اسناد)
|
||||
- §6 Customers (اشخاص)
|
||||
- §7 Users, permissions, cities, branches, workshops
|
||||
- §8 Promotions, SMS, notifications, newsletters, statics
|
||||
- §9 Reports
|
||||
- §3 Price formula and product/variant — ⏸️ stopped by D16
|
||||
- §4 Orders and the `gram_level` limit — ✅ done
|
||||
- §5 Financial documents (اسناد) — ✅ at parity
|
||||
- §6 Customers (اشخاص) — ✅ done in Phase 1(a)
|
||||
- §7 Users, permissions, cities, branches, workshops — ✅ at parity
|
||||
- §8 Promotions, SMS, notifications, newsletters, statics — ✅ at parity
|
||||
- §9 Reports — ✅ at parity (Excel export built)
|
||||
|
||||
---
|
||||
|
||||
@@ -242,3 +240,188 @@ owner's ruling, since `henza_pwa` computes rather than collects them.
|
||||
|---|---|---|
|
||||
| PRICE-01 | **Critical** | The price formula is ported and tested but **wired to nothing**: no gold price is fetched, `variantRow()` returns no `price`/`price_with_discount`, and the product list has no price column. The reference shows a price on every variant. |
|
||||
| PRICE-02 | Info | `rial_pay` is excluded from the live formula — the target matches; do not "restore" it from the superseded commented-out code. |
|
||||
|
||||
---
|
||||
|
||||
## §5 — Financial documents (اسناد مالی)
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/CashController.php` (149 lines)
|
||||
Target: `apps/api/src/modules/admin-documents/admin-documents.service.ts` (447 lines)
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| List documents | `index` + TableEngine | `list` scoped to REPAYMENT types | ✅ |
|
||||
| Create document (4 types) | `store` auto-confirms | `create` delegates to LedgerService | ✅ |
|
||||
| Update document | `update` | `update` — refuses amount change on confirmed | ✅ stricter |
|
||||
| Toggle confirm | `toggleConfiremCash` + SMS + notification | `toggleConfirm` → LedgerService (balance reversal on unconfirm) | ✅ |
|
||||
| Delete document | `destroy` | `remove` — refuses confirmed entries | ✅ stricter |
|
||||
| Ayar normalisation | `type 1: value*ayar/750` | delegated to LedgerService | ✅ |
|
||||
| Cash-to-gold conversion | `type 4: price/(pricePerGram/4.331802)` | delegated to LedgerService | ✅ |
|
||||
| SMS on confirm/unconfirm | `sendSms()` inside toggle | not yet wired | ⚠️ minor |
|
||||
| Wallet list + query | none | `listWallet` / `queryCustomers` | ➕ extra |
|
||||
|
||||
**Verdict: ✅ at parity.** SMS on document confirm/unconfirm is now wired via
|
||||
`notifyDocumentConfirm` (SMS-01 fixed).
|
||||
|
||||
---
|
||||
|
||||
## §6 — Customers (اشخاص)
|
||||
|
||||
Completed in Phase 1(a). No gaps remain.
|
||||
|
||||
---
|
||||
|
||||
## §7 — Users, permissions, cities, branches, workshops
|
||||
|
||||
### Users
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/UserController.php` (99 lines)
|
||||
Target: `apps/api/src/modules/admin-users/admin-users.service.ts` (493 lines)
|
||||
|
||||
| Field/Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| CRUD | store/update/destroy | create/update/remove | ✅ |
|
||||
| fname + lname | separate fields | D0 `fullName` + `nameFirst`/`nameLast` | ✅ |
|
||||
| password min 6 | validation rule | bcrypt hash | ✅ |
|
||||
| mobile unique | validation rule | `@unique` in schema | ✅ |
|
||||
| ut (user type) | must exist in config_statics | `AdminRole` enum | ✅ |
|
||||
| Disable → revoke sessions | none | session revocation + audit trail | ➕ stricter |
|
||||
| SalesExpertProfile | none | D17 | ➕ extra |
|
||||
|
||||
### Permissions
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/PermissionController.php` (89 lines)
|
||||
Target: `apps/api/src/modules/admin-users/admin-users.service.ts` + IAM module
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| Read permissions | `get()` / `getByUt()` | `findPermissions` | ✅ |
|
||||
| Sync (add/remove) | `create` diff + `store` firstOrCreate + `destroy` | `syncPermissions` | ✅ |
|
||||
| Has check | `has()` | guard middleware | ✅ |
|
||||
|
||||
### Cities
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/CitiesController.php` (77 lines)
|
||||
Target: `apps/api/src/modules/admin-misc/admin-misc.service.ts` + `admin-cities.controller.ts`
|
||||
|
||||
| Field/Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| CRUD | store/update/destroy | create/update/remove + loop prevention | ✅ stricter |
|
||||
| parent / level | `parent`, `level` fields | `parentId` | ✅ |
|
||||
| percent / percent_aux | both fields | both fields (`percentAux`) | ✅ |
|
||||
| `_getP()` inherit percent | walks up tree | `getCityPercent` walks up tree | ✅ |
|
||||
| Referential integrity | none | refuses delete if children exist | ➕ stricter |
|
||||
| Admin panel picker | simple dropdown | `CityTreeSelect` tree component | ➕ better UX |
|
||||
|
||||
### Branches
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/BranchController.php`
|
||||
Target: `apps/api/src/modules/admin-branches/admin-branches.service.ts:30-165`
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| List + table | `POST branch/table` | `listBranches` | ✅ |
|
||||
| Create | `POST branch` | `createBranch` | ✅ |
|
||||
| Update | `PUT branch/{id}` | `updateBranch` | ✅ |
|
||||
| Toggle active | `GET branch/active/{id}` | `toggleBranchActive` | ✅ |
|
||||
| Manager assignment | `user_id` → branch_id update pair | `assignBranchManager` in transaction | ✅ stricter |
|
||||
| City link | `city_id` | `cityId` | ✅ |
|
||||
|
||||
### Workshops
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/WorkshopController.php`
|
||||
Target: `apps/api/src/modules/admin-branches/admin-branches.service.ts:167-362`
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| List + table | `POST workshop/table` | `listWorkshops` | ✅ |
|
||||
| Create + inline supervisor | `POST workshop` | `createWorkshop` + `upsertSupervisor` | ✅ |
|
||||
| Update | `PUT workshop/{id}` | `updateWorkshop` | ✅ |
|
||||
| Toggle active | `GET workshop/active/{id}` | `toggleWorkshopActive` | ✅ |
|
||||
| Supervisor inline fields | `user_fname/lname/phone` | `upsertSupervisor` with mobile clash check | ✅ stricter |
|
||||
|
||||
**Verdict: ✅ all five areas at parity.** No gaps.
|
||||
|
||||
---
|
||||
|
||||
## §8 — Promotions, SMS, notifications, newsletters, statics
|
||||
|
||||
### Promotions
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/PromotionController.php` (252 lines)
|
||||
Target: `apps/api/src/modules/admin-promotions/admin-promotions.service.ts` (334 lines)
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| CRUD | store/update/destroy | create/update/remove | ✅ |
|
||||
| 4 scope types | product/category/brand/customer | enum mapping | ✅ |
|
||||
| PromotionItem denorm | PromotionProduct | Prisma relations | ✅ |
|
||||
| Exclusion management | IgnoreController | exclusion endpoints | ✅ |
|
||||
| Auto-promotion | hardcoded id=17 | Setting key | ✅ better |
|
||||
|
||||
### SMS
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/SmsController.php` (154 lines)
|
||||
Target: `apps/api/src/modules/admin-misc/admin-misc.service.ts` SMS section + D26 relay
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| Batch send (type 0,1,2,9) | `batch()` | `sendSms` with audience resolution | ✅ |
|
||||
| Today's SMS list | `index` | `listSms` | ✅ |
|
||||
| `%name` substitution | in batch text | needs verification | ⚠️ minor |
|
||||
| `getCustomer` campaign | hardcoded promo send | none | ⏸️ dead code |
|
||||
| SMS gateway | Trez | relay driver (D26) | ✅ |
|
||||
|
||||
### Notifications
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/NotifyController.php` (100 lines)
|
||||
Target: `apps/api/src/modules/admin-misc/admin-misc.controller.ts` notify section
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| Create (6 type_send) | `store` | `createNotification` + `notifyCustomer` | ✅ |
|
||||
| List / show / read | index/show/read | `listNotifications`/`findNotification`/`markRead` | ✅ |
|
||||
| Firebase push | `Notify::store()` → Firebase | none | ⏸️ needs PWA |
|
||||
|
||||
### Newsletter
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| List subscribers | `NewsletterController` | `listNewsletter` | ✅ |
|
||||
|
||||
### Settings / Consts / Brands
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| Read/write/delete consts | `ConfigStaticController` | `getConst`/`setConst`/`removeConst` | ✅ |
|
||||
| Mobile slider | part of consts | separate endpoint with own permission | ✅ stricter |
|
||||
| Brands CRUD | `BrandController` | admin-misc brands | ✅ |
|
||||
|
||||
**Verdict: ✅ at parity.** Firebase push is out of scope (needs PWA port).
|
||||
|
||||
---
|
||||
|
||||
## §9 — Reports
|
||||
|
||||
Reference: `henza_server/app/Http/Controllers/Adm/ReportController.php` (239 lines)
|
||||
Target: no admin report module exists.
|
||||
|
||||
| Operation | Reference | Target | Status |
|
||||
|---|---|---|---|
|
||||
| `getOrderItemWithDetails` Excel export | 32-column xlsx combining OrderItems + Cash, date-filtered, Jalali dates, RTL sheet | `GET admin/report/order-items` — `admin-report.service.ts` | ✅ fixed |
|
||||
|
||||
**Verdict: ✅ at parity.** The 32-column Excel export is implemented using
|
||||
`exceljs` with RTL sheet, Jalali dates, date filtering, and the same column
|
||||
layout as the reference. The target reads from `OrderItem` + `LedgerEntry`
|
||||
(equivalent to legacy's `OrderItem` + `Cash`).
|
||||
|
||||
---
|
||||
|
||||
## Issues raised by §5–§9
|
||||
|
||||
| ID | Severity | Summary | Status |
|
||||
|---|---|---|---|
|
||||
| RPT-01 | Medium | The reference's 32-column Excel export (`ReportController::getOrderItemWithDetails`) had no target equivalent. | ✅ fixed — `admin-report` module, `GET admin/report/order-items` |
|
||||
| SMS-01 | Low | SMS on document confirm/unconfirm was not wired in `toggleConfirm`. | ✅ fixed — `admin-documents.service.ts:notifyDocumentConfirm` |
|
||||
| SMS-02 | Low | `%name` substitution in batch SMS text was missing. | ✅ fixed — `admin-misc.service.ts:sendSms` + `customerNamesByMobile` |
|
||||
| PUSH-01 | Low | Firebase push notifications not implemented — deferred to PWA port phase. | ⏸️ deferred |
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
# D16 بخشهای (b) و (c) — خلاصه gapها
|
||||
|
||||
> این سند خلاصه بررسی field-by-field بخشهای باقیمانده فاز ۱ هست.
|
||||
> طبق D16: «قبل از fix، خلاصه gap به صاحبکار نشون داده بشه.»
|
||||
> تاریخ: ۱۳۸۵/۰۷/۱۷ (2026-10-08)
|
||||
|
||||
---
|
||||
|
||||
## (b) محصولات / دستهبندی / واریانت
|
||||
|
||||
### نتیجه: ✅ تقریباً کامل — gap عملکردی بحرانی نداره
|
||||
|
||||
| عملیات | reference | target | وضعیت |
|
||||
|---|---|---|---|
|
||||
| CRUD محصول | `ProductController` store/update/destroy | `admin-products.service.ts` create/update/remove | ✅ |
|
||||
| لیست/ساخت/ویرایش واریانت | `addVariant`, `getVariants` | `createVariant`, `listVariants`, `variantsOf` | ✅ |
|
||||
| تصاویر محصول (۴ slot) | gallery + mobile featured | `imageCreateData` + `syncImages` با ۴ role | ✅ |
|
||||
| تصویر واریانت | `image_id` روی واریانت | `imageId` در `variantCreateData` | ✅ |
|
||||
| اجرت (percentage_pay) | `percentage_pay` | `defaultWagePercent` | ✅ |
|
||||
| تغییر دستهجمعی اجرت | `changePercent` | `changePercent` / `changePercentCount` | ✅ |
|
||||
| برند CRUD | `BrandController` | `admin-misc` brands | ✅ |
|
||||
| دستهبندی CRUD | `CategoryController` | `admin-categories` | ✅ |
|
||||
| Collection (ciny) | `CinyController` | `collections` در product service | ✅ |
|
||||
| حذف محصول + حفاظت | حذف بدون بررسی | حذف با بررسی سفارش | ✅ بهتر |
|
||||
| `product_code` unique | implicit در DB | `@unique` در schema | ✅ |
|
||||
| `offer_day` toggle | `changeOffer` | **ندارد** | ⏸️ ← فیلد در schema نیست |
|
||||
| `is_exist` toggle | `changeIsExist` | **ندارد** | ⏸️ ← فیلد در schema نیست |
|
||||
| `has_warranty` toggle | `changeHasWarranty` | **ندارد** | ⏸️ ← فیلد در schema نیست |
|
||||
|
||||
### توضیح toggleها:
|
||||
سه فیلد `offer_day`, `is_exist`, `has_warranty` در reference وجود دارن ولی:
|
||||
- هیچکدوم در Prisma schema تعریف نشدن
|
||||
- اینا فیلدهای **خردهفروشی/فروشگاه اینترنتی** هستن (پیشنهاد ویژه، موجود در سایت، دارای گارانتی)
|
||||
- طبق D16 و D13، فروشگاه اینترنتی خارج از scope فاز ۱ هست → **⏸️ نیازی به اقدام نیست**
|
||||
|
||||
---
|
||||
|
||||
## (c) اسناد مالی / کاربران / شهرها / شعب / کارگاهها / پروموشن / SMS / اعلان / گزارش
|
||||
|
||||
### §5 — اسناد مالی (Cash → AdminDocuments)
|
||||
|
||||
| عملیات | reference (`CashController`) | target (`admin-documents.service.ts`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| لیست اسناد | `index` + TableEngine | `list` با TableService | ✅ |
|
||||
| ساخت سند | `store` با ۴ نوع | `create` با LedgerService delegation | ✅ |
|
||||
| ویرایش سند | `update` | `update` (با قفل تایید) | ✅ بهتر |
|
||||
| toggle تایید | `toggleConfiremCash` + SMS/notification | `toggleConfirm` با LedgerService | ✅ |
|
||||
| حذف سند | `destroy` | `remove` (رد تاییدشده) | ✅ بهتر |
|
||||
| تبدیل عیار (ayar) | `type 1: value*ayar/750` | در LedgerService | ✅ |
|
||||
| تبدیل نقد→طلا | `type 4: price/(pricePerGram/4.331802)` | در LedgerService | ✅ |
|
||||
| SMS تایید سند | `sendSms` در `toggleConfiremCash` | ❓ باید بررسی بشه | ⚠️ کوچک |
|
||||
| کیفپول | ندارد | `listWallet` / `queryCustomers` | ➕ اضافه |
|
||||
|
||||
**Gap واقعی:** ارسال SMS هنگام تایید/عدم تایید سند. بررسی لازم — ممکنه از طریق D26 relay انجام بشه.
|
||||
|
||||
### §6 — مشتریان (Customers)
|
||||
|
||||
**قبلاً انجام شده** — بخش (a) فاز ۱. Gap ندارد.
|
||||
|
||||
### §7 — کاربران / دسترسیها / شهرها / شعب / کارگاهها
|
||||
|
||||
#### کاربران (Users)
|
||||
|
||||
| عملیات | reference (`UserController`) | target (`admin-users.service.ts`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| CRUD کاربر | store/update/destroy + validation | create/update/remove + D0 name parts | ✅ بهتر |
|
||||
| `fname` + `lname` | جداگانه | D0 `fullName` + `nameFirst`/`nameLast` | ✅ |
|
||||
| رمز عبور min 6 | validation rule | `passwordHash` با bcrypt | ✅ |
|
||||
| mobile unique | validation rule | `@unique` در schema | ✅ |
|
||||
| `ut` (نوع کاربر) | must exist in config_statics | `AdminRole` enum | ✅ |
|
||||
| غیرفعالسازی | ندارد | session revocation + audit trail | ➕ بهتر |
|
||||
| SalesExpertProfile | ندارد | D17 — ➕ اضافه | ➕ |
|
||||
|
||||
#### دسترسیها (Permissions)
|
||||
|
||||
| عملیات | reference (`PermissionController`) | target (`admin-users.service.ts` + IAM) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| خواندن دسترسیها | `get()` / `getByUt()` | `findPermissions` | ✅ |
|
||||
| ثبت/حذف دسترسی | `create` diff + `store` firstOrCreate + `destroy` | `syncPermissions` | ✅ |
|
||||
| `has()` check | وجود بررسی | guard middleware | ✅ |
|
||||
|
||||
#### شهرها (Cities)
|
||||
|
||||
| عملیات | reference (`CitiesController`) | target (`admin-misc`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| CRUD شهر | store/update/destroy | create/update/remove + loop prevention | ✅ بهتر |
|
||||
| parent/level | `parent`, `level` | `parentId` | ✅ |
|
||||
| percent/percent_aux | هر دو فیلد | هر دو فیلد | ✅ |
|
||||
| `_getP()` (inherit percent) | walk up tree | `getCityPercent` walk up tree | ✅ |
|
||||
| referential integrity | ندارد | بررسی فرزند قبل از حذف | ➕ بهتر |
|
||||
| CityTreeSelect | dropdown ساده | ✅ component درختی جدید | ✅ بهتر |
|
||||
|
||||
#### شعب (Branches)
|
||||
|
||||
| عملیات | reference (`BranchController`) | target (`admin-branches.service.ts`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| لیست + table | `POST branch/table` | `listBranches` با TableService | ✅ |
|
||||
| ساخت شعبه | `POST branch` | `createBranch` | ✅ |
|
||||
| ویرایش شعبه | `PUT branch/{id}` | `updateBranch` | ✅ |
|
||||
| toggle فعال/غیرفعال | `GET branch/active/{id}` | `toggleBranchActive` | ✅ |
|
||||
| مدیر شعبه | `user_id` → branch_id update | `assignBranchManager` transaction | ✅ بهتر |
|
||||
| شهر شعبه | `city_id` | `cityId` | ✅ |
|
||||
|
||||
#### کارگاهها (Workshops)
|
||||
|
||||
| عملیات | reference (`WorkshopController`) | target (`admin-branches.service.ts`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| لیست + table | `POST workshop/table` | `listWorkshops` با TableService | ✅ |
|
||||
| ساخت کارگاه | `POST workshop` (+ inline supervisor) | `createWorkshop` + `upsertSupervisor` | ✅ |
|
||||
| ویرایش کارگاه | `PUT workshop/{id}` | `updateWorkshop` | ✅ |
|
||||
| toggle فعال/غیرفعال | `GET workshop/active/{id}` | `toggleWorkshopActive` | ✅ |
|
||||
| سرپرست inline | `user_fname/lname/phone` | `upsertSupervisor` + mobile clash check | ✅ بهتر |
|
||||
|
||||
### §8 — پروموشن / SMS / اعلان / خبرنامه / ثابتها
|
||||
|
||||
#### پروموشن (Promotions)
|
||||
|
||||
| عملیات | reference (`PromotionController`) | target (`admin-promotions.service.ts`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| CRUD | store/update/destroy | create/update/remove | ✅ |
|
||||
| ۴ نوع scope | product/category/brand/customer | enum mapping | ✅ |
|
||||
| PromotionItem denorm | PromotionProduct | via Prisma relations | ✅ |
|
||||
| exclusion management | IgnoreController | admin-promotions exclusions | ✅ |
|
||||
| auto-promotion (id=17) | hardcoded | Setting key | ✅ بهتر |
|
||||
|
||||
#### SMS
|
||||
|
||||
| عملیات | reference (`SmsController`) | target (`admin-misc`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| ارسال دستهجمعی | `batch` (type 0,1,2,9) | `sendSms` با audience resolution | ✅ |
|
||||
| لیست SMSهای امروز | `index` | `listSms` | ✅ |
|
||||
| `%name` substitution | در batch | ❓ | ⚠️ بررسی لازم |
|
||||
| `getCustomer` campaign | hardcoded promo | ❌ ندارد | ⏸️ dead code در reference |
|
||||
| `sendSmsToOther` | arbitrary number | ❓ covered by type 9? | ⚠️ بررسی لازم |
|
||||
| SMS gateway | Trez driver | relay driver (D26) | ✅ |
|
||||
|
||||
#### اعلان (Notifications)
|
||||
|
||||
| عملیات | reference (`NotifyController`) | target (`admin-misc`) | وضعیت |
|
||||
|---|---|---|---|
|
||||
| ساخت اعلان | store (6 type_send) | `createNotification` + `notifyCustomer` | ✅ |
|
||||
| لیست/خواندن | index/show/read | `listNotifications` / `findNotification` / `markRead` | ✅ |
|
||||
| Firebase push | `Notify::store()` | ❌ ندارد | ⚠️ Firebase push ندارد |
|
||||
|
||||
#### خبرنامه (Newsletter)
|
||||
|
||||
| عملیات | reference | target | وضعیت |
|
||||
|---|---|---|---|
|
||||
| لیست مشترکین | `NewsletterController` | `listNewsletter` | ✅ |
|
||||
|
||||
#### ثابتها و تنظیمات (Consts/Settings)
|
||||
|
||||
| عملیات | reference | target | وضعیت |
|
||||
|---|---|---|---|
|
||||
| خواندن/نوشتن/حذف | `ConfigStaticController` | `getConst` / `setConst` / `removeConst` | ✅ |
|
||||
| اسلایدر موبایل | بخشی از consts | endpoint مجزا با permission مجزا | ✅ بهتر |
|
||||
| برندها | `BrandController` | admin-misc brands | ✅ |
|
||||
|
||||
### §9 — گزارشها (Reports)
|
||||
|
||||
| عملیات | reference (`ReportController`) | target | وضعیت |
|
||||
|---|---|---|---|
|
||||
| Excel export (32 ستون) | `getOrderItemWithDetails` → xlsx | **❌ ندارد** | ❌ gap |
|
||||
| date filter | `start_date` / `end_date` | ❌ | ❌ |
|
||||
| Jalali dates | `Jalalian::forge` | ❌ | ❌ |
|
||||
|
||||
**این بزرگترین gap باقیماندهست.** یه Excel export که ۳۲ ستون از OrderItem + Cash ترکیب میکنه. ولی:
|
||||
- این گزارش **فقط خروجی xlsx** هست و هیچ UI مدیریتی خاصی نداره
|
||||
- target از سیستم Ledger استفاده میکنه نه Cash مستقیم
|
||||
- پیادهسازی Excel export نیازمند وابستگی جدید هست (مثل `exceljs`)
|
||||
|
||||
---
|
||||
|
||||
## جمعبندی gapها
|
||||
|
||||
### Gapهایی که نیاز به اقدام دارن:
|
||||
|
||||
| # | gap | اولویت | حجم کار |
|
||||
|---|---|---|---|
|
||||
| 1 | **Excel report** — ۳۲ ستونی ندارد | متوسط | بزرگ (endpoint جدید + exceljs) |
|
||||
| 2 | **Firebase push notification** — ارسال push به موبایل ندارد | کم (PWA port) | متوسط |
|
||||
| 3 | **SMS تایید سند** — ارسال SMS هنگام confirm/unconfirm | کم | کوچک |
|
||||
| 4 | **SMS `%name` substitution** — جایگزینی نام مشتری در متن | کم | کوچک |
|
||||
|
||||
### Gapهایی که خارج از scope فاز ۱ هستن (⏸️):
|
||||
|
||||
| # | gap | دلیل |
|
||||
|---|---|---|
|
||||
| 1 | `offer_day` / `is_exist` / `has_warranty` toggles | فروشگاه اینترنتی (D13) |
|
||||
| 2 | `getCustomer` campaign SMS | dead code در reference |
|
||||
| 3 | Firebase push | نیازمند PWA port |
|
||||
|
||||
### نتیجه:
|
||||
|
||||
**بخش (b): ✅ کامل — هیچ gap عملکردی B2B ندارد.**
|
||||
|
||||
**بخش (c): ✅ تقریباً کامل** — فقط Excel report واقعاً ندارد.
|
||||
بقیه gapها (SMS confirm، Firebase) یا خارج از scope هستن یا خیلی کوچک.
|
||||
|
||||
---
|
||||
|
||||
## اقدامات انجام شده (2026-10-08):
|
||||
|
||||
۱. ✅ **Excel report (RPT-01):** ماژول `admin-report` ساخته شد
|
||||
- `GET admin/report/order-items?start_date=...&end_date=...`
|
||||
- ۳۲ ستون فارسی، ترکیب OrderItem + LedgerEntry
|
||||
- Jalali dates، RTL sheet، فیلتر تاریخ
|
||||
- وابستگی `exceljs` اضافه شد
|
||||
- **بازبینی بعدی:**
|
||||
- **وزن:** سیستم قدیم در این گزارش وزن هر قلم را دوباره بر تعداد تقسیم میکرد، در حالی که وزن ذخیرهشده خودش وزن یک عدد است: ۸۱ از ۸۲ ردیف چندتایی در دیتای قدیم این را نشان میدهند. در نتیجه ستون «بدهکار» کمتر از واقع بود. این خطا تکرار نشد.
|
||||
- **«درصد»:** مثل سیستم قدیم، اجرت منهای تخفیف است.
|
||||
- **تاریخ:** «تا تاریخ» کل همان روز را شامل میشود، و تاریخ نامعتبر خطای روشن برمیگرداند.
|
||||
- **دکمه:** «دریافت فایل اکسل» در صفحهی گزارش تجمیعی گذاشته شد.
|
||||
|
||||
۲. ✅ **SMS تایید سند (SMS-01):** `notifyDocumentConfirm` در `admin-documents.service.ts`
|
||||
- تایید: «سند مالی شما توسط مدیر سیستم تایید شد.»
|
||||
- رد: «سند مالی شما توسط مدیر سیستم رد شد.»
|
||||
|
||||
۳. ✅ **SMS `%name` (SMS-02):** جایگزینی نام در `sendSms` در `admin-misc.service.ts`
|
||||
- `%name` → «نام مشتری عزیز» (یا «مشتری عزیز» اگه پیدا نشد)
|
||||
- طبق reference: `SmsController::replaceName`
|
||||
|
||||
۴. ⏸️ **Firebase push (PUSH-01):** به فاز PWA موکول شد.
|
||||
+13
-13
@@ -21,10 +21,10 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
| SEC-08 | ~~Critical~~ **FIXED — hotfix stage 2** | TGT `apps/api/src/modules/customers/customers.service.ts:6-23,44-50` + `customers.controller.ts:10` (`@Public()`) | **Full customer book exposed to anonymous callers.** Login downloads `GET /customers` and matches the phone client-side, so the endpoint returns **every** active customer with `fullName`, `mobile`, **`nationalCode`**, `goldDebtGrams`, `fiatDebtRial`, `goldCreditLimitGrams`, and the URLs of **national-ID / business-licence / shop scans** (and `GET uploads/:filename` is public too, so those URLs resolve). `passwordHash` is correctly excluded. Not possible in the reference, where `userVerfiy` returned **one** customer after the code matched. | Read `customers.service.ts:5-23`; `DECISIONS.md` D8 | ✅ Closed. The whole controller is deleted — no route accepts a customer id any more. Reads moved to token-derived `/customer/me*`. Stage 1 had only narrowed the fields, which left the ids and the `:id` routes exposed. |
|
||||
| SEC-09 | ~~Critical~~ **FIXED — hotfix stage 1** | TGT `apps/api/src/modules/accounting/accounting.controller.ts:7` | `@Public()` on the whole accounting controller exposes **5 routes, 4 of them writes**: reconcile a balance, record a gold repayment, record a rial repayment, confirm a ledger entry. Faithful to the reference (whose admin routes were all unauthenticated) but contradicts the confirmed decision D1. | `DECISIONS.md` §"@Public audit" group A | ✅ Done: rids `wallet.list`, `wallet.charge`, `document.create` ×2, `document.list.confirm`. Verified 401/403/pass-through by `apps/api/scripts/auth-smoke.sh`. |
|
||||
| SEC-10 | ~~High~~ **FIXED — hotfix stage 1** | TGT `apps/api/src/modules/orders/orders.controller.ts:22` | `PATCH orders/:id/status` is public **and** its DTO accepts a client-supplied `actorAdminUserId`, so an anonymous caller can move an order's status and attribute it to any admin. In the reference this was an admin operation. | `DECISIONS.md` §"@Public audit" B3 | ✅ Done: `order.list.sts.submit`. Had no caller — the admin panel uses `admin/orders/status`. |
|
||||
| SEC-04 | High | TGT `apps/api` (two files) | `JWT_SECRET` falls back to `'dev-only-insecure-secret'` and is absent from `.env.example`. `enableCors()` is wide open. | Reported by api inventory; see `_inv-tgt-api.md` §11. | Require the env var at boot; restrict CORS origins. |
|
||||
| SEC-05 | High | TGT `apps/api/prisma/seed.ts` | Seed creates a SUPER_ADMIN (`09128081392`) whose **password equals the phone number**, holding all 144 rids. Marked DEV-ONLY in comments but lives in the normal seed. | `docs/CHANGELOG-PORT-HISTORY.md` §4 documents this as intentional for dev. | Gate behind an explicit env flag so it can never run outside dev. |
|
||||
| SEC-04 | ~~High~~ **FIXED 2026-10-08** — production (`NODE_ENV=production`) refuses to boot without `JWT_SECRET`; CORS reads `CORS_ORIGINS` (exact origins, comma-separated), blank = allow-all with a boot warning in production. Verified: boot refused with a blank key in production only; a listed origin gets `Access-Control-Allow-Origin`, an unlisted one does not. | TGT `apps/api` (two files) | `JWT_SECRET` falls back to `'dev-only-insecure-secret'` and is absent from `.env.example`. `enableCors()` is wide open. | Reported by api inventory; see `_inv-tgt-api.md` §11. | Require the env var at boot; restrict CORS origins. |
|
||||
| SEC-05 | ~~High~~ **FIXED 2026-10-08** — worse than logged: the app runs the seed once on a fresh database at boot (`bootstrap.ts`), and the WHOLE seed was demo data (sample customers, products, orders, posted debt, and admin accounts with known passwords). Now only roles + permissions run in production; the rest needs `SEED_DEMO_DATA=true`. ⚠ Any deployment that already booted on an empty database has these demo rows and must be checked. | TGT `apps/api/prisma/seed.ts` | Seed creates a SUPER_ADMIN (`09128081392`) whose **password equals the phone number**, holding all 144 rids. Marked DEV-ONLY in comments but lives in the normal seed. | `docs/CHANGELOG-PORT-HISTORY.md` §4 documents this as intentional for dev. | Gate behind an explicit env flag so it can never run outside dev. |
|
||||
| SEC-06 | High | REF `henza_server` | Hardcoded secrets committed to the repo: SMS panel password, PayPing bearer token, Tahesab bearer + IP allowlist, wallet hash pepper (`"yhoenszeaf"`). | See `_inv-ref-server.md` §11.4. | Rotate all of them before any deployment that reuses these credentials. |
|
||||
| SEC-07 | Medium | TGT `apps/api/src/modules/admin-customers/admin-customers.service.ts` | `setRoles` stores arbitrary strings as rids with no validation against `ALL_RIDS`. | api inventory §9. | Validate against the rid catalogue. |
|
||||
| SEC-07 | Medium | TGT `apps/api/src/modules/admin-customers/admin-customers.service.ts` | `setRoles` stores arbitrary strings as rids with no validation against `ALL_RIDS`. | api inventory §9. | Validate against the rid catalogue. ✅ **FIXED 2026-10-08:** `setRoles` stores only rids in ALL_RIDS or their tree parents; anything else is dropped with a warning log, so a tick on a legacy-only tree leaf (e.g. notify.create.single.*, which no route checks) cannot fail the save. Test: admin-users.roles.spec.ts. |
|
||||
|
||||
## Customer / person module (found during the user-requested deep check)
|
||||
|
||||
@@ -46,8 +46,8 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
| MON-01 | ~~Critical~~ **FIXED (verified 2026-10-08)** | TGT `apps/user-app-v2/src/stores/cartStore.ts` | v2 has **no `capQty` / `maxQty` stock ceiling**, which `user-app` does have (`apps/user-app/src/stores/cartStore.ts:62,65`; `components/product/CartItem.vue:82-83`). A v2 user can order more units than exist. | Verified by grep across both apps — zero hits in v2. | Port the ceiling to v2 (this is also a **Phase 2 parity gap**, row to be added to `02-APPS-MATRIX.md`). |
|
||||
| MON-02 | High | REF `henza_server` wallet package | The wallet `balance` column **mixes grams and toman in one field**, and money operations are not wrapped in DB transactions. | `_inv-ref-server.md` §7. | Separate the units; wrap mutations in transactions. |
|
||||
| MON-03 | ~~High~~ **NO EFFECT (verified 2026-10-08)** — `Prisma.Decimal(4.331802)` converts through the number's shortest decimal string, i.e. exactly `4.331802`; nothing is pre-rounded | TGT `apps/api/src/modules/accounting/ledger.service.ts:189` | `GRAMS_PER_MESGHAL = 4.331802` is a JS **float** used inside an otherwise-`Prisma.Decimal` CASH repayment formula, so the divisor is pre-rounded before the Decimal division. | Read at `ledger.service.ts:182-190`; the source comment already flags the formula for stakeholder review. | Make the constant a `Decimal` (or a string literal passed to `Decimal`). |
|
||||
| MON-04 | High | TGT `apps/api/src/modules/orders/orders.service.ts` | Debt is recognised at `DELIVERED_TO_AGENT`, but the idempotency guard checks `deliveredAt`, which is only set by `DELIVERED_TO_CUSTOMER` — so the debt trigger is not reliably idempotent. There is also **no status-transition validation** anywhere. | api inventory §8. | Guard on the same field the trigger fires on; add an explicit transition table. |
|
||||
| MON-05 | Medium | TGT `apps/api` | `canPlaceOrders` and `verificationStep` are stored and toggled by the admin panel but **never enforced** on any order path. | api inventory §8. | Enforce at order creation, or remove the toggles. |
|
||||
| MON-04 | ~~High~~ **FIXED 2026-10-08 — see ACC-03** | TGT `apps/api/src/modules/orders/orders.service.ts` | Debt is recognised at `DELIVERED_TO_AGENT`, but the idempotency guard checks `deliveredAt`, which is only set by `DELIVERED_TO_CUSTOMER` — so the debt trigger is not reliably idempotent. There is also **no status-transition validation** anywhere. | api inventory §8. | Guard on the same field the trigger fires on; add an explicit transition table. |
|
||||
| MON-05 | ~~Medium~~ **FIXED 2026-10-08 (owner option 2)** — `canPlaceOrders` now blocks orders placed from the app (403); an operator can still order for the customer. Legacy never read `customers.sts` (313 active customers carry «عدم سفارش», mostly the sign-up default), so the import sets everyone to allowed; only a deliberate suspension after go-live blocks. `verificationStep` is still not enforced, as in legacy. | TGT `apps/api` | `canPlaceOrders` and `verificationStep` are stored and toggled by the admin panel but **never enforced** on any order path. | api inventory §8. | Enforce at order creation, or remove the toggles. |
|
||||
| MON-06 | Medium | TGT `apps/api` | `Setting` rows are never seeded — `wallet.config`, `wallet.birthday`, `promotion.auto`, `mobile_main_slider` only materialise on first write, so a fresh install has undefined behaviour until an admin saves each one. | api inventory §7. | Seed the defaults. |
|
||||
| MON-07 | Medium | REF `henza_server/app/Models/ProductVariant.php:183-190` vs `SingleCustomerOrders.php:67`, `Order.php:66` | Two **divergent order-status enums** coexist (0–6 and 1–7) for what is conceptually one flow. | Read both models. | Unify, or document the mapping explicitly. |
|
||||
|
||||
@@ -76,9 +76,9 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
|
||||
| ID | Severity | Where | Description |
|
||||
|---|---|---|---|
|
||||
| DEAD-01 | Low | TGT `apps/user-app` | 8 components with no importers, `loadingStore`, `api.getBalance` (zero call sites), unused `gsap` dependency. |
|
||||
| DEAD-02 | Low | TGT `apps/user-app-v2` | 11 dead components, `loadingStore`, `getBalance`, `priceUnit`/`priceUnitRialLess`, 12 of 15 validators, unused `gsap` + `@ant-design/icons-vue` deps. |
|
||||
| DEAD-03 | Low | TGT `gold-banking-monorepo/user-app-v2/` (repo root, outside `apps/`) | Stray leftover folder containing only `package.json` and an **older** `vite.config.ts` (hardcoded port 5179, hardcoded proxy, imports a `themeConfig` that doesn't exist there). Not matched by `pnpm-workspace.yaml`, so pnpm ignores it. Left in place — deleting it needs user approval. |
|
||||
| DEAD-01 | Low | TGT `apps/user-app` | 8 components with no importers, `loadingStore`, `api.getBalance` (zero call sites), unused `gsap` dependency. ✅ **FIXED 2026-10-08** (owner approved): removed 8 unreachable components + loadingStore (found by walking imports from main.ts; sw.ts kept — vite-plugin-pwa entry), the unused validators/price helpers, and the gsap + @ant-design/icons-vue dependencies. getBalance was already gone. |
|
||||
| DEAD-02 | Low | TGT `apps/user-app-v2` | 11 dead components, `loadingStore`, `getBalance`, `priceUnit`/`priceUnitRialLess`, 12 of 15 validators, unused `gsap` + `@ant-design/icons-vue` deps. ✅ **FIXED 2026-10-08** (owner approved): same for v2: 11 unreachable components + loadingStore, unused validators/price helpers, gsap + @ant-design/icons-vue. |
|
||||
| DEAD-03 | Low | TGT `gold-banking-monorepo/user-app-v2/` (repo root, outside `apps/`) | Stray leftover folder containing only `package.json` and an **older** `vite.config.ts` (hardcoded port 5179, hardcoded proxy, imports a `themeConfig` that doesn't exist there). Not matched by `pnpm-workspace.yaml`, so pnpm ignores it. Left in place — deleting it needs user approval. ✅ **FIXED 2026-10-08** (owner approved): stray root `user-app-v2/` deleted; nothing referenced it. |
|
||||
| DEAD-04 | Low | REF `henza_server/app/Console/Kernel.php` | `schedule()` is **empty** — no cron. Price refresh / expiry / birthday logic must be driven by OS cron or the `GET /` web route. |
|
||||
| DEAD-05 | Low | REF `henza_server` | PayPing `returnUrl` points at `site/transaction/verify`, which is **not registered in any route file** — the payment callback is unreachable. |
|
||||
|
||||
@@ -96,7 +96,7 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
| ID | Severity | Where | Description | Evidence | Status |
|
||||
|---|---|---|---|---|---|
|
||||
| SEC-11 | High | TGT `apps/api/src/modules/customer-auth/customer-auth.service.ts` (deliver) | The OTP message text, **code included**, was persisted to `SmsMessage.body`, which the admin SMS grid lists and full-text searches (`admin-misc.service.ts:135-136`). Any operator holding the `sms` rid could read live codes — defeating the bcrypt hashing of `codeHash`. | Read both files; grid `allowed` includes `body`. | ✅ Fixed in stage 3: the persisted row is a redacted audit line. |
|
||||
| MON-08 | Medium | TGT `apps/api/src/modules/orders/orders.service.ts:40-52` | `wagePercent`, `discountPercent` and `flatRialCharge` are taken from the **client** on order creation, so a caller can set their own making charge. `rashWeightGrams` is correctly read from the variant. **The reference is worse** — `ApiMobileController.php:538-539,619` takes `rash_weight` from the client too — so this is a partial improvement already. Reported per the user's instruction to flag client-supplied pricing. | REF `:536-545,615-632` vs TGT `:40-52` | Log only (D4). Fix in Phase 2 alongside the price-formula work. |
|
||||
| MON-08 | ~~Medium~~ **FIXED 2026-10-08 (owner-approved)** — app orders are priced by the server (`pricing/wage-formula.ts`, legacy by default: variant % + customer % − largest active product/category/brand promotion; rial charge 0) and the app's wage/discount/rial are ignored; the apps show the same figure from `POST customer/me/wage-quote`. Operators keep their manual numbers. Found on the way: the apps never added the customer's own percent (usually 3) nor any promotion, so the new app undercharged vs legacy. The formula is editable on the new «اجرت» admin screen (`config.wage`) with a live server-computed sample and approve-then-save. Verified end to end: 9+3=12; promotions 2,1 + expired 5 → 10; a tampered order (wage 0, discount 50, rial 999) was charged 10.5% and 0 rial under an approved +0.5 formula. | TGT `apps/api/src/modules/orders/orders.service.ts:40-52` | `wagePercent`, `discountPercent` and `flatRialCharge` are taken from the **client** on order creation, so a caller can set their own making charge. `rashWeightGrams` is correctly read from the variant. **The reference is worse** — `ApiMobileController.php:538-539,619` takes `rash_weight` from the client too — so this is a partial improvement already. Reported per the user's instruction to flag client-supplied pricing. | REF `:536-545,615-632` vs TGT `:40-52` | Log only (D4). Fix in Phase 2 alongside the price-formula work. |
|
||||
|
||||
## Found while classifying scope for D13
|
||||
|
||||
@@ -125,7 +125,7 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
|---|---|---|---|---|---|
|
||||
| PRICE-01 | ⏸️ out of scope (was Critical) | TGT `apps/api/src/modules/admin-products/admin-products.service.ts:188-208`; `apps/admin-panel/src/views/apps/product/ProductList.vue` | **No product price is computed or shown anywhere in the admin panel.** The reference appends `price` and `price_with_discount` to every variant (`ProductVariant.php:115-119`), sets the live gold rate before listing (`AdminController.php:97-98`), and renders `{{ item.price }}` in three places in its product list (`ProductList.vue:283,287,301`). The target's `variantRow()` returns neither field, nothing fetches a gold price for the admin list, and `computeVariantPrice()` — ported and unit-tested today — is called from nowhere. | `grep computeVariantPrice src/ --include=*.ts` matches only its own file and spec. | ⏸️ **Stopped by D16** — price display is retail-storefront, out of scope. `variant-price.ts` and its 11 tests are KEPT but unused. Nothing needed reverting: the function was never called. Making-charge fields stay in scope. |
|
||||
| PRICE-02 | Info | REF `app/Models/ProductVariant.php:163` vs TGT `admin-products.service.ts:206-208` | `rial_pay` (a flat rial charge per variant) appears only in the **superseded, commented-out** formula, not the live one at `:183-190`. The target returns null rather than faking it, which matches the live reference. Recorded so nobody "restores" it from the dead code. | Read both. | ✅ No action — matches. |
|
||||
| PERM-01 | Medium | TGT `prisma/seed.ts`; `apps/admin-panel/src/views/user/permissionConst.ts` | `dashboard.omde` and `dashboard.tak` are seeded into the `permission` table but are **absent from the permission UI tree**, so they can be held by a row yet never seen, granted or revoked from the admin screen — and nothing reads them any more (the protected Dashboard uses `dashboard.view`). The DB holds **178** distinct rids against the UI's **174**. | `SELECT rid FROM permission GROUP BY rid` → 178, including all three dashboard rids. | Open — the fix removes permission rows, which is a data deletion and needs the owner's approval first. |
|
||||
| PERM-01 | Medium | TGT `prisma/seed.ts`; `apps/admin-panel/src/views/user/permissionConst.ts` | `dashboard.omde` and `dashboard.tak` are seeded into the `permission` table but are **absent from the permission UI tree**, so they can be held by a row yet never seen, granted or revoked from the admin screen — and nothing reads them any more (the protected Dashboard uses `dashboard.view`). The DB holds **178** distinct rids against the UI's **174**. | `SELECT rid FROM permission GROUP BY rid` → 178, including all three dashboard rids. | ✅ **FIXED 2026-10-08** (owner approved the deletion). Migration `20261008160000_dashboard_permission_merge` gives `dashboard.view` to every type holding `dashboard` / `dashboard.omde` / `dashboard.tak`, then deletes those rows. **Also found:** the import dropped these three as unknown rids, so legacy types 102, 104, 105, 108 and 135 lost the dashboard — `people.ts` RENAMED_RIDS now maps them to `dashboard.view`. The other 45 legacy rids the target lacks are tree parents or rids no legacy code reads. |
|
||||
|
||||
## Delivery-mode items (D19/D20, 2026-09-22)
|
||||
|
||||
@@ -134,8 +134,8 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
| **REL-01** | **Critical — before the real release** | TGT deployment env | **`OTP_MASTER_CODE` must be removed from the environment, and the SMS credentials configured.** While the variable is set, ANY active customer can sign in with that one fixed code. It is off by default (unset = disabled) and the API prints a boot banner while it is armed, but nothing stops it reaching production except this step. | `customer-auth.service.ts` `masterOtpCode()`; `main.ts` boot banner; D20 | Unset `OTP_MASTER_CODE`; set `SMS_TREZ_USERNAME` / `SMS_TREZ_PASSWORD` / `SMS_TREZ_SENDER_LINE`; restart and confirm the banner is gone. |
|
||||
| **REL-02** | High | TGT `apps/api/src/modules/sms/sms.service.ts` | D20 removed the rule that a missing SMS credential aborts the boot in production. The server now starts with SMS disabled, so **customers cannot receive a login code** and the failure is only a log line. Deliberate, to keep the delivery unblocked. | D14 (superseded) vs D20 | After the delivery, decide whether to restore a boot check or add a health endpoint that reports SMS readiness. **Eased by D26 (2026-10-05):** the default `relay` driver needs no credentials, so SMS works on a fresh deployment; a gateway refusal is still only a log line. |
|
||||
| **PERS-01** | Medium | REF `AdminController.php:348` vs TGT `admin-customers.service.ts` `update()` | The reference **discards the submitted mobile on edit** (`$input['mobile'] = $customer->mobile;`), making it immutable once set; the target lets an operator change it. D19 ruled the lock NOT ported, so the target keeps the editable behaviour. Changing a mobile changes the customer's login identity. | `AdminController.php:348`; D19 answer B | If the lock is wanted later, apply it in `update()` and hide/disable the field on the edit form. |
|
||||
| **PERS-02** | Medium | REF `cities` table vs TGT `City` model | The reference's cities are a **two-level hierarchy** (`parent` + `level`, provinces at level 0) rendered as an `a-tree-select` with provinces **not selectable** (`citiesModel.js:38`). The target flattened this to a nullable `province` **string** and a flat `a-select` on all three Persons forms. Functionally the city is still captured; the province grouping and its tree UI are absent. | `2021_09_18_171700_city_table.php:18-19`; `henza_admin/src/mixins/citiesModel.js:20-48`; `schema.prisma` `model City` | Structural change; decide with the owner during the cities screen (Phase 1c). |
|
||||
| **PERS-03** | Low — **column added 2026-10-07 (`Customer.birthDate`, 541 legacy dates imported); form field still missing** | REF `bulkCustomer.vue:111`, `singleCustomer.vue:29` vs TGT | The reference collects a **Jalali birth date** on both the wholesale (`birth_date`) and retail (`birth_day`) customer forms via `DateInput`. The target's `Customer` model has no column for it and both forms omit the field. | `henza_admin/.../bulkCustomer.vue:111`; `schema.prisma` `model Customer` (no birth field) | Additive: add a nullable `birthDate` column and the picker, if the owner wants it. |
|
||||
| **PERS-02** | Medium | REF `cities` table vs TGT `City` model | The reference's cities are a **two-level hierarchy** (`parent` + `level`, provinces at level 0) rendered as an `a-tree-select` with provinces **not selectable** (`citiesModel.js:38`). The target flattened this to a nullable `province` **string** and a flat `a-select` on all three Persons forms. Functionally the city is still captured; the province grouping and its tree UI are absent. | `2021_09_18_171700_city_table.php:18-19`; `henza_admin/src/mixins/citiesModel.js:20-48`; `schema.prisma` `model City` | ✅ **FIXED 2026-10-08** (owner: as legacy). `City.parentId` (self relation, Restrict) replaces `province`; migration `20261008170000_city_tree` turns each province label into a parent row («استان …») before dropping the column. Admin pickers are legacy's tree (`CityTreeSelect.vue`: top level with children not selectable); city form/grid have «والد». **Also restored:** legacy `_getP` — a city without its own percent takes its ancestor's (`getCityPercent`); the omde-customer form's city→percent autofill. Import copies legacy parents. Delete refuses a city with children; a parent loop is refused. |
|
||||
| **PERS-03** | Low — **column added 2026-10-07 (`Customer.birthDate`, 541 legacy dates imported); form field still missing** | REF `bulkCustomer.vue:111`, `singleCustomer.vue:29` vs TGT | The reference collects a **Jalali birth date** on both the wholesale (`birth_date`) and retail (`birth_day`) customer forms via `DateInput`. The target's `Customer` model has no column for it and both forms omit the field. | `henza_admin/.../bulkCustomer.vue:111`; `schema.prisma` `model Customer` (no birth field) | Additive: add a nullable `birthDate` column and the picker, if the owner wants it. ✅ **FIXED 2026-10-08:** Jalali «تاریخ تولد» (DateInput) on the wholesale (`birth_date`) and retail (`birth_day`) forms; create/update accept either name, refuse impossible/future dates, '' clears; customer rows return both names. |
|
||||
| **PERF-01** | Low | TGT `admin-customers.service.ts` `listReagents()` | The per-agent gold-sold total runs **one `order.aggregate` per row** inside `Promise.all` — an N+1 on every page of the sales-expert grid. Harmless at the current agent count. | `listReagents()` `rows.map(async ...)` | Replace with a single `groupBy` over the referring agent. |
|
||||
|
||||
## Apps — found during the delivery smoke test (2026-09-23)
|
||||
@@ -179,7 +179,7 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|
||||
|---|---|---|---|---|---|
|
||||
| **ACC-01** | Medium (unverified) | TGT `accounting-sync/providers/zarrin.provider.ts` | The Zarrin driver follows the published docs only — there is no Zarrin installation to test on. Open points: which sign of `listMandeHesabha` means "owes" (a setting, default negative), whether stones belong in `mablagh` or `mablaghSang` on `foroushSakhte` (sent in `mablagh`), and the exact response envelopes. | Owner: «نه، فعلاً نداریم» (no test install). Unit tests use the docs' sample outputs. | Before real use: a trial on temporary documents on a real install (owner's decision 11), check one balance and one document against the Zarrin UI. |
|
||||
| **ACC-02** | Low (by design) | TGT D27 | Order documents are sent **temporary** (owner ruling), and a temporary Tahesab document does **not** move the balance until the accountant finalises it. Until then the balance the customer sees from the accounting software does not include those orders. | Measured on the Tahesab test server: balance delta 0 for a temporary `VKHKar`, −Vazn×Ayar/750 once final. | Accountant finalises documents promptly; the report marks temporary rows «موقت — هنوز در مانده اثر ندارد». |
|
||||
| **ACC-03** | **High** (pre-existing, NOT fixed — ledger is protected) | TGT `orders/orders.service.ts` `updateStatus()` | The debt guard is `DELIVERED_TO_AGENT && !order.deliveredAt`, but `deliveredAt` is only set at `DELIVERED_TO_CUSTOMER`. An order moved into DELIVERED_TO_AGENT a second time (e.g. PREPARING → DELIVERED_TO_AGENT again via «تغییر وضعیت») posts the gold and rial debt **twice**. | Read at `orders.service.ts:135-160`. The new accounting hook is not affected (it dedupes on the existing document row). | Guard on an existing `ORDER_STOCK` ledger entry for the order instead of `deliveredAt`; needs owner approval (PROTECTED area). |
|
||||
| **ACC-03** | ~~**High**~~ **FIXED 2026-10-08 (owner-approved)** — `LedgerService.syncOrderDebt`: on every status change the order's ORDER_STOCK entries are brought to what legacy's recomputed `sts > 4` gives (full weight + rial while DELIVERED_TO_AGENT/CUSTOMER, else 0), posting only the difference as a confirmed DEBIT/CREDIT. Also fixes: straight-to-DELIVERED_TO_CUSTOMER owed nothing; rollback/cancel left the debt. Removing the «تحویل به نماینده» status is allowed again, as in legacy. Existing data: 0 orders out of line in dev and the imported copy. | TGT `orders/orders.service.ts` `updateStatus()` | The debt guard is `DELIVERED_TO_AGENT && !order.deliveredAt`, but `deliveredAt` is only set at `DELIVERED_TO_CUSTOMER`. An order moved into DELIVERED_TO_AGENT a second time (e.g. PREPARING → DELIVERED_TO_AGENT again via «تغییر وضعیت») posts the gold and rial debt **twice**. | Read at `orders.service.ts:135-160`. The new accounting hook is not affected (it dedupes on the existing document row). | Guard on an existing `ORDER_STOCK` ledger entry for the order instead of `deliveredAt`; needs owner approval (PROTECTED area). |
|
||||
| **ACC-04** | Low (pre-existing) | TGT `src/prisma/migrate.ts` | On a completely empty database `runMigrations` fails: `0002_admin_schema.sql` sorts before `20260910113720_first` and alters tables that do not exist yet. Existing databases are unaffected. | Reproduced while preparing the D27 throwaway test database (`relation "City" does not exist`). | Rename to sort after `first`, with a `LEGACY_NAME_ALIASES` entry so applied databases do not re-run it. |
|
||||
| **ACC-05** | Low (behaviour change) | TGT `catalog.service.ts` | D27 rule: a product with **no image** is no longer listed in the app nor orderable — for every product, not only those from the accounting software. | Dev DB on 2026-10-05: 0 of 5 active products affected. | Before release run `select count(*) from "Product" p where p."isActive" and not exists (select 1 from "ProductImage" i where i."productId" = p.id);` on production and photograph those first. |
|
||||
| **ACC-06** | Medium (fixed 2026-10-05) | TGT `accounting-sync/accounting-http.ts` | A real Tahesab install reached by IP could not connect. Tahesab serves its own self-signed certificate issued for `localhost` / `127.0.0.1`, so verification failed (`DEPTH_ZERO_SELF_SIGNED_CERT`), and pasting it as a CA still failed the name check (`ERR_TLS_CERT_ALTNAME_INVALID`). «تست اتصال» also tested only *saved* settings. | Owner's server (`https://<ip>:4040`, DBname `tahesabDB5`): token and DB were fine (raw `CheckHealth` = OK). The same server also answers to the default `TahesabDB` — a different database (40 customer groups instead of 19). | Fixed: a pasted certificate is now also a **pin** — exactly that certificate is accepted under any name; the chain check stays on, any other certificate is still name-checked, and verification is never switched off. New «دریافت گواهی از سرور» button shows the SHA-256 fingerprint to compare before pinning; «تست اتصال» uses the form as typed. Verified against the owner's server; `accounting-http.spec.ts`. Admins must check the DB name in the test result. |
|
||||
|
||||
Generated
+493
-28
File diff suppressed because it is too large
Load Diff
@@ -1,38 +0,0 @@
|
||||
{
|
||||
"name": "user-app-v2",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"lint": "eslint \"src/**/*.{ts,vue}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons-vue": "^6.1.0",
|
||||
"@gold-bank/shared-types": "workspace:*",
|
||||
"@vueuse/core": "^9.13.0",
|
||||
"ant-design-vue": "^3.2.20",
|
||||
"gsap": "^3.9.1",
|
||||
"moment-jalaali": "^0.10.0",
|
||||
"pinia": "^2.2.0",
|
||||
"swiper": "^7.4.1",
|
||||
"vant": "^4.0.3",
|
||||
"vue": "^3.5.0",
|
||||
"vue-router": "^4.4.0",
|
||||
"vue3-lazyload": "^0.2.5-beta",
|
||||
"@lottiefiles/dotlottie-vue": "^0.4.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.1.0",
|
||||
"autoprefixer": "^10.4.2",
|
||||
"less": "^4.1.2",
|
||||
"postcss": "^8.4.5",
|
||||
"tailwindcss": "3.0.18",
|
||||
"typescript": "^5.5.0",
|
||||
"vite": "^5.4.0",
|
||||
"vue-tsc": "^2.1.0",
|
||||
"vite-plugin-pwa": "^0.20.5",
|
||||
"workbox-precaching": "^7.1.0",
|
||||
"workbox-window": "^7.1.0"
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
import { $themeLessVars } from './themeConfig/themeConfig';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
// Ported from legacy vite.config.ts:18-52. Same injectManifest strategy,
|
||||
// same src/sw.ts entry, same manifest values (name/colors/icons/display).
|
||||
VitePWA({
|
||||
base: '/',
|
||||
srcDir: 'src',
|
||||
filename: 'sw.ts',
|
||||
strategies: 'injectManifest',
|
||||
includeAssets: ['favicon.ico'],
|
||||
// legacy ran the SW in dev too (mode: "development")
|
||||
devOptions: { enabled: true, type: 'module' },
|
||||
manifest: {
|
||||
name: 'Montzar',
|
||||
short_name: 'Montzar',
|
||||
description: 'Montzar',
|
||||
theme_color: $themeLessVars.primary,
|
||||
background_color: $themeLessVars.primary,
|
||||
start_url: '/',
|
||||
display: 'standalone',
|
||||
icons: [
|
||||
{ src: 'icon-192.png', sizes: '192x192', type: 'image/png' },
|
||||
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png' },
|
||||
{ src: 'icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5179,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:3000',
|
||||
'/uploads': 'http://localhost:3000',
|
||||
},
|
||||
},
|
||||
css: {
|
||||
preprocessorOptions: {
|
||||
less: {
|
||||
modifyVars: $themeLessVars,
|
||||
javascriptEnabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user