merge: bring latest origin/main into dev (keep local UI)

Resolved UI conflicts in favor of local Ant Design screens; kept non-UI changes from main.
This commit is contained in:
2026-11-03 16:55:42 +03:30
201 changed files with 19202 additions and 1607 deletions
@@ -0,0 +1,488 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import type { CustomerGroupDto, PersonImportSourceStatDto, PersonMood } from '@mento/shared';
import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood';
import { groupSwatch } from '@/lib/customer-groups';
import { toFaDigits } from '@/lib/jalali';
import { UiButton } from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
export type ContactsFilterValue = {
groups: string[];
sources: string[];
moods: PersonMood[];
disc: string;
};
const props = defineProps<{
open: boolean;
tab: 'people' | 'companies';
value: ContactsFilterValue;
groups: CustomerGroupDto[];
sourceStats: PersonImportSourceStatDto[];
canBehavior: boolean;
/** اکشن‌شیت پایین صفحه (موبایل) به‌جای پاپ‌اور */
sheet?: boolean;
/** اگر داده شود بخش مرتب‌سازی داخل همین پنل نمایش داده می‌شود */
sort?: string;
sortOptions?: Array<{ value: string; label: string }>;
}>();
const emit = defineEmits<{
apply: [value: ContactsFilterValue, sort?: string];
close: [];
}>();
const draft = reactive<ContactsFilterValue>({ groups: [], sources: [], moods: [], disc: '' });
const draftSort = ref('');
const groupQuery = ref('');
const GROUP_SEARCH_MIN = 8;
const DISC_TYPES = ['D', 'I', 'S', 'C'];
const hasSort = computed(() => Boolean(props.sortOptions?.length));
const defaultSort = computed(() => props.sortOptions?.[0]?.value ?? '');
watch(
() => props.open,
(open) => {
if (!open) return;
draft.groups = [...props.value.groups];
draft.sources = [...props.value.sources];
draft.moods = [...props.value.moods];
draft.disc = props.value.disc;
draftSort.value = props.sort ?? defaultSort.value;
groupQuery.value = '';
},
{ immediate: true },
);
function onKey(ev: KeyboardEvent) {
if (ev.key === 'Escape' && props.open && props.sheet) emit('close');
}
onMounted(() => document.addEventListener('keydown', onKey));
onBeforeUnmount(() => document.removeEventListener('keydown', onKey));
const isPeople = computed(() => props.tab === 'people');
function groupCount(g: CustomerGroupDto) {
return isPeople.value ? g.personCount : g.companyCount;
}
const filteredGroups = computed(() => {
const q = groupQuery.value.trim().replace(/ي/g, 'ی').replace(/ك/g, 'ک');
const list = props.groups.filter((g) => groupCount(g) > 0 || draft.groups.includes(g.id));
return q ? list.filter((g) => g.name.includes(q)) : list;
});
const draftCount = computed(
() =>
draft.groups.length +
(isPeople.value ? draft.sources.length + draft.moods.length + (draft.disc ? 1 : 0) : 0) +
(hasSort.value && draftSort.value !== defaultSort.value ? 1 : 0),
);
function toggle<T extends string>(list: T[], value: T) {
const idx = list.indexOf(value);
if (idx >= 0) list.splice(idx, 1);
else list.push(value);
}
function clearAll() {
draft.groups = [];
draft.sources = [];
draft.moods = [];
draft.disc = '';
if (hasSort.value) draftSort.value = defaultSort.value;
}
function apply() {
emit(
'apply',
{
groups: [...draft.groups],
sources: [...draft.sources],
moods: [...draft.moods],
disc: draft.disc,
},
hasSort.value ? draftSort.value : undefined,
);
}
</script>
<template>
<Teleport to="body" :disabled="!sheet">
<div v-if="open && sheet" class="sheet-dim" @click="emit('close')" />
<div
v-if="open"
class="panel"
:class="{ sheet }"
role="dialog"
:aria-modal="sheet ? 'true' : undefined"
aria-label="فیلترها"
@click.stop
>
<span v-if="sheet" class="grip" aria-hidden="true" />
<header class="panel-head">
<strong>{{ hasSort ? 'فیلتر و مرتب‌سازی' : 'فیلترها' }}</strong>
<button type="button" class="link" :disabled="!draftCount" @click="clearAll">پاک کردن همه</button>
</header>
<div class="panel-body">
<section v-if="hasSort" class="sec">
<h4>مرتب‌سازی</h4>
<div class="pills">
<button
v-for="o in sortOptions"
:key="o.value"
type="button"
class="pill"
:class="{ on: draftSort === o.value }"
@click="draftSort = o.value"
>
{{ o.label }}
</button>
</div>
</section>
<section class="sec">
<h4>
گروه
<span v-if="draft.groups.length" class="sel">{{ toFaDigits(draft.groups.length) }} انتخاب</span>
</h4>
<label v-if="groups.length > GROUP_SEARCH_MIN" class="find">
<UiIcon name="search" :size="14" />
<input v-model="groupQuery" type="search" placeholder="جستجوی گروه…" />
</label>
<ul v-if="filteredGroups.length" class="checks">
<li v-for="g in filteredGroups" :key="g.id">
<label class="check">
<input
type="checkbox"
:checked="draft.groups.includes(g.id)"
@change="toggle(draft.groups, g.id)"
/>
<i class="dot" :style="{ background: groupSwatch(g.color).fg }" />
<span class="lbl">{{ g.name }}</span>
<em>{{ toFaDigits(groupCount(g)) }}</em>
</label>
</li>
</ul>
<p v-else class="empty">{{ groupQuery ? 'گروهی با این نام نیست.' : 'گروهی ثبت نشده است.' }}</p>
</section>
<template v-if="isPeople">
<section v-if="sourceStats.length" class="sec">
<h4>
منبع
<span v-if="draft.sources.length" class="sel">{{ toFaDigits(draft.sources.length) }} انتخاب</span>
</h4>
<ul class="checks">
<li v-for="row in sourceStats" :key="row.source">
<label class="check">
<input
type="checkbox"
:checked="draft.sources.includes(row.source)"
@change="toggle(draft.sources, row.source)"
/>
<span class="lbl">{{ row.label }}</span>
<em>{{ toFaDigits(row.count) }}</em>
</label>
</li>
</ul>
</section>
<section class="sec">
<h4>وضعیت مشتری</h4>
<div class="pills">
<button
v-for="m in PERSON_MOODS"
:key="m"
type="button"
class="pill"
:class="{ on: draft.moods.includes(m) }"
@click="toggle(draft.moods, m)"
>
{{ PERSON_MOOD_LABELS[m] }}
</button>
</div>
</section>
<section v-if="canBehavior" class="sec">
<h4>تیپ DISC</h4>
<div class="pills">
<button
v-for="t in DISC_TYPES"
:key="t"
type="button"
class="pill"
:class="{ on: draft.disc === t }"
@click="draft.disc = draft.disc === t ? '' : t"
>
{{ t }}
</button>
</div>
</section>
</template>
</div>
<footer class="panel-foot">
<UiButton variant="ghost" size="sm" @click="emit('close')">انصراف</UiButton>
<UiButton variant="primary" size="sm" @click="apply">
اعمال<template v-if="draftCount"> ({{ toFaDigits(draftCount) }})</template>
</UiButton>
</footer>
</div>
</Teleport>
</template>
<style scoped>
.panel {
position: absolute;
inset-inline-end: 0;
top: calc(100% + 6px);
z-index: 20;
width: min(22rem, calc(100vw - 1.5rem));
background: #fff;
border: 1px solid var(--line);
border-radius: 12px;
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.16);
display: flex;
flex-direction: column;
max-height: min(72vh, 36rem);
}
.panel-head,
.panel-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.7rem 0.9rem;
}
.panel-head {
border-bottom: 1px solid var(--line);
}
.panel-foot {
border-top: 1px solid var(--line);
justify-content: flex-end;
}
.link {
border: 0;
background: none;
color: var(--accent, #0f766e);
font: inherit;
font-size: var(--fs-sm);
cursor: pointer;
padding: 0;
}
.link:disabled {
color: #cbd5e1;
cursor: default;
}
.panel-body {
overflow-y: auto;
padding: 0.35rem 0.9rem 0.6rem;
}
.sec {
padding: 0.55rem 0;
}
.sec + .sec {
border-top: 1px dashed var(--line);
}
.sec h4 {
margin: 0 0 0.45rem;
font-size: var(--fs-sm);
color: var(--ink);
display: flex;
align-items: center;
gap: 0.4rem;
}
.sel {
font-weight: 500;
font-size: 0.72rem;
color: #0f766e;
background: #ccfbf1;
border-radius: 999px;
padding: 0.05rem 0.45rem;
}
.find {
display: flex;
align-items: center;
gap: 0.35rem;
border: 1px solid var(--line);
border-radius: 8px;
padding: 0 0.55rem;
height: 2rem;
margin-bottom: 0.4rem;
color: var(--muted);
}
.find input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
font: inherit;
font-size: var(--fs-sm);
}
.checks {
list-style: none;
margin: 0;
padding: 0;
max-height: 13rem;
overflow-y: auto;
}
.check {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.32rem 0.35rem;
border-radius: 6px;
cursor: pointer;
font-size: var(--fs-sm);
}
.check:hover {
background: var(--surface-subtle, #f8fafc);
}
.check input {
accent-color: #14b8a6;
margin: 0;
}
.dot {
width: 0.55rem;
height: 0.55rem;
border-radius: 50%;
flex-shrink: 0;
}
.lbl {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.check em {
font-style: normal;
font-size: 0.75rem;
color: #94a3b8;
}
.empty {
margin: 0;
font-size: 0.8rem;
color: #94a3b8;
}
.pills {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.pill {
border: 1px solid var(--line);
background: #fff;
border-radius: 999px;
padding: 0.25rem 0.7rem;
font: inherit;
font-size: 0.8rem;
color: var(--ink-secondary);
cursor: pointer;
}
.pill.on {
border-color: #14b8a6;
background: #f0fdfa;
color: #0f766e;
font-weight: 600;
}
/* ===== اکشن‌شیت موبایل ===== */
.sheet-dim {
position: fixed;
inset: 0;
z-index: 1000;
background: rgba(15, 23, 42, 0.4);
animation: dim-in 0.18s ease-out;
}
.panel.sheet {
position: fixed;
inset: auto 0 0 0;
top: auto;
z-index: 1001;
width: 100%;
max-height: 85vh;
border: 0;
border-radius: 16px 16px 0 0;
box-shadow: 0 -10px 30px rgba(15, 23, 42, 0.18);
padding-bottom: env(safe-area-inset-bottom, 0);
animation: sheet-up 0.22s ease-out;
}
.grip {
display: block;
width: 2.5rem;
height: 4px;
margin: 0.5rem auto 0;
border-radius: 999px;
background: #cbd5e1;
}
.panel.sheet .panel-head {
padding-top: 0.5rem;
}
.panel.sheet .checks {
max-height: none;
}
.panel.sheet .check {
padding-block: 0.5rem;
}
.panel.sheet .pill {
padding: 0.4rem 0.85rem;
}
.panel.sheet .panel-foot > * {
flex: 1 1 0;
justify-content: center;
}
@keyframes sheet-up {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
@keyframes dim-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
@@ -0,0 +1,48 @@
<script setup lang="ts">
import type { CustomerGroupSummaryDto } from '@mento/shared';
import { groupSwatch } from '@/lib/customer-groups';
defineProps<{
groups: CustomerGroupSummaryDto[] | undefined;
/** متن وقتی گروهی نیست */
empty?: string;
}>();
</script>
<template>
<span v-if="groups?.length" class="group-chips">
<span
v-for="g in groups"
:key="g.id"
class="group-chip"
:style="{ color: groupSwatch(g.color).fg, background: groupSwatch(g.color).bg }"
:title="g.source === 'tahesab' ? `${g.name} (از ته‌حساب)` : g.name"
>
{{ g.name }}
</span>
</span>
<span v-else-if="empty" class="group-empty">{{ empty }}</span>
</template>
<style scoped>
.group-chips {
display: inline-flex;
flex-wrap: wrap;
gap: 0.25rem;
vertical-align: middle;
}
.group-chip {
display: inline-block;
padding: 0.1rem 0.5rem;
border-radius: 999px;
font-size: 0.75rem;
font-weight: 600;
line-height: 1.5;
white-space: nowrap;
}
.group-empty {
color: #94a3b8;
}
</style>
@@ -0,0 +1,68 @@
<script setup lang="ts">
import { onMounted } from 'vue';
import { groupSwatch, useCustomerGroups } from '@/lib/customer-groups';
const model = defineModel<string[]>({ default: () => [] });
const { groups, loaded, load } = useCustomerGroups();
function toggle(id: string) {
model.value = model.value.includes(id)
? model.value.filter((x) => x !== id)
: [...model.value, id];
}
onMounted(() => {
void load().catch(() => undefined);
});
</script>
<template>
<div class="picker">
<button
v-for="g in groups"
:key="g.id"
type="button"
class="opt"
:class="{ on: model.includes(g.id) }"
:style="
model.includes(g.id)
? { color: groupSwatch(g.color).fg, background: groupSwatch(g.color).bg, borderColor: groupSwatch(g.color).fg }
: undefined
"
@click="toggle(g.id)"
>
{{ g.name }}
</button>
<span v-if="loaded && !groups.length" class="hint">
هنوز گروهی تعریف نشده؛ از صفحهٔ مخاطبین «مدیریت گروه‌ها» را بزنید.
</span>
</div>
</template>
<style scoped>
.picker {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.opt {
border: 1px solid #e2e8f0;
background: #fff;
color: #475569;
border-radius: 999px;
padding: 0.25rem 0.75rem;
font: inherit;
font-size: 0.82rem;
cursor: pointer;
}
.opt.on {
font-weight: 600;
}
.hint {
color: #94a3b8;
font-size: 0.82rem;
}
</style>
@@ -0,0 +1,295 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import axios from 'axios';
import type { CustomerGroupColor, CustomerGroupDto } from '@mento/shared';
import { CUSTOMER_GROUP_COLORS } from '@mento/shared';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import {
CUSTOMER_GROUP_COLOR_LABELS,
groupSwatch,
useCustomerGroups,
} from '@/lib/customer-groups';
import { UiButton, UiInput, UiModal } from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; changed: [] }>();
const { groups, load } = useCustomerGroups();
const newName = ref('');
const newColor = ref<CustomerGroupColor>('teal');
const editingId = ref<string | null>(null);
const editName = ref('');
const busy = ref(false);
const error = ref('');
function errorText(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] } | undefined)?.message;
if (Array.isArray(msg)) return msg[0] ?? fallback;
if (msg) return msg;
}
return fallback;
}
async function run(task: () => Promise<unknown>, fallback: string) {
busy.value = true;
error.value = '';
try {
await task();
await load(true);
emit('changed');
return true;
} catch (e) {
error.value = errorText(e, fallback);
return false;
} finally {
busy.value = false;
}
}
async function create() {
const name = newName.value.trim();
if (!name) return;
const ok = await run(
() => api.post('/customer-groups', { name, color: newColor.value }),
'ساخت گروه ناموفق بود.',
);
if (ok) newName.value = '';
}
function startEdit(g: CustomerGroupDto) {
editingId.value = g.id;
editName.value = g.name;
}
async function saveName(g: CustomerGroupDto) {
const name = editName.value.trim();
if (!name || name === g.name) {
editingId.value = null;
return;
}
const ok = await run(
() => api.patch(`/customer-groups/${g.id}`, { name }),
'تغییر نام ناموفق بود.',
);
if (ok) editingId.value = null;
}
async function setColor(g: CustomerGroupDto, color: CustomerGroupColor) {
if (g.color === color) return;
await run(() => api.patch(`/customer-groups/${g.id}`, { color }), 'تغییر رنگ ناموفق بود.');
}
async function remove(g: CustomerGroupDto) {
const used = g.personCount + g.companyCount;
const note = used ? ` این گروه از ${toFaDigits(used)} مخاطب برداشته می‌شود (خود مخاطب‌ها حذف نمی‌شوند).` : '';
if (!confirm(`گروه «${g.name}» حذف شود؟${note}`)) return;
await run(() => api.delete(`/customer-groups/${g.id}`), 'حذف گروه ناموفق بود.');
}
watch(
() => props.open,
(open) => {
if (!open) return;
error.value = '';
editingId.value = null;
void load(true).catch(() => {
error.value = 'بارگذاری گروه‌ها ناموفق بود.';
});
},
{ immediate: true },
);
</script>
<template>
<UiModal :open="open" title="گروه‌های مشتری" @close="emit('close')">
<div class="manager">
<p class="lead">
هر شخص یا شرکت می‌تواند چند گروه داشته باشد. گروه‌هایی که از ته‌حساب می‌آیند با برچسب
«ته‌حساب» مشخص شده‌اند.
</p>
<form class="new-row" @submit.prevent="create">
<UiInput v-model="newName" placeholder="نام گروه جدید" :maxlength="80" :disabled="busy" />
<div class="swatches">
<button
v-for="c in CUSTOMER_GROUP_COLORS"
:key="c"
type="button"
class="swatch"
:class="{ on: newColor === c }"
:style="{ background: groupSwatch(c).fg }"
:title="CUSTOMER_GROUP_COLOR_LABELS[c]"
@click="newColor = c"
/>
</div>
<UiButton type="submit" variant="primary" size="sm" :disabled="busy || !newName.trim()">
<UiIcon name="plus" :size="15" />
افزودن
</UiButton>
</form>
<p v-if="error" class="error">{{ error }}</p>
<ul v-if="groups.length" class="list">
<li v-for="g in groups" :key="g.id" class="row">
<div class="name-cell">
<form v-if="editingId === g.id" class="edit" @submit.prevent="saveName(g)">
<UiInput v-model="editName" :maxlength="80" :disabled="busy" />
<UiButton type="submit" variant="primary" size="sm" :disabled="busy">ذخیره</UiButton>
<UiButton type="button" variant="ghost" size="sm" @click="editingId = null">انصراف</UiButton>
</form>
<template v-else>
<span
class="chip"
:style="{ color: groupSwatch(g.color).fg, background: groupSwatch(g.color).bg }"
>
{{ g.name }}
</span>
<span v-if="g.fromTahesab" class="tag">ته‌حساب</span>
<span class="count">
{{ toFaDigits(g.personCount) }} شخص · {{ toFaDigits(g.companyCount) }} شرکت
</span>
</template>
</div>
<div v-if="editingId !== g.id" class="row-actions">
<div class="swatches">
<button
v-for="c in CUSTOMER_GROUP_COLORS"
:key="c"
type="button"
class="swatch small"
:class="{ on: g.color === c }"
:style="{ background: groupSwatch(c).fg }"
:title="CUSTOMER_GROUP_COLOR_LABELS[c]"
:disabled="busy"
@click="setColor(g, c)"
/>
</div>
<UiButton variant="ghost" size="sm" :disabled="busy" @click="startEdit(g)">تغییر نام</UiButton>
<UiButton variant="ghost" size="sm" :disabled="busy" @click="remove(g)">
<UiIcon name="trash" :size="14" />
</UiButton>
</div>
</li>
</ul>
<p v-else class="muted">هنوز گروهی ساخته نشده است.</p>
</div>
</UiModal>
</template>
<style scoped>
.manager {
display: grid;
gap: 0.85rem;
min-width: min(34rem, 100%);
}
.lead,
.muted {
margin: 0;
color: #64748b;
font-size: 0.85rem;
}
.error {
margin: 0;
color: #dc2626;
font-size: 0.85rem;
}
.new-row,
.edit {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.new-row > :first-child,
.edit > :first-child {
flex: 1 1 12rem;
}
.swatches {
display: inline-flex;
gap: 0.3rem;
}
.swatch {
width: 1.3rem;
height: 1.3rem;
border-radius: 50%;
border: 2px solid #fff;
box-shadow: 0 0 0 1px #e2e8f0;
cursor: pointer;
padding: 0;
}
.swatch.small {
width: 1rem;
height: 1rem;
}
.swatch.on {
box-shadow: 0 0 0 2px #0f172a;
}
.list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.4rem;
max-height: 55vh;
overflow-y: auto;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.5rem 0.65rem;
border: 1px solid #e2e8f0;
border-radius: 10px;
}
.name-cell {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem;
min-width: 0;
flex: 1 1 14rem;
}
.chip {
padding: 0.15rem 0.6rem;
border-radius: 999px;
font-weight: 600;
font-size: 0.85rem;
}
.tag {
font-size: 0.7rem;
color: #0369a1;
background: #e0f2fe;
border-radius: 6px;
padding: 0.05rem 0.4rem;
}
.count {
color: #94a3b8;
font-size: 0.78rem;
}
.row-actions {
display: flex;
align-items: center;
gap: 0.35rem;
}
</style>
@@ -0,0 +1,559 @@
<script setup lang="ts">
import { computed, watch } from 'vue';
import { Select as ASelect } from 'ant-design-vue';
import type {
DataAccessOwnerKind,
DataAccessRule,
DataAccessSection,
PersonMood,
SectionDataAccess,
} from '@mento/shared';
import {
DATA_ACCESS_SECTION_LABELS,
PERSON_IMPORT_SOURCES,
PERSON_MOOD_LABELS,
PERSON_MOODS,
sectionHasDataAccessLimits,
} from '@mento/shared';
export type IdOption = { id: string; name: string };
type Choice = { value: string; label: string };
const props = withDefaults(
defineProps<{
modelValue: SectionDataAccess;
section?: DataAccessSection;
groups?: IdOption[];
stages?: IdOption[];
pipelines?: IdOption[];
boards?: IdOption[];
activityTypes?: IdOption[];
/** منبع‌هایی که در مشتریان همین محیط رکورد دارند */
importSources?: Choice[];
importSourcesReady?: boolean;
importSourcesFailed?: boolean;
disabled?: boolean;
compact?: boolean;
}>(),
{
section: 'customers',
groups: () => [],
stages: () => [],
pipelines: () => [],
boards: () => [],
activityTypes: () => [],
importSources: () => [],
importSourcesReady: false,
importSourcesFailed: false,
},
);
const emit = defineEmits<{
'update:modelValue': [SectionDataAccess];
}>();
const sectionLabel = computed(() => DATA_ACCESS_SECTION_LABELS[props.section]);
const showGroups = computed(() => props.section === 'customers');
const showMoods = computed(() => props.section === 'customers');
const showImportSources = computed(() => props.section === 'customers');
const showLeadSources = computed(() => props.section === 'leads');
const showNoteTypes = computed(() => props.section === 'notes');
const showTicketStatuses = computed(() => props.section === 'tickets');
const showStages = computed(
() =>
props.section === 'leads' ||
props.section === 'sales' ||
props.section === 'activities' ||
props.section === 'projects',
);
const showPipelines = computed(() => props.section === 'sales');
const showBoards = computed(
() => props.section === 'activities' || props.section === 'projects',
);
const showTypes = computed(
() => props.section === 'activities' || props.section === 'routines',
);
const ownerSelfLabel = computed(() => {
if (
props.section === 'leads' ||
props.section === 'activities' ||
props.section === 'routines' ||
props.section === 'tickets'
) {
return 'مسئول خودش';
}
if (props.section === 'notes') return 'نویسنده خودش';
return 'پرونده‌های خود';
});
const noteTypeOptions = [
{ value: 'general', label: 'عمومی' },
{ value: 'call_result', label: 'نتیجه تماس' },
{ value: 'meeting', label: 'جلسه' },
{ value: 'important', label: 'مهم' },
{ value: 'warning', label: 'هشدار' },
{ value: 'next_action', label: 'اقدام بعدی' },
{ value: 'follow_up', label: 'پیگیری' },
{ value: 'idea', label: 'ایده' },
{ value: 'suggestion', label: 'پیشنهاد' },
{ value: 'personal', label: 'شخصی' },
];
const ticketStatusOptions = [
{ value: 'open', label: 'باز' },
{ value: 'in_progress', label: 'در حال انجام' },
{ value: 'waiting', label: 'در انتظار' },
{ value: 'resolved', label: 'حل‌شده' },
{ value: 'closed', label: 'بسته' },
];
const typesLegend = computed(() =>
props.section === 'routines' ? 'دسته روتین' : 'نوع فعالیت',
);
const boardsLegend = computed(() =>
props.section === 'projects' ? 'بورد پروژه' : 'بورد فعالیت',
);
/** چند قانون قدیمی → یک فیلتر (اتحاد گزینه‌ها) برای ویرایش ساده */
function collapseRules(rules: DataAccessRule[]): DataAccessRule {
if (!rules.length) return {};
if (rules.length === 1) return { ...rules[0]! };
const owners = new Set<DataAccessOwnerKind>();
const groupIds = new Set<string>();
const sources = new Set<string>();
const moods = new Set<PersonMood>();
const stageIds = new Set<string>();
const pipelineIds = new Set<string>();
const boardIds = new Set<string>();
const typeIds = new Set<string>();
for (const r of rules) {
for (const o of r.owners ?? []) owners.add(o);
for (const id of r.groupIds ?? []) groupIds.add(id);
for (const s of r.sources ?? []) sources.add(s);
for (const m of r.moods ?? []) moods.add(m);
for (const id of r.stageIds ?? []) stageIds.add(id);
for (const id of r.pipelineIds ?? []) pipelineIds.add(id);
for (const id of r.boardIds ?? []) boardIds.add(id);
for (const id of r.typeIds ?? []) typeIds.add(id);
}
const out: DataAccessRule = {};
if (owners.size) out.owners = [...owners];
if (groupIds.size) out.groupIds = [...groupIds];
if (sources.size) out.sources = [...sources];
if (moods.size) out.moods = [...moods];
if (stageIds.size) out.stageIds = [...stageIds];
if (pipelineIds.size) out.pipelineIds = [...pipelineIds];
if (boardIds.size) out.boardIds = [...boardIds];
if (typeIds.size) out.typeIds = [...typeIds];
return out;
}
function ruleHasAnyFilter(rule: DataAccessRule): boolean {
return Boolean(
rule.owners?.length ||
rule.groupIds?.length ||
rule.sources?.length ||
rule.moods?.length ||
rule.stageIds?.length ||
rule.pipelineIds?.length ||
rule.boardIds?.length ||
rule.typeIds?.length,
);
}
const hadMultipleRules = computed(
() => (props.modelValue?.rules?.length ?? 0) > 1,
);
const mode = computed({
get: () => (props.modelValue?.mode === 'rules' ? 'rules' : 'all'),
set: (next: 'all' | 'rules') => {
if (next === 'all') {
emit('update:modelValue', { mode: 'all', rules: [] });
return;
}
const collapsed = collapseRules(props.modelValue?.rules ?? []);
emit('update:modelValue', {
mode: 'rules',
rules: [ruleHasAnyFilter(collapsed) ? collapsed : {}],
});
},
});
const filter = computed(() => collapseRules(props.modelValue?.rules ?? []));
function emitFilter(next: DataAccessRule) {
const cleaned: DataAccessRule = {};
if (next.owners?.length) cleaned.owners = [...next.owners];
if (next.groupIds?.length) cleaned.groupIds = [...next.groupIds];
if (next.sources?.length) cleaned.sources = [...next.sources];
if (next.moods?.length) cleaned.moods = [...next.moods];
if (next.stageIds?.length) cleaned.stageIds = [...next.stageIds];
if (next.pipelineIds?.length) cleaned.pipelineIds = [...next.pipelineIds];
if (next.boardIds?.length) cleaned.boardIds = [...next.boardIds];
if (next.typeIds?.length) cleaned.typeIds = [...next.typeIds];
emit('update:modelValue', { mode: 'rules', rules: [cleaned] });
}
function patchFilter(patch: Partial<DataAccessRule>) {
emitFilter({ ...filter.value, ...patch });
}
function toggleOwner(kind: DataAccessOwnerKind) {
const current = new Set(filter.value.owners ?? []);
if (current.has(kind)) current.delete(kind);
else current.add(kind);
const owners = [...current] as DataAccessOwnerKind[];
patchFilter({ owners: owners.length ? owners : undefined });
}
type ListKey =
| 'groupIds'
| 'sources'
| 'moods'
| 'stageIds'
| 'pipelineIds'
| 'boardIds'
| 'typeIds';
type PickerMode = 'multiple' | 'tags';
type Picker = {
key: ListKey;
legend: string;
mode: PickerMode;
placeholder: string;
notFound: string;
hint?: string;
options: Choice[];
loading?: boolean;
};
function namedOptions(items: IdOption[]): Choice[] {
return items.map((item) => ({ value: item.id, label: item.name }));
}
function withSelected(options: Choice[], selected: readonly string[] | undefined): Choice[] {
const known = new Set(options.map((option) => option.value));
const extra = (selected ?? [])
.filter((id) => id && !known.has(id))
.map((id) => ({ value: id, label: id }));
return extra.length ? [...options, ...extra] : options;
}
function listValue(key: ListKey): string[] {
return ((filter.value[key] as string[] | undefined) ?? []).map(String);
}
const catalogSources = new Set<string>(PERSON_IMPORT_SOURCES);
/** کلیدهای ثابت کاتالوگ که در این محیط رکورد ندارند را نشان نده؛ متن سفارشی بماند. */
function sourcesInThisEnvironment(selected: readonly string[] | undefined): string[] {
const list = selected ?? [];
if (!props.importSourcesReady) {
return list.filter((source) => !catalogSources.has(source));
}
const present = new Set(props.importSources.map((option) => option.value));
return list.filter((source) => present.has(source) || !catalogSources.has(source));
}
const visibleImportSources = computed(() => sourcesInThisEnvironment(filter.value.sources));
function setList(key: ListKey, value: unknown) {
const raw = Array.isArray(value) ? value : value == null || value === '' ? [] : [value];
let list = [...new Set(raw.map((item) => String(item).trim()).filter(Boolean))];
if (key === 'sources' && showImportSources.value && props.importSourcesReady) {
list = sourcesInThisEnvironment(list);
}
patchFilter({ [key]: list.length ? list : undefined });
}
function pickerValue(picker: Picker): string[] {
if (picker.key === 'sources' && showImportSources.value && props.importSourcesReady) {
return visibleImportSources.value;
}
return listValue(picker.key);
}
watch(visibleImportSources, (next) => {
if (!showImportSources.value || !props.importSourcesReady) return;
const current = filter.value.sources ?? [];
if (current.length === next.length && current.every((source, index) => source === next[index])) {
return;
}
patchFilter({ sources: next.length ? next : undefined });
});
const moodOptions: Choice[] = PERSON_MOODS.map((mood) => ({
value: mood,
label: PERSON_MOOD_LABELS[mood],
}));
const pickers = computed((): Picker[] => {
const rule = filter.value;
const items: Picker[] = [];
if (showGroups.value) {
items.push({
key: 'groupIds',
legend: 'گروه‌ها',
mode: 'multiple',
placeholder: props.groups.length ? 'جستجو و انتخاب گروه…' : 'گروهی تعریف نشده',
notFound: props.groups.length ? 'موردی پیدا نشد' : 'گروهی تعریف نشده',
options: withSelected(namedOptions(props.groups), rule.groupIds),
});
}
if (showImportSources.value) {
const ready = props.importSourcesReady;
const failed = props.importSourcesFailed;
items.push({
key: 'sources',
legend: 'منبع',
mode: 'tags',
placeholder: failed
? 'فهرست منبع‌ها بارگذاری نشد'
: props.importSources.length
? 'جستجو، انتخاب یا نوشتن منبع جدید…'
: 'منبعی در این محیط نیست',
notFound: 'برای منبع جدید Enter بزنید',
hint: failed
? 'فهرست منبع‌های این محیط خوانده نشد؛ انتخاب ذخیره‌شده دست نخورده است.'
: 'فقط منبع‌هایی که در مشتریان این محیط هستند. نام تازه را بنویسید و Enter بزنید.',
loading: !ready && !failed,
options: withSelected(
ready ? props.importSources : [],
ready ? visibleImportSources.value : (rule.sources ?? []),
),
});
}
if (showLeadSources.value) {
items.push({
key: 'sources',
legend: 'منبع لید',
mode: 'tags',
placeholder: 'مثلاً اینستاگرام، سایت…',
notFound: 'نام را بنویسید و Enter بزنید',
hint: 'هر منبع را بنویسید و با Enter اضافه کنید.',
options: withSelected([], rule.sources),
});
}
if (showNoteTypes.value) {
items.push({
key: 'sources',
legend: 'نوع یادداشت',
mode: 'multiple',
placeholder: 'جستجو و انتخاب نوع…',
notFound: 'موردی پیدا نشد',
options: withSelected(noteTypeOptions, rule.sources),
});
}
if (showTicketStatuses.value) {
items.push({
key: 'sources',
legend: 'وضعیت تیکت',
mode: 'multiple',
placeholder: 'جستجو و انتخاب وضعیت…',
notFound: 'موردی پیدا نشد',
options: withSelected(ticketStatusOptions, rule.sources),
});
}
if (showMoods.value) {
items.push({
key: 'moods',
legend: 'حال مشتری',
mode: 'multiple',
placeholder: 'جستجو و انتخاب حال مشتری…',
notFound: 'موردی پیدا نشد',
options: withSelected(moodOptions, rule.moods),
});
}
if (showPipelines.value) {
items.push({
key: 'pipelineIds',
legend: 'پایپ‌لاین',
mode: 'multiple',
placeholder: props.pipelines.length ? 'جستجو و انتخاب پایپ‌لاین…' : 'پایپ‌لاینی نیست',
notFound: props.pipelines.length ? 'موردی پیدا نشد' : 'پایپ‌لاینی نیست',
options: withSelected(namedOptions(props.pipelines), rule.pipelineIds),
});
}
if (showStages.value) {
items.push({
key: 'stageIds',
legend: 'مرحله',
mode: 'multiple',
placeholder: props.stages.length ? 'جستجو و انتخاب مرحله…' : 'مرحله‌ای نیست',
notFound: props.stages.length ? 'موردی پیدا نشد' : 'مرحله‌ای نیست',
options: withSelected(namedOptions(props.stages), rule.stageIds),
});
}
if (showBoards.value) {
items.push({
key: 'boardIds',
legend: boardsLegend.value,
mode: 'multiple',
placeholder: props.boards.length ? 'جستجو و انتخاب…' : 'بوردی نیست',
notFound: props.boards.length ? 'موردی پیدا نشد' : 'بوردی نیست',
options: withSelected(namedOptions(props.boards), rule.boardIds),
});
}
if (showTypes.value) {
items.push({
key: 'typeIds',
legend: typesLegend.value,
mode: 'multiple',
placeholder: props.activityTypes.length ? 'جستجو و انتخاب…' : 'موردی تعریف نشده',
notFound: props.activityTypes.length ? 'موردی پیدا نشد' : 'موردی تعریف نشده',
options: withSelected(namedOptions(props.activityTypes), rule.typeIds),
});
}
return items;
});
const hasLimits = computed(() => sectionHasDataAccessLimits(props.modelValue));
const filterSummary = computed(() => {
const rule = filter.value;
const parts: string[] = [];
if (rule.owners?.includes('self')) parts.push(ownerSelfLabel.value);
if (rule.owners?.includes('team')) parts.push('تیم‌های عضو');
if (rule.groupIds?.length) parts.push(`${rule.groupIds.length} گروه`);
if (rule.sources?.length) parts.push(`${rule.sources.length} مورد منبع/نوع`);
if (rule.moods?.length) parts.push(`${rule.moods.length} حال`);
if (rule.pipelineIds?.length) parts.push(`${rule.pipelineIds.length} پایپ‌لاین`);
if (rule.stageIds?.length) parts.push(`${rule.stageIds.length} مرحله`);
if (rule.boardIds?.length) parts.push(`${rule.boardIds.length} بورد`);
if (rule.typeIds?.length) parts.push(`${rule.typeIds.length} نوع/دسته`);
return parts.length ? parts.join(' · ') : 'هنوز فیلتری انتخاب نشده';
});
</script>
<template>
<div class="dae" :class="{ compact }">
<div class="dae-mode">
<label>
<input v-model="mode" type="radio" value="all" :disabled="disabled" />
همهٔ {{ sectionLabel }}
</label>
<label>
<input v-model="mode" type="radio" value="rules" :disabled="disabled" />
محدود با فیلتر
</label>
</div>
<template v-if="mode === 'rules'">
<p class="hint">
فقط رکوردهایی دیده می‌شوند که با
<strong>همهٔ فیلترهای پرشده</strong>
جور باشند. در هر فهرست، چند انتخاب یعنی هر کدام کافی است. خالی یعنی بدون محدودیت.
</p>
<p v-if="hadMultipleRules" class="hint warn">
تنظیم قبلی چندتکه بود؛ اینجا در یک فیلتر ادغام شده. با ذخیره به همین شکل ساده ثبت می‌شود.
</p>
<p class="summary">{{ filterSummary }}</p>
<fieldset :disabled="disabled">
<legend>مالک / مسئول</legend>
<p class="muted">خالی = بدون محدودیت مالک</p>
<label class="chip">
<input
type="checkbox"
:checked="filter.owners?.includes('self')"
@change="toggleOwner('self')"
/>
{{ ownerSelfLabel }}
</label>
<label class="chip">
<input
type="checkbox"
:checked="filter.owners?.includes('team')"
@change="toggleOwner('team')"
/>
تیم‌های عضو
</label>
</fieldset>
<label v-for="picker in pickers" :key="picker.legend" class="pick">
<span>{{ picker.legend }}</span>
<p v-if="picker.loading" class="muted">در حال بارگذاری منبع‌ها…</p>
<a-select
v-else
:value="pickerValue(picker)"
:mode="picker.mode"
allow-clear
show-search
option-filter-prop="label"
:options="picker.options"
:disabled="disabled"
:placeholder="picker.placeholder"
:not-found-content="picker.notFound"
style="width: 100%"
@update:value="setList(picker.key, $event)"
/>
<p v-if="picker.hint" class="muted">{{ picker.hint }}</p>
</label>
</template>
<p v-else-if="!hasLimits" class="hint">
بدون محدودیت — همهٔ {{ sectionLabel }} قابل مشاهده‌اند.
</p>
</div>
</template>
<style scoped>
.dae {
display: grid;
gap: 0.75rem;
}
.dae-mode {
display: grid;
gap: 0.35rem;
}
.dae-mode label,
.chip {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-size: 0.88rem;
margin-inline-end: 0.55rem;
margin-bottom: 0.25rem;
}
.hint,
.muted,
.summary {
color: #64748b;
font-size: 0.82rem;
margin: 0;
}
.hint.warn {
color: #b45309;
}
.summary {
font-weight: 600;
color: #334155;
}
fieldset {
border: 1px dashed #e2e8f0;
border-radius: 8px;
padding: 0.5rem 0.65rem;
margin: 0;
}
legend {
padding-inline: 0.25rem;
font-size: 0.8rem;
color: #475569;
font-weight: 600;
}
.pick {
display: grid;
gap: 0.35rem;
}
.pick > span {
font-size: 0.8rem;
font-weight: 600;
color: #475569;
}
.compact fieldset {
padding: 0.45rem 0.55rem;
}
</style>
@@ -0,0 +1,271 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import type {
DataAccessPolicy,
DataAccessSection,
PersonImportSourceStatDto,
RolePermissionKey,
SectionDataAccess,
} from '@mento/shared';
import {
DATA_ACCESS_SECTION_LABELS,
DATA_ACCESS_SECTIONS,
emptySectionDataAccess,
} from '@mento/shared';
import { api } from '@/lib/api';
import { useCustomerGroups } from '@/lib/customer-groups';
import DataAccessEditor, { type IdOption } from '@/components/DataAccessEditor.vue';
const props = defineProps<{
modelValue: DataAccessPolicy;
/** فقط بخش‌هایی که این مجوزها را دارند نشان بده؛ خالی = همه */
enabledPermissions?: RolePermissionKey[];
disabled?: boolean;
compact?: boolean;
}>();
const emit = defineEmits<{
'update:modelValue': [DataAccessPolicy];
}>();
/** بخش‌هایی که به RolePermissionKey وصل‌اند؛ بقیه (روتین/پروژه/تیکت) همیشه دیده می‌شوند */
const SECTION_PERM: Partial<Record<DataAccessSection, RolePermissionKey>> = {
customers: 'customers',
leads: 'leads',
sales: 'sales',
activities: 'activities',
notes: 'notes',
};
const visibleSections = computed(() => {
const perms = props.enabledPermissions;
if (!perms?.length) return DATA_ACCESS_SECTIONS;
return DATA_ACCESS_SECTIONS.filter((s) => {
const key = SECTION_PERM[s];
if (!key) return true;
return perms.includes(key);
});
});
const active = ref<DataAccessSection>('customers');
watch(
visibleSections,
(list) => {
if (!list.includes(active.value) && list[0]) active.value = list[0];
},
{ immediate: true },
);
/** بدون parse سخت‌گیرانه تا فیلتر در حال ویرایش پاک نشود */
function sectionValue(key: DataAccessSection): SectionDataAccess {
const raw = props.modelValue?.[key];
if (raw && typeof raw === 'object') {
return {
mode: raw.mode === 'rules' ? 'rules' : 'all',
rules: Array.isArray(raw.rules) ? raw.rules.map((r) => ({ ...r })) : [],
};
}
return emptySectionDataAccess();
}
function setSection(key: DataAccessSection, next: SectionDataAccess) {
emit('update:modelValue', {
...props.modelValue,
[key]: next,
});
}
const { groups: customerGroups, load: loadCustomerGroups } = useCustomerGroups();
const importSources = ref<Array<{ value: string; label: string }>>([]);
const importSourcesReady = ref(false);
const importSourcesFailed = ref(false);
const leadStages = ref<IdOption[]>([]);
const pipelines = ref<IdOption[]>([]);
const dealStages = ref<IdOption[]>([]);
const activityBoards = ref<IdOption[]>([]);
const activityStages = ref<IdOption[]>([]);
const activityTypes = ref<IdOption[]>([]);
const projectBoards = ref<IdOption[]>([]);
const projectStages = ref<IdOption[]>([]);
const routineCategories = ref<IdOption[]>([]);
async function loadOptions() {
await loadCustomerGroups().catch(() => undefined);
try {
const { data } = await api.get<PersonImportSourceStatDto[]>('/people/source-stats');
importSources.value = data.map((row) => ({ value: row.source, label: row.label }));
importSourcesReady.value = true;
} catch {
importSourcesFailed.value = true;
}
try {
const { data } = await api.get<Array<{ id: string; name: string }>>('/leads/stages');
leadStages.value = data.map((s) => ({ id: s.id, name: s.name }));
} catch {
leadStages.value = [];
}
try {
const { data } = await api.get<
Array<{
id: string;
name: string;
stages?: Array<{ id: string; name: string }>;
}>
>('/pipelines');
pipelines.value = data.map((p) => ({ id: p.id, name: p.name }));
dealStages.value = data.flatMap((p) =>
(p.stages ?? []).map((s) => ({ id: s.id, name: `${p.name} · ${s.name}` })),
);
} catch {
pipelines.value = [];
dealStages.value = [];
}
try {
const { data } = await api.get<Array<{ id: string; name: string }>>('/activities/boards');
activityBoards.value = data.map((b) => ({ id: b.id, name: b.name }));
} catch {
activityBoards.value = [];
}
try {
const stageLists = await Promise.all(
activityBoards.value.map(async (b) => {
const { data } = await api.get<Array<{ id: string; name: string }>>(
'/activities/stages',
{ params: { boardId: b.id } },
);
return data.map((s) => ({
id: s.id,
name: `${b.name} · ${s.name}`,
}));
}),
);
activityStages.value = stageLists.flat();
} catch {
activityStages.value = [];
}
try {
const { data } = await api.get<Array<{ id: string; name: string }>>('/activities/types');
activityTypes.value = data.map((t) => ({ id: t.id, name: t.name }));
} catch {
activityTypes.value = [];
}
try {
const { data } = await api.get<
Array<{
id: string;
name: string;
stages?: Array<{ id: string; name: string }>;
}>
>('/project-boards');
projectBoards.value = data.map((b) => ({ id: b.id, name: b.name }));
projectStages.value = data.flatMap((b) =>
(b.stages ?? []).map((s) => ({ id: s.id, name: `${b.name} · ${s.name}` })),
);
} catch {
projectBoards.value = [];
projectStages.value = [];
}
try {
const { data } = await api.get<Array<{ id: string; name: string }>>('/routines/categories');
routineCategories.value = data.map((c) => ({ id: c.id, name: c.name }));
} catch {
routineCategories.value = [];
}
}
onMounted(() => {
void loadOptions();
});
const stagesForActive = computed(() => {
if (active.value === 'leads') return leadStages.value;
if (active.value === 'sales') return dealStages.value;
if (active.value === 'activities') return activityStages.value;
if (active.value === 'projects') return projectStages.value;
return [];
});
const boardsForActive = computed(() => {
if (active.value === 'activities') return activityBoards.value;
if (active.value === 'projects') return projectBoards.value;
return [];
});
const typesForActive = computed(() => {
if (active.value === 'activities') return activityTypes.value;
if (active.value === 'routines') return routineCategories.value;
return [];
});
</script>
<template>
<div class="dap">
<p v-if="!visibleSections.length" class="muted">
برای تنظیم محدوده، ابتدا مجوز بخش مربوط را روشن کنید.
</p>
<template v-else>
<div class="tabs" role="tablist">
<button
v-for="s in visibleSections"
:key="s"
type="button"
class="tab"
:class="{ on: active === s }"
role="tab"
:aria-selected="active === s"
@click="active = s"
>
{{ DATA_ACCESS_SECTION_LABELS[s] }}
</button>
</div>
<DataAccessEditor
:key="active"
:section="active"
:model-value="sectionValue(active)"
:groups="customerGroups"
:stages="stagesForActive"
:pipelines="pipelines"
:boards="boardsForActive"
:activity-types="typesForActive"
:import-sources="importSources"
:import-sources-ready="importSourcesReady"
:import-sources-failed="importSourcesFailed"
:disabled="disabled"
:compact="compact"
@update:model-value="setSection(active, $event)"
/>
</template>
</div>
</template>
<style scoped>
.dap {
display: grid;
gap: 0.75rem;
}
.tabs {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.tab {
font: inherit;
border: 1px solid #e2e8f0;
background: #fff;
border-radius: 999px;
padding: 0.3rem 0.7rem;
cursor: pointer;
color: #475569;
}
.tab.on {
border-color: #0f766e;
background: #f0fdfa;
color: #0f766e;
font-weight: 600;
}
.muted {
color: #64748b;
font-size: 0.85rem;
}
</style>
+13 -6
View File
@@ -212,9 +212,11 @@ onUnmounted(() => {
.org-btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
align-items: flex-start;
gap: 0.35rem;
width: 100%;
max-width: 100%;
min-width: 0;
border: 0;
background: transparent;
color: #94a3b8;
@@ -223,15 +225,20 @@ onUnmounted(() => {
font-weight: 600;
cursor: pointer;
text-align: right;
padding: 0 0.45rem 0.15rem;
padding: 0 0.15rem;
overflow: hidden;
}
.org-btn :deep(.ico) {
flex-shrink: 0;
margin-top: 0.05rem;
}
.org-btn span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
white-space: normal;
overflow-wrap: anywhere;
line-height: 1.35;
}
.org-btn:hover {
+61 -5
View File
@@ -39,6 +39,8 @@ const busy = ref(false);
const saveOpen = ref(false);
const saveName = ref('');
const saveShared = ref(false);
/** عکس فیلترهای اعمال‌شده در لحظهٔ باز شدن مودال ذخیره */
const saveFilters = ref<Record<string, unknown>>({});
const activeView = computed(
() => views.value.find((v) => v.id === activeId.value) ?? null,
@@ -51,6 +53,41 @@ const selectOptions = computed(() =>
})),
);
const saveFilterCount = computed(() => Object.keys(saveFilters.value).length);
const saveFilterSummary = computed(() => {
const parts: string[] = [];
const f = saveFilters.value;
if (typeof f.q === 'string' && f.q) parts.push(`جستجو: ${f.q}`);
if (typeof f.group === 'string' && f.group) {
parts.push(`گروه (${f.group.split(',').filter(Boolean).length})`);
}
if (typeof f.source === 'string' && f.source) {
parts.push(`منبع (${f.source.split(',').filter(Boolean).length})`);
}
if (typeof f.mood === 'string' && f.mood) {
parts.push(`وضعیت (${f.mood.split(',').filter(Boolean).length})`);
}
if (typeof f.disc === 'string' && f.disc) parts.push(`DISC: ${f.disc}`);
if (typeof f.sort === 'string' && f.sort) parts.push(`مرتب‌سازی: ${f.sort}`);
if (typeof f.viewMode === 'string' && f.viewMode) parts.push(`نمایش: ${f.viewMode}`);
if (typeof f.pipelineId === 'string' && f.pipelineId) parts.push('مسیر فروش');
if (f.amountMin != null && f.amountMin !== '') parts.push(`حداقل مبلغ`);
if (f.amountMax != null && f.amountMax !== '') parts.push(`حداکثر مبلغ`);
return parts.length ? parts.join(' · ') : 'هیچ فیلتری اعمال نشده';
});
/** فقط کلیدهای پر؛ برای JSON و جلوگیری از ذخیرهٔ خالی */
function compactFilters(raw: Record<string, unknown> | null | undefined): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(raw ?? {})) {
if (value == null || value === '') continue;
if (Array.isArray(value) && value.length === 0) continue;
out[key] = value;
}
return out;
}
async function loadViews() {
loading.value = true;
try {
@@ -71,10 +108,19 @@ function onPick(id: unknown) {
activeId.value = next || undefined;
if (!next) return;
const view = views.value.find((v) => v.id === next);
if (view) emit('apply', view.filters ?? {});
if (!view) return;
// کپی ساده تا مصرف‌کننده همان آبجکت ری‌اکتیو را دستکاری نکند
emit('apply', compactFilters(view.filters ?? {}));
}
function openSave() {
saveFilters.value = compactFilters(props.currentFilters);
if (!Object.keys(saveFilters.value).length) {
message.warning(
'ابتدا فیلترها را از دکمهٔ «فیلتر» اعمال کنید (یا جستجو بزنید)، بعد ذخیره کنید.',
);
return;
}
saveName.value = activeView.value?.name ?? '';
saveShared.value = activeView.value?.isShared ?? false;
saveOpen.value = true;
@@ -83,12 +129,17 @@ function openSave() {
async function saveView() {
const name = saveName.value.trim();
if (name.length < 2 || busy.value) return;
const filters = compactFilters(saveFilters.value);
if (!Object.keys(filters).length) {
message.warning('چیزی برای ذخیره نیست؛ اول فیلتر را روی صفحه اعمال کنید.');
return;
}
busy.value = true;
try {
const body = {
name,
scope: props.scope,
filters: props.currentFilters,
filters,
isShared: saveShared.value,
};
if (activeId.value) {
@@ -160,11 +211,11 @@ onMounted(() => {
:disabled="loading"
:loading="loading"
:options="selectOptions"
:placeholder="compact ? 'فیلتر ذخیره‌شده' : '— انتخاب —'"
:placeholder="compact ? 'فیلتر ذخیره‌شده' : 'فیلتر ذخیره‌شده را انتخاب کنید'"
:style="{ flex: 1, minWidth: 0, width: '100%' }"
@update:value="onPick"
/>
<a-button :disabled="loading" title="ذخیره فیلتر فعلی" @click="openSave">
<a-button :disabled="loading" title="ذخیره فیلتر فعلی صفحه" @click="openSave">
<template #icon><FlagOutlined /></template>
ذخیره
</a-button>
@@ -193,9 +244,14 @@ onMounted(() => {
<a-input
v-model:value="saveName"
:maxlength="120"
placeholder="مثلاً سرنخ‌های این هفته"
placeholder="مثلاً بنکداران بازار"
/>
</a-form-item>
<a-form-item :label="`محتوای فیلتر (${saveFilterCount} مورد)`">
<p :style="{ margin: 0, color: 'var(--ant-color-text-secondary, #64748b)' }">
{{ saveFilterSummary }}
</p>
</a-form-item>
<a-form-item :style="{ marginBottom: 0 }">
<a-checkbox v-model:checked="saveShared">اشتراک با سازمان</a-checkbox>
</a-form-item>
+95 -76
View File
@@ -5,21 +5,21 @@ import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import type {
DataAccessPolicy,
OrganizationDto,
OrgUserDto,
TeamDto,
TeamMemberRole,
UpdatePriorArchiveCutoffRequest,
UpdateUserVisibilityRequest,
} from '@mento/shared';
import {
DATA_SCOPE_LABELS,
DATA_SCOPES,
DATA_VISIBILITY_LABELS,
DATA_VISIBILITIES,
type DataVisibility,
DATA_ACCESS_SECTION_LABELS,
DATA_ACCESS_SECTIONS,
emptySectionDataAccess,
sectionHasDataAccessLimits,
} from '@mento/shared';
import { UiButton, UiEmptyState, UiField, UiInput } from '@/components/ui';
import DataAccessPolicyPanel from '@/components/DataAccessPolicyPanel.vue';
import { formatLocalDateInput, parseLocalInput, toFaDigits } from '@/lib/jalali';
const props = defineProps<{
@@ -96,7 +96,6 @@ async function setPriorArchive(userId: string, enabled: boolean) {
function cutoffPayload(value: string): UpdatePriorArchiveCutoffRequest {
const parsed = parseLocalInput(value);
if (!parsed) return { cutoffAt: null };
// پایان همان روز محلی تا ایمپورت همان روز هم قبل از تاریخ قطع شمرده شود
parsed.setHours(23, 59, 59, 999);
return { cutoffAt: parsed.toISOString() };
}
@@ -280,25 +279,75 @@ async function removeTeam(id: string) {
}
}
const expandedVisibility = ref<string | null>(null);
const expandedAccess = ref<string | null>(null);
const draftAccess = ref<DataAccessPolicy>({});
const accessMode = ref<'inherit' | 'custom'>('inherit');
const accessSaving = ref(false);
function scopeOverrides(u: OrgUserDto): number {
return Object.keys(u.dataVisibilityScopes ?? {}).length;
function clonePolicy(policy?: DataAccessPolicy | null): DataAccessPolicy {
const src = policy ?? {};
const out: DataAccessPolicy = {};
for (const [key, section] of Object.entries(src)) {
if (!section) continue;
out[key as keyof DataAccessPolicy] = {
mode: section.mode,
rules: (section.rules ?? []).map((r) => ({ ...r })),
};
}
return out;
}
async function setVisibility(userId: string, payload: UpdateUserVisibilityRequest) {
function accessSummary(u: OrgUserDto): string {
const override = u.dataAccessOverride ?? {};
const hasOverride = DATA_ACCESS_SECTIONS.some((s) => Boolean(override[s]));
const effective = u.effectiveDataAccess ?? {};
const limited = DATA_ACCESS_SECTIONS.filter((s) =>
sectionHasDataAccessLimits(effective[s] ?? emptySectionDataAccess()),
);
if (!hasOverride && !limited.length) return 'مثل نقش · بدون محدودیت';
if (!hasOverride) {
return `مثل نقش · ${toFaDigits(limited.length)} بخش محدود`;
}
const labels = limited.map((s) => DATA_ACCESS_SECTION_LABELS[s]).slice(0, 2);
return `سفارشی · ${labels.join('، ') || 'بدون محدودیت'}${limited.length > 2 ? '…' : ''}`;
}
function openAccessEditor(u: OrgUserDto) {
if (expandedAccess.value === u.id) {
expandedAccess.value = null;
return;
}
const override = u.dataAccessOverride ?? {};
const hasOverride = DATA_ACCESS_SECTIONS.some((s) => Boolean(override[s]));
accessMode.value = hasOverride ? 'custom' : 'inherit';
draftAccess.value = hasOverride
? { ...clonePolicy(u.effectiveDataAccess), ...clonePolicy(override) }
: clonePolicy(u.effectiveDataAccess);
expandedAccess.value = u.id;
}
async function saveUserAccess(userId: string) {
accessSaving.value = true;
error.value = '';
ok.value = '';
try {
await api.patch(`/users/${userId}/visibility`, payload);
ok.value = 'سطح دسترسی به پرونده‌ها به‌روز شد.';
const payload =
accessMode.value === 'inherit'
? { dataAccessOverride: null }
: { dataAccessOverride: draftAccess.value };
await api.patch(`/users/${userId}/data-access`, payload);
ok.value = 'محدوده داده به‌روز شد.';
expandedAccess.value = null;
emit('refreshUsers');
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'تغییر سطح دسترسی به پرونده‌ها ناموفق بود.',
'ذخیره محدوده داده ناموفق بود.',
)
: 'تغییر سطح دسترسی به پرونده‌ها ناموفق بود.';
: 'ذخیره محدوده داده ناموفق بود.';
} finally {
accessSaving.value = false;
}
}
@@ -448,70 +497,45 @@ onMounted(() => {
</section>
<section class="card">
<h3>سطح دسترسی به پرونده‌ها</h3>
<h3>محدوده داده</h3>
<p class="hint">
مالک و مدیر همیشه همه پرونده‌ها را می‌بینند. برای بقیه یک سطح پیش‌فرض (فقط خود، تیم‌های عضو،
یا کل سازمان) تعیین کنید و در صورت نیاز با «تنظیم تفکیکی» برای هر بخش سطح جداگانه بگذارید؛
مثلاً همه مشتریان را ببیند ولی معاملات فقط مال خودش.
مالک و مدیر همیشه همه را می‌بینند. پیش‌فرض از نقش می‌آید؛ برای کاربر خاص می‌توانید فیلتر
جدا بگذارید.
</p>
<UiEmptyState
v-if="!editableUsers.length"
title="کاربر قابل تنظیم نیست"
description="فقط نقش‌های فروش و پشتیبانی سطح دسترسی جدا به پرونده‌ها دارند."
description="فقط نقش‌های فروش و پشتیبانی محدوده داده جدا دارند."
/>
<div v-else class="vis-table">
<div v-for="u in editableUsers" :key="u.id" class="vis-user">
<div class="vis-row">
<span>
{{ u.fullName }}
<small v-if="scopeOverrides(u)" class="vis-badge">
{{ toFaDigits(scopeOverrides(u)) }} بخش تفکیکی
</small>
<small class="vis-badge">{{ accessSummary(u) }}</small>
</span>
<select
:value="u.dataVisibility ?? 'own'"
:disabled="!canEdit"
title="سطح پیش‌فرض"
@change="
setVisibility(u.id, {
dataVisibility: ($event.target as HTMLSelectElement).value as DataVisibility,
})
"
>
<option v-for="v in DATA_VISIBILITIES" :key="v" :value="v">
پیش‌فرض: {{ DATA_VISIBILITY_LABELS[v] }}
</option>
</select>
<UiButton
variant="secondary"
@click="expandedVisibility = expandedVisibility === u.id ? null : u.id"
>
{{ expandedVisibility === u.id ? 'بستن' : 'تنظیم تفکیکی' }}
<UiButton v-if="canEdit" variant="secondary" @click="openAccessEditor(u)">
{{ expandedAccess === u.id ? 'بستن' : 'تنظیم محدوده' }}
</UiButton>
</div>
<div v-if="expandedVisibility === u.id" class="vis-scopes">
<label v-for="s in DATA_SCOPES" :key="s" class="vis-scope">
<span>{{ DATA_SCOPE_LABELS[s] }}</span>
<select
:value="u.dataVisibilityScopes?.[s] ?? ''"
:disabled="!canEdit"
:class="{ custom: Boolean(u.dataVisibilityScopes?.[s]) }"
@change="
setVisibility(u.id, {
scopes: {
[s]: (($event.target as HTMLSelectElement).value || null) as DataVisibility | null,
},
})
"
>
<option value="">
مثل پیش‌فرض ({{ DATA_VISIBILITY_LABELS[u.dataVisibility ?? 'own'] }})
</option>
<option v-for="v in DATA_VISIBILITIES" :key="v" :value="v">
{{ DATA_VISIBILITY_LABELS[v] }}
</option>
</select>
<div v-if="expandedAccess === u.id" class="vis-scopes">
<label class="chip-row">
<input v-model="accessMode" type="radio" value="inherit" />
مثل نقش (بدون override)
</label>
<label class="chip-row">
<input v-model="accessMode" type="radio" value="custom" />
سفارشی برای این کاربر
</label>
<DataAccessPolicyPanel
v-if="accessMode === 'custom'"
v-model="draftAccess"
compact
/>
<div class="actions">
<UiButton :loading="accessSaving" @click="saveUserAccess(u.id)">ذخیره</UiButton>
<UiButton variant="secondary" @click="expandedAccess = null">انصراف</UiButton>
</div>
</div>
</div>
</div>
@@ -642,7 +666,7 @@ onMounted(() => {
}
.vis-row {
display: grid;
grid-template-columns: 1fr 240px auto;
grid-template-columns: 1fr auto;
gap: 0.75rem;
align-items: center;
padding: 0.45rem 0;
@@ -657,21 +681,16 @@ onMounted(() => {
}
.vis-scopes {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 0.5rem 1rem;
gap: 0.55rem;
padding: 0.6rem 0.75rem;
background: #f8fafc;
border-radius: 10px;
}
.vis-scope {
display: grid;
gap: 0.25rem;
font-size: 0.85rem;
color: #334155;
}
select.custom {
border-color: #6366f1;
background: #eef2ff;
.chip-row {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-size: 0.88rem;
}
select {
font: inherit;
+16
View File
@@ -68,6 +68,9 @@ defineProps<{
| 'pulse'
| 'sliders'
| 'camera'
| 'clip'
| 'download'
| 'upload'
| 'arrow-right'
| 'arrow-left'
| 'chevron-right'
@@ -211,6 +214,16 @@ defineProps<{
<path d="M14.5 4.5V9H19" />
<path d="M9 13h6M9 16.5h4" />
</template>
<template v-else-if="name === 'download'">
<path d="M12 4.5v9" />
<path d="M8.5 10.5 12 14l3.5-3.5" />
<path d="M6 17.5h12" />
</template>
<template v-else-if="name === 'upload'">
<path d="M12 14.5v-9" />
<path d="M8.5 8.5 12 5l3.5 3.5" />
<path d="M6 17.5h12" />
</template>
<template v-else-if="name === 'bag'">
<path d="M6.5 8h11l1 12.5H5.5L6.5 8Z" />
<path d="M9 8V6.5A3 3 0 0 1 12 3.5 3 3 0 0 1 15 6.5V8" />
@@ -411,6 +424,9 @@ defineProps<{
<path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3Z" />
<circle cx="12" cy="13" r="3" />
</template>
<template v-else-if="name === 'clip'">
<path d="M21.4 11.6 12.7 20.3a5 5 0 0 1-7.1-7.1l8.5-8.4a3.5 3.5 0 0 1 5 5L10.6 18.2a2 2 0 1 1-2.8-2.8l7.1-7.1" />
</template>
</svg>
</template>
@@ -42,7 +42,7 @@ const emit = defineEmits<{
stagesChanged: [];
add: [stageId: string];
error: [message: string];
menuDeal: [activity: ActivityDto];
menuDeal: [activity: ActivityDto, stageId?: string];
toggleSelect: [activityId: string];
bulkDelete: [];
}>();
@@ -218,7 +218,7 @@ function findActivity(id: string) {
function onMenuActivity(id: string) {
const item = findActivity(id);
if (item) emit('menuDeal', item);
if (item) emit('menuDeal', item, findStageOf(id));
}
function onDragStart(deal: PipelineDeal, event: DragEvent) {
@@ -391,7 +391,26 @@ async function onAddStage(name: string) {
}
function openActivity(id: string) {
void router.push({ name: 'activity-detail', params: { id } });
const query: Record<string, string> = {
from: 'desk',
nav: crypto.randomUUID(),
view: 'board',
};
const source = props.params;
if (source.filter) query.filter = source.filter;
if (source.boardId) query.board = source.boardId;
if (source.desk) query.desk = source.desk;
if (source.q) query.q = source.q;
if (source.typeDefId) query.typeDefId = source.typeDefId;
else if (source.type) query.type = source.type;
if (source.status) query.status = source.status;
if (source.assigneeId) query.assigneeId = source.assigneeId;
if (source.title) query.title = source.title;
if (source.customer) query.customer = source.customer;
if (source.due) query.due = source.due;
const columnId = findStageOf(id);
if (columnId) query.stage = columnId;
void router.push({ name: 'activity-detail', params: { id }, query });
}
</script>
@@ -6,6 +6,8 @@ import {
formatClockFa,
formatJalaliDay,
} from '@/lib/jalali';
import { prepareActivityAttachment } from '@/lib/activity-attachment';
import { startVoiceRecorder, type VoiceRecorder } from '@/lib/voice-note';
import { appendSpokenText } from '@/lib/spoken-text';
import UiIcon from '@/components/UiIcon.vue';
import VoiceToTextButton from '@/components/VoiceToTextButton.vue';
@@ -14,11 +16,11 @@ import type { ActivityDto, ActivityType, OrganizationDto, OrgUserDto } from '@me
const props = defineProps<{
activity: ActivityDto;
saving?: boolean;
save: (payload: { text: string; photoOnly: boolean }) => Promise<void>;
}>();
const emit = defineEmits<{
close: [];
submit: [text: string];
}>();
const typeIcon: Record<ActivityType, 'phone' | 'users' | 'check' | 'chat'> = {
@@ -28,8 +30,26 @@ const typeIcon: Record<ActivityType, 'phone' | 'users' | 'check' | 'chat'> = {
note: 'chat',
};
const PHOTO_LIMIT = 8;
const VOICE_LIMIT = 5;
const FILE_LIMIT = 8;
type PendingPhoto = { localId: string; name: string; dataUrl: string; file: File };
type PendingVoice = { localId: string; name: string; url: string; file: File };
type PendingFile = { localId: string; name: string; file: File };
const comment = ref('');
const textareaRef = ref<HTMLTextAreaElement | null>(null);
const pendingPhotos = ref<PendingPhoto[]>([]);
const pendingVoices = ref<PendingVoice[]>([]);
const pendingFiles = ref<PendingFile[]>([]);
const uploadedCount = ref(0);
const photoBusy = ref(false);
const uploading = ref(false);
const photoError = ref('');
const fileInput = ref<HTMLInputElement | null>(null);
const voiceNoteOn = ref(false);
const voiceNoteSeconds = ref(0);
let voiceNote: VoiceRecorder | null = null;
const orgName = ref('سازمان');
const users = ref<OrgUserDto[]>([]);
const mentionOpen = ref(false);
@@ -61,8 +81,29 @@ const nowLabel = computed(
() => `${formatJalaliDay(now.value)} ساعت ${formatClockFa(now.value)}`,
);
function imageCount(kind: 'image' | 'audio' | 'file') {
return (
props.activity.images?.filter((image) => {
const mime = image.mimeType.toLowerCase();
if (kind === 'audio') return mime.startsWith('audio/');
if (kind === 'image') return mime.startsWith('image/');
return !mime.startsWith('audio/') && !mime.startsWith('image/');
}).length ?? 0
);
}
const canSubmit = computed(
() => comment.value.trim().length > 0 && !props.saving && !voiceBusy.value,
() =>
(comment.value.trim().length > 0 ||
pendingPhotos.value.length > 0 ||
pendingVoices.value.length > 0 ||
pendingFiles.value.length > 0 ||
uploadedCount.value > 0) &&
!props.saving &&
!voiceBusy.value &&
!photoBusy.value &&
!uploading.value &&
!voiceNoteOn.value,
);
function onVoiceTranscript(text: string) {
@@ -77,10 +118,164 @@ function onVoiceBusy(active: boolean) {
}
}
function submit() {
function apiMessage(error: unknown, fallback: string) {
const raw = (error as { response?: { data?: { message?: string | string[] } } }).response?.data
?.message;
if (Array.isArray(raw)) return raw.join('، ');
if (typeof raw === 'string' && raw.trim()) return raw;
return fallback;
}
async function onFilesPicked(event: Event) {
const input = event.target as HTMLInputElement;
const files = Array.from(input.files ?? []);
input.value = '';
if (!files.length) return;
photoError.value = '';
for (const file of files) {
photoBusy.value = true;
try {
const prepared = await prepareActivityAttachment(file);
if (prepared.kind === 'image') {
if (imageCount('image') + pendingPhotos.value.length >= PHOTO_LIMIT) {
photoError.value = `حداکثر ${PHOTO_LIMIT} عکس برای هر فعالیت.`;
continue;
}
pendingPhotos.value = [
...pendingPhotos.value,
{ localId: crypto.randomUUID(), name: prepared.name, dataUrl: prepared.previewUrl, file: prepared.file },
];
} else if (prepared.kind === 'audio') {
if (imageCount('audio') + pendingVoices.value.length >= VOICE_LIMIT) {
URL.revokeObjectURL(prepared.previewUrl);
photoError.value = `حداکثر ${VOICE_LIMIT} صوت برای هر فعالیت.`;
continue;
}
pendingVoices.value = [
...pendingVoices.value,
{ localId: crypto.randomUUID(), name: prepared.name, url: prepared.previewUrl, file: prepared.file },
];
} else if (imageCount('file') + pendingFiles.value.length >= FILE_LIMIT) {
photoError.value = `حداکثر ${FILE_LIMIT} فایل برای هر فعالیت.`;
} else {
pendingFiles.value = [
...pendingFiles.value,
{ localId: crypto.randomUUID(), name: prepared.name, file: prepared.file },
];
}
} catch (error) {
photoError.value = error instanceof Error ? error.message : 'افزودن فایل ناموفق بود.';
} finally {
photoBusy.value = false;
}
}
}
function removePendingPhoto(localId: string) {
pendingPhotos.value = pendingPhotos.value.filter((photo) => photo.localId !== localId);
}
function removePendingVoice(localId: string) {
const voice = pendingVoices.value.find((item) => item.localId === localId);
if (voice) URL.revokeObjectURL(voice.url);
pendingVoices.value = pendingVoices.value.filter((item) => item.localId !== localId);
}
function removePendingFile(localId: string) {
pendingFiles.value = pendingFiles.value.filter((item) => item.localId !== localId);
}
function voiceClock(total: number) {
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
}
function addVoiceNote(file: File) {
if (imageCount('audio') + pendingVoices.value.length >= VOICE_LIMIT) {
photoError.value = `حداکثر ${VOICE_LIMIT} صوت برای هر فعالیت.`;
return;
}
pendingVoices.value = [
...pendingVoices.value,
{ localId: crypto.randomUUID(), name: file.name, url: URL.createObjectURL(file), file },
];
}
async function toggleVoiceNote() {
photoError.value = '';
if (voiceNote) {
const handle = voiceNote;
voiceNote = null;
voiceNoteOn.value = false;
try {
addVoiceNote(await handle.stop());
} catch (error) {
photoError.value = error instanceof Error ? error.message : 'ضبط صوت ناموفق بود.';
}
return;
}
try {
voiceNoteSeconds.value = 0;
voiceNote = await startVoiceRecorder({
onTick: (seconds) => {
voiceNoteSeconds.value = seconds;
},
onAutoStop: (file) => {
voiceNote = null;
voiceNoteOn.value = false;
addVoiceNote(file);
},
});
voiceNoteOn.value = true;
} catch (error) {
photoError.value = error instanceof Error ? error.message : 'ضبط صوت ناموفق بود.';
}
}
async function uploadQueue(items: Array<{ localId: string; name: string; file: File }>, drop: (localId: string) => void) {
for (const item of items) {
const form = new FormData();
form.append('file', item.file, item.name);
await api.post(`/activities/${props.activity.id}/images`, form);
drop(item.localId);
uploadedCount.value += 1;
}
}
async function uploadPendingPhotos() {
await uploadQueue([...pendingPhotos.value], (localId) => {
pendingPhotos.value = pendingPhotos.value.filter((item) => item.localId !== localId);
});
await uploadQueue([...pendingVoices.value], (localId) => {
const voice = pendingVoices.value.find((item) => item.localId === localId);
if (voice) URL.revokeObjectURL(voice.url);
pendingVoices.value = pendingVoices.value.filter((item) => item.localId !== localId);
});
await uploadQueue([...pendingFiles.value], (localId) => {
pendingFiles.value = pendingFiles.value.filter((item) => item.localId !== localId);
});
}
async function submit() {
const text = comment.value.trim();
if (!text || props.saving || voiceBusy.value) return;
emit('submit', text);
if (!canSubmit.value) return;
photoError.value = '';
uploading.value = true;
const hadPhoto =
pendingPhotos.value.length > 0 ||
pendingVoices.value.length > 0 ||
pendingFiles.value.length > 0 ||
uploadedCount.value > 0;
try {
await uploadPendingPhotos();
await props.save({ text, photoOnly: hadPhoto && !text });
} catch (error) {
photoError.value =
pendingPhotos.value.length > 0
? apiMessage(error, 'افزودن فایل ناموفق بود.')
: apiMessage(error, 'ثبت نظر ناموفق بود.');
} finally {
uploading.value = false;
}
}
function close() {
@@ -150,6 +345,8 @@ onMounted(async () => {
});
onBeforeUnmount(() => {
voiceNote?.cancel();
for (const voice of pendingVoices.value) URL.revokeObjectURL(voice.url);
document.body.style.overflow = '';
window.removeEventListener('keydown', onKeydown);
clearInterval(clockTimer);
@@ -215,13 +412,40 @@ onBeforeUnmount(() => {
rows="6"
placeholder="متن خود را بنویسید..."
/>
<p v-if="photoError" class="photo-err">{{ photoError }}</p>
<div v-if="pendingPhotos.length" class="photo-grid">
<figure v-for="photo in pendingPhotos" :key="photo.localId">
<img :src="photo.dataUrl" :alt="photo.name" />
<button type="button" aria-label="حذف عکس" :disabled="uploading" @click="removePendingPhoto(photo.localId)">
×
</button>
</figure>
</div>
<div v-if="pendingVoices.length" class="voice-list">
<div v-for="voice in pendingVoices" :key="voice.localId" class="voice-item">
<audio :src="voice.url" controls preload="metadata" />
<button type="button" aria-label="حذف صوت" :disabled="uploading" @click="removePendingVoice(voice.localId)">
×
</button>
</div>
</div>
<ul v-if="pendingFiles.length" class="file-list">
<li v-for="file in pendingFiles" :key="file.localId">
<UiIcon name="document" :size="15" />
<span>{{ file.name }}</span>
<button type="button" aria-label="حذف فایل" :disabled="uploading" @click="removePendingFile(file.localId)">
×
</button>
</li>
</ul>
<div class="tools">
<div class="tool-cluster">
<div class="tool-wrap">
<button
class="tool"
type="button"
aria-label="منشن"
:disabled="recording"
:disabled="recording || voiceNoteOn"
@click="mentionOpen = !mentionOpen"
>
@
@@ -235,12 +459,36 @@ onBeforeUnmount(() => {
</li>
</ul>
</div>
<button
class="tool"
type="button"
aria-label="پیوست"
title="پیوست"
:disabled="photoBusy || uploading || recording || voiceNoteOn"
@click="fileInput?.click()"
>
<UiIcon name="clip" :size="16" />
</button>
<input ref="fileInput" class="photo-file" type="file" multiple @change="onFilesPicked" />
<button
class="tool"
type="button"
:class="{ 'voice-on': voiceNoteOn }"
:aria-label="voiceNoteOn ? 'توقف ضبط پیام صوتی' : 'ضبط پیام صوتی'"
:title="voiceNoteOn ? 'توقف ضبط پیام صوتی' : 'ضبط پیام صوتی'"
:disabled="photoBusy || uploading || recording"
@click="toggleVoiceNote"
>
<UiIcon name="mic" :size="16" />
</button>
<span v-if="voiceNoteOn" class="rec-time">{{ voiceClock(voiceNoteSeconds) }}</span>
</div>
<div class="tool-wrap">
<p v-if="voiceTip && !recording" class="tip">تایپ صوتی را امتحان کنید! 🎙️✨</p>
<VoiceToTextButton
variant="toolbar"
hide-error
:disabled="saving"
:disabled="saving || voiceNoteOn"
@transcript="onVoiceTranscript"
@recording="recording = $event"
@busy="onVoiceBusy"
@@ -259,9 +507,9 @@ onBeforeUnmount(() => {
<div class="actions">
<button class="act primary" type="button" :disabled="!canSubmit" @click="submit">
{{ recording ? 'در حال ضبط…' : 'ثبت نظر' }}
{{ recording ? 'در حال ضبط…' : uploading || saving ? 'در حال ثبت…' : 'ثبت نظر' }}
</button>
<button class="act ghost" type="button" :disabled="saving || voiceBusy" @click="close">انصراف</button>
<button class="act ghost" type="button" :disabled="saving || voiceBusy || uploading" @click="close">انصراف</button>
</div>
</div>
</section>
@@ -457,6 +705,85 @@ onBeforeUnmount(() => {
color: #94a3b8;
}
.photo-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem;
padding: 0 0.7rem;
}
.photo-row small {
color: #64748b;
font-size: 0.75rem;
}
.photo-add {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border: 1px dashed #99f6e4;
background: #f0fdfa;
color: #0f766e;
border-radius: var(--radius);
padding: 0.35rem 0.7rem;
font: inherit;
font-weight: 700;
cursor: pointer;
}
.photo-add:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.photo-file {
display: none;
}
.photo-err {
margin: 0;
padding: 0 0.7rem;
color: #b91c1c;
font-size: 0.8rem;
}
.photo-grid {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
padding: 0 0.7rem;
}
.photo-grid figure {
position: relative;
margin: 0;
width: 4.5rem;
height: 4.5rem;
}
.photo-grid img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 0.6rem;
border: 1px solid #e2e8f0;
}
.photo-grid figure button {
position: absolute;
top: 0.15rem;
inset-inline-end: 0.15rem;
width: 1.2rem;
height: 1.2rem;
border: 0;
border-radius: 999px;
background: rgba(15, 23, 42, 0.72);
color: #fff;
cursor: pointer;
line-height: 1;
}
.tools {
display: flex;
justify-content: space-between;
@@ -464,6 +791,73 @@ onBeforeUnmount(() => {
padding: 0.35rem 0.5rem 0.5rem;
}
.tool-cluster {
display: flex;
align-items: center;
gap: 0.35rem;
}
.tool.voice-on {
border-color: #fecaca;
background: #fef2f2;
color: #b91c1c;
}
.rec-time {
color: #b91c1c;
font-size: 0.78rem;
font-weight: 700;
}
.voice-list {
display: grid;
gap: 0.35rem;
padding: 0 0.5rem;
}
.voice-item {
display: flex;
align-items: center;
gap: 0.35rem;
}
.voice-item audio {
flex: 1;
min-width: 0;
height: 2.1rem;
}
.voice-item button,
.file-list button {
width: 1.4rem;
height: 1.4rem;
border: 0;
border-radius: 999px;
background: #e2e8f0;
cursor: pointer;
}
.file-list {
list-style: none;
margin: 0;
padding: 0 0.5rem;
display: grid;
gap: 0.3rem;
}
.file-list li {
display: flex;
align-items: center;
gap: 0.35rem;
min-width: 0;
}
.file-list span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tool-wrap {
position: relative;
}
@@ -0,0 +1,492 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
export type DeskFilterField = 'title' | 'who' | 'customer' | 'type' | 'when' | 'status';
const props = defineProps<{
/** یک ستون، یا پنل کامل بالای صفحه */
field: DeskFilterField | 'all';
title: string;
customer: string;
due: '' | 'set' | 'unset';
typeKey: string;
statusKey: string;
assigneeId: string;
showAssignee: boolean;
users: Array<{ id: string; fullName: string }>;
types: Array<{ key: string; label: string }>;
statuses: Array<{ key: string; label: string }>;
}>();
const emit = defineEmits<{
title: [value: string];
customer: [value: string];
due: [value: '' | 'set' | 'unset'];
type: [value: string];
status: [value: string];
assignee: [value: string];
clear: [];
done: [];
}>();
const LIST_CAP = 40;
const titleDraft = ref(props.title);
const customerDraft = ref(props.customer);
const whoQuery = ref('');
const typeQuery = ref('');
const openSection = ref<DeskFilterField | null>(null);
watch(
() => props.title,
(value) => {
titleDraft.value = value;
},
);
watch(
() => props.customer,
(value) => {
customerDraft.value = value;
},
);
function norm(value: string) {
return value.trim().replace(/ي/g, 'ی').replace(/ك/g, 'ک').toLowerCase();
}
const filteredUsers = computed(() => {
const q = norm(whoQuery.value);
const matches = props.users.filter((user) => !q || norm(user.fullName).includes(q));
const selected = props.assigneeId
? props.users.find((user) => user.id === props.assigneeId)
: undefined;
const head = selected && !matches.slice(0, LIST_CAP).some((user) => user.id === selected.id)
? [selected]
: [];
return [...head, ...matches.filter((user) => user.id !== selected?.id)].slice(0, LIST_CAP);
});
const hiddenUsers = computed(() => {
const q = norm(whoQuery.value);
const count = props.users.filter((user) => !q || norm(user.fullName).includes(q)).length;
return Math.max(0, count - filteredUsers.value.length);
});
const showTypeSearch = computed(() => props.types.length > 8);
const visibleTypes = computed(() => {
const q = norm(typeQuery.value);
const all = props.types.filter((item) => item.key === 'all');
const rest = props.types.filter(
(item) => item.key !== 'all' && (!q || norm(item.label).includes(q)),
);
return [...all, ...rest];
});
const hasAny = computed(
() =>
Boolean(props.title.trim() || props.customer.trim() || props.due || props.assigneeId) ||
props.typeKey !== 'all' ||
props.statusKey !== 'all',
);
const dueOptions: Array<{ key: '' | 'set' | 'unset'; label: string }> = [
{ key: '', label: 'همه' },
{ key: 'set', label: 'دارد' },
{ key: 'unset', label: 'ندارد' },
];
const whoLabel = computed(
() => props.users.find((user) => user.id === props.assigneeId)?.fullName || 'همه',
);
const typeLabel = computed(
() => props.types.find((item) => item.key === props.typeKey)?.label || 'همه',
);
const statusLabel = computed(
() => props.statuses.find((item) => item.key === props.statusKey)?.label || 'همه',
);
const dueLabel = computed(() => dueOptions.find((item) => item.key === props.due)?.label ?? 'همه');
function opened(name: DeskFilterField) {
return props.field !== 'all' || openSection.value === name;
}
function toggleSection(name: DeskFilterField) {
openSection.value = openSection.value === name ? null : name;
}
function finish() {
if (props.field === 'all') openSection.value = null;
else emit('done');
}
function shows(name: DeskFilterField) {
if (name === 'who' && !props.showAssignee) return false;
return props.field === 'all' || props.field === name;
}
function applyTitle() {
emit('title', titleDraft.value.trim());
finish();
}
function applyCustomer() {
emit('customer', customerDraft.value.trim());
finish();
}
function pickDue(next: '' | 'set' | 'unset') {
emit('due', props.due === next ? '' : next);
finish();
}
function pickType(next: string) {
emit('type', props.typeKey === next && next !== 'all' ? 'all' : next);
finish();
}
function pickStatus(next: string) {
emit('status', props.statusKey === next && next !== 'all' ? 'all' : next);
finish();
}
function pickAssignee(next: string) {
emit('assignee', props.assigneeId === next ? '' : next);
finish();
}
</script>
<template>
<div class="filters" @click.stop>
<section v-if="shows('title')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: Boolean(title.trim()) }"
@click="toggleSection('title')"
>
<span>عنوان فعالیت</span>
<em>{{ title.trim() || 'همه' }}</em>
</button>
<form v-if="opened('title')" class="draft" @submit.prevent="applyTitle">
<input
v-model="titleDraft"
type="search"
placeholder="بخشی از عنوان"
autocomplete="off"
/>
<button type="submit">اعمال</button>
<button v-if="title" type="button" class="quiet" @click="titleDraft = ''; applyTitle()">
پاک
</button>
</form>
</section>
<section v-if="shows('who')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: Boolean(assigneeId) }"
@click="toggleSection('who')"
>
<span>کارشناس</span>
<em>{{ whoLabel }}</em>
</button>
<input
v-if="opened('who')"
v-model="whoQuery"
class="find"
type="search"
placeholder="جستجوی نام کارشناس"
autocomplete="off"
/>
<div v-if="opened('who')" class="pick" role="listbox" aria-label="کارشناس">
<button type="button" :class="{ on: !assigneeId }" @click="pickAssignee('')">
همه کارشناسان
</button>
<button
v-for="user in filteredUsers"
:key="user.id"
type="button"
:class="{ on: assigneeId === user.id }"
@click="pickAssignee(user.id)"
>
{{ user.fullName }}
</button>
<p v-if="whoQuery.trim() && !filteredUsers.length" class="empty">کارشناسی با این نام نیست</p>
</div>
<p v-if="opened('who') && hiddenUsers" class="hint">برای دیدن بقیه، نام را دقیق‌تر بنویسید</p>
</section>
<section v-if="shows('customer')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: Boolean(customer.trim()) }"
@click="toggleSection('customer')"
>
<span>مشتری</span>
<em>{{ customer.trim() || 'همه' }}</em>
</button>
<form v-if="opened('customer')" class="draft" @submit.prevent="applyCustomer">
<input
v-model="customerDraft"
type="search"
placeholder="نام شخص یا شرکت"
autocomplete="off"
/>
<button type="submit">اعمال</button>
<button
v-if="customer"
type="button"
class="quiet"
@click="customerDraft = ''; applyCustomer()"
>
پاک
</button>
</form>
</section>
<section v-if="shows('type')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: typeKey !== 'all' }"
@click="toggleSection('type')"
>
<span>نوع فعالیت</span>
<em>{{ typeLabel }}</em>
</button>
<input
v-if="opened('type') && showTypeSearch"
v-model="typeQuery"
class="find"
type="search"
placeholder="جستجوی نوع"
autocomplete="off"
/>
<div v-if="opened('type')" class="pick" role="listbox" aria-label="نوع فعالیت">
<button
v-for="opt in visibleTypes"
:key="opt.key"
type="button"
:class="{ on: typeKey === opt.key }"
@click="pickType(opt.key)"
>
{{ opt.label }}
</button>
<p v-if="visibleTypes.length <= 1 && typeQuery.trim()" class="empty">این نوع پیدا نشد</p>
</div>
</section>
<section v-if="shows('when')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: Boolean(due) }"
@click="toggleSection('when')"
>
<span>زمان شروع</span>
<em>{{ dueLabel }}</em>
</button>
<p v-else class="hint tight">فقط بودن یا نبودن زمان شروع</p>
<div v-if="opened('when')" class="seg" role="radiogroup" aria-label="زمان شروع">
<button
v-for="opt in dueOptions"
:key="opt.key || 'any'"
type="button"
role="radio"
:aria-checked="due === opt.key"
:class="{ on: due === opt.key }"
@click="pickDue(opt.key)"
>
{{ opt.label }}
</button>
</div>
</section>
<section v-if="shows('status')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: statusKey !== 'all' }"
@click="toggleSection('status')"
>
<span>وضعیت</span>
<em>{{ statusLabel }}</em>
</button>
<div v-if="opened('status')" class="pick" role="listbox" aria-label="وضعیت">
<button
v-for="opt in statuses"
:key="opt.key"
type="button"
:class="{ on: statusKey === opt.key }"
@click="pickStatus(opt.key)"
>
{{ opt.label }}
</button>
</div>
</section>
<button
v-if="field === 'all' && hasAny"
type="button"
class="clear"
@click="openSection = null; emit('clear')"
>
پاک کردن فیلترها
</button>
</div>
</template>
<style scoped>
.filters {
display: grid;
gap: 0.65rem;
}
.acc {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
width: 100%;
margin: 0;
padding: 0.28rem 0.15rem;
border: 0;
background: transparent;
font: inherit;
text-align: start;
cursor: pointer;
color: #0f172a;
}
.acc em {
font-style: normal;
color: #94a3b8;
font-size: 0.78rem;
max-width: 9.5rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.acc.on em {
color: #0f766e;
font-weight: 700;
}
.draft {
display: flex;
gap: 0.3rem;
}
.draft input,
.find {
width: 100%;
min-width: 0;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #fff;
padding: 0.4rem 0.55rem;
font: inherit;
color: #0f172a;
}
.draft input {
flex: 1;
}
.draft button,
.pick button,
.seg button,
.clear {
border: 0;
background: transparent;
font: inherit;
cursor: pointer;
}
.draft button {
flex: none;
border-radius: 8px;
background: #0f766e;
color: #fff;
padding: 0.4rem 0.65rem;
}
.draft button.quiet {
background: #f1f5f9;
color: #475569;
}
.pick {
max-height: 11.5rem;
overflow: auto;
display: grid;
align-content: start;
margin-top: 0.35rem;
}
.pick button {
text-align: start;
border-radius: 8px;
padding: 0.42rem 0.5rem;
color: #0f172a;
}
.pick button:hover,
.pick button.on {
background: #f0fdfa;
color: #0f766e;
}
.pick button.on {
font-weight: 700;
}
.seg {
display: flex;
gap: 0.25rem;
padding: 0.2rem;
border-radius: 10px;
background: #f8fafc;
}
.seg button {
flex: 1;
border-radius: 8px;
padding: 0.4rem 0.2rem;
color: #475569;
}
.seg button.on {
background: #fff;
color: #0f766e;
font-weight: 700;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06);
}
.empty,
.hint {
margin: 0.25rem 0.2rem 0;
color: #94a3b8;
font-size: 0.75rem;
}
.hint.tight {
margin: 0 0 0.35rem;
}
.clear {
border-top: 1px solid #e2e8f0;
padding: 0.55rem 0.2rem 0.15rem;
text-align: start;
color: #b91c1c;
}
</style>
@@ -8,7 +8,7 @@ import {
import UiIcon from '@/components/UiIcon.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
type PostponeKey = 'm15' | 'm30' | 'h1' | 'tomorrow-am' | 'tomorrow-pm' | 'custom';
type PostponeKey = 'h1' | 'tomorrow-am' | 'next-saturday' | 'next-week' | 'custom';
const props = defineProps<{
dueAt?: string | null;
@@ -21,7 +21,7 @@ const emit = defineEmits<{
}>();
const nowTick = ref(Date.now());
const selected = ref<PostponeKey | null>(null);
const customOpen = ref(false);
const customLocal = ref('');
let tickTimer: number | null = null;
@@ -43,47 +43,50 @@ function tomorrowAt(hour: number, minute = 0) {
return d;
}
/** شنبهٔ بعد، ساعت ۱۰. اگر امروز شنبه باشد، شنبهٔ هفتهٔ بعد. */
function nextSaturdayMorning() {
const d = startOfLocalDay(new Date(nowTick.value));
const untilSaturday = (6 - d.getDay() + 7) % 7;
d.setDate(d.getDate() + (untilSaturday === 0 ? 7 : untilSaturday));
d.setHours(10, 0, 0, 0);
return d;
}
function nextWeekSameTime() {
const d = new Date(base.value.getTime());
d.setDate(d.getDate() + 7);
return d;
}
const options = computed(() => {
const m15 = addMinutes(15);
const m30 = addMinutes(30);
const h1 = addMinutes(60);
const am = tomorrowAt(10);
const pm = tomorrowAt(13);
const saturday = nextSaturdayMorning();
const week = nextWeekSameTime();
return [
{
key: 'm15' as const,
icon: 'refresh' as const,
label: 'یک ربع دیرتر',
time: formatClockFa(m15),
at: m15,
},
{
key: 'm30' as const,
icon: 'refresh' as const,
label: 'نیم ساعت دیرتر',
time: formatClockFa(m30),
at: m30,
},
{
key: 'h1' as const,
icon: 'refresh' as const,
label: 'یک ساعت دیرتر',
time: formatClockFa(h1),
at: h1,
},
{
key: 'tomorrow-am' as const,
icon: 'calendar-sun' as const,
label: 'فردا صبح',
time: `فردا ${formatClockFa(am)}`,
time: formatClockFa(am),
at: am,
},
{
key: 'tomorrow-pm' as const,
icon: 'calendar-sun' as const,
label: 'فردا بعد از ظهر',
time: `فردا ${formatClockFa(pm)}`,
at: pm,
key: 'next-saturday' as const,
label: 'شنبه آینده',
time: formatJalaliDayClock(saturday),
at: saturday,
},
{
key: 'next-week' as const,
label: 'هفته آینده',
time: formatJalaliDayClock(week),
at: week,
},
];
});
@@ -100,31 +103,27 @@ const customDate = computed(() => {
});
const customPreview = computed(() =>
customDate.value ? formatJalaliDayClock(customDate.value) : 'تاریخ و ساعت را انتخاب کنید',
customDate.value ? formatJalaliDayClock(customDate.value) : '',
);
const canSubmit = computed(() => {
if (props.saving || !selected.value) return false;
if (selected.value === 'custom') return Boolean(customDate.value);
return true;
});
function chosenDate(): Date | null {
if (selected.value === 'custom') return customDate.value;
return options.value.find((item) => item.key === selected.value)?.at ?? null;
function apply(at: Date) {
if (props.saving) return;
emit('submit', at.toISOString());
}
function pick(key: PostponeKey) {
selected.value = key;
if (key === 'custom' && !customLocal.value) {
customLocal.value = toLocalInput(addMinutes(60));
if (key === 'custom') {
customOpen.value = true;
if (!customLocal.value) customLocal.value = toLocalInput(addMinutes(60));
return;
}
const at = options.value.find((item) => item.key === key)?.at;
if (at) apply(at);
}
function submit() {
const at = chosenDate();
if (!at || props.saving) return;
emit('submit', at.toISOString());
function submitCustom() {
if (!customDate.value || props.saving) return;
apply(customDate.value);
}
function close() {
@@ -156,73 +155,57 @@ onBeforeUnmount(() => {
<template>
<Teleport to="body">
<div class="layer" role="presentation">
<div class="backdrop" aria-hidden="true" />
<button class="backdrop" type="button" aria-label="بستن" @click="close" />
<section class="sheet" role="dialog" aria-modal="true" aria-labelledby="postpone-title">
<div class="handle" aria-hidden="true" />
<header class="head">
<button class="icon" type="button" aria-label="تأیید تعویق" :disabled="!canSubmit" @click="submit">
<UiIcon name="check-plain" :size="22" />
</button>
<div class="titles">
<h2 id="postpone-title">به تعویق انداختن فعالیت</h2>
</div>
<h2 id="postpone-title">به تعویق انداختن</h2>
<button class="icon" type="button" aria-label="بستن" @click="close">
<UiIcon name="x" :size="20" />
</button>
</header>
<p class="lead">زمان جدید برای این فعالیت را انتخاب کنید.</p>
<div class="body">
<button
v-for="item in options"
:key="item.key"
class="card"
type="button"
:class="{ on: selected === item.key }"
:disabled="saving"
@click="pick(item.key)"
>
<span class="label">{{ item.label }}</span>
<span class="aside">
<span class="ico-box">
<UiIcon :name="item.icon" :size="20" />
</span>
<div class="presets">
<button
v-for="item in options"
:key="item.key"
class="card"
type="button"
:disabled="saving"
@click="pick(item.key)"
>
<span class="label">{{ item.label }}</span>
<span class="when">{{ item.time }}</span>
</span>
</button>
</button>
</div>
<button
class="card custom"
type="button"
:class="{ on: selected === 'custom' }"
:class="{ on: customOpen }"
:disabled="saving"
@click="pick('custom')"
>
<span class="copy">
<strong>تنظیم زمان دلخواه</strong>
<small>انتخاب تاریخ و ساعت</small>
</span>
<span class="aside">
<span class="ico-box">
<UiIcon name="calendar-edit" :size="20" />
</span>
</span>
<span class="label">زمان دلخواه</span>
<span class="when">{{ customOpen && customPreview ? customPreview : 'تاریخ و ساعت' }}</span>
</button>
<div v-if="selected === 'custom'" class="custom-box">
<div v-if="customOpen" class="custom-box">
<label class="picker">
<span>تاریخ و ساعت جدید</span>
<JalaliDateInput v-model="customLocal" mode="datetime" />
</label>
<p class="preview">{{ customPreview }}</p>
<button
class="confirm"
type="button"
:disabled="saving || !customDate"
@click="submitCustom"
>
{{ saving ? 'در حال ثبت…' : 'ثبت تعویق' }}
</button>
</div>
<p class="notice">
<UiIcon name="lightbulb" :size="18" />
با تعویق انداختن، این فعالیت در زمان جدید به لیست فعالیت‌های شما منتقل می‌شود.
</p>
</div>
</section>
</div>
@@ -236,20 +219,27 @@ onBeforeUnmount(() => {
z-index: 90;
display: flex;
justify-content: center;
align-items: stretch;
align-items: flex-end;
}
.backdrop {
display: none;
position: absolute;
inset: 0;
border: 0;
background: rgba(15, 23, 42, 0.28);
cursor: pointer;
}
.sheet {
position: relative;
width: 100%;
height: 100dvh;
max-height: 92dvh;
background: #fff;
display: flex;
flex-direction: column;
font-family: IRANSans, Tahoma, sans-serif;
border-radius: 16px 16px 0 0;
box-shadow: 0 -12px 40px rgba(15, 23, 42, 0.12);
}
.handle {
@@ -261,75 +251,65 @@ onBeforeUnmount(() => {
}
.head {
display: grid;
grid-template-columns: 40px 1fr 40px;
display: flex;
align-items: center;
padding: 0.1rem 0.7rem 0.15rem;
justify-content: space-between;
gap: 0.5rem;
padding: 0.15rem 0.85rem 0.35rem;
}
.titles h2,
.lead {
.head h2 {
margin: 0;
text-align: center;
}
.titles h2 {
font-size: 16px;
font-weight: 500;
font-weight: 600;
color: #0f172a;
}
.lead {
color: #94a3b8;
font-size: 0.82rem;
padding: 0 1.2rem 0.55rem;
}
.icon {
width: 40px;
height: 40px;
width: 36px;
height: 36px;
border: 0;
background: none;
color: #0f766e;
color: #64748b;
display: grid;
place-items: center;
cursor: pointer;
}
.icon:disabled {
opacity: 0.35;
cursor: not-allowed;
.body {
overflow: auto;
padding: 0.35rem 1rem calc(1rem + env(safe-area-inset-bottom));
display: grid;
gap: 0.55rem;
}
.body {
flex: 1;
overflow: auto;
padding: 0.15rem 1rem calc(1rem + env(safe-area-inset-bottom));
.presets {
display: grid;
align-content: start;
grid-template-columns: 1fr 1fr;
gap: 0.55rem;
}
.card {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.8rem;
min-height: 72px;
padding: 0.7rem 0.9rem;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 0.2rem;
min-height: 64px;
padding: 0.7rem 0.85rem;
border: 1px solid #e8eef3;
border-radius: var(--radius);
border-radius: var(--radius, 10px);
background: #fff;
font: inherit;
text-align: start;
cursor: pointer;
}
.card.on {
.card.on,
.card:hover:not(:disabled) {
border-color: #99f6e4;
background: #f0fdfa;
box-shadow: 0 0 0 1px #99f6e4;
}
.card:disabled {
@@ -337,54 +317,27 @@ onBeforeUnmount(() => {
cursor: not-allowed;
}
.label,
.copy strong {
font-size: 0.95rem;
font-weight: 600;
.label {
font-size: 0.92rem;
font-weight: 700;
color: #0f172a;
}
.copy {
display: grid;
gap: 0.15rem;
}
.copy small {
color: #94a3b8;
font-size: 0.78rem;
}
.aside {
display: grid;
justify-items: center;
gap: 0.28rem;
min-width: 3.6rem;
flex-shrink: 0;
}
.ico-box {
width: 40px;
height: 40px;
border-radius: var(--radius);
background: #e6f7f4;
color: #0d9488;
display: grid;
place-items: center;
}
.when {
color: #0d9488;
font-size: 0.74rem;
color: #0f766e;
font-size: 0.84rem;
font-weight: 600;
white-space: nowrap;
}
.custom {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.custom-box {
border: 1px solid #e8eef3;
border-radius: var(--radius);
padding: 0.85rem 0.9rem;
display: grid;
gap: 0.55rem;
gap: 0.65rem;
}
.picker {
@@ -394,65 +347,31 @@ onBeforeUnmount(() => {
font-size: 0.8rem;
}
.picker input {
width: 100%;
min-height: var(--control-h);
height: var(--control-h);
border: 1px solid #e2e8f0;
border-radius: var(--radius);
padding: 0.45rem 0.7rem;
.confirm {
border: 0;
background: #0f766e;
color: #fff;
border-radius: var(--radius, 10px);
min-height: 42px;
font: inherit;
color: #0f172a;
background: #fff;
}
.preview {
margin: 0;
color: #0f766e;
font-size: 0.82rem;
font-weight: 700;
cursor: pointer;
}
.notice {
margin: 0.35rem 0 0;
display: flex;
align-items: flex-start;
gap: 0.55rem;
padding: 0.85rem 0.9rem;
border-radius: var(--radius);
background: #f8fafc;
color: #475569;
font-size: 0.8rem;
line-height: 1.75;
}
.notice :deep(.ico) {
margin-top: 0.15rem;
color: #0d9488;
flex-shrink: 0;
.confirm:disabled {
opacity: 0.55;
cursor: not-allowed;
}
@media (min-width: 900px) {
.layer {
background: rgba(15, 23, 42, 0.28);
align-items: center;
padding: 1.2rem;
}
.backdrop {
display: block;
position: absolute;
inset: 0;
border: 0;
background: transparent;
cursor: pointer;
}
.sheet {
position: relative;
max-width: 480px;
height: min(92dvh, 860px);
border-radius: var(--radius, 10px);
max-width: 420px;
border-radius: 16px;
box-shadow: 0 28px 70px rgba(15, 23, 42, 0.22);
}
}
@@ -20,7 +20,7 @@ withDefaults(
<div v-if="showBubble" class="popup">
<span>من دستیار هوشمند</span>
<span>سیستم هستم 👋</span>
<svg class="tail" viewBox="0 0 10 14" aria-hidden="true">
<svg class="tail" viewBox="0 0 10 14" width="10" height="14" aria-hidden="true">
<path d="M10 0 L0 7 L10 14 Z" fill="#fff" />
</svg>
</div>
@@ -0,0 +1,204 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import UiIcon from '@/components/UiIcon.vue';
import type { NoteCategoryDto, NoteCategoryTone } from '@mento/shared';
const emit = defineEmits<{
close: [];
saved: [];
}>();
const tones: Array<{ value: NoteCategoryTone; label: string }> = [
{ value: 'general', label: 'معمولی' },
{ value: 'follow_up', label: 'پیگیری' },
{ value: 'idea', label: 'ایده' },
{ value: 'suggestion', label: 'پیشنهاد' },
{ value: 'meeting', label: 'جلسه' },
{ value: 'personal', label: 'شخصی' },
];
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const items = ref<NoteCategoryDto[]>([]);
const label = ref('');
async function load() {
loading.value = true;
error.value = '';
try {
items.value = (await api.get<NoteCategoryDto[]>('/notes/categories')).data;
} catch {
error.value = 'بارگذاری دسته‌ها ناموفق بود.';
} finally {
loading.value = false;
}
}
async function createCategory() {
if (!label.value.trim()) {
error.value = 'عنوان دسته را وارد کنید.';
return;
}
saving.value = true;
error.value = '';
try {
await api.post('/notes/categories', { label: label.value.trim(), showInBar: true });
label.value = '';
await load();
emit('saved');
} catch (e) {
error.value = axios.isAxiosError(e)
? 'ثبت دسته ناموفق بود.'
: 'ثبت دسته ناموفق بود.';
} finally {
saving.value = false;
}
}
async function patch(item: NoteCategoryDto, data: Partial<NoteCategoryDto>) {
error.value = '';
try {
await api.patch(`/notes/categories/${item.id}`, data);
await load();
emit('saved');
} catch {
error.value = 'ذخیره دسته ناموفق بود.';
}
}
async function move(index: number, dir: -1 | 1) {
const next = index + dir;
if (next < 0 || next >= items.value.length) return;
const ids = items.value.map((item) => item.id);
const [picked] = ids.splice(index, 1);
if (!picked) return;
ids.splice(next, 0, picked);
try {
items.value = (await api.patch<NoteCategoryDto[]>('/notes/categories/reorder', { ids })).data;
emit('saved');
} catch {
error.value = 'جابه‌جایی ناموفق بود.';
}
}
async function remove(item: NoteCategoryDto) {
if (!confirm(`دسته «${item.label}» حذف شود؟`)) return;
try {
await api.delete(`/notes/categories/${item.id}`);
await load();
emit('saved');
} catch {
error.value = 'این دستهٔ پیش‌فرض حذف نمی‌شود. از نوار پنهانش کنید.';
}
}
onMounted(load);
</script>
<template>
<div class="cat-root">
<div class="cat-backdrop" @click="emit('close')" />
<aside class="cat-panel" role="dialog" aria-label="دسته‌های یادداشت">
<header class="cat-head">
<h2>دسته‌های نوار یادداشت</h2>
<button type="button" class="icon-btn" @click="emit('close')">
<UiIcon name="x" :size="20" />
</button>
</header>
<div class="cat-scroll">
<p class="hint">همین عنوان‌ها در نوار بالای یادداشت‌ها دیده می‌شوند. «همه»، «تیمی» و «فقط من» ثابت‌اند.</p>
<p v-if="error" class="banner-error">{{ error }}</p>
<form class="create-form" @submit.prevent="createCategory">
<input v-model="label" type="text" placeholder="دسته جدید، مثلاً قرارداد" />
<button type="submit" class="btn-primary" :disabled="saving">افزودن</button>
</form>
<p v-if="loading" class="hint">در حال بارگذاری…</p>
<ul v-else class="cat-list">
<li v-for="(item, index) in items" :key="item.id">
<input
:value="item.label"
type="text"
@change="patch(item, { label: ($event.target as HTMLInputElement).value })"
/>
<select
:value="item.tone"
@change="patch(item, { tone: ($event.target as HTMLSelectElement).value })"
>
<option v-for="tone in tones" :key="tone.value" :value="tone.value">
{{ tone.label }}
</option>
</select>
<label class="check-line">
<input
type="checkbox"
:checked="item.showInBar && item.isActive"
@change="patch(item, { showInBar: ($event.target as HTMLInputElement).checked, isActive: true })"
/>
<span>در نوار</span>
</label>
<div class="row-actions">
<button type="button" :disabled="index === 0" @click="move(index, -1)">بالا</button>
<button type="button" :disabled="index === items.length - 1" @click="move(index, 1)">پایین</button>
<button v-if="!item.isSystem" type="button" class="danger" @click="remove(item)">حذف</button>
</div>
</li>
</ul>
</div>
</aside>
</div>
</template>
<style scoped>
.cat-root { position: fixed; inset: 0; z-index: 140; }
.cat-backdrop { position: absolute; inset: 0; background: rgba(15, 23, 42, 0.35); }
.cat-panel {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: min(460px, 100%);
background: #fff;
display: flex;
flex-direction: column;
box-shadow: 0 12px 40px rgba(15, 23, 42, 0.18);
}
.cat-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.9rem 1rem;
border-bottom: 1px solid #e2e8f0;
}
.cat-head h2 { margin: 0; font-size: 1.05rem; }
.cat-scroll { overflow: auto; padding: 1rem; display: flex; flex-direction: column; gap: 0.75rem; }
.hint { margin: 0; color: #64748b; font-size: 0.88rem; }
.banner-error { margin: 0; padding: 0.55rem 0.7rem; border-radius: 10px; background: #fef2f2; color: #b91c1c; }
.create-form { display: flex; gap: 0.45rem; }
.create-form input, .cat-list input, .cat-list select {
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 0.45rem 0.55rem;
font-size: 0.9rem;
color: #0f172a;
background: #fff;
}
.create-form input { flex: 1; }
.btn-primary, .row-actions button, .icon-btn { border: 0; cursor: pointer; }
.btn-primary { background: #0f766e; color: #fff; border-radius: 10px; padding: 0.45rem 0.8rem; font-weight: 700; }
.icon-btn { background: transparent; color: #64748b; }
.cat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.55rem; }
.cat-list li {
display: grid;
grid-template-columns: minmax(0, 1.4fr) minmax(0, 0.8fr) auto;
gap: 0.4rem;
align-items: center;
}
.row-actions { grid-column: 1 / -1; display: flex; gap: 0.35rem; }
.row-actions button { background: #f8fafc; color: #334155; border-radius: 8px; padding: 0.3rem 0.5rem; }
.row-actions button:disabled { opacity: 0.4; }
.row-actions .danger { color: #b91c1c; }
.check-line { display: flex; align-items: center; gap: 0.3rem; font-size: 0.8rem; color: #334155; white-space: nowrap; }
</style>
@@ -0,0 +1,128 @@
<script setup lang="ts">
import type { CustomFieldDefinitionDto } from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
const props = defineProps<{
fields: CustomFieldDefinitionDto[];
modelValue: Record<string, unknown>;
}>();
const emit = defineEmits<{
'update:modelValue': [value: Record<string, unknown>];
}>();
function setValue(key: string, value: unknown) {
emit('update:modelValue', { ...props.modelValue, [key]: value });
}
function textValue(key: string) {
const value = props.modelValue[key];
if (value == null) return '';
return String(value);
}
function numberValue(key: string) {
const value = props.modelValue[key];
if (value == null || value === '') return '';
const n = Number(value);
return Number.isFinite(n) ? String(n) : '';
}
</script>
<template>
<div v-if="fields.length" class="note-custom-fields">
<p class="note-custom-title">فیلدهای اختصاصی</p>
<div v-for="field in fields" :key="field.id" class="field">
<span>
{{ field.label }}
<em v-if="field.required">*</em>
</span>
<select
v-if="field.fieldType === 'select'"
:value="textValue(field.key)"
@change="setValue(field.key, ($event.target as HTMLSelectElement).value)"
>
<option value="">انتخاب کنید</option>
<option v-for="opt in field.options" :key="opt" :value="opt">{{ opt }}</option>
</select>
<label v-else-if="field.fieldType === 'boolean'" class="check-line">
<input
type="checkbox"
:checked="props.modelValue[field.key] === true"
@change="setValue(field.key, ($event.target as HTMLInputElement).checked)"
/>
<span>بله</span>
</label>
<input
v-else-if="field.fieldType === 'number'"
type="number"
:value="numberValue(field.key)"
@input="
setValue(
field.key,
($event.target as HTMLInputElement).value === ''
? null
: Number(($event.target as HTMLInputElement).value),
)
"
/>
<JalaliDateInput
v-else-if="field.fieldType === 'date'"
:model-value="textValue(field.key)"
@update:model-value="setValue(field.key, $event || null)"
/>
<input
v-else
type="text"
:value="textValue(field.key)"
@input="setValue(field.key, ($event.target as HTMLInputElement).value)"
/>
</div>
</div>
</template>
<style scoped>
.note-custom-fields {
display: flex;
flex-direction: column;
gap: 0.55rem;
}
.note-custom-title {
margin: 0.2rem 0 0;
font-size: 0.82rem;
font-weight: 700;
color: #0f766e;
}
.field {
display: flex;
flex-direction: column;
gap: 0.3rem;
font-size: 0.82rem;
color: #64748b;
}
.field em {
color: #b91c1c;
font-style: normal;
}
.field select,
.field input[type='text'],
.field input[type='number'] {
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 0.45rem 0.55rem;
font-size: 0.9rem;
color: #0f172a;
background: #fff;
}
.check-line {
display: flex;
align-items: center;
gap: 0.4rem;
color: #0f172a;
}
</style>
@@ -15,12 +15,20 @@ import type {
PersonAccountingLinkDto,
PersonAssetsDto,
TahesabConnectionDto,
TahesabInvoiceSettingsDto,
TahesabSanadType,
} from '@mento/shared';
import { TAHSAB_SANAD_LABELS } from '@/lib/tahesab';
import { formatTahesabBedBes, TAHSAB_SANAD_LABELS } from '@/lib/tahesab';
import type { TahesabInvoiceGroup } from '@/lib/tahesab-invoice-pdf';
import TahesabInvoiceSettingsModal from '@/components/person-assets/TahesabInvoiceSettingsModal.vue';
import TahesabInvoicePreviewModal from '@/components/person-assets/TahesabInvoicePreviewModal.vue';
const props = defineProps<{
personId: string;
/** نام نمایشی مشتری برای فاکتور PDF */
personName?: string;
/** موبایل مشتری برای فاکتور */
personPhone?: string;
}>();
const emit = defineEmits<{
@@ -37,6 +45,10 @@ const assets = ref<PersonAssetsDto | null>(null);
const activeTab = ref<'مانده حساب' | 'جزئیات حساب' | 'ثبت سند'>('مانده حساب');
const asnadLoading = ref(false);
const asnadItems = ref<Record<string, unknown>[]>([]);
const invoiceSettingsOpen = ref(false);
const invoiceSettings = ref<TahesabInvoiceSettingsDto | null>(null);
const invoicePreviewOpen = ref(false);
const invoicePreviewGroup = ref<TahesabInvoiceGroup | null>(null);
/** مدل JalaliDateInput = تاریخ محلی میلادی YYYY-MM-DD */
const fromDate = ref('');
const toDate = ref('');
@@ -174,6 +186,8 @@ const ASNAD_ORDER = Object.keys(ASNAD_FIELD_LABELS);
const ASNAD_HEAD_KEYS = new Set(['Sh_Factor', 'Sh_factor', 'Tarikh', 'NO']);
/** مقادیر کمّی که جداکنندهٔ هزارگان می‌گیرند؛ بقیه (کدها، شناسه‌ها، عیار، تاریخ) خام */
const ASNAD_AMOUNT_KEYS = new Set(['Vazn', 'TabdilVazn', 'Mali', 'Fi', 'Mazaneh', 'Count']);
/** مبالغ علامت‌دار اسناد/مانده — منفی=بد، مثبت=بس (مثل ته‌حساب) */
const ASNAD_SIGNED_KEYS = new Set(['Mali', 'TabdilVazn']);
function asnadFields(item: Record<string, unknown>) {
const keys = Object.keys(item).filter((k) => !ASNAD_HEAD_KEYS.has(k));
@@ -202,6 +216,7 @@ function asnadCell(k: string, v: unknown): string {
if (!s) return '—';
if (k === 'Jens_Felez') return JENS_FELEZ_LABELS[s] ?? showRaw(s);
if (typeof v === 'boolean') return v ? 'بله' : 'خیر';
if (ASNAD_SIGNED_KEYS.has(k)) return formatTahesabBedBes(s);
return ASNAD_AMOUNT_KEYS.has(k) ? showValue(s) : showRaw(s);
}
@@ -383,6 +398,102 @@ async function refreshAssets() {
}
}
async function loadInvoiceSettings() {
try {
const { data } = await api.get<TahesabInvoiceSettingsDto>(
'/integrations/tahesab/invoice-settings',
);
invoiceSettings.value = data;
} catch {
invoiceSettings.value = null;
}
}
function onInvoiceSettingsSaved(dto: TahesabInvoiceSettingsDto) {
invoiceSettings.value = dto;
}
function parseBalanceNum(v: unknown): number | null {
if (v == null) return null;
const s = String(v).trim().replace(/,/g, '');
if (!s || s === 'null' || s === 'undefined' || s === 'NaN') return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
function sumGroupField(g: TahesabInvoiceGroup, key: string): number {
let t = 0;
for (const r of g.rows) {
const n = parseBalanceNum(r[key]);
if (n != null) t += n;
}
return t;
}
function normalizeAsnadDate(d: string): string {
const s = d
.replace(/-/g, '/')
.trim()
.replace(/[۰-۹]/g, (ch) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(ch)));
const m = /^(\d{4})\/(\d{1,2})\/(\d{1,2})/.exec(s);
if (!m) return s;
return `${m[1]}/${m[2]!.padStart(2, '0')}/${m[3]!.padStart(2, '0')}`;
}
function asnadDocNoNum(no: string): number {
const s = String(no)
.trim()
.replace(/[۰-۹]/g, (ch) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(ch)));
const n = Number(s.replace(/[^\d.-]/g, ''));
return Number.isFinite(n) ? n : 0;
}
/** سندهای قبل از این فاکتور (تاریخ، و در همان روز شماره سند کوچک‌تر) */
function isAsnadBeforeInvoice(
item: Record<string, unknown>,
g: TahesabInvoiceGroup,
): boolean {
const d = normalizeAsnadDate(dash(item.Tarikh, ''));
const gd = normalizeAsnadDate(g.date);
if (!d || d === '—') return false;
if (d < gd) return true;
if (d > gd) return false;
return asnadDocNoNum(sanadNo(item)) < asnadDocNoNum(g.no);
}
function sumAsnadBeforeInvoice(g: TahesabInvoiceGroup, key: string): number {
let t = 0;
for (const item of asnadItems.value) {
if (!isAsnadBeforeInvoice(item, g)) continue;
const n = parseBalanceNum(item[key]);
if (n != null) t += n;
}
return t;
}
const invoicePriorWeight = ref<number | null>(null);
const invoicePriorRial = ref<number | null>(null);
const invoiceFinalWeight = ref<number | null>(null);
const invoiceFinalRial = ref<number | null>(null);
async function exportAsnadPdf(g: TahesabInvoiceGroup) {
error.value = '';
// حساب قبل = جمع اثر اسناد قبل از تاریخ/شماره این سند (نه مانده فعلی ته‌حساب)
const priorW = sumAsnadBeforeInvoice(g, 'TabdilVazn');
const priorR = sumAsnadBeforeInvoice(g, 'Mali');
const invW = sumGroupField(g, 'TabdilVazn');
const invR = sumGroupField(g, 'Mali');
invoicePriorWeight.value = priorW;
invoicePriorRial.value = priorR;
invoiceFinalWeight.value = priorW + invW;
invoiceFinalRial.value = priorR + invR;
invoicePreviewGroup.value = g;
invoicePreviewOpen.value = true;
if (!invoiceSettings.value) {
await loadInvoiceSettings();
}
}
async function loadAsnad() {
if (!connectionId.value || !currentLink.value) return;
const from = toShamsiYmd(fromDate.value);
@@ -394,22 +505,26 @@ async function loadAsnad() {
asnadLoading.value = true;
error.value = '';
try {
const { data } = await api.get<{ items: Record<string, unknown>[] }>(
`/integrations/tahesab/people/${props.personId}/asnad`,
{
params: {
connectionId: connectionId.value,
from,
to,
const [{ data }] = await Promise.all([
api.get<{ items: Record<string, unknown>[] }>(
`/integrations/tahesab/people/${props.personId}/asnad`,
{
params: {
connectionId: connectionId.value,
from,
to,
},
timeout: 60_000,
},
timeout: 60_000,
},
);
),
loadInvoiceSettings(),
]);
asnadItems.value = data.items ?? [];
ok.value = asnadItems.value.length
? `${asnadItems.value.length} سند نمایش داده شد.`
: 'در این بازه سندی یافت نشد.';
} catch (e) {
asnadItems.value = [];
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
@@ -636,17 +751,17 @@ onMounted(async () => {
<div v-if="mandehFields?.length" class="balance-grid">
<article v-for="f in mandehFields" :key="f.key" class="balance-box">
<span>{{ mandehFieldLabel(f.key) }}</span>
<strong dir="ltr">{{ showValue(f.value) }}</strong>
<strong dir="ltr">{{ formatTahesabBedBes(f.value) }}</strong>
</article>
</div>
<div v-else class="balance-grid">
<article class="balance-box">
<span>مانده وزنی (طلا)</span>
<strong dir="ltr">{{ showValue(assets.goldBalance) }}</strong>
<strong dir="ltr">{{ formatTahesabBedBes(assets.goldBalance) }}</strong>
</article>
<article class="balance-box">
<span>مانده مالی</span>
<strong dir="ltr">{{ showValue(assets.rialBalance) }}</strong>
<strong dir="ltr">{{ formatTahesabBedBes(assets.rialBalance) }}</strong>
</article>
</div>
<p class="muted tiny">
@@ -683,7 +798,7 @@ onMounted(async () => {
>
<span role="cell" class="raw-name">{{ d.Name }}</span>
<span v-for="c in detailCols" :key="c.key" role="cell" dir="ltr" class="raw-num">
{{ showValue(d[c.key]) }}
{{ formatTahesabBedBes(d[c.key]) }}
</span>
</div>
</div>
@@ -692,7 +807,7 @@ onMounted(async () => {
<div class="name">{{ item.Name }}:</div>
<div class="vals">
<template v-for="(v, vi) in item.values" :key="vi">
<span dir="ltr">{{ showValue(v.amount) }}</span>
<span dir="ltr">{{ formatTahesabBedBes(v.amount) }}</span>
<span class="unit">{{ v.unit }}</span>
<span v-if="vi < item.values.length - 1" class="sep">|</span>
</template>
@@ -715,6 +830,9 @@ onMounted(async () => {
<button type="button" class="btn" :disabled="asnadLoading" @click="loadAsnad">
{{ asnadLoading ? '…' : 'نمایش اسناد' }}
</button>
<button type="button" class="btn ghost" @click="invoiceSettingsOpen = true">
تنظیمات فاکتور
</button>
</div>
<div v-if="asnadItems.length" class="view-bar">
<span class="muted">
@@ -748,6 +866,14 @@ onMounted(async () => {
<strong>سند شماره {{ showRaw(g.no) }}</strong>
<span v-if="g.rows[0]?.isSanadMovaghat === true" class="inv-badge">موقت</span>
<span class="sg-count">{{ g.rows.length.toLocaleString('fa-IR') }} ردیف</span>
<button
type="button"
class="btn inv-pdf-btn"
title="پیش‌نمایش و چاپ فاکتور"
@click="exportAsnadPdf(g)"
>
پیش‌نمایش فاکتور
</button>
</div>
<dl class="inv-meta">
<div>
@@ -830,7 +956,7 @@ onMounted(async () => {
</div>
<div class="sc-row cash">
<span>مالی</span>
<strong dir="ltr">{{ dash(item.Mali) }}</strong>
<strong dir="ltr">{{ formatTahesabBedBes(item.Mali) }}</strong>
</div>
<div class="sc-row">
<span>شرح</span>
@@ -954,6 +1080,23 @@ onMounted(async () => {
</form>
</template>
</template>
<TahesabInvoiceSettingsModal
v-model:open="invoiceSettingsOpen"
@saved="onInvoiceSettingsSaved"
/>
<TahesabInvoicePreviewModal
v-model:open="invoicePreviewOpen"
:group="invoicePreviewGroup"
:settings="invoiceSettings"
:customer-name="personName?.trim() || 'مشتری'"
:customer-phone="personPhone?.trim() || ''"
:moshtari-code="currentLink?.moshtariCode ?? null"
:prior-weight="invoicePriorWeight"
:prior-rial="invoicePriorRial"
:final-weight="invoiceFinalWeight"
:final-rial="invoiceFinalRial"
/>
</div>
</template>
@@ -1195,9 +1338,15 @@ onMounted(async () => {
.inv-title {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
font-size: 0.95rem;
}
.inv-pdf-btn {
margin-inline-start: auto;
font-size: 0.8rem;
padding: 0.3rem 0.65rem;
}
.inv-badge {
font-size: 0.72rem;
padding: 0.1rem 0.45rem;
@@ -0,0 +1,722 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { TahesabInvoiceSettingsDto } from '@mento/shared';
import { formatJalaliDateTime, toFaDigits } from '@/lib/jalali';
import { useEscClose } from '@/lib/modal-stack';
import { formatTahesabBedBes } from '@/lib/tahesab';
import {
aggregateSameNameInvoiceRows,
dashInvoice,
fmtInvoiceNum,
pickInvoiceDarsad,
pickInvoiceMazaneh,
printTahesabInvoicePdf,
rowInvoiceDesc,
formatInvoiceWeightBalance,
invoiceMesghalLabels,
sumInvoiceMali,
tabdilVaznColumnLabel,
type TahesabInvoiceGroup,
} from '@/lib/tahesab-invoice-pdf';
const props = defineProps<{
open: boolean;
group: TahesabInvoiceGroup | null;
settings: TahesabInvoiceSettingsDto | null;
customerName: string;
customerPhone?: string;
moshtariCode?: number | null;
priorWeight?: number | null;
priorRial?: number | null;
finalWeight?: number | null;
finalRial?: number | null;
}>();
const emit = defineEmits<{
'update:open': [value: boolean];
}>();
useEscClose(
() => props.open,
() => close(),
);
function close() {
emit('update:open', false);
}
const first = computed(() => props.group?.rows[0] ?? {});
const temporary = computed(() => first.value.isSanadMovaghat === true);
const issuerName = computed(
() => dashInvoice(first.value.User, '') || '—',
);
const invoiceRows = computed(() =>
props.group ? aggregateSameNameInvoiceRows(props.group.rows) : [],
);
const total = computed(() => sumInvoiceMali(invoiceRows.value));
const sourceRows = computed(
() => props.group?.rows ?? invoiceRows.value,
);
const totalVaznLabel = computed(() =>
formatInvoiceWeightBalance(sourceRows.value, 'Vazn', false),
);
const totalTabdilLabel = computed(() =>
formatInvoiceWeightBalance(sourceRows.value, 'TabdilVazn', true),
);
const tabdilColLabel = computed(() =>
tabdilVaznColumnLabel(sourceRows.value),
);
const company = computed(
() => props.settings?.companyName?.trim() || 'فاکتور ته‌حساب',
);
const generatedAtLabel = computed(() =>
props.open ? formatJalaliDateTime(new Date()) : '',
);
const mesghalLabels = computed(() =>
invoiceMesghalLabels(sourceRows.value),
);
function printPdf() {
if (!props.group) return;
const ok = printTahesabInvoicePdf({
group: props.group,
settings: props.settings,
customerName: props.customerName,
customerPhone: props.customerPhone,
moshtariCode: props.moshtariCode,
priorWeight: props.priorWeight,
priorRial: props.priorRial,
finalWeight: props.finalWeight,
finalRial: props.finalRial,
});
if (!ok) {
// در مرورگر Cursor پاپ‌آپ کار نمی‌کند؛ پیش‌نمایش همین‌جا کافی است
window.alert(
'چاپ در این مرورگر باز نشد. از Chrome استفاده کنید یا از منوی چاپ سیستم روی همین پیش‌نمایش استفاده کنید.',
);
}
}
</script>
<template>
<div v-if="open && group" class="backdrop" @click.self="close">
<div
class="sheet"
role="dialog"
aria-modal="true"
aria-label="پیش‌نمایش فاکتور ته‌حساب"
>
<header class="sheet-head">
<div>
<h3>پیش‌نمایش فاکتور ته‌حساب</h3>
<p class="muted">
سند {{ toFaDigits(group.no) }} · همین‌جا قابل بررسی است (بدون پاپ‌آپ)
</p>
</div>
<div class="head-actions">
<button type="button" class="btn" @click="printPdf">چاپ / PDF</button>
<button type="button" class="btn ghost" @click="close">بستن</button>
</div>
</header>
<div class="paper">
<div class="top">
<div class="top-side top-start">
<p v-if="settings?.headerText?.trim()" class="header-text">
{{ settings.headerText }}
</p>
<p class="org">{{ company }}</p>
<div v-if="settings?.phone?.trim()" class="dim">
تلفن: <bdi dir="ltr">{{ settings.phone }}</bdi>
</div>
</div>
<div class="top-center">
<img
v-if="settings?.logoDataUrl"
class="logo"
:src="settings.logoDataUrl"
alt=""
/>
</div>
<div class="top-side top-end">
<div class="doc-date">
تاریخ: {{ toFaDigits(group.date) }}
</div>
<div>
شماره سند:
<strong>{{ toFaDigits(group.no) }}</strong>
</div>
<div
v-if="settings?.companySubtitle?.trim()"
class="sub"
dir="ltr"
>
{{ settings.companySubtitle }}
</div>
<span v-if="temporary" class="badge">سند موقت</span>
</div>
</div>
<div class="party">
<span class="party-item">
حساب:
<strong>{{ customerName || '—' }}</strong>
</span>
<span class="party-item">
کد:
<strong class="ltr">{{
moshtariCode != null ? toFaDigits(String(moshtariCode)) : '—'
}}</strong>
</span>
<span class="party-item party-phone">
موبایل:
<strong class="ltr">{{
customerPhone?.trim()
? toFaDigits(customerPhone.trim())
: '—'
}}</strong>
</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th class="col-radif">ردیف</th>
<th class="col-desc">شرح</th>
<th class="col-darsad">درصد</th>
<th>عیار</th>
<th>وزن</th>
<th class="col-tabdil">{{ tabdilColLabel }}</th>
<th>مظنه/فی</th>
<th class="col-mali">مبلغ (ریال)</th>
</tr>
</thead>
<tbody>
<tr
v-for="(r, i) in invoiceRows"
:key="String(r.ID ?? r.No_Kar ?? i)"
>
<td class="col-radif">
{{ toFaDigits(dashInvoice(r.Radif, String(i + 1))) }}
</td>
<td class="col-desc">{{ rowInvoiceDesc(r) }}</td>
<td class="ltr col-darsad">
{{ fmtInvoiceNum(pickInvoiceDarsad(r)) }}
</td>
<td class="ltr">{{ fmtInvoiceNum(r.Ayar) }}</td>
<td class="ltr">{{ fmtInvoiceNum(r.Vazn) }}</td>
<td class="ltr col-tabdil">
{{ formatTahesabBedBes(r.TabdilVazn) }}
</td>
<td class="ltr">{{ fmtInvoiceNum(pickInvoiceMazaneh(r)) }}</td>
<td class="ltr col-mali">
{{ formatTahesabBedBes(r.Mali) }}
</td>
</tr>
</tbody>
<tfoot>
<tr class="totals-row">
<td colspan="3" class="totals-label">مجموع کل اجناس</td>
<td></td>
<td class="ltr weight-sum">{{ totalVaznLabel }}</td>
<td class="ltr weight-sum col-tabdil">{{ totalTabdilLabel }}</td>
<td></td>
<td class="ltr col-mali">{{ formatTahesabBedBes(total) }}</td>
</tr>
</tfoot>
</table>
</div>
<div class="invoice-balance">
<div class="ib-when">
<span class="ib-k">زمان چاپ:</span>
{{ generatedAtLabel }}
</div>
<div class="ib-label">مانده این فاکتور:</div>
<div class="ib-cell">
<span class="ib-k">مانده وزنی:</span>
<strong class="ib-val" dir="ltr">{{ totalTabdilLabel }}</strong>
</div>
<div class="ib-cell">
<span class="ib-k">مانده ریالی:</span>
<strong class="ib-val" dir="ltr">{{
formatTahesabBedBes(total)
}}</strong>
</div>
</div>
<div class="account-row">
<div class="mesghal-box">
<div
v-for="label in mesghalLabels"
:key="label"
class="mesghal-line"
>
<span class="ib-k">{{ label }}</span>
<span class="mesghal-blank" aria-hidden="true" />
</div>
</div>
<div class="account-box">
<div class="acc-line">
<span class="acc-title">حساب قبل:</span>
<span class="acc-pair">
<span class="ib-k">وزنی</span>
<strong dir="ltr">{{ formatTahesabBedBes(priorWeight) }}</strong>
</span>
<span class="acc-pair">
<span class="ib-k">ریالی</span>
<strong dir="ltr">{{ formatTahesabBedBes(priorRial) }}</strong>
</span>
</div>
<div class="acc-line">
<span class="acc-title">مانده نهایی:</span>
<span class="acc-pair">
<span class="ib-k">وزنی</span>
<strong dir="ltr">{{ formatTahesabBedBes(finalWeight) }}</strong>
</span>
<span class="acc-pair">
<span class="ib-k">ریالی</span>
<strong dir="ltr">{{ formatTahesabBedBes(finalRial) }}</strong>
</span>
</div>
</div>
</div>
<footer class="page-foot">
<p v-if="settings?.footerText?.trim()" class="note foot">
{{ settings.footerText }}
</p>
<div class="sign-row">
<div class="sign-col">
<span class="ib-k">صادر کننده سند:</span>
<strong class="sign-name">{{ issuerName }}</strong>
<div class="sign-space" aria-hidden="true"></div>
</div>
<div class="sign-addr">
{{ settings?.address?.trim() || '—' }}
</div>
<div class="sign-col">
<span class="ib-k">گیرنده سند:</span>
<strong class="sign-name">{{ customerName || '—' }}</strong>
<div class="sign-space" aria-hidden="true"></div>
</div>
</div>
</footer>
</div>
</div>
</div>
</template>
<style scoped>
.backdrop {
position: fixed;
inset: 0;
z-index: 85;
background: rgba(15, 23, 42, 0.45);
display: grid;
place-items: center;
padding: 12px;
}
.sheet {
width: min(920px, 100%);
max-height: min(92vh, 960px);
overflow: auto;
background: #f3f4f6;
border-radius: 12px;
border: 1px solid #e5e7eb;
padding: 12px;
display: flex;
flex-direction: column;
gap: 12px;
}
.sheet-head {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: flex-start;
flex-wrap: wrap;
background: #fff;
border-radius: 8px;
padding: 10px 12px;
}
.sheet-head h3 {
margin: 0;
font-size: 1rem;
}
.muted {
margin: 4px 0 0;
color: #6b7280;
font-size: 0.85rem;
}
.head-actions {
display: flex;
gap: 8px;
}
.paper {
background: #fff;
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 20px 22px;
color: #111827;
font-size: 13px;
}
.top {
display: grid;
grid-template-columns: 1fr auto 1fr;
gap: 12px 16px;
align-items: center;
margin-bottom: 6px;
border: 1px solid #111827;
border-radius: 10px;
padding: 12px 14px;
}
.top-side {
min-width: 0;
}
.top-start {
text-align: right;
}
.top-end {
text-align: left;
}
.top-center {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.header-text {
margin: 0 0 8px;
white-space: pre-wrap;
font-size: 16px;
font-weight: 800;
line-height: 1.5;
color: #111827;
}
.logo {
max-height: 110px;
max-width: 220px;
object-fit: contain;
}
.org {
font-size: 16px;
font-weight: 800;
margin: 0;
}
.sub {
color: #374151;
margin-top: 8px;
direction: ltr;
unicode-bidi: isolate;
text-align: left;
font-size: 13px;
}
.dim {
color: #6b7280;
margin-top: 2px;
}
.doc-date {
font-weight: 800;
font-size: 15px;
margin-bottom: 4px;
}
.badge {
display: inline-block;
margin-top: 4px;
padding: 2px 8px;
border: 1px solid #d97706;
color: #b45309;
border-radius: 999px;
font-size: 11px;
}
.party {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 20px;
margin-bottom: 14px;
border: 1px solid #111827;
border-radius: 10px;
padding: 8px 14px;
font-size: 13px;
}
.party-item {
white-space: nowrap;
}
.party-phone {
margin-inline-start: auto;
}
.page-foot {
margin-top: 16px;
display: flex;
flex-direction: column;
gap: 10px;
}
.note {
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 8px 10px;
margin: 0;
white-space: pre-wrap;
}
.sign-row {
display: grid;
grid-template-columns: 1fr 1.2fr 1fr;
gap: 12px;
align-items: start;
margin-top: 4px;
}
.sign-col {
display: flex;
flex-direction: column;
gap: 4px;
text-align: center;
}
.sign-name {
font-size: 13px;
font-weight: 800;
}
.sign-space {
min-height: 56px;
margin-top: 4px;
border-bottom: 1px dashed #d1d5db;
}
.sign-addr {
color: #6b7280;
font-size: 12px;
text-align: center;
line-height: 1.55;
max-width: 100%;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
padding-top: 2px;
}
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
th,
td {
padding: 7px 8px;
border: 1px solid #e5e7eb;
text-align: right;
vertical-align: top;
}
th {
background: #f3f4f6;
font-size: 11px;
text-align: center;
vertical-align: middle;
}
.col-radif {
width: 5%;
white-space: nowrap;
padding-inline: 4px;
text-align: center;
vertical-align: middle;
}
.col-desc {
width: 32%;
word-break: break-word;
}
.col-darsad {
width: 6%;
white-space: nowrap;
padding-inline: 4px;
}
.col-tabdil {
width: 14%;
white-space: nowrap;
}
.col-mali {
width: 13%;
white-space: nowrap;
}
.ltr {
direction: ltr;
unicode-bidi: isolate;
text-align: left;
}
.totals-row td {
font-weight: 800;
background: #f9fafb;
vertical-align: middle;
}
.totals-label {
text-align: right;
}
.weight-sum {
font-size: 11px;
white-space: nowrap;
line-height: 1.35;
}
.invoice-balance {
display: grid;
grid-template-columns: 1.2fr 1fr 1fr 1fr;
gap: 0;
margin-top: 10px;
border: 1px solid #111827;
border-radius: 10px;
overflow: hidden;
font-size: 13px;
background: #f3f4f6;
}
.invoice-balance > div {
padding: 8px 12px;
}
.invoice-balance > .ib-cell {
border-inline-start: 1px solid #e5e7eb;
}
.ib-when {
display: flex;
align-items: center;
gap: 6px;
font-weight: 600;
white-space: nowrap;
}
.ib-label {
font-weight: 800;
display: flex;
align-items: center;
justify-content: left;
text-align: left;
}
.ib-cell {
position: relative;
display: flex;
align-items: center;
width: 100%;
min-height: 1.4em;
padding-left: 7.5rem;
box-sizing: border-box;
white-space: nowrap;
}
.ib-k {
color: #6b7280;
font-size: 12px;
}
.ib-val {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
text-align: left;
unicode-bidi: isolate;
font-weight: 800;
}
.account-row {
display: grid;
grid-template-columns: 1fr 1.4fr;
gap: 10px;
margin-top: 10px;
}
.mesghal-box {
border: 1px solid #111827;
border-radius: 10px;
background: transparent;
padding: 8px 12px;
display: flex;
flex-direction: column;
justify-content: center;
gap: 8px;
min-height: 2.5rem;
}
.mesghal-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.mesghal-blank {
flex: 1;
min-width: 4rem;
border-bottom: 1px dotted #9ca3af;
align-self: flex-end;
margin-bottom: 0.35rem;
margin-inline-start: 0.5rem;
}
.account-box {
border: 1px solid #111827;
border-radius: 10px;
background: transparent;
overflow: hidden;
display: flex;
flex-direction: column;
}
.acc-line {
display: grid;
grid-template-columns: auto 1fr 1fr;
align-items: stretch;
gap: 0;
border-top: 1px solid #e5e7eb;
}
.acc-line:first-child {
border-top: 0;
}
.acc-title {
font-weight: 800;
white-space: nowrap;
padding: 6px 12px;
display: flex;
align-items: center;
}
.acc-pair {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-width: 0;
padding: 6px 12px;
border-inline-start: 1px solid #e5e7eb;
}
.acc-pair strong {
font-weight: 800;
unicode-bidi: isolate;
}
.btn {
border: 0;
border-radius: 8px;
padding: 0.45rem 0.8rem;
background: var(--accent, #0d9488);
color: #fff;
font-weight: 600;
cursor: pointer;
}
.btn.ghost {
background: transparent;
color: #111827;
border: 1px solid #e5e7eb;
}
@media (max-width: 720px) {
.party-phone {
margin-inline-start: 0;
}
.top {
grid-template-columns: 1fr;
justify-items: stretch;
}
.top-center {
order: -1;
}
.top-end {
text-align: right;
}
.invoice-balance {
grid-template-columns: 1fr 1fr;
}
.account-row {
grid-template-columns: 1fr;
}
.sign-row {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,305 @@
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import type { TahesabInvoiceSettingsDto } from '@mento/shared';
import { useEscClose } from '@/lib/modal-stack';
const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{
'update:open': [value: boolean];
saved: [value: TahesabInvoiceSettingsDto];
}>();
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const logoDataUrl = ref<string | null>(null);
const companyName = ref('');
const companySubtitle = ref('');
const address = ref('');
const phone = ref('');
const headerText = ref('');
const footerText = ref('');
useEscClose(
() => props.open,
() => close(),
);
function close() {
emit('update:open', false);
}
function fill(dto: TahesabInvoiceSettingsDto) {
logoDataUrl.value = dto.logoDataUrl;
companyName.value = dto.companyName ?? '';
companySubtitle.value = dto.companySubtitle ?? '';
address.value = dto.address ?? '';
phone.value = dto.phone ?? '';
headerText.value = dto.headerText ?? '';
footerText.value = dto.footerText ?? '';
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<TahesabInvoiceSettingsDto>(
'/integrations/tahesab/invoice-settings',
);
fill(data);
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'بارگذاری تنظیمات ناموفق بود.',
)
: 'بارگذاری تنظیمات ناموفق بود.';
} finally {
loading.value = false;
}
}
function onLogoFile(ev: Event) {
const input = ev.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
if (!file.type.startsWith('image/')) {
error.value = 'فقط فایل تصویر مجاز است.';
return;
}
if (file.size > 400_000) {
error.value = 'حجم تصویر حداکثر حدود ۴۰۰ کیلوبایت باشد.';
return;
}
const reader = new FileReader();
reader.onload = () => {
const result = typeof reader.result === 'string' ? reader.result : '';
if (!result.startsWith('data:image/')) {
error.value = 'خواندن تصویر ناموفق بود.';
return;
}
logoDataUrl.value = result;
error.value = '';
};
reader.readAsDataURL(file);
}
function clearLogo() {
logoDataUrl.value = null;
}
async function save() {
saving.value = true;
error.value = '';
ok.value = '';
try {
const { data } = await api.patch<TahesabInvoiceSettingsDto>(
'/integrations/tahesab/invoice-settings',
{
logoDataUrl: logoDataUrl.value,
companyName: companyName.value,
companySubtitle: companySubtitle.value,
address: address.value,
phone: phone.value,
headerText: headerText.value,
footerText: footerText.value,
},
);
fill(data);
ok.value = 'تنظیمات فاکتور ذخیره شد.';
emit('saved', data);
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
(e.response?.data as { message?: string })?.message ??
'ذخیره تنظیمات ناموفق بود.',
)
: 'ذخیره تنظیمات ناموفق بود.';
} finally {
saving.value = false;
}
}
watch(
() => props.open,
(open) => {
if (open) {
ok.value = '';
error.value = '';
void load();
}
},
);
onMounted(() => {
if (props.open) void load();
});
</script>
<template>
<div v-if="open" class="backdrop" @click.self="close">
<div class="sheet" role="dialog" aria-modal="true" aria-label="تنظیمات فاکتور ته‌حساب">
<header class="sheet-head">
<div>
<h3>تنظیمات فاکتور ته‌حساب</h3>
<p class="muted">لوگو و متن‌های ثابت خروجی PDF اسناد — جدا از فاکتور CRM</p>
</div>
<button type="button" class="btn ghost" @click="close">بستن</button>
</header>
<p v-if="error" class="err">{{ error }}</p>
<p v-if="ok" class="ok">{{ ok }}</p>
<p v-if="loading" class="muted">در حال بارگذاری…</p>
<div v-else class="grid">
<label class="field logo-field">
<span>لوگو</span>
<div class="logo-row">
<img v-if="logoDataUrl" :src="logoDataUrl" alt="لوگو" class="logo-preview" />
<div class="logo-actions">
<input type="file" accept="image/*" @change="onLogoFile" />
<button v-if="logoDataUrl" type="button" class="btn ghost" @click="clearLogo">
حذف لوگو
</button>
</div>
</div>
</label>
<label class="field">
<span>نام شرکت / فروشگاه</span>
<input v-model="companyName" type="text" maxlength="200" />
</label>
<label class="field">
<span>زیرعنوان</span>
<input v-model="companySubtitle" type="text" maxlength="200" />
</label>
<label class="field">
<span>آدرس</span>
<input v-model="address" type="text" maxlength="500" />
</label>
<label class="field">
<span>تلفن</span>
<input v-model="phone" type="text" maxlength="80" dir="ltr" />
</label>
<label class="field full">
<span>متن بالای فاکتور</span>
<textarea v-model="headerText" rows="2" maxlength="1000" />
</label>
<label class="field full">
<span>متن پایین فاکتور</span>
<textarea v-model="footerText" rows="2" maxlength="1000" />
</label>
</div>
<footer class="sheet-foot">
<button type="button" class="btn" :disabled="saving || loading" @click="save">
{{ saving ? '…' : 'ذخیره تنظیمات' }}
</button>
</footer>
</div>
</div>
</template>
<style scoped>
.backdrop {
position: fixed;
inset: 0;
z-index: 80;
background: rgba(15, 23, 42, 0.45);
display: grid;
place-items: center;
padding: 16px;
}
.sheet {
width: min(640px, 100%);
max-height: min(90vh, 820px);
overflow: auto;
background: var(--surface, #fff);
border-radius: 12px;
border: 1px solid var(--line, #e5e7eb);
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.sheet-head {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: flex-start;
}
.sheet-head h3 {
margin: 0;
font-size: 1.05rem;
}
.muted {
margin: 4px 0 0;
color: var(--ink-secondary, #6b7280);
font-size: 0.85rem;
}
.err {
color: #b91c1c;
margin: 0;
}
.ok {
color: #047857;
margin: 0;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 0.85rem;
}
.field.full,
.logo-field {
grid-column: 1 / -1;
}
.field input,
.field textarea {
border: 1px solid var(--line, #e5e7eb);
border-radius: 8px;
padding: 8px 10px;
font: inherit;
background: var(--surface, #fff);
}
.logo-row {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
}
.logo-preview {
max-height: 64px;
max-width: 140px;
object-fit: contain;
border: 1px solid var(--line, #e5e7eb);
border-radius: 8px;
padding: 4px;
background: #fff;
}
.logo-actions {
display: flex;
flex-direction: column;
gap: 8px;
}
.sheet-foot {
display: flex;
justify-content: flex-end;
}
@media (max-width: 640px) {
.grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -8,8 +8,9 @@ withDefaults(
defineProps<{
accent: PipelineAccent;
label?: string;
count?: string;
}>(),
{ label: 'افزودن معامله' },
{ label: 'افزودن معامله', count: '' },
);
const emit = defineEmits<{
@@ -21,11 +22,18 @@ const emit = defineEmits<{
<a-button
type="dashed"
block
:style="{ color: PIPELINE_ACCENT[accent].text }"
:style="{
color: PIPELINE_ACCENT[accent].text,
display: 'flex',
justifyContent: 'space-between',
}"
:aria-label="label"
@click="emit('add')"
>
<template #icon><PlusOutlined /></template>
{{ label }}
<span :style="{ display: 'inline-flex', alignItems: 'center', gap: '8px' }">
<PlusOutlined />
{{ label }}
</span>
<span v-if="count">{{ count }}</span>
</a-button>
</template>
+9 -21
View File
@@ -18,11 +18,7 @@ import {
} from 'ant-design-vue';
import { userAvatarSrc } from '@/lib/userAvatars';
import type { PipelineAccent, PipelineDeal, PipelineUiCopy } from '@/lib/pipeline-board';
import {
DEAL_BOARD_COPY,
formatCurrencyParts,
PIPELINE_ACCENT,
} from '@/lib/pipeline-board';
import { DEAL_BOARD_COPY, formatCurrencyParts } from '@/lib/pipeline-board';
const props = withDefaults(
defineProps<{
@@ -54,7 +50,6 @@ const showAmount = computed(
const money = computed(() =>
formatCurrencyParts(props.deal.amount ?? 0, props.deal.currencyUnit ?? 'ریال'),
);
const colors = computed(() => PIPELINE_ACCENT[props.accent]);
const assigneeTitle = computed(() =>
(props.deal.assigneeNames ?? []).filter(Boolean).join('، ') || 'مسئول',
);
@@ -113,24 +108,17 @@ const cardStyle = computed(() => ({
<CheckOutlined v-if="selected" />
</template>
</a-button>
<a-avatar
v-else
:style="{
background: colors.soft,
color: colors.text,
flexShrink: 0,
fontWeight: 700,
fontSize: `${token.fontSizeSM}px`,
}"
>
{{ deal.initials }}
</a-avatar>
<div :style="{ flex: 1, minWidth: 0 }">
<a-typography-text
strong
ellipsis
:style="{ display: 'block', margin: 0, lineHeight: 1.35, cursor: 'pointer' }"
:style="{
display: 'block',
margin: 0,
lineHeight: 1.35,
cursor: 'pointer',
fontSize: `${token.fontSizeSM}px`,
fontWeight: 600,
}"
:title="deal.title"
@click.stop="selectMode ? emit('toggleSelect', deal.id) : emit('open', deal.id)"
>
@@ -131,8 +131,8 @@ function submitAdd() {
<div
v-if="canManage"
:style="{
flex: '0 0 280px',
width: '280px',
flex: '0 0 310px',
width: '310px',
alignSelf: 'stretch',
display: 'flex',
alignItems: 'flex-start',
@@ -1,10 +1,6 @@
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import {
HolderOutlined,
MoreOutlined,
PlusOutlined,
} from '@ant-design/icons-vue';
import { HolderOutlined, MoreOutlined } from '@ant-design/icons-vue';
import {
Button as AButton,
Dropdown as ADropdown,
@@ -17,7 +13,7 @@ import {
import AddDealButton from './AddDealButton.vue';
import DealCard from './DealCard.vue';
import type { PipelineDeal, PipelineStage, PipelineUiCopy } from '@/lib/pipeline-board';
import { DEAL_BOARD_COPY, PIPELINE_ACCENT, toFaItemCount } from '@/lib/pipeline-board';
import { DEAL_BOARD_COPY, PIPELINE_ACCENT } from '@/lib/pipeline-board';
const props = withDefaults(
defineProps<{
@@ -67,8 +63,8 @@ const columnStyle = computed(() => ({
display: 'flex',
flexDirection: 'column' as const,
gap: '12px',
flex: '0 0 280px',
width: '280px',
flex: '0 0 310px',
width: '310px',
alignSelf: 'stretch' as const,
minHeight: 0,
padding: 0,
@@ -154,15 +150,21 @@ function onColumnDragStart(event: DragEvent) {
}
const menuItems = computed(() => [
{ key: 'add', label: 'افزودن' },
{ key: 'rename', label: 'تغییر نام' },
{ key: 'right', label: 'انتقال به راست', disabled: props.isFirst },
{ key: 'left', label: 'انتقال به چپ', disabled: props.isLast },
{ key: 'delete', label: 'حذف ستون', danger: true },
]);
const itemCountLabel = computed(() =>
new Intl.NumberFormat('fa-IR').format(props.stage.total ?? props.stage.deals.length),
);
function onMenuClick({ key }: { key: string | number }) {
menuOpen.value = false;
if (key === 'rename') startRename();
if (key === 'add') emit('addDeal', props.stage.id);
else if (key === 'rename') startRename();
else if (key === 'right') emit('move', props.stage.id, -1);
else if (key === 'left') emit('move', props.stage.id, 1);
else if (key === 'delete') emit('delete', props.stage.id);
@@ -224,12 +226,13 @@ function onMenuClick({ key }: { key: string | number }) {
/>
<a-typography-text
v-else
strong
ellipsis
:style="{
flex: 1,
minWidth: 0,
margin: 0,
fontSize: `${token.fontSizeSM}px`,
fontWeight: 600,
cursor: canManage ? 'text' : 'default',
}"
:title="canManage ? 'برای تغییر نام کلیک کنید' : stage.title"
@@ -242,10 +245,6 @@ function onMenuClick({ key }: { key: string | number }) {
{{ stage.badge }}
</a-tag>
<a-typography-text type="secondary" :style="{ whiteSpace: 'nowrap', flexShrink: 0 }">
{{ toFaItemCount(stage.total ?? stage.deals.length, copy.itemNoun) }}
</a-typography-text>
<a-dropdown
v-if="canManage"
v-model:open="menuOpen"
@@ -259,15 +258,6 @@ function onMenuClick({ key }: { key: string | number }) {
<a-menu :items="menuItems" @click="onMenuClick" />
</template>
</a-dropdown>
<a-button
type="text"
:aria-label="copy.addItemAria"
:style="{ color: accent.solid }"
@click="emit('addDeal', stage.id)"
>
<template #icon><PlusOutlined /></template>
</a-button>
</div>
<div role="list" :aria-label="stage.title" :style="bodyStyle">
@@ -311,7 +301,12 @@ function onMenuClick({ key }: { key: string | number }) {
</div>
<div :style="{ padding: '0 12px 12px', flexShrink: 0 }">
<AddDealButton :accent="stage.color" :label="copy.addItem" @add="emit('addDeal', stage.id)" />
<AddDealButton
:accent="stage.color"
:label="copy.addItem"
:count="itemCountLabel"
@add="emit('addDeal', stage.id)"
/>
</div>
</section>
</template>
@@ -23,7 +23,6 @@ import {
Typography,
} from 'ant-design-vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import EntityLinkPicker, { type PickedEntity } from '@/components/routines/EntityLinkPicker.vue';
import { api } from '@/lib/api';
import {
ENTITY_TYPE_LABELS,
@@ -34,6 +33,7 @@ import {
todayKey,
} from '@/lib/routines';
import { useAuthStore } from '@/stores/auth';
import { canAssignToOthers } from '@/lib/assign-access';
const { Text: ATypographyText } = Typography;
@@ -64,7 +64,6 @@ const form = reactive({
categoryId: '',
assigneeId: '',
isMandatory: false,
entity: null as PickedEntity | null,
});
const saving = ref(false);
const error = ref('');
@@ -110,7 +109,6 @@ watch(
categoryId: '',
assigneeId: props.defaultAssigneeId || auth.user?.id || '',
isMandatory: false,
entity: null,
});
error.value = '';
void ensureContext();
@@ -120,7 +118,7 @@ watch(
const assignees = computed(() => {
const c = ctx.value;
if (!c?.isManager) return [];
if (!c?.isManager || !canAssignToOthers(auth.user, 'routines')) return [];
return c.users;
});
@@ -138,14 +136,14 @@ async function submit() {
error.value = 'عنوان کار را وارد کنید.';
return Promise.reject();
}
const link = props.preset ?? form.entity;
const link = props.preset;
const body: CreateRoutineTaskRequest = {
title: form.title.trim(),
description: form.description.trim() || null,
priority: form.priority,
categoryId: form.categoryId || null,
assigneeId: form.assigneeId || null,
isMandatory: form.isMandatory,
isMandatory: link ? false : form.isMandatory,
source: sourceFor(link?.type),
scheduledFor: form.date || todayKey(),
dueAt: form.time ? localInputToIso(form.date || todayKey(), form.time) : null,
@@ -182,7 +180,7 @@ async function submit() {
<a-form-item label="عنوان" required>
<a-input
v-model:value="form.title"
placeholder="مثلاً: تماس با مشتری برای پیگیری پیش‌فاکتور"
placeholder="مثلاً: آماده‌سازی گزارش هفتگی تیم"
:maxlength="200"
/>
</a-form-item>
@@ -229,16 +227,20 @@ async function submit() {
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="اتصال به پرونده">
<a-space v-if="preset" :size="8">
<a-col v-if="preset" :span="24">
<a-form-item label="پرونده">
<a-space :size="8">
<a-tag :bordered="false">{{ ENTITY_TYPE_LABELS[preset.type] }}</a-tag>
<a-typography-text strong>{{ preset.label }}</a-typography-text>
</a-space>
<EntityLinkPicker v-else v-model="form.entity" />
</a-form-item>
<a-alert
type="info"
show-icon
message="این کار روی همین پرونده می‌ماند و در برنامه روزانه کارهای روتین دیده نمی‌شود."
/>
</a-col>
<a-col :span="24">
<a-col v-else :span="24">
<a-checkbox v-model:checked="form.isMandatory">
کار اجباری (در امتیاز روزانه و Streak حساب می‌شود)
</a-checkbox>
@@ -1,6 +1,5 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
Alert as AAlert,
Button as AButton,
@@ -19,7 +18,14 @@ import RoutineTaskRow, { type RoutineTaskRowAction } from '@/components/routines
import RoutineTaskModals from '@/components/routines/RoutineTaskModals.vue';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { apiError, isOpenStatus } from '@/lib/routines';
import {
ROUTINE_TASK_STATUS_LABELS,
apiError,
formatDayNumeric,
formatTime,
hasExplicitTime,
isOpenStatus,
} from '@/lib/routines';
import { useRoutineTaskActions } from '@/lib/useRoutineTaskActions';
import { useAuthStore } from '@/stores/auth';
@@ -38,7 +44,6 @@ const props = withDefaults(
},
);
const router = useRouter();
const auth = useAuthStore();
const enabled = computed(() => {
@@ -51,6 +56,7 @@ const loading = ref(false);
const error = ref('');
const showClosed = ref(false);
const quickOpen = ref(false);
const detail = ref<RoutineTaskDto | null>(null);
async function load() {
if (!enabled.value || !props.entity.id) return;
@@ -73,6 +79,7 @@ watch(() => `${props.entity.type}:${props.entity.id}`, load, { immediate: true }
const actions = useRoutineTaskActions((updated) => {
const i = items.value.findIndex((t) => t.id === updated.id);
if (i >= 0) items.value[i] = updated;
if (detail.value?.id === updated.id) detail.value = updated;
});
function onAction(kind: RoutineTaskRowAction, task: RoutineTaskDto) {
@@ -88,7 +95,7 @@ const open = computed(() => items.value.filter((t) => isOpenStatus(t.status)));
const closed = computed(() => items.value.filter((t) => !isOpenStatus(t.status)));
function openTask(t: RoutineTaskDto) {
void router.push({ path: '/routines', query: { task: t.id } });
detail.value = t;
}
function onCreated(t: RoutineTaskDto) {
@@ -182,5 +189,27 @@ function onCreated(t: RoutineTaskDto) {
<QuickTaskModal :open="quickOpen" :preset="entity" @close="quickOpen = false" @created="onCreated" />
<RoutineTaskModals :actions="actions" />
<a-drawer :open="detail != null" title="جزئیات کار" @close="detail = null">
<template v-if="detail">
<a-typography-paragraph v-if="detail.description">{{ detail.description }}</a-typography-paragraph>
<a-descriptions :column="1">
<a-descriptions-item label="وضعیت">
{{ ROUTINE_TASK_STATUS_LABELS[detail.status] }}
</a-descriptions-item>
<a-descriptions-item label="مسئول">
{{ detail.assignee?.fullName || '—' }}
</a-descriptions-item>
<a-descriptions-item label="روز برنامه">
{{ formatDayNumeric(detail.scheduledFor) }}
</a-descriptions-item>
<a-descriptions-item label="مهلت">
{{ detail.dueAt && hasExplicitTime(detail) ? formatTime(detail.dueAt) : 'تا پایان روز' }}
</a-descriptions-item>
</a-descriptions>
<a-typography-paragraph v-if="detail.resultNote" :style="{ marginTop: '12px' }">
{{ detail.resultNote }}
</a-typography-paragraph>
</template>
</a-drawer>
</a-card>
</template>
@@ -22,6 +22,8 @@ import {
UiTextarea,
} from '@/components/ui';
import { api } from '@/lib/api';
import { canAssignToOthers } from '@/lib/assign-access';
import { useAuthStore } from '@/stores/auth';
import { formatJalaliDayClock } from '@/lib/jalali';
import {
ENTITY_TYPE_LABELS,
@@ -97,8 +99,15 @@ const actions = useRoutineTaskActions((updated) => {
});
const isOpen = computed(() => (task.value ? isOpenStatus(task.value.status) : false));
const customerTask = computed(() => {
const t = task.value;
if (!t) return false;
return (t.source !== 'routine' && t.source !== 'manual') || t.entities.length > 0;
});
const done = computed(() => task.value?.status === 'completed');
const auth = useAuthStore();
const canManage = computed(() => !!shell?.context.value?.isManager);
const canAssignOthers = computed(() => canAssignToOthers(auth.user, 'routines'));
const priorities = Object.entries(PRIORITY_LABELS) as Array<[ActivityPriority, string]>;
function startEdit() {
@@ -190,10 +199,13 @@ function eventText(ev: RoutineTaskEventDto): string {
</div>
<h3 class="td-title" :class="{ done }">{{ task.title }}</h3>
<p v-if="task.description" class="td-desc">{{ task.description }}</p>
<p v-if="customerTask" class="note">
این کار مربوط به پرونده است و در برنامه روزانه کارهای روتین نیست.
</p>
</section>
<!-- اکشن اصلی -->
<section v-if="!editing" class="td-actions">
<section v-if="!editing && !customerTask" class="td-actions">
<UiButton
v-if="isOpen"
variant="success"
@@ -268,7 +280,7 @@ function eventText(ev: RoutineTaskEventDto): string {
<JalaliDateInput v-model="edit.time" mode="time" />
</UiField>
</template>
<UiField v-if="canManage" label="مسئول" class="span-2">
<UiField v-if="canManage && canAssignOthers" label="مسئول" class="span-2">
<UiSelect v-model="edit.assigneeId">
<option v-for="u in shell?.context.value?.users ?? []" :key="u.id" :value="u.id">
{{ u.fullName }}
@@ -370,7 +382,7 @@ function eventText(ev: RoutineTaskEventDto): string {
</section>
</div>
<template v-if="task && !editing" #footer>
<template v-if="task && !editing && !customerTask" #footer>
<UiButton variant="ghost" size="sm" @click="startEdit">
<template #icon><UiIcon name="pencil" :size="14" /></template>
ویرایش
@@ -0,0 +1,333 @@
<script setup lang="ts">
import { computed } from 'vue';
import {
Alert as AAlert,
Card as ACard,
Col as ACol,
Empty as AEmpty,
List as AList,
Row as ARow,
Statistic as AStatistic,
Table as ATable,
Typography,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
const { Paragraph: ATypographyParagraph, Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
import type {
SalesFactorOverviewDto,
SalesMovementStatsDto,
SalesNamedMovementDto,
TahesabSalesOverviewDto,
} from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
import { formatTahesabBedBes } from '@/lib/tahesab';
const props = defineProps<{
overview: TahesabSalesOverviewDto | null;
showInternet?: boolean;
}>();
function formatNum(n: number | null | undefined) {
if (n == null || Number.isNaN(n)) return '—';
return toFaDigits(new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 3 }).format(n));
}
function formatMali(n: number | null | undefined) {
if (n == null) return '—';
return formatTahesabBedBes(n, 0);
}
function formatRial(n: number | null | undefined) {
if (n == null) return '—';
return `${toFaDigits(new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 0 }).format(Math.abs(n)))} ریال`;
}
type GroupRow = {
id: string;
label: string;
netSaleWeight: number;
saleReturnWeight: number;
netSaleMali: number;
children?: GroupRow[];
};
const groupRows = computed<GroupRow[]>(() =>
(props.overview?.groups ?? []).map((group) => ({
id: group.id,
label: group.label,
netSaleWeight: group.netSaleWeight,
saleReturnWeight: group.saleReturnWeight,
netSaleMali: group.netSaleMali,
children: group.children.length
? group.children.map((child) => ({
id: child.id,
label: child.label,
netSaleWeight: child.netSaleWeight,
saleReturnWeight: child.saleReturnWeight,
netSaleMali: child.netSaleMali,
}))
: undefined,
})),
);
const groupColumns: TableColumnsType<GroupRow> = [
{ title: 'گروه', dataIndex: 'label', key: 'label', ellipsis: true },
{
title: 'فروش (گرم)',
key: 'weight',
width: 120,
customRender: ({ record }) => formatNum(record.netSaleWeight),
},
{
title: 'مرجوعی (گرم)',
key: 'return',
width: 120,
customRender: ({ record }) => formatNum(record.saleReturnWeight),
},
{
title: 'مبلغ',
key: 'mali',
width: 160,
customRender: ({ record }) => formatRial(record.netSaleMali),
},
];
function percentText(stats: SalesMovementStatsDto, empty = 'درصدی ثبت نشده') {
const p = stats.percent;
if (!p || p.avg == null) return empty;
return `اول ${formatNum(p.first)} · آخر ${formatNum(p.last)} · میانگین ${formatNum(p.avg)} · کم ${formatNum(p.min)} · بیش ${formatNum(p.max)}`;
}
function percentShort(stats: SalesMovementStatsDto) {
const p = stats.percent;
if (!p || p.avg == null) return '—';
return `میانگین ${formatNum(p.avg)} · از ${formatNum(p.min)} تا ${formatNum(p.max)}`;
}
const factors = computed(() =>
(props.overview?.factors ?? []).filter((f) => f.key !== 'other' || f.sale.grossWeight > 0 || f.purchase.grossWeight > 0),
);
const factorColumns = computed<TableColumnsType<SalesFactorOverviewDto>>(() => {
const cols: TableColumnsType<SalesFactorOverviewDto> = [
{
title: 'بخش کالا',
dataIndex: 'label',
key: 'label',
fixed: 'right',
width: 150,
customRender: ({ record }) => (record.key === 'other' ? 'سایر عنوان‌ها' : record.label),
},
{
title: 'وزن فروش (گرم)',
key: 'saleWeight',
customRender: ({ record }) => formatNum(record.sale.netWeight),
},
{
title: 'مرجوعی فروش (گرم)',
key: 'saleReturn',
customRender: ({ record }) => formatNum(record.sale.returnWeight),
},
{
title: 'مبلغ فروش (ریال)',
key: 'saleMali',
customRender: ({ record }) => formatRial(record.sale.netMali),
},
{
title: 'وزن خرید (گرم)',
key: 'buyWeight',
customRender: ({ record }) => formatNum(record.purchase.netWeight),
},
{
title: 'مرجوعی خرید (گرم)',
key: 'buyReturn',
customRender: ({ record }) => formatNum(record.purchase.returnWeight),
},
{
title: 'مبلغ خرید (ریال)',
key: 'buyMali',
customRender: ({ record }) => formatRial(record.purchase.netMali),
},
{
title: 'تعداد فروش',
key: 'saleCount',
width: 110,
customRender: ({ record }) =>
record.key === 'bullion' ? formatNum(record.sale.netCount) : '—',
},
];
if (props.overview?.percentReady) {
cols.push(
{
title: 'درصد فروش',
key: 'salePercent',
customRender: ({ record }) => percentShort(record.sale),
},
{
title: 'درصد خرید',
key: 'buyPercent',
customRender: ({ record }) => percentShort(record.purchase),
},
);
}
return cols;
});
const karColumns: TableColumnsType<SalesNamedMovementDto> = [
{ title: 'نام کالا', dataIndex: 'name', key: 'name', ellipsis: true },
{
title: 'وزن فروش (گرم)',
key: 'saleNet',
customRender: ({ record }) => formatNum(record.sale.netWeight),
},
{
title: 'مرجوعی فروش (گرم)',
key: 'saleRet',
customRender: ({ record }) => formatNum(record.sale.returnWeight),
},
{
title: 'درصد خروج',
key: 'salePct',
customRender: ({ record }) => percentText(record.sale),
},
{
title: 'وزن خرید (گرم)',
key: 'buyNet',
customRender: ({ record }) => formatNum(record.purchase.netWeight),
},
{
title: 'مرجوعی خرید (گرم)',
key: 'buyRet',
customRender: ({ record }) => formatNum(record.purchase.returnWeight),
},
{
title: 'درصد ورود',
key: 'buyPct',
customRender: ({ record }) => percentText(record.purchase),
},
];
</script>
<template>
<a-row v-if="overview" :gutter="[16, 16]">
<a-col v-if="!overview.percentReady" :span="24">
<a-alert
type="info"
show-icon
message="درصد ورود و خروج بعد از یک به‌روزرسانی تازه از ته‌حساب پر می‌شود. وزن و مرجوعی با سندهای فعلی حساب شده‌اند."
/>
</a-col>
<a-col :span="24">
<a-card :bordered="false" title="نتیجهٔ این بازه">
<a-typography-paragraph type="secondary">
هر ردیف یک بخش کالاست. وزن فروش، گرم فروخته‌شده بعد از کم شدن مرجوعی همان بازه است.
مبلغ، ریال همان فروش است. تعداد فقط برای شمش و سکه معنی دارد.
«سایر عنوان‌ها» سندهایی است که در نامشان کارساخته، اتیکت، شمش یا سکه نبوده.
</a-typography-paragraph>
<a-table
:columns="factorColumns"
:data-source="factors"
row-key="key"
:pagination="false"
:scroll="{ x: 1100 }"
/>
</a-card>
</a-col>
<a-col :span="24">
<a-card :bordered="false" title="ریز کارساخته، به تفکیک نام کالا">
<a-table
:columns="karColumns"
:data-source="overview.karsakhte"
row-key="name"
:pagination="{ pageSize: 8, showSizeChanger: false }"
:scroll="{ x: 980 }"
>
<template #emptyText>
<a-empty description="در این بازه سند کارساخته نیست." />
</template>
</a-table>
</a-card>
</a-col>
<a-col :span="24">
<a-card :bordered="false" title="فروش به تفکیک گروه">
<a-typography-paragraph type="secondary">
عدد گروه اصلی، فروش خودش و زیرگروه‌ها را با هم نشان می‌دهد.
</a-typography-paragraph>
<a-table
:columns="groupColumns"
:data-source="groupRows"
row-key="id"
default-expand-all-rows
:pagination="groupRows.length > 6 ? { pageSize: 6, showSizeChanger: false } : false"
:scroll="{ x: 560 }"
>
<template #emptyText>
<a-empty description="گروهی در این بازه فروش ندارد." />
</template>
</a-table>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :bordered="false" title="پورسانت کارشناس">
<a-typography-paragraph type="secondary">
{{
showInternet
? 'کارساختهٔ نقره جدا از سرمایه‌گذاری (اتیکت جواهر و فروش اینترنتی) حساب می‌شود.'
: 'کارساختهٔ نقره جدا از سرمایه‌گذاری (اتیکت جواهر) حساب می‌شود.'
}}
</a-typography-paragraph>
<a-list
:data-source="overview.experts"
item-layout="vertical"
:locale="{ emptyText: 'کارشناسی برای این بازه نیست.' }"
>
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta :title="item.name" :description="`درصد ${formatNum(item.percent)}`" />
<div>
کارساخته نقره: وزن {{ formatNum(item.silverWeight) }} · پورسانت
{{ formatMali(item.silverCommission) }}
</div>
<div>
سرمایه‌گذاری: وزن {{ formatNum(item.investWeight) }} · پورسانت
{{ formatMali(item.investCommission) }}
</div>
</a-list-item>
</template>
</a-list>
</a-card>
</a-col>
<a-col v-if="showInternet" :span="24">
<a-card :bordered="false" title="فروش اینترنتی (مونتیفای)">
<a-row :gutter="[16, 16]">
<a-col :xs="24" :sm="8">
<a-statistic title="سفارش" :value="formatNum(overview.internet.orderCount)" />
</a-col>
<a-col :xs="24" :sm="8">
<a-statistic title="خالص نقره" :value="formatNum(overview.internet.netSilver)" />
</a-col>
<a-col :xs="24" :sm="8">
<a-statistic title="خالص طلا" :value="formatNum(overview.internet.netGold)" />
</a-col>
<a-col :span="24">
<a-typography-text type="secondary">
مبلغ {{ formatMali(overview.internet.netMali) }} · لغوشده
{{ formatNum(overview.internet.returnCount) }} سفارش، نقره
{{ formatNum(overview.internet.returnSilver) }} ·
{{ formatNum(overview.internet.linkedSkipped) }} سفارش چون در ته‌حساب سند دارد اینجا دوباره نیامده
</a-typography-text>
</a-col>
</a-row>
</a-card>
</a-col>
</a-row>
</template>