From dc691c51923b2dd1e6c0bebe7d6f8d4164957566 Mon Sep 17 00:00:00 2001 From: mahmood Date: Thu, 5 Nov 2026 19:48:41 +0330 Subject: [PATCH 01/62] Preparation for MONSYS --- .dockerignore | 15 +++++ .gitea/workflows/build.yml | 124 +++++++++++++++++++++++++++++++++++++ Dockerfile.api | 29 +++++++++ Dockerfile.stt | 15 +++++ Dockerfile.web | 16 +++++ docker/web.nginx.conf | 11 ++++ 6 files changed, 210 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitea/workflows/build.yml create mode 100644 Dockerfile.api create mode 100644 Dockerfile.stt create mode 100644 Dockerfile.web create mode 100644 docker/web.nginx.conf diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b7abdcf --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +.git +node_modules +**/dist +**/.env +**/.env.* +apps/stt/.venv +uploads +docs +e2e +test-results +playwright-report +graphify-out +.worktrees +*.md +crm-node_modules.tgz diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml new file mode 100644 index 0000000..91ad123 --- /dev/null +++ b/.gitea/workflows/build.yml @@ -0,0 +1,124 @@ +name: Build & Push Docker Image + +on: + push: + tags: + - "*" + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Start time + run: echo "BUILD_STARTED=$(date +%s)" >> "$GITHUB_ENV" + + - name: Free disk space + id: prune + run: | + df -h / /workspace /var/lib/containerd 2>/dev/null || df -h / + docker builder prune -af || true + docker image prune -af || true + docker system prune -af --volumes || true + df -h / /workspace /var/lib/containerd 2>/dev/null || df -h / + + - name: Checkout code + id: checkout + uses: actions/checkout@v4 + + - name: Resolve image tag + id: meta + run: | + if [ "${GITHUB_REF_TYPE}" = "tag" ]; then + TAG="${GITHUB_REF_NAME}" + else + TAG="$(git rev-parse --short HEAD)" + fi + echo "tag=${TAG}" >> "$GITHUB_OUTPUT" + echo "registry=dock.monsys.ir" >> "$GITHUB_OUTPUT" + + - name: Login to registry + id: login + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + run: | + USER_NAME="${REGISTRY_USERNAME:-admin}" + printf '%s\n' "$REGISTRY_PASSWORD" | docker login "dock.monsys.ir" -u "$USER_NAME" --password-stdin + + - name: Build Docker images + id: build + run: | + set -eu + tag="${{ steps.meta.outputs.tag }}" + reg="${{ steps.meta.outputs.registry }}" + docker build -f Dockerfile.api -t "$reg/montact-api:$tag" -t "$reg/montact-api:latest" . + docker build -f Dockerfile.web -t "$reg/montact-web:$tag" -t "$reg/montact-web:latest" . + docker build -f Dockerfile.stt -t "$reg/montact-stt:$tag" -t "$reg/montact-stt:latest" . + + - name: Push Docker images + id: push + run: | + set -eu + tag="${{ steps.meta.outputs.tag }}" + reg="${{ steps.meta.outputs.registry }}" + for name in montact-api montact-web montact-stt; do + docker push "$reg/$name:$tag" + docker push "$reg/$name:latest" + done + + - name: Notify Bale + if: always() + continue-on-error: true + env: + BALE_TOKEN: ${{ secrets.BALE_BOT_TOKEN || vars.BALE_BOT_TOKEN }} + BALE_CHAT_ID: ${{ vars.BALE_CHAT_ID }} + TAG: ${{ steps.meta.outputs.tag }} + REG: ${{ steps.meta.outputs.registry }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }} + STEP_OUTCOMES: | + Checkout code=${{ steps.checkout.outcome }} + Resolve image tag=${{ steps.meta.outcome }} + Login to registry=${{ steps.login.outcome }} + Build Docker images=${{ steps.build.outcome }} + Push Docker images=${{ steps.push.outcome }} + run: | + if [ -z "$BALE_TOKEN" ] || [ -z "$BALE_CHAT_ID" ]; then + echo "BALE_BOT_TOKEN / BALE_CHAT_ID not set in Gitea — skipping notification" + exit 0 + fi + + failed_step=$(printf '%s\n' "$STEP_OUTCOMES" | grep -E '=(failure|cancelled)$' | head -n1 | cut -d= -f1) + if [ -n "$failed_step" ]; then + title="❌ بیلد ناموفق" + elif printf '%s\n' "$STEP_OUTCOMES" | grep -q '^Push Docker images=success$'; then + title="✅ بیلد موفق" + else + title="⚠️ بیلد کامل نشد" + fi + + commit=$(git log -1 --pretty='%h — %s' 2>/dev/null || echo "${GITHUB_SHA:0:7}") + elapsed=$(( $(date +%s) - ${BUILD_STARTED:-$(date +%s)} )) + + text="${title} + پروژه: ${GITHUB_REPOSITORY} + تگ: ${TAG:-${GITHUB_REF_NAME}}" + if [ -z "$failed_step" ] && [ -n "$TAG" ]; then + text="${text} + image: ${REG}/montact-api:${TAG} + image: ${REG}/montact-web:${TAG} + image: ${REG}/montact-stt:${TAG}" + fi + [ -n "$failed_step" ] && text="${text} + مرحلهٔ خطا: ${failed_step}" + text="${text} + کامیت: ${commit} + توسط: ${GITHUB_ACTOR} + مدت: $((elapsed / 60))m$((elapsed % 60))s + لاگ: ${RUN_URL}" + msg_file=$(mktemp) + printf '%s\n' "$text" | sed 's/^[[:space:]]*//' > "$msg_file" + + curl -sS -m 20 -X POST "https://tapi.bale.ai/bot${BALE_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${BALE_CHAT_ID}" \ + --data-urlencode "text@${msg_file}" diff --git a/Dockerfile.api b/Dockerfile.api new file mode 100644 index 0000000..adfa0b9 --- /dev/null +++ b/Dockerfile.api @@ -0,0 +1,29 @@ +# NestJS API + Prisma. Build context is the monorepo root. +FROM node:20-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +COPY apps/api/package.json apps/api/package.json +COPY apps/web/package.json apps/web/package.json +COPY packages/shared/package.json packages/shared/package.json +RUN npm ci +COPY apps/api apps/api +COPY packages/shared packages/shared +RUN npm run build -w @mento/shared \ + && npm run prisma:generate -w @mento/api \ + && npm run build -w @mento/api + +FROM node:20-bookworm-slim +WORKDIR /app +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +COPY --from=build /app/package.json /app/package-lock.json ./ +COPY --from=build /app/node_modules ./node_modules +COPY --from=build /app/packages/shared ./packages/shared +COPY --from=build /app/apps/api/package.json ./apps/api/package.json +COPY --from=build /app/apps/api/dist ./apps/api/dist +COPY --from=build /app/apps/api/prisma ./apps/api/prisma +WORKDIR /app/apps/api +ENV NODE_ENV=production +EXPOSE 3000 +CMD ["node", "dist/src/main.js"] diff --git a/Dockerfile.stt b/Dockerfile.stt new file mode 100644 index 0000000..781fe44 --- /dev/null +++ b/Dockerfile.stt @@ -0,0 +1,15 @@ +# Local Faster-Whisper. Not published on Ingress. +FROM python:3.11-slim-bookworm +RUN apt-get update \ + && apt-get install -y --no-install-recommends ffmpeg \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY apps/stt/requirements.txt ./requirements.txt +RUN pip install --no-cache-dir -r requirements.txt +COPY apps/stt/main.py ./main.py +ENV STT_MODEL=small \ + STT_DEVICE=cpu \ + STT_COMPUTE_TYPE=int8 \ + HF_HOME=/models +EXPOSE 3040 +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3040"] diff --git a/Dockerfile.web b/Dockerfile.web new file mode 100644 index 0000000..e5c127a --- /dev/null +++ b/Dockerfile.web @@ -0,0 +1,16 @@ +# Vue panel. The built app calls /api on the same host; Traefik sends that to the API. +FROM node:20-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +COPY apps/api/package.json apps/api/package.json +COPY apps/web/package.json apps/web/package.json +COPY packages/shared/package.json packages/shared/package.json +RUN npm ci +COPY apps/web apps/web +COPY packages/shared packages/shared +RUN npm run build -w @mento/shared && npm run build -w @mento/web + +FROM nginx:1.27-alpine +COPY docker/web.nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/apps/web/dist /usr/share/nginx/html +EXPOSE 80 diff --git a/docker/web.nginx.conf b/docker/web.nginx.conf new file mode 100644 index 0000000..8e047e5 --- /dev/null +++ b/docker/web.nginx.conf @@ -0,0 +1,11 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + client_max_body_size 50m; + + location / { + try_files $uri $uri/ /index.html; + } +} From 0ca9540524dcf8673b40a4f8e85b6c6be72fb747 Mon Sep 17 00:00:00 2001 From: mahmood Date: Thu, 5 Nov 2026 19:53:52 +0330 Subject: [PATCH 02/62] Fix change build level for test docker build --- .gitea/workflows/build.yml | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 91ad123..0e42e95 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -37,15 +37,6 @@ jobs: echo "tag=${TAG}" >> "$GITHUB_OUTPUT" echo "registry=dock.monsys.ir" >> "$GITHUB_OUTPUT" - - name: Login to registry - id: login - env: - REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} - REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} - run: | - USER_NAME="${REGISTRY_USERNAME:-admin}" - printf '%s\n' "$REGISTRY_PASSWORD" | docker login "dock.monsys.ir" -u "$USER_NAME" --password-stdin - - name: Build Docker images id: build run: | @@ -56,8 +47,22 @@ jobs: docker build -f Dockerfile.web -t "$reg/montact-web:$tag" -t "$reg/montact-web:latest" . docker build -f Dockerfile.stt -t "$reg/montact-stt:$tag" -t "$reg/montact-stt:latest" . + # Registry login is unsolved. These two steps stay off so a tag run + # only proves the three images build. Remove `if: false` on both when + # dock.monsys.ir accepts the runner. + - name: Login to registry + id: login + if: false + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + run: | + USER_NAME="${REGISTRY_USERNAME:-admin}" + printf '%s\n' "$REGISTRY_PASSWORD" | docker login "dock.monsys.ir" -u "$USER_NAME" --password-stdin + - name: Push Docker images id: push + if: false run: | set -eu tag="${{ steps.meta.outputs.tag }}" @@ -79,8 +84,8 @@ jobs: STEP_OUTCOMES: | Checkout code=${{ steps.checkout.outcome }} Resolve image tag=${{ steps.meta.outcome }} - Login to registry=${{ steps.login.outcome }} Build Docker images=${{ steps.build.outcome }} + Login to registry=${{ steps.login.outcome }} Push Docker images=${{ steps.push.outcome }} run: | if [ -z "$BALE_TOKEN" ] || [ -z "$BALE_CHAT_ID" ]; then @@ -93,6 +98,8 @@ jobs: title="❌ بیلد ناموفق" elif printf '%s\n' "$STEP_OUTCOMES" | grep -q '^Push Docker images=success$'; then title="✅ بیلد موفق" + elif printf '%s\n' "$STEP_OUTCOMES" | grep -q '^Build Docker images=success$'; then + title="✅ بیلد موفق؛ پوش رجیستری هنوز خاموش است" else title="⚠️ بیلد کامل نشد" fi From 21d2c69227ea330f8be46af4dd6e8cbd1052d3dc Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sat, 7 Nov 2026 11:02:47 +0330 Subject: [PATCH 03/62] feat(leads): expand filters and tidy the list chrome on mobile Owners can filter by assignee and follow-up status, with extra filters in a drawer, while mobile keeps a compact search-and-filter bar without the stage chip grid. Co-authored-by: Cursor --- apps/api/src/leads/leads.controller.ts | 16 + apps/api/src/leads/leads.service.ts | 69 +++ apps/web/src/views/LeadsView.vue | 631 +++++++++++++++++++------ 3 files changed, 580 insertions(+), 136 deletions(-) diff --git a/apps/api/src/leads/leads.controller.ts b/apps/api/src/leads/leads.controller.ts index c346ed1..ffa4310 100644 --- a/apps/api/src/leads/leads.controller.ts +++ b/apps/api/src/leads/leads.controller.ts @@ -246,7 +246,11 @@ export class LeadsController { @Query('source') source?: string, @Query('unassigned') unassigned?: string, @Query('archived') archived?: string, + @Query('converted') converted?: string, @Query('hasMobile') hasMobile?: string, + @Query('followUp') followUp?: string, + @Query('createdFrom') createdFrom?: string, + @Query('createdTo') createdTo?: string, ) { return this.leads.listIds(user, { q, @@ -258,7 +262,11 @@ export class LeadsController { source, unassigned: unassigned === '1' || unassigned === 'true', archived: archived === '1' || archived === 'true', + converted: converted === '1' || converted === 'true', hasMobile: hasMobile === '1' || hasMobile === 'true', + followUp, + createdFrom, + createdTo, }); } @@ -276,8 +284,12 @@ export class LeadsController { @Query('source') source?: string, @Query('unassigned') unassigned?: string, @Query('archived') archived?: string, + @Query('converted') converted?: string, @Query('sort') sort?: string, @Query('hasMobile') hasMobile?: string, + @Query('followUp') followUp?: string, + @Query('createdFrom') createdFrom?: string, + @Query('createdTo') createdTo?: string, ) { return this.leads.list(user, { q, @@ -291,8 +303,12 @@ export class LeadsController { source, unassigned: unassigned === '1' || unassigned === 'true', archived: archived === '1' || archived === 'true', + converted: converted === '1' || converted === 'true', sort, hasMobile: hasMobile === '1' || hasMobile === 'true', + followUp, + createdFrom, + createdTo, }); } diff --git a/apps/api/src/leads/leads.service.ts b/apps/api/src/leads/leads.service.ts index 29dcfc0..aa125cd 100644 --- a/apps/api/src/leads/leads.service.ts +++ b/apps/api/src/leads/leads.service.ts @@ -49,6 +49,12 @@ import { StorageQuotaService } from '../billing/storage-quota.service'; import { LeadStagesService } from './lead-stages.service'; import { buildSearchWhere, ci } from '../common/search'; import { GamificationService } from '../gamification/gamification.service'; +import { + addDays, + isDayKey, + tehranDayKey, + tehranDayStart, +} from '../routines/routine-dates'; const LOGO_MAX_BYTES = 2 * 1024 * 1024; const LOGO_EXT: Record = { @@ -142,7 +148,11 @@ export class LeadsService { source?: string; unassigned?: boolean; archived?: boolean; + converted?: boolean; hasMobile?: boolean; + followUp?: string; + createdFrom?: string; + createdTo?: string; }, ): Prisma.LeadWhereInput { const search = buildSearchWhere(opts.q, (t) => [ @@ -161,10 +171,15 @@ export class LeadsService { if (opts.hasMobile) { and.push({ mobile: { not: '' } }); } + const follow = this.followUpWhere(opts.followUp); + if (follow) and.push(follow); + const createdRange = this.createdAtWhere(opts.createdFrom, opts.createdTo); + if (createdRange) and.push(createdRange); return { organizationId: actor.organizationId, ...leadAccessWhere(actor), archivedAt: opts.archived ? { not: null } : null, + ...(opts.converted ? { convertedPersonId: { not: null } } : {}), ...(opts.stageId ? { stageId: opts.stageId } : {}), ...(opts.assigneeId ? { assigneeId: opts.assigneeId } : {}), ...(opts.unassigned ? { assigneeId: null } : {}), @@ -180,6 +195,52 @@ export class LeadsService { }; } + /** مرز روز به وقت تهران برای فیلترهای «امروز». */ + private tehranDayBounds(day = tehranDayKey()) { + const start = tehranDayStart(day); + const end = tehranDayStart(addDays(day, 1)); + return { start, end }; + } + + private followUpWhere(followUp?: string): Prisma.LeadWhereInput | null { + if (!followUp) return null; + const { start, end } = this.tehranDayBounds(); + switch (followUp) { + case 'due_today': + return { nextFollowUpAt: { gte: start, lt: end } }; + case 'overdue': + return { nextFollowUpAt: { not: null, lt: start } }; + case 'called_today': + return { lastContactAt: { gte: start, lt: end } }; + case 'missed_today': + return { + nextFollowUpAt: { not: null, lt: end }, + OR: [{ lastContactAt: null }, { lastContactAt: { lt: start } }], + }; + case 'no_follow_up': + return { nextFollowUpAt: null }; + default: + return null; + } + } + + private createdAtWhere( + createdFrom?: string, + createdTo?: string, + ): Prisma.LeadWhereInput | null { + const from = isDayKey(createdFrom) ? tehranDayStart(createdFrom) : null; + const to = isDayKey(createdTo) + ? tehranDayStart(addDays(createdTo, 1)) + : null; + if (!from && !to) return null; + return { + createdAt: { + ...(from ? { gte: from } : {}), + ...(to ? { lt: to } : {}), + }, + }; + } + async list( actor: Actor, opts: { @@ -194,8 +255,12 @@ export class LeadsService { source?: string; unassigned?: boolean; archived?: boolean; + converted?: boolean; sort?: string; hasMobile?: boolean; + followUp?: string; + createdFrom?: string; + createdTo?: string; }, ): Promise> { await this.stages.ensureDefaults(actor.organizationId); @@ -243,7 +308,11 @@ export class LeadsService { source?: string; unassigned?: boolean; archived?: boolean; + converted?: boolean; hasMobile?: boolean; + followUp?: string; + createdFrom?: string; + createdTo?: string; }, max = FILTERED_IDS_MAX, ): Promise { diff --git a/apps/web/src/views/LeadsView.vue b/apps/web/src/views/LeadsView.vue index 716a2a7..72b0e6e 100644 --- a/apps/web/src/views/LeadsView.vue +++ b/apps/web/src/views/LeadsView.vue @@ -5,10 +5,12 @@ import axios from 'axios'; import { Alert as AAlert, Avatar as AAvatar, + Badge as ABadge, Button as AButton, Card as ACard, Checkbox as ACheckbox, Col as ACol, + Drawer as ADrawer, Dropdown as ADropdown, Empty as AEmpty, Flex as AFlex, @@ -48,7 +50,6 @@ import { PlusOutlined, SearchOutlined, UnorderedListOutlined, - UserOutlined, } from '@ant-design/icons-vue'; import { api } from '@/lib/api'; import { @@ -61,6 +62,7 @@ import { canManageSettings } from '@/lib/roles'; import { canAssignToOthers } from '@/lib/assign-access'; import { registerTableColumns, useTableColumns } from '@/lib/tableColumns'; import TableColumnsMenu from '@/components/TableColumnsMenu.vue'; +import JalaliDateInput from '@/components/JalaliDateInput.vue'; import ExcelImportFlow from '@/components/ExcelImportFlow.vue'; import PhoneContactsImport from '@/components/PhoneContactsImport.vue'; import { @@ -92,8 +94,25 @@ const isMobile = computed(() => !screens.value.md); const PAGE_SIZE = 10; type SortKey = 'updated' | 'newest' | 'follow_up' | 'last_contact'; +type FollowUpKey = + | '' + | 'due_today' + | 'overdue' + | 'called_today' + | 'missed_today' + | 'no_follow_up'; type StageTint = 'mint' | 'amber' | 'peach' | 'sky' | 'violet' | 'rose' | 'teal'; +const FOLLOW_UP_OPTIONS: Array<{ value: FollowUpKey; label: string }> = [ + { value: '', label: 'همه پیگیری‌ها' }, + { value: 'due_today', label: 'قرار امروز' }, + { value: 'overdue', label: 'عقب‌افتاده' }, + { value: 'called_today', label: 'امروز تماس گرفته' }, + { value: 'missed_today', label: 'امروز باید می‌گرفت و نگرفته' }, + { value: 'no_follow_up', label: 'بدون پیگیری' }, +]; +const UNASSIGNED_VALUE = '__unassigned__'; + /** ردیف آمار صفحه لیدها — ترتیب و نام‌ها مطابق طرح */ const LEAD_STAT_DEFS: Array<{ label: string; @@ -162,8 +181,11 @@ const stages = ref([]); const stats = ref(null); const users = ref([]); const cityOptions = ref([]); +const regionOptions = ref([]); +const tradeOptions = ref([]); const sourceOptions = ref([]); const selected = ref>(new Set()); +const moreFiltersOpen = ref(false); const sortOpen = ref(false); const rowMenuId = ref(null); const logoMenuId = ref(null); @@ -235,12 +257,70 @@ const assigneeId = computed(() => const cityFilter = computed(() => typeof route.query.city === 'string' ? route.query.city : '', ); +const regionFilter = computed(() => + typeof route.query.region === 'string' ? route.query.region : '', +); +const tradeFilter = computed(() => + typeof route.query.trade === 'string' ? route.query.trade : '', +); const sourceFilter = computed(() => typeof route.query.source === 'string' ? route.query.source : '', ); +const followUpFilter = computed(() => { + const value = route.query.followUp; + if ( + value === 'due_today' || + value === 'overdue' || + value === 'called_today' || + value === 'missed_today' || + value === 'no_follow_up' + ) { + return value; + } + return ''; +}); +const createdFromFilter = computed(() => + typeof route.query.createdFrom === 'string' ? route.query.createdFrom : '', +); +const createdToFilter = computed(() => + typeof route.query.createdTo === 'string' ? route.query.createdTo : '', +); const unassigned = computed( () => route.query.unassigned === '1' || route.query.unassigned === 'true', ); +const archivedFilter = computed( + () => route.query.archived === '1' || route.query.archived === 'true', +); +const convertedFilter = computed( + () => route.query.converted === '1' || route.query.converted === 'true', +); +const assigneeSelectValue = computed(() => { + if (unassigned.value) return UNASSIGNED_VALUE; + return assigneeId.value || undefined; +}); +const moreFiltersCount = computed(() => + [ + cityFilter.value, + regionFilter.value, + tradeFilter.value, + sourceFilter.value, + createdFromFilter.value, + createdToFilter.value, + archivedFilter.value ? '1' : '', + convertedFilter.value ? '1' : '', + ].filter(Boolean).length, +); +/** در موبایل مرتب‌سازی و مسئول و پیگیری هم داخل کشو هستند. */ +const mobileFilterBadgeCount = computed(() => { + const extra = isMobile.value + ? [ + sort.value !== 'updated' ? '1' : '', + assigneeSelectValue.value ? '1' : '', + followUpFilter.value, + ].filter(Boolean).length + : 0; + return moreFiltersCount.value + extra; +}); const total = computed(() => data.value?.total ?? 0); const pageCount = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE))); @@ -514,14 +594,79 @@ function setStageFilter(id: string) { patchQuery({ stageId: id || undefined, page: undefined }); } +function setAssigneeFilter(value: string | undefined) { + if (value === UNASSIGNED_VALUE) { + patchQuery({ assigneeId: undefined, unassigned: '1', page: undefined }); + return; + } + patchQuery({ + assigneeId: value || undefined, + unassigned: undefined, + page: undefined, + }); +} + +function setFollowUpFilter(value: string | undefined) { + patchQuery({ + followUp: value || undefined, + page: undefined, + }); +} + function setCityFilter(value: string) { patchQuery({ city: value || undefined, page: undefined }); } +function setRegionFilter(value: string) { + patchQuery({ region: value || undefined, page: undefined }); +} + +function setTradeFilter(value: string) { + patchQuery({ trade: value || undefined, page: undefined }); +} + function setSourceFilter(value: string) { patchQuery({ source: value || undefined, page: undefined }); } +function setCreatedFromFilter(value: string) { + patchQuery({ createdFrom: value || undefined, page: undefined }); +} + +function setCreatedToFilter(value: string) { + patchQuery({ createdTo: value || undefined, page: undefined }); +} + +function setArchivedFilter(checked: boolean) { + patchQuery({ archived: checked ? '1' : undefined, page: undefined }); +} + +function setConvertedFilter(checked: boolean) { + patchQuery({ converted: checked ? '1' : undefined, page: undefined }); +} + +function clearMoreFilters() { + patchQuery({ + city: undefined, + region: undefined, + trade: undefined, + source: undefined, + createdFrom: undefined, + createdTo: undefined, + archived: undefined, + converted: undefined, + ...(isMobile.value + ? { + sort: undefined, + assigneeId: undefined, + unassigned: undefined, + followUp: undefined, + } + : {}), + page: undefined, + }); +} + function setPage(next: number) { if (next < 1 || next > pageCount.value) return; patchQuery({ page: next === 1 ? undefined : String(next) }); @@ -594,12 +739,18 @@ function onCardClick(lead: LeadDto) { function mergeFacets(items: LeadDto[]) { const cities = new Set(cityOptions.value); + const regions = new Set(regionOptions.value); + const trades = new Set(tradeOptions.value); const sources = new Set(sourceOptions.value); for (const lead of items) { if (lead.city?.trim()) cities.add(lead.city.trim()); + if (lead.region?.trim()) regions.add(lead.region.trim()); + if (lead.trade?.trim()) trades.add(lead.trade.trim()); if (lead.source?.trim()) sources.add(lead.source.trim()); } cityOptions.value = [...cities].sort((a, b) => a.localeCompare(b, 'fa')); + regionOptions.value = [...regions].sort((a, b) => a.localeCompare(b, 'fa')); + tradeOptions.value = [...trades].sort((a, b) => a.localeCompare(b, 'fa')); sourceOptions.value = [...sources].sort((a, b) => a.localeCompare(b, 'fa')); } @@ -631,8 +782,15 @@ async function load() { stageId: stageId.value || undefined, assigneeId: assigneeId.value || undefined, city: cityFilter.value || undefined, + region: regionFilter.value || undefined, + trade: tradeFilter.value || undefined, source: sourceFilter.value || undefined, unassigned: unassigned.value ? '1' : undefined, + archived: archivedFilter.value ? '1' : undefined, + converted: convertedFilter.value ? '1' : undefined, + followUp: followUpFilter.value || undefined, + createdFrom: createdFromFilter.value || undefined, + createdTo: createdToFilter.value || undefined, }, }); data.value = res; @@ -1114,8 +1272,15 @@ watch( route.query.stageId, route.query.assigneeId, route.query.city, + route.query.region, + route.query.trade, route.query.source, route.query.unassigned, + route.query.archived, + route.query.converted, + route.query.followUp, + route.query.createdFrom, + route.query.createdTo, ], () => { q.value = typeof route.query.q === 'string' ? route.query.q : ''; @@ -1181,176 +1346,370 @@ onBeforeUnmount(() => { + +

{{ error }}

{{ ok }}

- -

- سانترال یا سرویس VoIP شما باید رویداد تماس را با JSON به آدرس وب‌هوک بفرستد. - فیلدهای اصلی: - callId، - direction (inbound/outbound)، - status، - from، - to. - برای خلاصه خودکار یکی از - recordingUrl - (لینک فایل ضبط) یا - transcript - (متن آماده) را بفرستید؛ پس از - completed - / - answered - صف خلاصه ساخته می‌شود. - امضا اختیاری با هدر - X-Voip-Signature - (HMAC-SHA256 هگز). -

-
- - - - - - - - - -
- ذخیره اتصال -
+ + + { display: grid; gap: 1rem; } +.tabs { + display: flex; + justify-content: flex-start; + gap: 1.75rem; + border-bottom: 1px solid #e2e8f0; +} +.tabs button { + appearance: none; + background: none; + border: 0; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + padding: 0.55rem 0.15rem; + color: #94a3b8; + font: inherit; + font-weight: 600; + cursor: pointer; +} +.tabs button.on { + color: #0d9488; + border-bottom-color: #14b8a6; +} .hint, .muted { color: #64748b; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 182f11d..c4dfcc9 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -5511,13 +5511,21 @@ export type VoipCallStatus = | "completed" | "failed"; +export type VoipProvider = "generic" | "daftareshoma"; + export interface VoipConnectionDto { id: string; label: string; + provider: VoipProvider; enabled: boolean; webhookSecretSet: boolean; + apiTokenSet: boolean; /** قالب URL برای شروع تماس؛ {number} جایگزین می‌شود */ clickToCallUrl: string | null; + /** شماره مبدأ تماس خروجی (دفتر شما) */ + fromNumber: string | null; + /** خط/داخلی سازمان (دفتر شما) */ + callerExtension: string | null; lastEventAt: string | null; lastError: string | null; callCount: number; @@ -5527,8 +5535,13 @@ export interface VoipConnectionDto { export interface CreateVoipConnectionRequest { label: string; + provider?: VoipProvider; webhookSecret?: string; clickToCallUrl?: string | null; + /** توکن Bearer API دفتر شما */ + apiToken?: string; + fromNumber?: string | null; + callerExtension?: string | null; enabled?: boolean; } @@ -5536,6 +5549,9 @@ export interface UpdateVoipConnectionRequest { label?: string; webhookSecret?: string | null; clickToCallUrl?: string | null; + apiToken?: string | null; + fromNumber?: string | null; + callerExtension?: string | null; enabled?: boolean; } From f36711174e036348753b84731d3e51631b0bcdf7 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sat, 7 Nov 2026 13:58:42 +0330 Subject: [PATCH 05/62] feat(voip): make Daftaresoma setup inbound-first and filter calls by line Drop required from_number for webhook logging, persist CalleeExtension as lineExtension, and add direction/status/line filters on the calls list. Co-authored-by: Cursor --- .../migration.sql | 8 ++ apps/api/prisma/schema.prisma | 4 + .../src/integrations/voip/calls.service.ts | 24 +++- .../integrations/voip/connections.service.ts | 9 +- .../integrations/voip/daftareshoma-webhook.ts | 32 +++-- .../src/integrations/voip/voip.controller.ts | 10 +- apps/web/src/views/VoipSettingsView.vue | 127 +++++++++++++++--- packages/shared/src/index.ts | 4 + 8 files changed, 176 insertions(+), 42 deletions(-) create mode 100644 apps/api/prisma/migrations/20261107140000_voip_call_line_extension/migration.sql diff --git a/apps/api/prisma/migrations/20261107140000_voip_call_line_extension/migration.sql b/apps/api/prisma/migrations/20261107140000_voip_call_line_extension/migration.sql new file mode 100644 index 0000000..7045074 --- /dev/null +++ b/apps/api/prisma/migrations/20261107140000_voip_call_line_extension/migration.sql @@ -0,0 +1,8 @@ +-- AlterTable +ALTER TABLE "VoipCallLog" ADD COLUMN "lineExtension" TEXT; + +-- CreateIndex +CREATE INDEX "VoipCallLog_organizationId_lineExtension_idx" ON "VoipCallLog"("organizationId", "lineExtension"); + +-- CreateIndex +CREATE INDEX "VoipCallLog_organizationId_status_idx" ON "VoipCallLog"("organizationId", "status"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 77de609..f4afa3a 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -2997,6 +2997,8 @@ model VoipCallLog { status String @default("completed") fromNumber String? toNumber String? + /// خط/داخلی سازمان که تماس روی آن بوده (مثلاً CalleeExtension دفتر شما) + lineExtension String? personId String? activityId String? durationSec Int? @@ -3021,6 +3023,8 @@ model VoipCallLog { @@unique([connectionId, externalCallId]) @@index([organizationId, syncedAt]) + @@index([organizationId, lineExtension]) + @@index([organizationId, status]) @@index([personId]) @@index([activityId]) @@index([summaryStatus, summaryNextAttemptAt]) diff --git a/apps/api/src/integrations/voip/calls.service.ts b/apps/api/src/integrations/voip/calls.service.ts index ccc7f24..97bc54a 100644 --- a/apps/api/src/integrations/voip/calls.service.ts +++ b/apps/api/src/integrations/voip/calls.service.ts @@ -67,15 +67,27 @@ export class VoipCallsService { async listRecent( organizationId: string, - connectionId?: string, + opts?: { + connectionId?: string; + direction?: string; + status?: string; + lineExtension?: string; + }, ): Promise { const rows = await this.prisma.voipCallLog.findMany({ where: { organizationId, - ...(connectionId ? { connectionId } : {}), + ...(opts?.connectionId ? { connectionId: opts.connectionId } : {}), + ...(opts?.direction === 'inbound' || opts?.direction === 'outbound' + ? { direction: opts.direction } + : {}), + ...(opts?.status?.trim() ? { status: opts.status.trim() } : {}), + ...(opts?.lineExtension?.trim() + ? { lineExtension: opts.lineExtension.trim() } + : {}), }, orderBy: { syncedAt: 'desc' }, - take: 50, + take: 100, }); const personIds = rows .map((r) => r.personId) @@ -97,6 +109,7 @@ export class VoipCallsService { status: r.status, fromNumber: r.fromNumber, toNumber: r.toNumber, + lineExtension: r.lineExtension ?? null, personId: r.personId, personName: r.personId ? (nameById.get(r.personId) ?? null) : null, activityId: r.activityId, @@ -133,6 +146,9 @@ export class VoipCallsService { const toDigits = digitsOnly(event.to ?? event.callee); const fromNumber = fromNormalized || fromDigits || null; const toNumber = toNormalized || toDigits || null; + const lineRaw = String(event.lineExtension ?? '').trim(); + const lineExtension = + normalizePhone(lineRaw) || digitsOnly(lineRaw) || lineRaw || null; const matchNumber = direction === 'inbound' ? fromNumber : toNumber; const personId = await this.findPersonId( conn.organizationId, @@ -199,6 +215,7 @@ export class VoipCallsService { status, fromNumber, toNumber, + lineExtension: lineExtension ?? existing.lineExtension, personId: personId ?? existing.personId, activityId: activityId ?? existing.activityId, durationSec, @@ -219,6 +236,7 @@ export class VoipCallsService { status, fromNumber, toNumber, + lineExtension, personId, activityId, durationSec, diff --git a/apps/api/src/integrations/voip/connections.service.ts b/apps/api/src/integrations/voip/connections.service.ts index e52efda..6fc17b4 100644 --- a/apps/api/src/integrations/voip/connections.service.ts +++ b/apps/api/src/integrations/voip/connections.service.ts @@ -52,14 +52,7 @@ export class VoipConnectionsService { if (provider === 'daftareshoma') { const token = dto.apiToken?.trim(); if (!token) throw new BadRequestException('توکن API دفتر شما الزامی است'); - if (!dto.callerExtension?.trim()) { - throw new BadRequestException('خط / داخلی سازمان الزامی است'); - } - if (!dto.fromNumber?.trim()) { - throw new BadRequestException( - 'شماره مبدأ (from_number) برای تماس خروجی الزامی است', - ); - } + // fromNumber / callerExtension فقط برای تماس خروجی از CRM لازم‌اند؛ ثبت وب‌هوک بدون آن‌ها ممکن است } const secret = dto.webhookSecret?.trim(); diff --git a/apps/api/src/integrations/voip/daftareshoma-webhook.ts b/apps/api/src/integrations/voip/daftareshoma-webhook.ts index 054e1c1..b432140 100644 --- a/apps/api/src/integrations/voip/daftareshoma-webhook.ts +++ b/apps/api/src/integrations/voip/daftareshoma-webhook.ts @@ -76,16 +76,17 @@ export function mapDaftaresomaWebhook( 'From', 'fromNumber', ); - const callee = pick( + /** خط سازمانی که تماس روی آن آمده/رفته */ + const lineExtension = + pick(obj, 'CalleeExtension', 'calleeExtension', 'Extension', 'extension') || + undefined; + /** مقصد انتقال / شماره طرف مقابل روی خط */ + const transferred = pick( obj, 'TransferredToNumber', 'transferredToNumber', - 'CalleeExtension', - 'calleeExtension', - 'to', - 'To', - 'toNumber', ); + const startedAt = pick(obj, 'StartDateTime', 'startDateTime', 'startedAt') || undefined; const endedAt = @@ -128,17 +129,28 @@ export function mapDaftaresomaWebhook( 'recordId', ); + // inbound: from=مشتری، to=همکار/مقصد انتقال یا خود خط + // outbound: from=همکار، to=مشتری (TransferredToNumber) + let from = caller || undefined; + let to: string | undefined; + if (isOutbound) { + to = transferred || undefined; + } else { + to = transferred || lineExtension || undefined; + } + const event: VoipWebhookEvent = { callId, direction: isOutbound ? 'outbound' : 'inbound', status, - from: caller || undefined, - to: callee || undefined, + from, + to, + lineExtension, startedAt, endedAt, durationSec, - caller: caller || undefined, - callee: callee || undefined, + caller: from, + callee: to, }; if (recordingId) { event.recordingUrl = daftareshomaRecordingRef(recordingId); diff --git a/apps/api/src/integrations/voip/voip.controller.ts b/apps/api/src/integrations/voip/voip.controller.ts index bb2e7af..4835d82 100644 --- a/apps/api/src/integrations/voip/voip.controller.ts +++ b/apps/api/src/integrations/voip/voip.controller.ts @@ -82,8 +82,16 @@ export class VoipController { recent( @CurrentUser() user: { organizationId: string }, @Query('connectionId') connectionId?: string, + @Query('direction') direction?: string, + @Query('status') status?: string, + @Query('lineExtension') lineExtension?: string, ) { - return this.calls.listRecent(user.organizationId, connectionId); + return this.calls.listRecent(user.organizationId, { + connectionId, + direction, + status, + lineExtension, + }); } @Post('click-to-call') diff --git a/apps/web/src/views/VoipSettingsView.vue b/apps/web/src/views/VoipSettingsView.vue index 9762ea2..57e54d6 100644 --- a/apps/web/src/views/VoipSettingsView.vue +++ b/apps/web/src/views/VoipSettingsView.vue @@ -29,6 +29,11 @@ const ok = ref(''); const items = ref([]); const calls = ref([]); const tab = ref('daftareshoma'); +const callFilters = reactive({ + direction: '', + status: '', + lineExtension: '', +}); const form = reactive({ label: 'سانترال اصلی', @@ -54,6 +59,16 @@ const daftaItems = computed(() => const activeDafta = computed(() => daftaItems.value[0] ?? null); +const knownLines = ref([]); +const lineOptions = computed(() => { + const set = new Set(knownLines.value); + for (const c of calls.value) { + if (c.lineExtension) set.add(c.lineExtension); + } + if (callFilters.lineExtension) set.add(callFilters.lineExtension); + return [...set].sort(); +}); + const webhookUrlFor = (id: string | undefined) => { if (!id) return ''; const origin = typeof window !== 'undefined' ? window.location.origin : ''; @@ -88,16 +103,31 @@ function noteLink(c: VoipCallLogDto): string | null { return '/notes'; } +async function loadCalls() { + const params: Record = {}; + if (callFilters.direction) params.direction = callFilters.direction; + if (callFilters.status) params.status = callFilters.status; + if (callFilters.lineExtension) params.lineExtension = callFilters.lineExtension; + const callRes = await api.get('/integrations/voip/calls', { + params, + }); + calls.value = callRes.data; + const merged = new Set(knownLines.value); + for (const c of callRes.data) { + if (c.lineExtension) merged.add(c.lineExtension); + } + knownLines.value = [...merged].sort(); +} + async function load() { loading.value = true; error.value = ''; try { - const [connRes, callRes] = await Promise.all([ + const [connRes] = await Promise.all([ api.get('/integrations/voip/connections'), - api.get('/integrations/voip/calls'), + loadCalls(), ]); items.value = connRes.data; - calls.value = callRes.data; fillDaftaFromActive(); } catch (e) { if (axios.isAxiosError(e) && e.response?.status === 403) { @@ -110,6 +140,18 @@ async function load() { } } +async function applyCallFilters() { + loading.value = true; + error.value = ''; + try { + await loadCalls(); + } catch { + error.value = 'فیلتر تماس‌ها ناموفق بود.'; + } finally { + loading.value = false; + } +} + async function createGeneric() { if (!form.label.trim()) { error.value = 'نام اتصال را وارد کنید.'; @@ -148,10 +190,6 @@ async function saveDafta() { error.value = 'توکن API دفتر شما را وارد کنید.'; return; } - if (!daftaForm.fromNumber.trim() || !daftaForm.callerExtension.trim()) { - error.value = 'شماره مبدأ و خط / داخلی را وارد کنید.'; - return; - } saving.value = true; error.value = ''; ok.value = ''; @@ -159,8 +197,8 @@ async function saveDafta() { if (activeDafta.value) { await api.patch(`/integrations/voip/connections/${activeDafta.value.id}`, { label: daftaForm.label.trim(), - fromNumber: daftaForm.fromNumber.trim(), - callerExtension: daftaForm.callerExtension.trim(), + fromNumber: daftaForm.fromNumber.trim() || null, + callerExtension: daftaForm.callerExtension.trim() || null, enabled: daftaForm.enabled, ...(daftaForm.apiToken.trim() ? { apiToken: daftaForm.apiToken.trim() } @@ -173,8 +211,8 @@ async function saveDafta() { label: daftaForm.label.trim(), provider: 'daftareshoma', apiToken: daftaForm.apiToken.trim(), - fromNumber: daftaForm.fromNumber.trim(), - callerExtension: daftaForm.callerExtension.trim(), + fromNumber: daftaForm.fromNumber.trim() || null, + callerExtension: daftaForm.callerExtension.trim() || null, enabled: daftaForm.enabled, }; await api.post('/integrations/voip/connections', payload); @@ -265,11 +303,11 @@ onMounted(async () => { +
+ + + + + + + + + +
{ جهت وضعیت + خط از / به مشتری مدت @@ -452,6 +522,7 @@ onMounted(async () => { {{ c.direction === 'outbound' ? 'خروجی' : 'ورودی' }} {{ statusLabel[c.status] ?? c.status }} + {{ c.lineExtension || '—' }} {{ c.fromNumber || '—' }} → {{ c.toNumber || '—' }} {{ c.personName || '—' }} @@ -536,6 +607,21 @@ onMounted(async () => { gap: 0.75rem; margin: 0.75rem 0 1rem; } +.call-filters { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0.75rem; + margin-bottom: 1rem; +} +.filter-select { + width: 100%; + min-height: 36px; + border: 1px solid #e2e8f0; + border-radius: 8px; + padding: 0.35rem 0.6rem; + background: #fff; + font: inherit; +} .list { display: grid; gap: 0.75rem; @@ -628,7 +714,8 @@ th { color: #0f766e; } @media (max-width: 800px) { - .form-grid { + .form-grid, + .call-filters { grid-template-columns: 1fr; } } diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index c4dfcc9..f3fcbc7 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -5569,6 +5569,8 @@ export interface VoipCallLogDto { status: VoipCallStatus | string; fromNumber: string | null; toNumber: string | null; + /** خط/داخلی سازمانی که تماس روی آن بوده */ + lineExtension: string | null; personId: string | null; personName: string | null; activityId: string | null; @@ -5595,6 +5597,8 @@ export interface VoipWebhookEvent { status: VoipCallStatus | string; from?: string; to?: string; + /** خط/داخلی سازمان */ + lineExtension?: string; startedAt?: string; endedAt?: string; durationSec?: number; From b8c49293f750983d210838c025f6774f0509da77 Mon Sep 17 00:00:00 2001 From: "m.lotfi" Date: Sun, 8 Nov 2026 06:37:08 +0000 Subject: [PATCH 06/62] Update .gitea/workflows/build.yml Fix build.yml for push to registery --- .gitea/workflows/build.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 0e42e95..767dce7 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -52,7 +52,6 @@ jobs: # dock.monsys.ir accepts the runner. - name: Login to registry id: login - if: false env: REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} @@ -62,7 +61,6 @@ jobs: - name: Push Docker images id: push - if: false run: | set -eu tag="${{ steps.meta.outputs.tag }}" From 97f00d7e6dbca6df74a8f4b43b287ee2918952a2 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 8 Nov 2026 11:49:47 +0330 Subject: [PATCH 07/62] fix(products): open one row menu so edit and other actions run Desktop and mobile dropdowns shared an id, so both opened and the extra menu closed the click before the action. Co-authored-by: Cursor --- apps/web/src/views/ProductsSettingsView.vue | 42 ++++++++++++++------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/apps/web/src/views/ProductsSettingsView.vue b/apps/web/src/views/ProductsSettingsView.vue index 3b8e819..5fcef1b 100644 --- a/apps/web/src/views/ProductsSettingsView.vue +++ b/apps/web/src/views/ProductsSettingsView.vue @@ -411,25 +411,25 @@ onMounted(load); - - + - + @@ -460,25 +460,25 @@ onMounted(load);
- - + - + {{ p.isActive ? 'فعال' : 'غیرفعال' }} @@ -680,6 +680,22 @@ tr:last-child td { .ops { width: 64px; } +.more { + width: 32px; + height: 32px; + border: 0; + background: none; + color: #94a3b8; + border-radius: var(--radius); + display: grid; + place-items: center; + cursor: pointer; + padding: 0; +} +.more:hover { + background: var(--accent-soft); + color: var(--accent); +} .mob-list { display: none; gap: 0.65rem; From 33f33f952150704c9766262504a3d52806a9cea8 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 8 Nov 2026 14:19:35 +0330 Subject: [PATCH 08/62] fix(notes): keep the card menu above the grid The menu was clipped by the card, so the lower actions disappeared under the next row. Co-authored-by: Cursor --- apps/web/src/views/NotesView.vue | 64 +++++++++++--------------------- 1 file changed, 21 insertions(+), 43 deletions(-) diff --git a/apps/web/src/views/NotesView.vue b/apps/web/src/views/NotesView.vue index 82a81bd..c30baac 100644 --- a/apps/web/src/views/NotesView.vue +++ b/apps/web/src/views/NotesView.vue @@ -10,6 +10,7 @@ import NoteCategoriesManager from '@/components/notes/NoteCategoriesManager.vue' import JalaliDateInput from '@/components/JalaliDateInput.vue'; import VoiceToTextButton from '@/components/VoiceToTextButton.vue'; import UiIcon from '@/components/UiIcon.vue'; +import { UiDropdownMenu } from '@/components/ui'; import { appendSpokenText } from '@/lib/spoken-text'; import { canManageSettings } from '@/lib/roles'; import { useAuthStore } from '@/stores/auth'; @@ -721,7 +722,7 @@ function syncMobileFlag() { function onDocClick(ev: MouseEvent) { const t = ev.target as HTMLElement | null; - if (!t?.closest?.('.card-menu')) menuOpenId.value = null; + if (!t?.closest?.('.card-menu, .ui-dd-panel')) menuOpenId.value = null; } watch(typeFilter, () => { @@ -962,27 +963,34 @@ onBeforeUnmount(() => {
- - + +
@@ -1893,36 +1901,6 @@ onBeforeUnmount(() => { position: relative; margin-inline-start: auto; } -.menu-pop { - position: absolute; - inset-inline-end: 0; - top: 100%; - z-index: 5; - background: #fff; - border: 1px solid #e2e8f0; - border-radius: var(--radius); - box-shadow: var(--shadow); - min-width: 140px; - padding: 0.25rem; - display: flex; - flex-direction: column; -} -.menu-pop button { - border: 0; - background: transparent; - text-align: start; - padding: 0.45rem 0.65rem; - border-radius: var(--radius); - cursor: pointer; - font-size: 0.85rem; - color: #334155; -} -.menu-pop button:hover { - background: #f8fafc; -} -.menu-pop .danger { - color: #dc2626; -} .card-title { margin: 0 0 0.35rem; From 6ebd45f2cbf7dfce0a22ab59ec9eff06aef9f602 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 8 Nov 2026 14:20:00 +0330 Subject: [PATCH 09/62] feat(finance): show invoice balances in treasury and split payroll Issued invoices feed debtors, creditors, and period profit without a second income document. Payroll is split into setup, staged payment, and a filtered report. Co-authored-by: Cursor --- apps/api/src/treasury/invoice-ledger.ts | 212 ++++++++ apps/api/src/treasury/treasury-ops.service.ts | 44 +- apps/api/src/treasury/treasury.service.ts | 41 +- apps/web/src/router/index.ts | 6 +- .../src/views/treasury/TreasuryHomeView.vue | 6 +- .../views/treasury/TreasuryPayrollView.vue | 491 ++++++++++++------ .../views/treasury/TreasuryReportsView.vue | 14 +- 7 files changed, 647 insertions(+), 167 deletions(-) create mode 100644 apps/api/src/treasury/invoice-ledger.ts diff --git a/apps/api/src/treasury/invoice-ledger.ts b/apps/api/src/treasury/invoice-ledger.ts new file mode 100644 index 0000000..5101380 --- /dev/null +++ b/apps/api/src/treasury/invoice-ledger.ts @@ -0,0 +1,212 @@ +import { Prisma } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; + +const OPEN_INVOICE_STATUSES = ['issued', 'partially_paid', 'paid'] as const; + +export type InvoicePartyPosition = { + key: string; + partyKind: 'person' | 'company'; + partyName: string; + /** فاکتورهای عادی به‌علاوهٔ ماندهٔ اول دورهٔ مثبت */ + billed: Prisma.Decimal; + /** برگشتی‌ها و اضافه‌دریافت، برای ستون تسویه‌شدهٔ بدهکار */ + offset: Prisma.Decimal; + /** مثبت = طلب ما، منفی = بدهی ما */ + net: Prisma.Decimal; +}; + +type Bucket = { + key: string; + partyKind: 'person' | 'company'; + partyName: string; + sales: Prisma.Decimal; + credits: Prisma.Decimal; + paid: Prisma.Decimal; + opening: Prisma.Decimal; +}; + +function zero() { + return new Prisma.Decimal(0); +} + +function round2(value: Prisma.Decimal) { + return value.toDecimalPlaces(2); +} + +/** همان فرمول ماندهٔ فاکتور: جمع ردیف‌ها − تخفیف + مالیات، برگشتی منفی. */ +export function signedInvoicePayable(invoice: { + kind: string; + discountAmount: Prisma.Decimal; + taxPercent: Prisma.Decimal; + lineItems: Array<{ quantity: Prisma.Decimal; unitPrice: Prisma.Decimal }>; +}) { + const subtotal = invoice.lineItems.reduce( + (sum, line) => sum.plus(line.quantity.mul(line.unitPrice)), + zero(), + ); + const discount = invoice.discountAmount ?? zero(); + const taxable = Prisma.Decimal.max(subtotal.minus(discount), 0); + const tax = taxable.mul(invoice.taxPercent ?? 0).div(100); + const signed = round2(subtotal.minus(discount).plus(tax)); + return invoice.kind === 'credit' ? signed.neg() : signed; +} + +export async function internalBooksEnabled(prisma: PrismaService, organizationId: string) { + const connections = await prisma.accountingConnection.count({ + where: { organizationId, enabled: true }, + }); + return connections === 0; +} + +/** + * ماندهٔ طرف‌حساب از فاکتور صادرشده و ماندهٔ اول دوره. + * سند درآمد جدا ساخته نمی‌شود تا همان فروش دو بار طلب نشود. + * اگر حسابداری بیرونی وصل باشد، خالی برمی‌گردد. + */ +export async function loadInvoicePartyPositions( + prisma: PrismaService, + organizationId: string, +): Promise { + if (!(await internalBooksEnabled(prisma, organizationId))) return []; + + const [invoices, openings] = await Promise.all([ + prisma.invoice.findMany({ + where: { organizationId, status: { in: [...OPEN_INVOICE_STATUSES] } }, + select: { + kind: true, + discountAmount: true, + taxPercent: true, + personId: true, + companyId: true, + person: { select: { firstName: true, lastName: true } }, + company: { select: { name: true } }, + lineItems: { select: { quantity: true, unitPrice: true } }, + payments: { select: { amount: true } }, + }, + }), + prisma.partyOpeningBalance.findMany({ + where: { organizationId }, + select: { + personId: true, + amount: true, + person: { select: { firstName: true, lastName: true } }, + }, + }), + ]); + + const buckets = new Map(); + const ensure = ( + key: string, + partyKind: 'person' | 'company', + partyName: string, + ) => { + const current = buckets.get(key); + if (current) return current; + const created: Bucket = { + key, + partyKind, + partyName, + sales: zero(), + credits: zero(), + paid: zero(), + opening: zero(), + }; + buckets.set(key, created); + return created; + }; + + for (const invoice of invoices) { + const personId = invoice.personId; + const companyId = invoice.companyId; + const party = personId + ? { + key: `person:${personId}`, + partyKind: 'person' as const, + partyName: + `${invoice.person?.firstName ?? ''} ${invoice.person?.lastName ?? ''}`.trim() || + 'مشتری', + } + : companyId + ? { + key: `company:${companyId}`, + partyKind: 'company' as const, + partyName: invoice.company?.name?.trim() || 'شرکت', + } + : null; + if (!party) continue; + const bucket = ensure(party.key, party.partyKind, party.partyName); + const payable = signedInvoicePayable(invoice); + if (payable.greaterThan(0)) bucket.sales = bucket.sales.plus(payable); + else if (payable.lessThan(0)) bucket.credits = bucket.credits.plus(payable.abs()); + const paid = invoice.payments.reduce((sum, row) => sum.plus(row.amount), zero()); + bucket.paid = bucket.paid.plus(paid); + } + + for (const opening of openings) { + if (opening.amount.equals(0)) continue; + const bucket = ensure( + `person:${opening.personId}`, + 'person', + `${opening.person.firstName} ${opening.person.lastName}`.trim() || 'مشتری', + ); + bucket.opening = bucket.opening.plus(opening.amount); + } + + const positions: InvoicePartyPosition[] = []; + for (const bucket of buckets.values()) { + const net = round2( + bucket.opening.plus(bucket.sales).minus(bucket.credits).minus(bucket.paid), + ); + if (net.equals(0)) continue; + const billed = round2(bucket.sales.plus(Prisma.Decimal.max(bucket.opening, 0))); + const offset = round2(billed.minus(net)); + positions.push({ + key: bucket.key, + partyKind: bucket.partyKind, + partyName: bucket.partyName, + billed, + offset: Prisma.Decimal.max(offset, 0), + net, + }); + } + return positions; +} + +/** فروش و برگشتیِ فاکتورهای صادرشده در بازه. وجه نقد را دوباره جمع نمی‌کند. */ +export async function invoiceSalesInPeriod( + prisma: PrismaService, + organizationId: string, + from: Date | null, + to: Date | null, +) { + const empty = { sales: '0.00', credits: '0.00', net: '0.00' }; + if (!(await internalBooksEnabled(prisma, organizationId))) return empty; + + const invoices = await prisma.invoice.findMany({ + where: { organizationId, status: { in: [...OPEN_INVOICE_STATUSES] } }, + select: { + kind: true, + discountAmount: true, + taxPercent: true, + issuedAt: true, + createdAt: true, + lineItems: { select: { quantity: true, unitPrice: true } }, + }, + }); + + let sales = zero(); + let credits = zero(); + for (const invoice of invoices) { + const when = invoice.issuedAt ?? invoice.createdAt; + if (from && when < from) continue; + if (to && when > to) continue; + const payable = signedInvoicePayable(invoice); + if (payable.greaterThan(0)) sales = sales.plus(payable); + else if (payable.lessThan(0)) credits = credits.plus(payable.abs()); + } + return { + sales: round2(sales).toFixed(2), + credits: round2(credits).toFixed(2), + net: round2(sales.minus(credits)).toFixed(2), + }; +} diff --git a/apps/api/src/treasury/treasury-ops.service.ts b/apps/api/src/treasury/treasury-ops.service.ts index 4c1f779..a2595fc 100644 --- a/apps/api/src/treasury/treasury-ops.service.ts +++ b/apps/api/src/treasury/treasury-ops.service.ts @@ -5,6 +5,7 @@ import ExcelJS from 'exceljs'; import type { TreasuryPartyBalanceDto } from '@mento/shared'; import { PrismaService } from '../prisma/prisma.service'; import type { Actor } from '../common/record-scope'; +import { invoiceSalesInPeriod } from './invoice-ledger'; function dec(value: Prisma.Decimal | number | string | null | undefined) { return new Prisma.Decimal(value ?? 0); @@ -36,9 +37,15 @@ export class TreasuryOpsService { async listPayroll(actor: Actor) { const rows = await this.prisma.financialPayroll.findMany({ where: { organizationId: actor.organizationId }, - include: { movements: true }, + include: { + movements: { + where: { voidedAt: null }, + include: { account: { select: { name: true } } }, + orderBy: { occurredAt: 'desc' }, + }, + }, orderBy: { dueDate: 'desc' }, - take: 100, + take: 500, }); const users = await this.prisma.user.findMany({ where: { id: { in: rows.map((row) => row.userId) } }, @@ -88,7 +95,13 @@ export class TreasuryOpsService { notes: input.notes?.trim() || null, createdById: actor.userId, }, - include: { movements: true }, + include: { + movements: { + where: { voidedAt: null }, + include: { account: { select: { name: true } } }, + orderBy: { occurredAt: 'desc' }, + }, + }, }); const user = await this.prisma.user.findUnique({ where: { id: row.userId }, select: { fullName: true } }); return this.payrollDto(row, user?.fullName ?? ''); @@ -327,6 +340,8 @@ export class TreasuryOpsService { sheet.addRow(['شاخص', 'این دوره', 'دوره قبل']); const rows: Array<[string, string, string]> = [ ['درآمد ثبت‌شده', data.current.bookedIncome, data.previous.bookedIncome], + ['فروش فاکتور', data.current.invoiceSales, data.previous.invoiceSales], + ['فاکتور برگشتی', data.current.invoiceCredits, data.previous.invoiceCredits], ['هزینه ثبت‌شده', data.current.bookedExpense, data.previous.bookedExpense], ['سود عملیاتی', data.current.operatingProfit, data.previous.operatingProfit], ['ورود وجه', data.current.cashIn, data.previous.cashIn], @@ -411,10 +426,15 @@ export class TreasuryOpsService { amount: money(amount), share: bookedExpense.equals(0) ? '0' : amount.div(bookedExpense).mul(100).toFixed(1), })); + const invoiceSales = await invoiceSalesInPeriod(this.prisma, organizationId, from, to); return { bookedIncome: money(bookedIncome), + invoiceSales: invoiceSales.sales, + invoiceCredits: invoiceSales.credits, bookedExpense: money(bookedExpense), - operatingProfit: money(bookedIncome.minus(bookedExpense)), + operatingProfit: money( + bookedIncome.plus(invoiceSales.net).minus(bookedExpense), + ), cashIn: money(cashIn), cashOut: money(cashOut), cashNet: money(cashIn.minus(cashOut)), @@ -480,7 +500,13 @@ export class TreasuryOpsService { payable: Prisma.Decimal; dueDate: Date; status: string; - movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>; + movements: Array<{ + id: string; + amount: Prisma.Decimal; + voidedAt: Date | null; + occurredAt: Date; + account?: { name: string } | null; + }>; }, fullName: string, ) { @@ -500,6 +526,14 @@ export class TreasuryOpsService { remaining: money(left.isNegative() ? 0 : left), dueDate: row.dueDate.toISOString(), status: row.status, + payments: row.movements + .filter((item) => !item.voidedAt) + .map((item) => ({ + id: item.id, + amount: money(item.amount), + occurredAt: item.occurredAt.toISOString(), + accountName: item.account?.name ?? '', + })), }; } diff --git a/apps/api/src/treasury/treasury.service.ts b/apps/api/src/treasury/treasury.service.ts index b83c03e..a4952e4 100644 --- a/apps/api/src/treasury/treasury.service.ts +++ b/apps/api/src/treasury/treasury.service.ts @@ -25,6 +25,7 @@ import { PrismaService } from '../prisma/prisma.service'; import { LocalFileStorage } from '../storage/local-file.storage'; import { StorageQuotaService } from '../billing/storage-quota.service'; import type { Actor } from '../common/record-scope'; +import { loadInvoicePartyPositions, invoiceSalesInPeriod } from './invoice-ledger'; import { TreasuryReceivablesService } from './treasury-receivables.service'; const INCOME_CATEGORIES = ['فروش خدمات', 'فروش کالا', 'سایر درآمدها']; @@ -753,7 +754,34 @@ export class TreasuryService { current.remaining = current.remaining.plus(rawRemaining); buckets.set(key, current); } + + const invoiceParties = await loadInvoicePartyPositions(this.prisma, actor.organizationId); + for (const party of invoiceParties) { + const onDebtorSide = party.net.greaterThan(0); + if (kind === 'income' && !onDebtorSide) continue; + if (kind === 'expense' && onDebtorSide) continue; + const remaining = party.net.abs(); + const amount = onDebtorSide ? party.billed : Prisma.Decimal.max(party.billed, remaining); + const settled = Prisma.Decimal.max(amount.minus(remaining), 0); + const current = buckets.get(party.key) ?? { + key: party.key, + partyKind: party.partyKind, + partyName: party.partyName, + amount: new Prisma.Decimal(0), + settled: new Prisma.Decimal(0), + remaining: new Prisma.Decimal(0), + }; + current.amount = current.amount.plus(amount); + current.settled = current.settled.plus(settled); + current.remaining = current.remaining.plus(remaining); + if (!current.partyName || current.partyName === 'بدون طرف حساب') { + current.partyName = party.partyName; + } + buckets.set(party.key, current); + } + return [...buckets.values()] + .filter((row) => row.remaining.greaterThan(0)) .sort((a, b) => b.remaining.comparedTo(a.remaining)) .map((row) => ({ key: row.key, @@ -1092,6 +1120,17 @@ export class TreasuryService { } const bookedIncome = dec(income._sum.amount); const bookedExpense = dec(expense._sum.amount); + const invoiceSales = await invoiceSalesInPeriod( + this.prisma, + actor.organizationId, + from, + to, + ); + const invoiceParties = await loadInvoicePartyPositions(this.prisma, actor.organizationId); + for (const party of invoiceParties) { + if (party.net.greaterThan(0)) receivables = receivables.plus(party.net); + else payables = payables.plus(party.net.abs()); + } const totalBalance = accounts.reduce( (sum, account) => sum.plus(account.balance), new Prisma.Decimal(0), @@ -1101,7 +1140,7 @@ export class TreasuryService { actualReceipts: money(dec(receipts._sum.amount)), bookedExpense: money(bookedExpense), actualPayments: money(dec(payments._sum.amount)), - operatingProfit: money(bookedIncome.minus(bookedExpense)), + operatingProfit: money(bookedIncome.plus(invoiceSales.net).minus(bookedExpense)), receivables: money(receivables), payables: money(payables), totalBalance: money(totalBalance), diff --git a/apps/web/src/router/index.ts b/apps/web/src/router/index.ts index 5a271fa..fd4130c 100644 --- a/apps/web/src/router/index.ts +++ b/apps/web/src/router/index.ts @@ -330,7 +330,8 @@ export const router = createRouter({ meta: { roles: ['owner', 'admin'] as UserRole[], treasuryTitle: 'حقوق و دستمزد', - treasuryDescription: 'پرداخت حقوق فقط با دسترسی جداگانه حقوق و دستمزد باز است.', + treasuryDescription: + 'تعیین حقوق، پرداخت یکجا یا چندمرحله‌ای، و گزارش دوره‌ها. پرداخت فقط با دسترسی حقوق و دستمزد باز است.', }, }, { @@ -350,7 +351,8 @@ export const router = createRouter({ meta: { roles: ['owner', 'admin'] as UserRole[], treasuryTitle: 'گزارش مالی', - treasuryDescription: 'سود عملیاتی از درآمد و هزینه ثبت‌شده است، نه از خالص وجه.', + treasuryDescription: + 'سود از درآمد، فروش فاکتور و هزینه است. بدهکاران و بستانکاران مانده فاکتور و اسناد باز را یک‌جا نشان می‌دهند.', }, }, { diff --git a/apps/web/src/views/treasury/TreasuryHomeView.vue b/apps/web/src/views/treasury/TreasuryHomeView.vue index 2995869..1fe5a8b 100644 --- a/apps/web/src/views/treasury/TreasuryHomeView.vue +++ b/apps/web/src/views/treasury/TreasuryHomeView.vue @@ -28,9 +28,9 @@ const cards = [ { key: 'actualReceipts', label: 'دریافت واقعی', hint: 'ورود به حساب' }, { key: 'bookedExpense', label: 'هزینه ثبت‌شده', hint: 'تعهدی' }, { key: 'actualPayments', label: 'پرداخت واقعی', hint: 'خروج از حساب' }, - { key: 'operatingProfit', label: 'سود یا زیان عملیاتی', hint: 'درآمد ثبت‌شده − هزینه ثبت‌شده' }, - { key: 'receivables', label: 'مطالبات وصول‌نشده', hint: 'درآمد بدون دریافت کامل' }, - { key: 'payables', label: 'تعهدات پرداخت', hint: 'هزینه بدون پرداخت کامل' }, + { key: 'operatingProfit', label: 'سود یا زیان عملیاتی', hint: 'درآمد و فروش فاکتور − هزینه' }, + { key: 'receivables', label: 'مطالبات وصول‌نشده', hint: 'اسناد باز و مانده فاکتور' }, + { key: 'payables', label: 'تعهدات پرداخت', hint: 'هزینه باز، حقوق و برگشتی' }, { key: 'totalBalance', label: 'موجودی حساب‌ها', hint: 'صندوق و بانک' }, ] as const; diff --git a/apps/web/src/views/treasury/TreasuryPayrollView.vue b/apps/web/src/views/treasury/TreasuryPayrollView.vue index 01a4493..857d44f 100644 --- a/apps/web/src/views/treasury/TreasuryPayrollView.vue +++ b/apps/web/src/views/treasury/TreasuryPayrollView.vue @@ -1,41 +1,60 @@ @@ -1507,12 +1698,12 @@ onBeforeUnmount(() => { - + - - - - فیلترها - - - - - - - - - - - فیلترها - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - فقط تبدیل‌شده‌ها - - - - - فقط بایگانی‌شده‌ها - - - - - - From 3c9b906bd6c3010884b7730e6067a442e7d772f6 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Sun, 8 Nov 2026 20:58:18 +0330 Subject: [PATCH 14/62] fix(leads): keep the filter panel from shifting the page Co-authored-by: Cursor --- apps/web/src/components/JalaliDateInput.vue | 2 +- apps/web/src/views/LeadsView.vue | 104 +++++++++++--------- 2 files changed, 58 insertions(+), 48 deletions(-) diff --git a/apps/web/src/components/JalaliDateInput.vue b/apps/web/src/components/JalaliDateInput.vue index 609568b..d34fcbd 100644 --- a/apps/web/src/components/JalaliDateInput.vue +++ b/apps/web/src/components/JalaliDateInput.vue @@ -360,7 +360,7 @@ function place() { function liftAboveOverlays() { let z = 120; - for (const el of document.querySelectorAll('.ant-modal-wrap, .ant-drawer, .ant-popover')) { + for (const el of document.querySelectorAll('.ant-modal-wrap, .ant-drawer, .ant-popover, [data-lead-filter]')) { const zi = Number.parseInt(window.getComputedStyle(el).zIndex, 10); if (Number.isFinite(zi)) z = Math.max(z, zi + 20); } diff --git a/apps/web/src/views/LeadsView.vue b/apps/web/src/views/LeadsView.vue index 249761a..6ee10ac 100644 --- a/apps/web/src/views/LeadsView.vue +++ b/apps/web/src/views/LeadsView.vue @@ -22,7 +22,6 @@ import { Modal, Modal as AModal, Pagination as APagination, - Popover as APopover, RadioButton as ARadioButton, RadioGroup as ARadioGroup, Row as ARow, @@ -340,6 +339,20 @@ function toggleFilterSection(name: NonNullable) { const filterAnchor = ref(null); const filterPopoverMaxHeight = ref('min(70vh, 32rem)'); +const filterPanelStyle = computed(() => ({ + position: 'absolute' as const, + top: 'calc(100% + 6px)', + insetInlineStart: '0', + zIndex: 1050, + width: 'min(20rem, calc(100vw - 1.5rem))', + maxHeight: filterPopoverMaxHeight.value, + overflow: 'auto', + background: token.value.colorBgElevated, + borderRadius: `${token.value.borderRadiusLG}px`, + boxShadow: token.value.boxShadowSecondary, + padding: `${token.value.paddingSM}px`, +})); + function placeFilterPopover() { const el = filterAnchor.value; if (!el) return; @@ -347,18 +360,26 @@ function placeFilterPopover() { filterPopoverMaxHeight.value = `${Math.max(220, space)}px`; } -function onFilterPopover(open: boolean) { - if (!open && document.getElementById('jalali-picker')) return; - if (open) placeFilterPopover(); - moreFiltersOpen.value = open; - if (open) { - window.addEventListener('resize', placeFilterPopover); - window.addEventListener('scroll', placeFilterPopover, true); - } else { +function onFilterDocPointer(event: Event) { + const target = event.target; + if (!(target instanceof Node)) return; + if (filterAnchor.value?.contains(target)) return; + if (document.getElementById('jalali-picker')?.contains(target)) return; + moreFiltersOpen.value = false; + filterSection.value = null; + document.removeEventListener('pointerdown', onFilterDocPointer, true); +} + +function toggleFilterPopover() { + if (moreFiltersOpen.value) { + moreFiltersOpen.value = false; filterSection.value = null; - window.removeEventListener('resize', placeFilterPopover); - window.removeEventListener('scroll', placeFilterPopover, true); + document.removeEventListener('pointerdown', onFilterDocPointer, true); + return; } + placeFilterPopover(); + moreFiltersOpen.value = true; + document.addEventListener('pointerdown', onFilterDocPointer, true); } function dateFacetLabel(value: string) { @@ -1531,13 +1552,12 @@ onMounted(async () => { onBeforeUnmount(() => { stopImportPoll(); revokeLogoUrls(); - window.removeEventListener('resize', placeFilterPopover); - window.removeEventListener('scroll', placeFilterPopover, true); + document.removeEventListener('pointerdown', onFilterDocPointer, true); }); -
- + - - - - {{ filterBtnLabel }} - - - - - +
Date: Mon, 9 Nov 2026 11:20:20 +0330 Subject: [PATCH 15/62] fix(access): honor finance sections and team-member data scope Role treasury keys now open the first allowed finance page, and team-member ownership limits lists, dashboard, and reports instead of the whole organization. Co-authored-by: Cursor --- apps/api/src/auth/auth.service.ts | 14 +++- apps/api/src/auth/jwt.strategy.ts | 4 + apps/api/src/common/record-scope.ts | 84 +++++++++++++++++-- apps/api/src/contacts/companies.service.ts | 10 ++- apps/api/src/contacts/people.service.ts | 14 ++-- apps/api/src/leads/leads.service.ts | 38 +++++---- apps/api/src/reports/reports.service.ts | 5 +- .../api/src/treasury/treasury-access.guard.ts | 30 ++++--- apps/web/src/layouts/AppLayout.vue | 18 ++-- apps/web/src/lib/section-permissions.ts | 24 ++++++ apps/web/src/router/index.ts | 16 ++-- apps/web/src/stores/auth.ts | 6 ++ .../views/treasury/TreasuryExpensesView.vue | 14 +++- .../views/treasury/TreasuryIncomesView.vue | 14 +++- packages/shared/src/index.ts | 16 ++++ 15 files changed, 243 insertions(+), 64 deletions(-) diff --git a/apps/api/src/auth/auth.service.ts b/apps/api/src/auth/auth.service.ts index 2dafba4..118e9fa 100644 --- a/apps/api/src/auth/auth.service.ts +++ b/apps/api/src/auth/auth.service.ts @@ -19,6 +19,10 @@ import type { StorageUsageDto, SubscriptionSummaryDto, } from '@mento/shared'; +import { + parseUserTreasuryAccess, + permissionsWithTreasuryOverride, +} from '@mento/shared'; import { Prisma } from '@prisma/client'; /** Ensures Express.Multer.File augmentation is loaded for saveAvatar. */ import type {} from 'multer'; @@ -848,6 +852,9 @@ export class AuthService { }, }); const role = membership?.role ?? user.role; + const rolePermissions = Array.isArray(membership?.orgRole?.permissions) + ? membership.orgRole.permissions.filter((item) => typeof item === 'string') + : []; const orgName = membership?.organization.name; const sub = subscription ?? @@ -879,9 +886,10 @@ export class AuthService { storage, isOrgOwner: role === 'owner', priorArchive: this.priorArchiveFor(membership), - permissions: (Array.isArray(membership?.orgRole?.permissions) - ? membership.orgRole.permissions.filter((item) => typeof item === 'string') - : []) as AuthUserDto['permissions'], + permissions: permissionsWithTreasuryOverride( + rolePermissions, + parseUserTreasuryAccess(membership?.treasuryAccessOverride), + ) as AuthUserDto['permissions'], ...(viewAs ? { viewAs } : {}), }); } diff --git a/apps/api/src/auth/jwt.strategy.ts b/apps/api/src/auth/jwt.strategy.ts index 83595b1..950c17f 100644 --- a/apps/api/src/auth/jwt.strategy.ts +++ b/apps/api/src/auth/jwt.strategy.ts @@ -195,6 +195,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) { const peers = await this.prisma.teamMember.findMany({ where: { teamId: { in: memberships.map((m) => m.teamId) }, + team: { organizationId }, + user: { + memberships: { some: { organizationId, isActive: true } }, + }, }, select: { userId: true }, }); diff --git a/apps/api/src/common/record-scope.ts b/apps/api/src/common/record-scope.ts index 7bd435e..fb51243 100644 --- a/apps/api/src/common/record-scope.ts +++ b/apps/api/src/common/record-scope.ts @@ -5,7 +5,7 @@ import type { SectionDataAccess, UserRole, } from '@mento/shared'; -import { DATA_SCOPES, canViewAllRecords } from '@mento/shared'; +import { DATA_SCOPES, canViewAllRecords, sectionHasDataAccessLimits } from '@mento/shared'; import type { Prisma } from '@prisma/client'; import { activitiesDeepWhere, @@ -13,6 +13,7 @@ import { notesDeepWhere, projectsDeepWhere, routinesDeepWhere, + sectionOwnerIdUnion, ticketsDeepWhere, } from './data-access'; @@ -60,6 +61,65 @@ export type Actor = { export type ScopedActor = Pick; +type DeepAccessActor = ScopedActor & + Partial< + Pick< + Actor, + | 'customersAccess' + | 'leadsAccess' + | 'salesAccess' + | 'activitiesAccess' + | 'notesAccess' + | 'routinesAccess' + | 'projectsAccess' + | 'ticketsAccess' + | 'teamPeerIds' + > + >; + +function sectionForScope(actor: DeepAccessActor, scope: DataScope): SectionDataAccess | undefined { + switch (scope) { + case 'contacts': + return actor.customersAccess; + case 'leads': + return actor.leadsAccess; + case 'deals': + return actor.salesAccess; + case 'activities': + return actor.activitiesAccess; + case 'notes': + return actor.notesAccess; + case 'routines': + return actor.routinesAccess; + case 'projects': + return actor.projectsAccess; + case 'tickets': + return actor.ticketsAccess; + default: + return undefined; + } +} + +/** + * شناسه‌های مالک از قانون عمق داده. + * legacy = بخش عمیق روی این Actor نیست. + * open = محدودیت مالکی ندارد (همه، یا فقط فیلترهای غیرمالک). + */ +function deepOwnerIds( + actor: DeepAccessActor, + scope: DataScope, +): { kind: 'legacy' } | { kind: 'open' } | { kind: 'ids'; ids: string[] } { + const section = sectionForScope(actor, scope); + if (!section) return { kind: 'legacy' }; + if (!sectionHasDataAccessLimits(section)) return { kind: 'open' }; + const ids = sectionOwnerIdUnion(section, { + userId: actor.userId, + teamPeerIds: actor.teamPeerIds ?? null, + }); + if (ids === null) return { kind: 'open' }; + return { kind: 'ids', ids }; +} + /** Actor با سطح دید مخصوص یک بخش (اگر تنظیم شده باشد). */ export function forScope(actor: T, scope: DataScope): T { const s = actor.scopes?.[scope]; @@ -109,9 +169,16 @@ export function scopedOwnerIds( /** فیلتر مالکیت؛ پیش‌فرض بخش «مشتریان» (Person / Company). برای فاکتور/پیش‌فاکتور scope=finance. */ export function ownerWhere( - actor: ScopedActor, + actor: DeepAccessActor, scope: DataScope = 'contacts', ): { ownerId: string } | { ownerId: { in: string[] } } | Record { + const deep = deepOwnerIds(actor, scope); + if (deep.kind === 'open') return {}; + if (deep.kind === 'ids') { + if (deep.ids.length === 1) return { ownerId: deep.ids[0]! }; + if (!deep.ids.length) return { ownerId: '__no_access__' }; + return { ownerId: { in: deep.ids } }; + } const ids = scopedOwnerIds(actor, scope); if (!ids) return {}; if (ids.length === 1) return { ownerId: ids[0]! }; @@ -153,11 +220,16 @@ export function projectCardAccessWhere( } /** فعالیت‌ها بر اساس مسئول اصلی یا مسئولان مشترک */ -export function assigneeWhere( - actor: ScopedActor, -): Prisma.ActivityWhereInput { - const ids = scopedOwnerIds(actor, 'activities'); +export function assigneeWhere(actor: DeepAccessActor): Prisma.ActivityWhereInput { + const deep = deepOwnerIds(actor, 'activities'); + const ids = + deep.kind === 'open' + ? null + : deep.kind === 'ids' + ? deep.ids + : scopedOwnerIds(actor, 'activities'); if (!ids) return {}; + if (!ids.length) return { assigneeId: '__no_access__' }; return { OR: [ { assigneeId: { in: ids } }, diff --git a/apps/api/src/contacts/companies.service.ts b/apps/api/src/contacts/companies.service.ts index c44e60d..d7143ed 100644 --- a/apps/api/src/contacts/companies.service.ts +++ b/apps/api/src/contacts/companies.service.ts @@ -112,9 +112,13 @@ export class CompaniesService { ...(groupIds.length ? [{ groupLinks: { some: { groupId: { in: groupIds } } } }] : []), ]; const where: Prisma.CompanyWhereInput = { - organizationId: actor.organizationId, - ...customersCompanyWhere(actor), - ...(and.length ? { AND: and } : {}), + AND: [ + { + organizationId: actor.organizationId, + ...customersCompanyWhere(actor), + }, + ...and, + ], }; const [rows, total] = await this.prisma.$transaction([ diff --git a/apps/api/src/contacts/people.service.ts b/apps/api/src/contacts/people.service.ts index 9fce8b6..4e469c1 100644 --- a/apps/api/src/contacts/people.service.ts +++ b/apps/api/src/contacts/people.service.ts @@ -218,11 +218,15 @@ export class PeopleService implements OnModuleInit { if (disc) and.push(disc); if (groupIds.length) and.push({ groupLinks: { some: { groupId: { in: groupIds } } } }); return { - organizationId: actor.organizationId, - ...customersPersonWhere(actor), - ...(moods.length ? { mood: { in: moods } } : {}), - ...(sources.length ? { importSource: { in: sources } } : {}), - ...(and.length ? { AND: and } : {}), + AND: [ + { + organizationId: actor.organizationId, + ...customersPersonWhere(actor), + }, + ...(moods.length ? [{ mood: { in: moods } }] : []), + ...(sources.length ? [{ importSource: { in: sources } }] : []), + ...and, + ], }; } diff --git a/apps/api/src/leads/leads.service.ts b/apps/api/src/leads/leads.service.ts index aa125cd..f693e13 100644 --- a/apps/api/src/leads/leads.service.ts +++ b/apps/api/src/leads/leads.service.ts @@ -176,22 +176,26 @@ export class LeadsService { const createdRange = this.createdAtWhere(opts.createdFrom, opts.createdTo); if (createdRange) and.push(createdRange); return { - organizationId: actor.organizationId, - ...leadAccessWhere(actor), - archivedAt: opts.archived ? { not: null } : null, - ...(opts.converted ? { convertedPersonId: { not: null } } : {}), - ...(opts.stageId ? { stageId: opts.stageId } : {}), - ...(opts.assigneeId ? { assigneeId: opts.assigneeId } : {}), - ...(opts.unassigned ? { assigneeId: null } : {}), - ...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}), - ...(opts.region - ? { region: { contains: opts.region, mode: 'insensitive' } } - : {}), - ...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}), - ...(opts.source - ? { source: { contains: opts.source, mode: 'insensitive' } } - : {}), - ...(and.length ? { AND: and } : {}), + AND: [ + { + organizationId: actor.organizationId, + ...leadAccessWhere(actor), + archivedAt: opts.archived ? { not: null } : null, + ...(opts.converted ? { convertedPersonId: { not: null } } : {}), + ...(opts.stageId ? { stageId: opts.stageId } : {}), + ...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}), + ...(opts.region + ? { region: { contains: opts.region, mode: 'insensitive' } } + : {}), + ...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}), + ...(opts.source + ? { source: { contains: opts.source, mode: 'insensitive' } } + : {}), + }, + ...(opts.unassigned ? [{ assigneeId: null }] : []), + ...(opts.assigneeId && !opts.unassigned ? [{ assigneeId: opts.assigneeId }] : []), + ...and, + ], }; } @@ -1185,7 +1189,7 @@ export class LeadsService { newStage ? this.prisma.lead.count({ where: { ...base, stageId: newStage.id } }) : Promise.resolve(0), - this.prisma.lead.count({ where: { ...base, assigneeId: null } }), + this.prisma.lead.count({ where: { AND: [base, { assigneeId: null }] } }), convertedIds.length ? this.prisma.lead.count({ where: { ...base, stageId: { in: convertedIds } }, diff --git a/apps/api/src/reports/reports.service.ts b/apps/api/src/reports/reports.service.ts index 7eed9b4..62e0214 100644 --- a/apps/api/src/reports/reports.service.ts +++ b/apps/api/src/reports/reports.service.ts @@ -18,6 +18,7 @@ import { } from '@mento/shared'; import { Prisma } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; +import { customersPersonWhere } from '../common/data-access'; import { type Actor, assigneeWhere, @@ -54,7 +55,7 @@ export class ReportsService { const invoiceScope = ownerWhere(actor, 'finance'); const activityScope = assigneeWhere(actor); const ticketScope = ticketAccessWhere(actor); - const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId }; + const personScope = customersPersonWhere(actor); const durationMs = end.getTime() - start.getTime(); const prevEnd = new Date(start.getTime() - 1); @@ -1534,7 +1535,7 @@ export class ReportsService { const orgId = actor.organizationId; const dealScope = ownerWhere(actor, 'deals'); const activityScope = assigneeWhere(actor); - const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId }; + const personScope = customersPersonWhere(actor); const rates = await loadOrgRates(this.prisma, orgId); const now = new Date(); const { jy, jm } = dateToJalali(now); diff --git a/apps/api/src/treasury/treasury-access.guard.ts b/apps/api/src/treasury/treasury-access.guard.ts index c08bc00..30b6c5c 100644 --- a/apps/api/src/treasury/treasury-access.guard.ts +++ b/apps/api/src/treasury/treasury-access.guard.ts @@ -1,6 +1,7 @@ import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common'; import { parseUserTreasuryAccess, + permissionsWithTreasuryOverride, treasurySectionAllowed, type TreasurySectionKey, } from '@mento/shared'; @@ -16,7 +17,12 @@ export class TreasuryAccessGuard implements CanActivate { constructor(private readonly prisma: PrismaService) {} async canActivate(context: ExecutionContext): Promise { - const req = context.switchToHttp().getRequest<{ user?: Actor; originalUrl?: string; url?: string }>(); + const req = context.switchToHttp().getRequest<{ + user?: Actor; + method?: string; + originalUrl?: string; + url?: string; + }>(); const actor = req.user; if (!actor) throw new ForbiddenException('دسترسی مالی مجاز نیست.'); if (actor.role === 'owner' || actor.role === 'admin') return true; @@ -30,11 +36,18 @@ export class TreasuryAccessGuard implements CanActivate { const rolePermissions = Array.isArray(membership?.orgRole?.permissions) ? membership.orgRole.permissions.map(String) : []; - const permissions = permissionsForTreasury( + const permissions = permissionsWithTreasuryOverride( rolePermissions, parseUserTreasuryAccess(membership?.treasuryAccessOverride), ); + const method = (req.method || 'GET').toUpperCase(); const url = req.originalUrl || req.url || ''; + if ( + isLookupForDocuments(method, url) && + treasurySectionAllowed(actor.role, permissions, 'treasury_documents') + ) { + return true; + } if (!treasurySectionAllowed(actor.role, permissions, sectionForUrl(url))) { throw new ForbiddenException('به این بخش مدیریت مالی دسترسی ندارید.'); } @@ -42,14 +55,11 @@ export class TreasuryAccessGuard implements CanActivate { } } -function permissionsForTreasury( - rolePermissions: string[], - override: ReturnType, -): string[] { - if (!override) return rolePermissions; - const rest = rolePermissions.filter((key) => key !== 'treasury' && !key.startsWith('treasury_')); - if (!override.enabled) return rest; - return ['treasury', ...override.sections, ...rest]; +/** فهرست حساب و دسته برای ثبت سند لازم است؛ صفحهٔ مدیریت‌شان جدا می‌ماند. */ +function isLookupForDocuments(method: string, url: string): boolean { + if (method !== 'GET' && method !== 'HEAD') return false; + const path = (url.split('?')[0] || '').replace(/\/+$/, ''); + return path.endsWith('/treasury/accounts') || path.endsWith('/treasury/categories'); } function sectionForUrl(url: string): TreasurySectionKey | 'treasury_documents' { diff --git a/apps/web/src/layouts/AppLayout.vue b/apps/web/src/layouts/AppLayout.vue index 2cdebc1..56bdc1f 100644 --- a/apps/web/src/layouts/AppLayout.vue +++ b/apps/web/src/layouts/AppLayout.vue @@ -21,6 +21,7 @@ import type { import { canManageSettings, canViewAllRecords } from '@/lib/roles'; import { canOpenPath, + firstAllowedFinancePath, hasSectionPermission, sectionPermissionForPath, } from '@/lib/section-permissions'; @@ -204,12 +205,11 @@ function cardAllowedForNav(card: { }) { if (card.ownerOnly && auth.user?.role !== 'owner') return false; const perms = auth.user?.permissions ?? []; - const canTreasury = auth.user?.role === 'owner' - || auth.user?.role === 'admin' - || perms.includes('treasury') - || perms.some((key) => key.startsWith('treasury_')); if (card.to?.startsWith('/finance')) { - return moduleAllowed(card.module ?? 'treasury') && canTreasury; + return ( + moduleAllowed(card.module ?? 'treasury') + && Boolean(firstAllowedFinancePath(auth.user?.role, perms)) + ); } const section = card.to ? sectionPermissionForPath(card.to) : null; const hasSection = section @@ -246,7 +246,13 @@ const openHub = computed(() => { if (!openHubKey.value) return null; const hub = NAV_HUBS.find((item) => item.key === openHubKey.value); if (!hub) return null; - const cards = hub.cards.filter((card) => cardAllowedForNav(card)); + const financeTo = firstAllowedFinancePath(auth.user?.role, auth.user?.permissions); + const cards = hub.cards + .filter((card) => cardAllowedForNav(card)) + .map((card) => { + if (!financeTo || !card.to.startsWith('/finance') || card.to === financeTo) return card; + return { ...card, to: financeTo }; + }); if ( hub.key === 'customers' && isMobileNav.value && diff --git a/apps/web/src/lib/section-permissions.ts b/apps/web/src/lib/section-permissions.ts index c81ebe8..5988cf7 100644 --- a/apps/web/src/lib/section-permissions.ts +++ b/apps/web/src/lib/section-permissions.ts @@ -69,6 +69,30 @@ export function canOpenFinancePath( return treasurySectionAllowed(role, permissions, section); } +const FINANCE_ENTRIES: Array<{ path: string; section: TreasurySectionKey }> = [ + { path: '/finance', section: 'treasury_dashboard' }, + { path: '/finance/incomes', section: 'treasury_incomes' }, + { path: '/finance/expenses', section: 'treasury_expenses' }, + { path: '/finance/receivables', section: 'treasury_receivables' }, + { path: '/finance/accounts', section: 'treasury_accounts' }, + { path: '/finance/payroll', section: 'treasury_payroll' }, + { path: '/finance/recurring', section: 'treasury_recurring' }, + { path: '/finance/reports', section: 'treasury_reports' }, + { path: '/finance/audit', section: 'treasury_audit' }, + { path: '/finance/categories', section: 'treasury_categories' }, +]; + +/** اولین صفحهٔ مالی که این نقش واقعاً می‌تواند باز کند. */ +export function firstAllowedFinancePath( + role: UserRole | string | null | undefined, + permissions: readonly string[] | null | undefined, +): string | null { + for (const entry of FINANCE_ENTRIES) { + if (treasurySectionAllowed(role, permissions, entry.section)) return entry.path; + } + return null; +} + export function canOpenPath( role: UserRole | string | null | undefined, permissions: readonly string[] | null | undefined, diff --git a/apps/web/src/router/index.ts b/apps/web/src/router/index.ts index fd4130c..8446b8a 100644 --- a/apps/web/src/router/index.ts +++ b/apps/web/src/router/index.ts @@ -2,7 +2,12 @@ import { createRouter, createWebHistory } from 'vue-router'; import type { UserRole } from '@mento/shared'; import { useAuthStore } from '@/stores/auth'; import { usePlatformAuthStore } from '@/stores/platform-auth'; -import { canOpenFinancePath, canOpenPath, sectionPermissionForPath } from '@/lib/section-permissions'; +import { + canOpenFinancePath, + canOpenPath, + firstAllowedFinancePath, + sectionPermissionForPath, +} from '@/lib/section-permissions'; export const router = createRouter({ history: createWebHistory(), @@ -683,13 +688,8 @@ router.beforeEach((to) => { if (canOpenFinancePath(auth.user?.role, auth.user?.permissions, String(to.path))) { return true; } - const exactHome = to.path === '/finance' || to.path === '/finance/'; - if ( - exactHome && - canOpenFinancePath(auth.user?.role, auth.user?.permissions, '/finance/payroll') - ) { - return { path: '/finance/payroll' }; - } + const next = firstAllowedFinancePath(auth.user?.role, auth.user?.permissions); + if (next && next !== to.path) return { path: next }; } return { name: 'home' }; } diff --git a/apps/web/src/stores/auth.ts b/apps/web/src/stores/auth.ts index 1fdca36..d15d782 100644 --- a/apps/web/src/stores/auth.ts +++ b/apps/web/src/stores/auth.ts @@ -214,6 +214,12 @@ export const useAuthStore = defineStore('auth', () => { if (token.value) void hydrate(); + if (typeof document !== 'undefined') { + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') void hydrate(); + }); + } + return { token, user, diff --git a/apps/web/src/views/treasury/TreasuryExpensesView.vue b/apps/web/src/views/treasury/TreasuryExpensesView.vue index dd2a0f7..ba07a14 100644 --- a/apps/web/src/views/treasury/TreasuryExpensesView.vue +++ b/apps/web/src/views/treasury/TreasuryExpensesView.vue @@ -96,8 +96,18 @@ function docLine(item: FinancialDocumentDto) { async function load() { const [docs, cats, acc, bals] = await Promise.all([ api.get('/treasury/documents', { params: { kind, q: q.value || undefined } }), - api.get('/treasury/categories', { params: { kind } }), - api.get('/treasury/accounts'), + api.get('/treasury/categories', { params: { kind } }).catch((e: unknown) => { + if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) { + return { data: [] as FinancialCategoryDto[] }; + } + throw e; + }), + api.get('/treasury/accounts').catch((e: unknown) => { + if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) { + return { data: [] as FinancialAccountDto[] }; + } + throw e; + }), api.get('/treasury/party-balances', { params: { kind } }).catch((e: unknown) => { if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] }; throw e; diff --git a/apps/web/src/views/treasury/TreasuryIncomesView.vue b/apps/web/src/views/treasury/TreasuryIncomesView.vue index 227dd12..323bfc7 100644 --- a/apps/web/src/views/treasury/TreasuryIncomesView.vue +++ b/apps/web/src/views/treasury/TreasuryIncomesView.vue @@ -151,8 +151,18 @@ function docLine(item: FinancialDocumentDto) { async function load() { const [docs, cats, acc, dash, bals] = await Promise.all([ api.get('/treasury/documents', { params: { kind, q: q.value || undefined } }), - api.get('/treasury/categories', { params: { kind } }), - api.get('/treasury/accounts'), + api.get('/treasury/categories', { params: { kind } }).catch((e: unknown) => { + if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) { + return { data: [] as FinancialCategoryDto[] }; + } + throw e; + }), + api.get('/treasury/accounts').catch((e: unknown) => { + if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) { + return { data: [] as FinancialAccountDto[] }; + } + throw e; + }), api.get('/treasury/dashboard').catch(() => null), api.get('/treasury/party-balances', { params: { kind } }).catch((e: unknown) => { if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] }; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index f3fcbc7..a88e449 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -636,6 +636,22 @@ export function parseUserTreasuryAccess(raw: unknown): UserTreasuryAccess | null }; } +/** + * دسترسی مالی کاربر، اگر تنظیم شده باشد، کلیدهای مالی نقش را جایگزین می‌کند. + * null یعنی همان مجوزهای نقش. + */ +export function permissionsWithTreasuryOverride( + rolePermissions: readonly string[], + override: UserTreasuryAccess | null, +): string[] { + if (!override) return [...rolePermissions]; + const rest = rolePermissions.filter( + (key) => key !== "treasury" && !key.startsWith("treasury_"), + ); + if (!override.enabled) return rest; + return ["treasury", ...override.sections, ...rest]; +} + export function emptySectionDataAccess(): SectionDataAccess { return { mode: "all", rules: [] }; } From 4764562bd4735ee927b472df5ba9b2c922339e96 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Mon, 9 Nov 2026 14:42:46 +0330 Subject: [PATCH 16/62] fix(tahesab): stop treating shared phone numbers as new customers A second Tahesab code with the same phone stays linked to the existing person, so the import list no longer counts it as unimported and sync no longer overwrites that person's name. Co-authored-by: Cursor --- .../tahesab/person-link.service.ts | 165 ++++++++++++++---- apps/web/src/views/TahesabSettingsView.vue | 84 ++++++++- 2 files changed, 204 insertions(+), 45 deletions(-) diff --git a/apps/api/src/integrations/tahesab/person-link.service.ts b/apps/api/src/integrations/tahesab/person-link.service.ts index 21c74df..38989c5 100644 --- a/apps/api/src/integrations/tahesab/person-link.service.ts +++ b/apps/api/src/integrations/tahesab/person-link.service.ts @@ -438,6 +438,77 @@ export class TahesabPersonLinkService { }; } + /** + * کدهایی که لینک ندارند ولی شماره‌شان مال مشتریِ از قبل لینک‌شدهٔ همین اتصال است. + * یک شخص فقط یک کد ته‌حساب دارد؛ این کدها مشتری تازه نیستند. + */ + private async duplicateOwners( + organizationId: string, + connectionId: string, + rows: Array<{ moshtariCode: number | null; tel: string }>, + ) { + const pending = rows.filter( + (row): row is { moshtariCode: number; tel: string } => row.moshtariCode != null, + ); + const keys = [ + ...new Set(pending.flatMap((row) => phoneIdentityKeys(storedPhoneNumber(row.tel)))), + ]; + const out = new Map< + number, + { moshtariCode: number; personId: string; personName: string } + >(); + if (!keys.length) return out; + + const people = await this.prisma.person.findMany({ + where: { + organizationId, + OR: [{ mobile: { in: keys } }, { phone: { in: keys } }], + accountingLinks: { some: { connectionId } }, + }, + select: { + id: true, + firstName: true, + lastName: true, + mobile: true, + phone: true, + accountingLinks: { + where: { connectionId }, + select: { moshtariCode: true }, + take: 1, + }, + }, + }); + const byKey = new Map< + string, + { moshtariCode: number; personId: string; personName: string } + >(); + for (const person of people) { + const link = person.accountingLinks[0]; + if (!link) continue; + const info = { + moshtariCode: link.moshtariCode, + personId: person.id, + personName: `${person.firstName} ${person.lastName}`.trim(), + }; + for (const key of [ + ...phoneIdentityKeys(person.mobile), + ...phoneIdentityKeys(person.phone), + ]) { + if (!byKey.has(key)) byKey.set(key, info); + } + } + for (const row of pending) { + for (const key of phoneIdentityKeys(storedPhoneNumber(row.tel))) { + const hit = byKey.get(key); + if (hit && hit.moshtariCode !== row.moshtariCode) { + out.set(row.moshtariCode, hit); + break; + } + } + } + return out; + } + async search(organizationId: string, dto: SearchTahesabDto) { const { api } = await this.connections.getApi( organizationId, @@ -516,7 +587,7 @@ export class TahesabPersonLinkService { }); const byCode = new Map(existing.map((e) => [e.moshtariCode, e])); - const results = mapped.map((row) => { + const linked = mapped.map((row) => { const link = row.moshtariCode != null ? byCode.get(row.moshtariCode) : undefined; return { ...row, @@ -527,6 +598,22 @@ export class TahesabPersonLinkService { : null, }; }); + const duplicates = await this.duplicateOwners( + organizationId, + dto.connectionId, + linked.filter((row) => !row.alreadyLinked), + ); + const results = linked.map((row) => { + if (row.alreadyLinked || row.moshtariCode == null) return row; + const dup = duplicates.get(row.moshtariCode); + if (!dup) return row; + return { + ...row, + duplicateOfCode: dup.moshtariCode, + duplicatePersonId: dup.personId, + duplicatePersonName: dup.personName, + }; + }); await this.prisma.accountingSyncJob.create({ data: { @@ -601,7 +688,6 @@ export class TahesabPersonLinkService { const sourceRef = String(dto.moshtariCode); let personId = dto.personId; - let preserveExistingLink = false; if (personId) { const existing = await this.getPerson(organizationId, personId); const prevFirst = existing.firstName; @@ -630,8 +716,8 @@ export class TahesabPersonLinkService { }); } else { // اگر موبایل تکراری است → همان شخص؛ نام قبلی حفظ و نام ته‌حساب جایگزین. - // اگر همان شخص قبلاً به کد دیگری از این اتصال لینک شده، لینک جابه‌جا نمی‌شود - // تا کد قبلی دوباره «واردنشده» نشود و مشتری تکراری ساخته نشود. + // اگر همان شخص قبلاً به کد دیگری از این اتصال لینک شده، نام و لینک دست نمی‌خورند + // تا کد قبلی جابه‌جا نشود و این کد هم مشتری تکراری نسازد. const mobileKeys = phoneIdentityKeys(mobile); const matches = mobileKeys.length ? await this.prisma.person.findMany({ @@ -651,7 +737,22 @@ export class TahesabPersonLinkService { const byMobile = matches.find((person) => person.importSource === 'tahesab') ?? matches[0] ?? null; if (byMobile) { const linkedCode = byMobile.accountingLinks[0]?.moshtariCode; - preserveExistingLink = linkedCode != null && linkedCode !== dto.moshtariCode; + if (linkedCode != null && linkedCode !== dto.moshtariCode) { + const existing = await this.prisma.personAccountingLink.findFirst({ + where: { personId: byMobile.id, connectionId: dto.connectionId }, + include: { + connection: { select: { label: true, dbName: true, isDefault: true } }, + }, + }); + if (!existing) { + throw new NotFoundException('لینک ته‌حساب این مشتری یافت نشد.'); + } + return { + personId: byMobile.id, + link: this.linkDto(existing), + duplicateOf: linkedCode, + }; + } const nameChanged = `${byMobile.firstName} ${byMobile.lastName}`.trim() !== `${firstName} ${lastName}`.trim(); @@ -670,7 +771,7 @@ export class TahesabPersonLinkService { : {}), ...carryPreviousSource(byMobile, 'tahesab'), importSource: 'tahesab', - sourceRef: preserveExistingLink ? String(linkedCode) : sourceRef, + sourceRef, ...(!byMobile.birthDate && pickBirthDate(row) ? { birthDate: pickBirthDate(row) } : {}), ...canonicalMobileUpdate(mobile, byMobile), }, @@ -696,32 +797,6 @@ export class TahesabPersonLinkService { } } - if (preserveExistingLink) { - await this.applyTahesabGroup(organizationId, dto.connectionId, personId, row); - const existing = await this.prisma.personAccountingLink.findFirst({ - where: { personId, connectionId: dto.connectionId }, - include: { - connection: { select: { label: true, dbName: true, isDefault: true } }, - }, - }); - if (!existing) { - throw new NotFoundException('لینک ته‌حساب این مشتری یافت نشد.'); - } - if (!options?.skipJob) { - await this.prisma.accountingSyncJob.create({ - data: { - organizationId, - connectionId: dto.connectionId, - kind: 'import', - status: 'success', - request: dto as unknown as Prisma.InputJsonValue, - result: { personId, linkId: existing.id, keptLink: true } as Prisma.InputJsonValue, - }, - }); - } - return { personId, link: this.linkDto(existing) }; - } - const link = await this.prisma.personAccountingLink.upsert({ where: { personId_connectionId: { @@ -822,6 +897,7 @@ export class TahesabPersonLinkService { let emptyStreak = 0; let imported = 0; let updated = 0; + let duplicate = 0; let failed = 0; const errors: string[] = []; const maxPages = 300; @@ -869,13 +945,14 @@ export class TahesabPersonLinkService { ); updated += 1; } else { - await this.importFromTahesab( + const created = await this.importFromTahesab( organizationId, { connectionId, moshtariCode: code }, { api, row }, { skipJob: true }, ); - imported += 1; + if (created.duplicateOf) duplicate += 1; + else imported += 1; } } catch (err) { failed += 1; @@ -891,20 +968,26 @@ export class TahesabPersonLinkService { errors.push('فهرست مشتریان از سقف خواندن خودکار بیشتر بود.'); } - const summary = `${imported} وارد شد، ${updated} به‌روز شد، ${failed} خطا`; + const summary = [ + `${imported} وارد شد`, + `${updated} به‌روز شد`, + ...(duplicate ? [`${duplicate} شماره تکراری`] : []), + `${failed} خطا`, + ].join('، '); await this.prisma.accountingSyncJob.create({ data: { organizationId, connectionId, kind: 'customer-sync', status: !imported && !updated && (failed > 0 || errors.length > 0) ? 'error' : 'success', - result: { imported, updated, failed, pages: page - 1 } as Prisma.InputJsonValue, + result: { imported, updated, duplicate, failed, pages: page - 1 } as Prisma.InputJsonValue, }, }); this.logger.log(`همگام‌سازی مشتریان ته‌حساب ${connectionId}: ${summary}`); return { imported, updated, + duplicate, failed, summary, error: errors.length ? errors.join('؛ ') : null, @@ -1029,6 +1112,16 @@ export class TahesabPersonLinkService { { connectionId: dto.connectionId, moshtariCode }, bulkApi ? { api: bulkApi, row: rowsByCode.get(moshtariCode) } : undefined, ); + if (r.duplicateOf) { + items.push({ + moshtariCode, + ok: true, + skipped: true, + personId: r.personId, + error: `شماره تکراری است و قبلاً با کد ${r.duplicateOf} لینک شده`, + }); + continue; + } items.push({ moshtariCode, ok: true, personId: r.personId }); } catch (e) { const message = diff --git a/apps/web/src/views/TahesabSettingsView.vue b/apps/web/src/views/TahesabSettingsView.vue index 467f379..5b87bcb 100644 --- a/apps/web/src/views/TahesabSettingsView.vue +++ b/apps/web/src/views/TahesabSettingsView.vue @@ -64,6 +64,9 @@ type SyncResult = { alreadyLinked?: boolean; personId?: string | null; personName?: string | null; + duplicateOfCode?: number | null; + duplicatePersonId?: string | null; + duplicatePersonName?: string | null; }; const syncResults = ref([]); /** هر درخواست listAll یک بازهٔ ۲۰۰۰ کدی است؛ بعد از دو بازهٔ خالی پشت‌سرهم، خواندن تمام می‌شود */ @@ -145,9 +148,61 @@ async function saveAutoSync() { autoSyncSaving.value = false; } } +/** همان قاعدهٔ سرور: موبایل ایران 09… است، بقیهٔ شماره‌ها فقط رقم‌اند. */ +function customerPhoneKey(value?: string | null): string { + const fa = '۰۱۲۳۴۵۶۷۸۹'; + const ar = '٠١٢٣٤٥٦٧٨٩'; + let digits = String(value ?? '') + .replace(/[۰-۹٠-٩]/g, (ch) => { + const faIndex = fa.indexOf(ch); + return String(faIndex >= 0 ? faIndex : ar.indexOf(ch)); + }) + .replace(/\D/g, ''); + if (!digits) return ''; + if (digits.startsWith('0098') && digits.length >= 14) digits = digits.slice(4); + else if (digits.startsWith('98') && digits.length >= 12) digits = digits.slice(2); + if (digits.length === 10 && digits.startsWith('9')) digits = `0${digits}`; + return digits; +} + +const linkedPhoneOwners = computed(() => { + const owners = new Map(); + for (const row of syncResults.value) { + if (!row.alreadyLinked || row.moshtariCode == null) continue; + const key = customerPhoneKey(row.tel); + if (key && !owners.has(key)) { + owners.set(key, { + code: row.moshtariCode, + personId: row.personId ?? null, + personName: row.personName ?? null, + }); + } + } + return owners; +}); + +function duplicateOwner(row: SyncResult) { + if (row.alreadyLinked || row.moshtariCode == null) return null; + if (row.duplicateOfCode != null) { + return { + code: row.duplicateOfCode, + personId: row.duplicatePersonId ?? null, + personName: row.duplicatePersonName ?? null, + }; + } + const key = customerPhoneKey(row.tel); + if (!key) return null; + const owner = linkedPhoneOwners.value.get(key); + if (!owner || owner.code === row.moshtariCode) return null; + return owner; +} + +const duplicateCustomerCount = computed( + () => syncResults.value.filter((row) => duplicateOwner(row)).length, +); const syncVisibleResults = computed(() => syncOnlyNew.value - ? syncResults.value.filter((r) => !r.alreadyLinked) + ? syncResults.value.filter((row) => !row.alreadyLinked && !duplicateOwner(row)) : syncResults.value, ); const syncTableTotalPages = computed(() => @@ -184,7 +239,7 @@ const productCategoryLabel = ref('کارساخته'); function pendingImportCodes() { return syncResults.value - .filter((r) => r.moshtariCode != null && !r.alreadyLinked) + .filter((r) => r.moshtariCode != null && !r.alreadyLinked && !duplicateOwner(r)) .map((r) => r.moshtariCode as number); } @@ -458,10 +513,12 @@ async function searchTahesab(mode: 'range' | 'filter') { ok.value = 'نتیجه‌ای یافت نشد.'; } else { const linked = syncResults.value.filter((r) => r.alreadyLinked).length; - const pending = syncResults.value.length - linked; + const duplicate = syncResults.value.filter((r) => duplicateOwner(r)).length; + const pending = syncResults.value.length - linked - duplicate; ok.value = `${toFaDigits(syncResults.value.length)} مشتری پیدا شد` + - ` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده`; + ` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده` + + (duplicate ? ` · ${toFaDigits(duplicate)} شماره تکراری` : ''); } } catch (e) { error.value = apiErr(e, 'جستجو ناموفق'); @@ -953,7 +1010,8 @@ onMounted(load);

تعداد دفعات در روز و ساعت هر بار را برای همین اتصال مشخص کنید. سرور در آن ساعت‌ها، به وقت تهران، مشتریان تازه را وارد می‌کند و نام مشتری‌های قبلی را هم با ته‌حساب تازه می‌کند. اگر شماره یکی باشد - همان مشتری می‌ماند، نام قبلی حفظ می‌شود و شماره به شکل ۰۹۱۲ ذخیره می‌شود. خاموش یعنی فقط ورود دستی. + همان مشتری می‌ماند و کد دیگر به‌عنوان مشتری تازه وارد نمی‌شود. شماره به شکل ۰۹۱۲ ذخیره می‌شود. + خاموش یعنی فقط ورود دستی.

نتایج جستجو ({{ syncVisibleResults.length }}) +

+ {{ toFaDigits(duplicateCustomerCount) }} مشتری شمارهٔ تکراری دارند و جداگانه وارد نمی‌شوند؛ همان شخص با کد دیگری از قبل لینک است. +

@@ -1120,7 +1181,9 @@ onMounted(load); - همهٔ مشتریان این نتایج قبلاً وارد شده‌اند. + + مشتری تازه‌ای برای ورود نیست. شماره‌های تکراری از قبل با کد دیگری لینک شده‌اند. + {{ r.moshtariCode }} @@ -1130,11 +1193,14 @@ onMounted(load); لینک شده{{ r.personName ? ` (${r.personName})` : '' }} + + شماره تکراری، کد {{ toFaDigits(duplicateOwner(r)!.code) }} + آماده ورود مشاهده شخص From 8b8d01976d8c85ec90c1eda0ac43b87ecab69301 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Mon, 9 Nov 2026 15:09:49 +0330 Subject: [PATCH 17/62] fix(pipeline): hide prior-only sales paths from current work The board lists a pipeline in current work only when it has a deal in that period, and keeps archive-only paths for the prior-data view. Co-authored-by: Cursor --- .../api/src/pipelines/pipelines.controller.ts | 7 ++- apps/api/src/pipelines/pipelines.service.ts | 47 +++++++++++++++---- apps/web/src/views/PipelineBoardView.vue | 23 ++++++--- 3 files changed, 60 insertions(+), 17 deletions(-) diff --git a/apps/api/src/pipelines/pipelines.controller.ts b/apps/api/src/pipelines/pipelines.controller.ts index e7d26f8..518456d 100644 --- a/apps/api/src/pipelines/pipelines.controller.ts +++ b/apps/api/src/pipelines/pipelines.controller.ts @@ -31,8 +31,11 @@ export class PipelinesController { constructor(private readonly pipelinesService: PipelinesService) {} @Get() - list(@CurrentUser() user: { organizationId: string }) { - return this.pipelinesService.list(user.organizationId); + list( + @CurrentUser() user: Actor, + @Query('forLens') forLens?: string, + ) { + return this.pipelinesService.list(user, forLens === '1'); } @Get('board') diff --git a/apps/api/src/pipelines/pipelines.service.ts b/apps/api/src/pipelines/pipelines.service.ts index f5db4d1..e7eac1c 100644 --- a/apps/api/src/pipelines/pipelines.service.ts +++ b/apps/api/src/pipelines/pipelines.service.ts @@ -102,24 +102,55 @@ export class PipelinesService { return this.toPipelineDto(created); } - async list(organizationId: string): Promise { + async list(actorOrOrgId: Actor | string, forLens = false): Promise { + const organizationId = + typeof actorOrOrgId === 'string' ? actorOrOrgId : actorOrOrgId.organizationId; + const actor = typeof actorOrOrgId === 'string' ? undefined : actorOrOrgId; await this.ensureDefaultPipeline(organizationId); const rows = await this.prisma.pipeline.findMany({ where: { organizationId }, include: { stages: { orderBy: { position: 'asc' } } }, orderBy: [{ isDefault: 'desc' }, { name: 'asc' }], }); - const counts = await this.prisma.deal.groupBy({ - by: ['pipelineId'], - where: { organizationId }, - _count: { _all: true }, - }); + const lens = actor?.priorLens; + const lensActive = forLens && (lens === 'current' || lens === 'archive'); + const access = actor ? dealAccessWhere(actor) : {}; + const prior = lensActive + ? dealPriorWhere(actor?.priorLens, actor?.priorCutoff) + : {}; + const [counts, lensCounts] = await Promise.all([ + this.prisma.deal.groupBy({ + by: ['pipelineId'], + where: lensActive ? { organizationId, AND: [access] } : { organizationId }, + _count: { _all: true }, + }), + lensActive + ? this.prisma.deal.groupBy({ + by: ['pipelineId'], + where: { organizationId, AND: [access, prior] }, + _count: { _all: true }, + }) + : Promise.resolve([]), + ]); const dealCountByPipeline = new Map( counts.map((row) => [row.pipelineId, row._count._all]), ); - return rows.map((row) => ({ + const lensCountByPipeline = new Map( + lensCounts.map((row) => [row.pipelineId, row._count._all]), + ); + const visible = lensActive + ? rows.filter((row) => { + const inLens = lensCountByPipeline.get(row.id) ?? 0; + const total = dealCountByPipeline.get(row.id) ?? 0; + if (lens === 'archive') return inLens > 0; + return inLens > 0 || total === 0; + }) + : rows; + return visible.map((row) => ({ ...this.toPipelineDto(row), - dealCount: dealCountByPipeline.get(row.id) ?? 0, + dealCount: lensActive + ? (lensCountByPipeline.get(row.id) ?? 0) + : (dealCountByPipeline.get(row.id) ?? 0), })); } diff --git a/apps/web/src/views/PipelineBoardView.vue b/apps/web/src/views/PipelineBoardView.vue index 94f1dd6..6a50291 100644 --- a/apps/web/src/views/PipelineBoardView.vue +++ b/apps/web/src/views/PipelineBoardView.vue @@ -177,7 +177,9 @@ function findAccent(dealId: string): PipelineStage['color'] { } async function loadPipelines() { - const { data } = await api.get('/pipelines'); + const { data } = await api.get('/pipelines', { + params: { forLens: '1' }, + }); pipelines.value = data; } @@ -186,16 +188,23 @@ async function load() { error.value = ''; try { await loadPipelines(); - const pipelineId = - typeof route.query.pipelineId === 'string' - ? route.query.pipelineId - : undefined; + const requested = + typeof route.query.pipelineId === 'string' ? route.query.pipelineId : ''; + const pipelineId = pipelines.value.some((item) => item.id === requested) + ? requested + : pipelines.value[0]?.id; + if (!pipelineId) { + boardPipelineId.value = ''; + stages.value = []; + if (requested) await router.replace({ name: 'pipeline', query: {} }); + return; + } const { data } = await api.get('/pipelines/board', { - params: pipelineId ? { pipelineId } : undefined, + params: { pipelineId }, }); boardPipelineId.value = data.pipeline.id; stages.value = mapBoardToStages(data, formatDealDate); - if (!pipelineId || pipelineId !== data.pipeline.id) { + if (requested !== data.pipeline.id) { await router.replace({ name: 'pipeline', query: { pipelineId: data.pipeline.id }, From b03d97dd9e21ebcffcf2627084d7e0be9233db17 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Mon, 9 Nov 2026 16:39:06 +0330 Subject: [PATCH 18/62] fix(activities): show each note as its own dated message The colon inside the clock was splitting the stamp from the comment, so date, author, text, and attachments now stay together. Co-authored-by: Cursor --- apps/web/src/lib/activity-thread.ts | 71 ++++++++ apps/web/src/views/ActivityDetailView.vue | 188 ++++++++++++++++++++-- 2 files changed, 248 insertions(+), 11 deletions(-) create mode 100644 apps/web/src/lib/activity-thread.ts diff --git a/apps/web/src/lib/activity-thread.ts b/apps/web/src/lib/activity-thread.ts new file mode 100644 index 0000000..d2ebd56 --- /dev/null +++ b/apps/web/src/lib/activity-thread.ts @@ -0,0 +1,71 @@ +import { jalaliToDate } from '@/lib/jalali'; + +export type ActivityThreadEntry = { + at: Date | null; + dateLabel: string; + timeLabel: string; + author: string; + body: string; +}; + +const STAMP = /^\[(.+?) ساعت (\S+?)(?: — (.+))?\]$/; + +/** یادداشت فعالیت را به نظرهای جدا با مهر تاریخ/ساعت/نویسنده تبدیل می‌کند. */ +export function parseActivityThread(raw: string | null | undefined): ActivityThreadEntry[] | null { + const text = (raw ?? '').replace(/\r\n/g, '\n').trim(); + if (!text) return null; + + const entries: ActivityThreadEntry[] = []; + const preamble: string[] = []; + let current: ActivityThreadEntry | null = null; + let sawStamp = false; + + for (const line of text.split('\n')) { + const match = line.trim().match(STAMP); + if (match) { + sawStamp = true; + if (current) entries.push(trimEntry(current)); + current = { + at: stampToDate(match[1] ?? '', match[2] ?? ''), + dateLabel: (match[1] ?? '').trim(), + timeLabel: (match[2] ?? '').trim(), + author: (match[3] ?? '').trim(), + body: '', + }; + continue; + } + if (current) current.body += `${current.body ? '\n' : ''}${line}`; + else preamble.push(line); + } + if (current) entries.push(trimEntry(current)); + if (!sawStamp) return null; + + const head = preamble.join('\n').trim(); + if (head) { + entries.unshift({ at: null, dateLabel: '', timeLabel: '', author: '', body: head }); + } + return entries; +} + +function trimEntry(entry: ActivityThreadEntry): ActivityThreadEntry { + return { ...entry, body: entry.body.trim() }; +} + +function latinDigits(value: string): string { + const fa = '۰۱۲۳۴۵۶۷۸۹'; + const ar = '٠١٢٣٤٥٦٧٨٩'; + return value.replace(/[۰-۹٠-٩]/g, (ch) => { + const faIndex = fa.indexOf(ch); + return String(faIndex >= 0 ? faIndex : ar.indexOf(ch)); + }); +} + +function stampToDate(dateLabel: string, timeLabel: string): Date | null { + const date = latinDigits(dateLabel).match(/(\d{4})\/(\d{1,2})\/(\d{1,2})/); + if (!date) return null; + const at = jalaliToDate(Number(date[1]), Number(date[2]), Number(date[3])); + if (Number.isNaN(at.getTime())) return null; + const time = latinDigits(timeLabel).match(/(\d{1,2}):(\d{2})/); + if (time) at.setHours(Number(time[1]), Number(time[2]), 0, 0); + return at; +} diff --git a/apps/web/src/views/ActivityDetailView.vue b/apps/web/src/views/ActivityDetailView.vue index b5101e1..880b958 100644 --- a/apps/web/src/views/ActivityDetailView.vue +++ b/apps/web/src/views/ActivityDetailView.vue @@ -25,6 +25,7 @@ import { useAuthStore } from '@/stores/auth'; import { canAssignToOthers } from '@/lib/assign-access'; import { activityTypeView, typeColorStyle, useActivityTypes } from '@/lib/activity-types'; import { brand } from '@mento/shared'; +import { parseActivityThread, type ActivityThreadEntry } from '@/lib/activity-thread'; import { leadNoteFileIsImage, noteChips, @@ -64,12 +65,22 @@ const loading = ref(true); const saving = ref(false); const error = ref(''); const activity = ref(null); -const imageUrls = ref>([]); +type NoteMedia = { + id: string; + name: string; + url: string; + kind: 'image' | 'audio' | 'file'; + createdAt: string; +}; +const imageUrls = ref([]); const moreOpen = ref(false); const commentOpen = ref(false); const postponeOpen = ref(false); const noteOpen = ref(true); -const noteModel = computed(() => parseLeadFormNotes(activity.value?.description)); +const thread = computed(() => parseActivityThread(activity.value?.description)); +const noteModel = computed(() => + thread.value ? { mode: 'prose' as const, prose: '', rows: [] as LeadNoteRow[] } : parseLeadFormNotes(activity.value?.description), +); const noteRows = computed(() => noteModel.value.mode === 'answers' ? noteModel.value.rows : ([] as LeadNoteRow[]), ); @@ -80,8 +91,53 @@ const noteExtra = computed(() => (chip) => !(chip.kind === 'text' && chip.text.replace(/\s+/g, '').trim() === 'پاسخ‌هایفرم:'), ), ); +const COMMENT_MEDIA_WINDOW_MS = 3 * 60 * 1000; + +const threadBlocks = computed(() => { + const entries = thread.value; + if (!entries) return null; + const blocks = entries.map((entry) => ({ ...entry, media: [] as NoteMedia[] })); + const used = new Set(); + for (const image of imageUrls.value) { + const at = new Date(image.createdAt).getTime(); + if (Number.isNaN(at)) continue; + let best = -1; + let bestDelta = Number.POSITIVE_INFINITY; + blocks.forEach((block, index) => { + if (!block.at) return; + const delta = block.at.getTime() - at; + if (delta >= -60_000 && delta < bestDelta) { + best = index; + bestDelta = delta; + } + }); + if (best >= 0 && bestDelta <= COMMENT_MEDIA_WINDOW_MS) { + blocks[best]!.media.push(image); + used.add(image.id); + } + } + const firstStamp = blocks.find((block) => block.at)?.at?.getTime() ?? Number.POSITIVE_INFINITY; + const preamble = blocks.find((block) => !block.at); + const loose: NoteMedia[] = []; + for (const image of imageUrls.value) { + if (used.has(image.id)) continue; + const at = new Date(image.createdAt).getTime(); + if (preamble && !Number.isNaN(at) && at < firstStamp) preamble.media.push(image); + else loose.push(image); + } + return { blocks, loose }; +}); + +const looseMedia = computed(() => threadBlocks.value?.loose ?? imageUrls.value); + const recoveredImages = ref>({}); +function entryRows(entry: ActivityThreadEntry): LeadNoteRow[] { + if (entry.at) return []; + const parsed = parseLeadFormNotes(entry.body); + return parsed.mode === 'answers' ? parsed.rows : []; +} + function noteImageSrc(file: LeadNoteFile): string | null { if (!leadNoteFileIsImage(file)) return null; return file.dataUrl || recoveredImages.value[file.name] || null; @@ -226,7 +282,7 @@ function clearImageUrls() { async function loadActivityImages(row: ActivityDto) { clearImageUrls(); - const next: Array<{ id: string; name: string; url: string; kind: 'image' | 'audio' | 'file' }> = []; + const next: NoteMedia[] = []; for (const image of row.images ?? []) { const mime = image.mimeType.toLowerCase(); const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file'; @@ -239,6 +295,7 @@ async function loadActivityImages(row: ActivityDto) { name: image.fileName, url: URL.createObjectURL(data), kind, + createdAt: image.createdAt, }); } catch { /* فایل در دسترس نیست */ @@ -617,7 +674,76 @@ onMounted(() => {
-
+
+
+
+ + {{ entry.author }} +
+
+
+
{{ row.label }}
+
+ + {{ row.file.name }} + +
+
+
+

+ +

+
+ + + +
+
+
+ +
+
+
{{ row.label }}
@@ -652,7 +778,7 @@ onMounted(() => {

یادداشتی ثبت نشده.

-

+

-
+ -
+
-
    -
  • + @@ -1098,6 +1224,46 @@ dd { color: #94a3b8; } +.note-thread { + display: flex; + flex-direction: column; + gap: 0.75rem; + margin-top: 0.75rem; +} + +.note-bubble { + border: 1px solid #e2e8f0; + border-radius: 0.85rem; + background: #f8fafc; + padding: 0.7rem 0.85rem; +} + +.note-bubble header { + display: flex; + justify-content: space-between; + gap: 0.75rem; + margin-bottom: 0.35rem; + color: #64748b; + font-size: 0.78rem; +} + +.note-bubble header span { + color: #0f766e; + font-weight: 700; +} + +.note .note-bubble-body { + margin: 0; + color: #334155; + line-height: 1.9; + white-space: pre-line; + overflow-wrap: anywhere; +} + +.note-bubble .note-rows { + margin-top: 0; +} + .note-rows { margin: 0.75rem 0 0; display: grid; From dae3ae3f7ea9bf624bfe223209eb418940e4abc8 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Mon, 9 Nov 2026 18:34:23 +0330 Subject: [PATCH 19/62] fix(notes): keep card titles visible when the square card is crowded Co-authored-by: Cursor --- apps/web/src/views/NotesView.vue | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/web/src/views/NotesView.vue b/apps/web/src/views/NotesView.vue index c30baac..a46e07a 100644 --- a/apps/web/src/views/NotesView.vue +++ b/apps/web/src/views/NotesView.vue @@ -1906,7 +1906,11 @@ onBeforeUnmount(() => { margin: 0 0 0.35rem; font-size: 0.95rem; font-weight: 700; + line-height: 1.35; color: #0f172a; + flex-shrink: 0; + min-width: 0; + overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; @@ -1918,7 +1922,7 @@ onBeforeUnmount(() => { color: #334155; font-size: 0.82rem; line-height: 1.45; - flex: 1; + flex: 1 1 2.9em; min-height: 0; overflow: hidden; display: -webkit-box; @@ -1953,13 +1957,15 @@ onBeforeUnmount(() => { margin-top: 0.45rem; border-radius: var(--radius); overflow: hidden; - flex-shrink: 0; + flex: 0 1 72px; + min-height: 0; max-height: 72px; } .card-thumb img { display: block; width: 100%; height: 72px; + max-height: 100%; object-fit: cover; } @@ -2176,11 +2182,16 @@ onBeforeUnmount(() => { } .title-input { + width: 100%; + min-width: 0; + box-sizing: border-box; border: 0; border-bottom: 1px solid #e2e8f0; padding: 0.35rem 0; font-size: 1rem; font-weight: 600; + line-height: 1.4; + color: #0f172a; outline: none; background: transparent; } From da851bd9e5429253e1ba3d0b6fb029626bda150c Mon Sep 17 00:00:00 2001 From: Mahdi Date: Mon, 9 Nov 2026 20:48:43 +0330 Subject: [PATCH 20/62] feat(activities): let every assignee finish their own share Co-authored-by: Cursor --- .../migration.sql | 6 + apps/api/prisma/schema.prisma | 9 + .../src/activities/activities.controller.ts | 12 +- apps/api/src/activities/activities.service.ts | 212 +++++++++++++++--- apps/api/src/activities/dto.ts | 8 + .../activities/ActivitiesKanban.vue | 16 ++ apps/web/src/views/ActivitiesView.vue | 35 ++- apps/web/src/views/ActivityDetailView.vue | 183 +++++++++++++-- apps/web/src/views/ActivityFormView.vue | 40 +++- packages/shared/src/index.ts | 9 + 10 files changed, 479 insertions(+), 51 deletions(-) create mode 100644 apps/api/prisma/migrations/20261109170000_activity_completion_mode/migration.sql diff --git a/apps/api/prisma/migrations/20261109170000_activity_completion_mode/migration.sql b/apps/api/prisma/migrations/20261109170000_activity_completion_mode/migration.sql new file mode 100644 index 0000000..9e44bab --- /dev/null +++ b/apps/api/prisma/migrations/20261109170000_activity_completion_mode/migration.sql @@ -0,0 +1,6 @@ +-- CreateEnum +CREATE TYPE "ActivityCompletionMode" AS ENUM ('any', 'all'); + +-- AlterTable +ALTER TABLE "Activity" ADD COLUMN "completionMode" "ActivityCompletionMode" NOT NULL DEFAULT 'any', +ADD COLUMN "completedByIds" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[]; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index d78e2bb..05ebe03 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -33,6 +33,11 @@ enum ActivityStatus { canceled } +enum ActivityCompletionMode { + any + all +} + enum ActivityPriority { low medium @@ -883,6 +888,10 @@ model Activity { /// زمان ارسال یادآور؛ با تغییر reminderAt پاک می‌شود reminderSentAt DateTime? completedAt DateTime? + /// any = با انجام یکی بسته می‌شود؛ all = هر مسئول باید سهم خودش را بزند + completionMode ActivityCompletionMode @default(any) + /// مسئولانی که سهم خود را در حالت all ثبت کرده‌اند + completedByIds String[] @default([]) tags String[] @default([]) personId String? person Person? @relation(fields: [personId], references: [id], onDelete: SetNull) diff --git a/apps/api/src/activities/activities.controller.ts b/apps/api/src/activities/activities.controller.ts index af1e778..d8f161f 100644 --- a/apps/api/src/activities/activities.controller.ts +++ b/apps/api/src/activities/activities.controller.ts @@ -438,8 +438,16 @@ export class ActivitiesController { } @Patch(':id/complete') - complete(@CurrentUser() user: Actor, @Param('id') id: string) { - return this.activitiesService.complete(user.organizationId, id, user); + complete( + @CurrentUser() user: Actor, + @Param('id') id: string, + @Query('force') force?: string, + @Query('undo') undo?: string, + ) { + return this.activitiesService.complete(user.organizationId, id, user, { + force: force === '1' || force === 'true', + undo: undo === '1' || undo === 'true', + }); } @Delete(':id') diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts index 537d2ef..4c235cc 100644 --- a/apps/api/src/activities/activities.service.ts +++ b/apps/api/src/activities/activities.service.ts @@ -52,6 +52,28 @@ type ActivityActor = Pick< 'userId' | 'role' | 'priorLens' | 'priorCutoff' | 'leadsAccess' | 'teamPeerIds' >; +function assigneeIdList(row: { + assigneeId?: string | null; + assignees?: Array<{ id: string }>; +}): string[] { + const ids = row.assignees?.map((item) => item.id) ?? []; + if (ids.length) return [...new Set(ids)]; + return row.assigneeId ? [row.assigneeId] : []; +} + +function canForceClose( + actor: { userId: string; role: string }, + createdById: string | null | undefined, +): boolean { + return actor.role === 'owner' || actor.role === 'admin' || actor.userId === createdById; +} + +function reconcileAllShares(assigneeIds: string[], completedByIds: string[]) { + const kept = [...new Set(completedByIds.filter((id) => assigneeIds.includes(id)))]; + const done = assigneeIds.length > 0 && assigneeIds.every((id) => kept.includes(id)); + return { status: done ? ('done' as const) : ('open' as const), completedByIds: kept }; +} + /** stageId = شناسهٔ مرحله یا 'all'؛ وقتی ست باشد فیلتر زمانی وضعیت را تحمیل نمی‌کند (جز عقب‌افتاده) */ type StageScope = { stageId: string }; @@ -82,6 +104,8 @@ type ActivityRow = { reminderNotifySms: boolean; reminderSentAt: Date | null; completedAt: Date | null; + completionMode?: 'any' | 'all'; + completedByIds?: string[]; importSource?: string; promotedFromPriorAt?: Date | null; tags: string[]; @@ -186,22 +210,39 @@ export class ActivitiesService { return { stages, types }; } + /** کارهای بازِ «من» که سهم‌شان ثبت شده، از میز کار شخص خارج می‌شوند. */ + private deskScope( + actor: ActivityActor, + desk?: 'mine' | 'team', + ): Prisma.ActivityWhereInput { + if (desk !== 'mine') return activityAccessWhere(actor); + return { + AND: [ + { + OR: [ + { assigneeId: actor.userId }, + { assignees: { some: { id: actor.userId } } }, + { participantIds: { has: actor.userId } }, + ], + }, + { + NOT: { + completionMode: 'all', + status: 'open', + completedByIds: { has: actor.userId }, + }, + }, + ], + }; + } + async summary( organizationId: string, actor: ActivityActor, desk?: 'mine' | 'team', ): Promise { const { start, end } = dayBounds(); - const scope: Prisma.ActivityWhereInput = - desk === 'mine' - ? { - OR: [ - { assigneeId: actor.userId }, - { assignees: { some: { id: actor.userId } } }, - { participantIds: { has: actor.userId } }, - ], - } - : activityAccessWhere(actor); + const scope = this.deskScope(actor, desk); const prior = activityPriorWhere(actor.priorLens, actor.priorCutoff); const [todayCount, overdueCount] = await Promise.all([ this.prisma.activity.count({ @@ -534,8 +575,24 @@ export class ActivitiesService { const stage = await this.stages.get(organizationId, stageId); const existing = await this.prisma.activity.findFirst({ where: { id, organizationId }, - select: { status: true, completedAt: true }, + select: { + status: true, + completedAt: true, + completionMode: true, + completedByIds: true, + createdById: true, + assigneeId: true, + assignees: { select: { id: true } }, + }, }); + if ( + stage.kind === 'done' && + existing?.completionMode === 'all' && + assigneeIdList(existing).length > 1 && + !canForceClose(actor, existing.createdById) + ) { + return this.complete(organizationId, id, actor); + } const row = await this.prisma.activity.update({ where: { id }, data: { @@ -550,6 +607,9 @@ export class ActivitiesService { : stage.kind === 'open' ? null : undefined, + ...(stage.kind === 'open' && existing?.status !== 'open' + ? { completedByIds: [] } + : {}), }, include, }); @@ -675,6 +735,8 @@ export class ActivitiesService { assignees: assigneeIds.length ? { connect: assigneeIds.map((id) => ({ id })) } : undefined, + completionMode: dto.completionMode === 'all' ? 'all' : 'any', + completedByIds: [], createdById: userId, }, include, @@ -743,7 +805,17 @@ export class ActivitiesService { const existing = await this.prisma.activity.findFirst({ where: { id, organizationId }, - select: { status: true, type: true, typeDefId: true, fields: true, participantIds: true }, + select: { + status: true, + type: true, + typeDefId: true, + fields: true, + participantIds: true, + completionMode: true, + completedByIds: true, + assigneeId: true, + assignees: { select: { id: true } }, + }, }); const data: Prisma.ActivityUncheckedUpdateInput = {}; if (dto.title !== undefined) data.title = dto.title.trim(); @@ -812,6 +884,7 @@ export class ActivitiesService { if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null); if ('leadId' in dto) data.leadId = emptyToNull(dto.leadId ?? null); let assigneeConnect: Array<{ id: string }> | undefined; + let nextAssigneeIds: string[] | undefined; if (dto.assigneeIds !== undefined || 'assigneeId' in dto) { const current = await this.prisma.activity.findFirst({ where: { id, organizationId }, @@ -839,6 +912,7 @@ export class ActivitiesService { ); data.assigneeId = assigneeIds[0]!; assigneeConnect = assigneeIds.map((uid) => ({ id: uid })); + nextAssigneeIds = assigneeIds; } else { const assigneeId = emptyToNull(dto.assigneeId ?? null); if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId); @@ -852,12 +926,41 @@ export class ActivitiesService { data.assigneeId = assigneeId; if (assigneeId) assigneeConnect = [{ id: assigneeId }]; else assigneeConnect = []; + nextAssigneeIds = assigneeId ? [assigneeId] : []; } } - if (dto.status !== undefined) { - data.status = dto.status; - data.completedAt = - dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined; + const modeChanged = dto.completionMode === 'any' || dto.completionMode === 'all'; + const nextMode = modeChanged ? dto.completionMode! : (existing?.completionMode ?? 'any'); + if (modeChanged) data.completionMode = nextMode; + const prevAssigneeIds = assigneeIdList(existing ?? {}); + const nextIds = nextAssigneeIds ?? prevAssigneeIds; + const explicitDone = dto.status === 'done'; + const explicitReopen = dto.status === 'open' && existing?.status !== 'open'; + const explicitCancel = dto.status === 'canceled'; + if (explicitDone) { + data.status = 'done'; + data.completedAt = new Date(); + } else if (explicitReopen) { + data.status = 'open'; + data.completedAt = null; + data.completedByIds = []; + } else if (explicitCancel) { + data.status = 'canceled'; + } else if (nextMode === 'any' && modeChanged) { + data.completedByIds = []; + } else if (nextMode === 'all' && (modeChanged || nextAssigneeIds)) { + const reconciled = reconcileAllShares(nextIds, existing?.completedByIds ?? []); + data.completedByIds = reconciled.completedByIds; + const finishedStaysFinished = existing?.status === 'done' && !nextAssigneeIds; + if (existing?.status !== 'canceled' && !finishedStaysFinished) { + if (reconciled.status === 'done' && existing?.status !== 'done') { + data.status = 'done'; + data.completedAt = new Date(); + } else if (reconciled.status === 'open' && existing?.status === 'done') { + data.status = 'open'; + data.completedAt = null; + } + } } const row = await this.prisma.activity.update({ @@ -881,7 +984,7 @@ export class ActivitiesService { addedParticipants.filter((uid) => !assigneeSet.has(uid)), ); } - if (dto.status === 'done' && existing?.status !== 'done') { + if (data.status === 'done' && existing?.status !== 'done') { await this.fireDone(organizationId, row); } return this.toDto(row, await this.ctx(organizationId)); @@ -891,18 +994,74 @@ export class ActivitiesService { organizationId: string, id: string, actor: ActivityActor, + options: { force?: boolean; undo?: boolean } = {}, ): Promise { await this.ensureExists(organizationId, id, actor); const existing = await this.prisma.activity.findFirst({ where: { id, organizationId }, - select: { status: true }, + select: { + status: true, + completionMode: true, + completedByIds: true, + createdById: true, + assigneeId: true, + assignees: { select: { id: true } }, + }, }); + if (!existing) throw new NotFoundException('فعالیت پیدا نشد'); + if (existing.status === 'canceled') { + throw new BadRequestException('فعالیت لغو شده است'); + } + + const assignees = assigneeIdList(existing); + const allowedForce = canForceClose(actor, existing.createdById); + if (options.force && !allowedForce) { + throw new ForbiddenException('بستن فعالیت برای همه فقط برای سازنده یا مدیر ممکن است'); + } + + if (options.undo) { + if (existing.completionMode !== 'all' || existing.status !== 'open') { + throw new BadRequestException('سهم انجام‌شده را فقط تا وقتی فعالیت باز است می‌توان لغو کرد'); + } + const row = await this.prisma.activity.update({ + where: { id }, + data: { + completedByIds: existing.completedByIds.filter((uid) => uid !== actor.userId), + }, + include, + }); + return this.toDto(row, await this.ctx(organizationId)); + } + + const personal = + existing.completionMode === 'all' && assignees.length > 1 && !options.force; + if (!personal) { + const row = await this.prisma.activity.update({ + where: { id }, + data: { status: 'done', completedAt: new Date() }, + include, + }); + if (existing.status !== 'done') await this.fireDone(organizationId, row); + return this.toDto(row, await this.ctx(organizationId)); + } + + if (!assignees.includes(actor.userId)) { + throw new ForbiddenException('فقط مسئول این فعالیت می‌تواند سهم خودش را ثبت کند'); + } + const reconciled = reconcileAllShares(assignees, [ + ...existing.completedByIds, + actor.userId, + ]); const row = await this.prisma.activity.update({ where: { id }, - data: { status: 'done', completedAt: new Date() }, + data: { + completedByIds: reconciled.completedByIds, + status: reconciled.status, + completedAt: reconciled.status === 'done' ? new Date() : null, + }, include, }); - if (existing?.status !== 'done') { + if (reconciled.status === 'done' && existing.status !== 'done') { await this.fireDone(organizationId, row); } return this.toDto(row, await this.ctx(organizationId)); @@ -1108,16 +1267,7 @@ export class ActivitiesService { typeRows: TypeRow[] = [], ): Prisma.ActivityWhereInput { const { start, end } = dayBounds(); - const scope: Prisma.ActivityWhereInput = - desk === 'mine' - ? { - OR: [ - { assigneeId: actor.userId }, - { assignees: { some: { id: actor.userId } } }, - { participantIds: { has: actor.userId } }, - ], - } - : activityAccessWhere(actor); + const scope = this.deskScope(actor, desk); const facetAssignee = facets?.assigneeId?.trim(); const facetTypeDef = facets?.typeDefId?.trim(); const facetTitle = facets?.title?.trim(); @@ -1418,6 +1568,8 @@ export class ActivitiesService { reminderNotifySms: row.reminderNotifySms, reminderSentAt: row.reminderSentAt?.toISOString() ?? null, completedAt: row.completedAt?.toISOString() ?? null, + completionMode: row.completionMode ?? 'any', + completedByIds: row.completedByIds ?? [], importSource: row.importSource ?? 'manual', promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null, tags: row.tags ?? [], diff --git a/apps/api/src/activities/dto.ts b/apps/api/src/activities/dto.ts index cab5131..0d80d7b 100644 --- a/apps/api/src/activities/dto.ts +++ b/apps/api/src/activities/dto.ts @@ -384,6 +384,10 @@ export class CreateActivityDto { @IsArray() @IsString({ each: true }) assigneeIds?: string[]; + + @IsOptional() + @IsIn(['any', 'all']) + completionMode?: 'any' | 'all'; } export class UpdateActivityDto { @@ -484,4 +488,8 @@ export class UpdateActivityDto { @IsArray() @IsString({ each: true }) assigneeIds?: string[]; + + @IsOptional() + @IsIn(['any', 'all']) + completionMode?: 'any' | 'all'; } diff --git a/apps/web/src/components/activities/ActivitiesKanban.vue b/apps/web/src/components/activities/ActivitiesKanban.vue index d939153..20d7d11 100644 --- a/apps/web/src/components/activities/ActivitiesKanban.vue +++ b/apps/web/src/components/activities/ActivitiesKanban.vue @@ -41,6 +41,7 @@ const emit = defineEmits<{ stagesChanged: []; add: [stageId: string]; error: [message: string]; + notice: [message: string]; menuDeal: [activity: ActivityDto, stageId?: string]; toggleSelect: [activityId: string]; bulkDelete: []; @@ -292,6 +293,21 @@ async function moveCard(activityId: string, toStageId: string, index?: number) { stageId: toStageId, position: insertAt, }); + if (!same && data.status !== toStage.kind) { + const hideFromMine = props.params.desk === 'mine'; + from.items = hideFromMine + ? prevFrom.filter((row) => row.id !== activityId) + : prevFrom.map((row) => (row.id === activityId ? data : row)); + from.total = hideFromMine ? Math.max(0, prevFromTotal - 1) : prevFromTotal; + to.items = prevTo; + to.total = prevToTotal; + emit( + 'notice', + 'سهم شما ثبت شد. فعالیت وقتی انجام‌شده می‌شود که همهٔ مسئول‌ها سهم خود را بزنند.', + ); + emit('changed'); + return; + } const column = same ? from : to; column.items = column.items.map((i) => (i.id === activityId ? data : i)); emit('changed'); diff --git a/apps/web/src/views/ActivitiesView.vue b/apps/web/src/views/ActivitiesView.vue index d44c8fc..a1ff255 100644 --- a/apps/web/src/views/ActivitiesView.vue +++ b/apps/web/src/views/ActivitiesView.vue @@ -201,6 +201,7 @@ const page = computed(() => { const loading = ref(false); const error = ref(''); +const notice = ref(''); const data = ref | null>(null); const q = ref(typeof route.query.q === 'string' ? route.query.q : ''); const users = ref([]); @@ -837,6 +838,30 @@ function onFacetDone() { openCol.value = null; } +function assigneePeopleOf(item: ActivityDto) { + if (item.assignees?.length) return item.assignees; + return item.assignee ? [item.assignee] : []; +} + +function needsEveryone(item: ActivityDto) { + return item.completionMode === 'all' && assigneePeopleOf(item).length > 1; +} + +function canMarkShare(item: ActivityDto) { + if (item.status !== 'open') return false; + if (!needsEveryone(item)) return true; + const mine = auth.user?.id; + if (!mine) return false; + return ( + assigneePeopleOf(item).some((person) => person.id === mine) && + !item.completedByIds?.includes(mine) + ); +} + +function completeLabel(item: ActivityDto) { + return needsEveryone(item) ? 'انجام سهم من' : 'انجام شد'; +} + async function complete(id: string) { menuId.value = null; boardMenuId.value = null; @@ -1503,6 +1528,7 @@ onUnmounted(() => {

{{ error }}

+

{{ notice }}

{{ importMsg }}

@@ -1532,6 +1558,7 @@ onUnmounted(() => { @stages-changed="onStagesChanged" @add="openAddInStage" @error="(msg: string) => (error = msg)" + @notice="(msg: string) => (notice = msg)" @menu-deal="onBoardMenu" @toggle-select="toggleSelect" @bulk-delete="askBulkDelete" @@ -1755,8 +1782,8 @@ onUnmounted(() => { - - + +
+ +
@@ -855,15 +937,25 @@ onMounted(() => { بازگشایی +
+
+ نحوهٔ انجام + + +
{{ canAssignOthers @@ -1799,6 +1816,27 @@ watch([id, isNew], () => void load(), { immediate: true }); font-size: 0.75rem; } +.completion-mode { + display: flex; + flex-wrap: wrap; + gap: 0.65rem 1rem; + margin-top: 0.75rem; + color: #334155; + font-size: 0.88rem; +} + +.completion-mode span { + width: 100%; + font-weight: 600; +} + +.completion-mode label { + display: inline-flex; + align-items: center; + gap: 0.35rem; + cursor: pointer; +} + .assignee-chips { display: flex; flex-wrap: wrap; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index a88e449..b77e2ee 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2038,6 +2038,8 @@ export interface ActivityImageDto { createdAt: string; } +export type ActivityCompletionMode = "any" | "all"; + export interface ActivityDto { id: string; type: ActivityType; @@ -2055,6 +2057,10 @@ export interface ActivityDto { /** زمان ارسال یادآور (اگر ارسال شده باشد) */ reminderSentAt: string | null; completedAt: string | null; + /** any = با انجام یکی کافی است؛ all = هر مسئول باید سهم خودش را بزند */ + completionMode?: ActivityCompletionMode; + /** شناسهٔ مسئولانی که سهم خود را در حالت all ثبت کرده‌اند */ + completedByIds?: string[]; /** manual یا didar؛ برای جدا کردن سابقهٔ قبلی */ importSource?: string; promotedFromPriorAt?: string | null; @@ -2112,6 +2118,8 @@ export interface CreateActivityRequest { assigneeId?: string | null; /** چند مسئول؛ اولی به‌عنوان assigneeId ذخیره می‌شود */ assigneeIds?: string[]; + /** پیش‌فرض any. فقط وقتی چند مسئول دارد معنی دارد */ + completionMode?: ActivityCompletionMode; } export interface UpdateActivityRequest { @@ -2136,6 +2144,7 @@ export interface UpdateActivityRequest { leadId?: string | null; assigneeId?: string | null; assigneeIds?: string[]; + completionMode?: ActivityCompletionMode; } export interface ActivitySummaryDto { From 7a8007fff0f3d6c7f0ecbd139710bf1988cebfe9 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Mon, 9 Nov 2026 21:30:05 +0330 Subject: [PATCH 21/62] feat(activities): keep multi-assignee completion readable for large teams Co-authored-by: Cursor --- apps/web/src/components/UserMultiSelect.vue | 87 +++++-- apps/web/src/views/ActivityDetailView.vue | 261 +++++++++++++++++++- apps/web/src/views/ActivityFormView.vue | 50 +++- 3 files changed, 374 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/UserMultiSelect.vue b/apps/web/src/components/UserMultiSelect.vue index aaff795..982e961 100644 --- a/apps/web/src/components/UserMultiSelect.vue +++ b/apps/web/src/components/UserMultiSelect.vue @@ -1,6 +1,7 @@ + + diff --git a/apps/web/src/views/ActivityDetailView.vue b/apps/web/src/views/ActivityDetailView.vue index 898f0c7..e48a2b0 100644 --- a/apps/web/src/views/ActivityDetailView.vue +++ b/apps/web/src/views/ActivityDetailView.vue @@ -20,6 +20,7 @@ import type { ActivityDto, ActivityPriority, OrgUserDto, + TeamDto, } from '@mento/shared'; import { useAuthStore } from '@/stores/auth'; import { canAssignToOthers } from '@/lib/assign-access'; @@ -171,7 +172,9 @@ watch( { immediate: true }, ); const users = ref([]); +const teams = ref([]); const assignUserIds = ref([]); +const shareOpen = ref>({}); const assigneePeople = computed(() => { const a = activity.value; @@ -187,7 +190,110 @@ const needsEveryone = computed( () => activity.value?.completionMode === 'all' && assigneePeople.value.length > 1, ); + +type SharePerson = { id: string; fullName: string }; +type ShareGroup = { + key: string; + kind: 'team' | 'role' | 'rest'; + name: string; + members: SharePerson[]; +}; + +const shareGroups = computed(() => { + const people = assigneePeople.value; + if (people.length < 2) return []; + const byId = new Map(people.map((person) => [person.id, person])); + const claimed = new Set(); + const groups: ShareGroup[] = []; + + const teamCandidates = teams.value + .map((team) => { + const members = [ + ...new Map( + team.members + .map((member) => byId.get(member.userId)) + .filter((person): person is SharePerson => Boolean(person)) + .map((person) => [person.id, person]), + ).values(), + ].sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa')); + return { id: team.id, name: team.name, members }; + }) + .filter((team) => team.members.length >= 2) + .sort( + (a, b) => b.members.length - a.members.length || a.name.localeCompare(b.name, 'fa'), + ); + + for (const team of teamCandidates) { + const free = team.members.filter((member) => !claimed.has(member.id)); + if (free.length < 2) continue; + for (const member of free) claimed.add(member.id); + groups.push({ key: `team:${team.id}`, kind: 'team', name: team.name, members: free }); + } + + const roleMap = new Map(); + for (const user of users.value) { + const person = byId.get(user.id); + if (!person || claimed.has(person.id) || !user.orgRoleId || !user.orgRoleName) continue; + const row = roleMap.get(user.orgRoleId) ?? { name: user.orgRoleName, members: [] }; + row.members.push(person); + roleMap.set(user.orgRoleId, row); + } + const roles = [...roleMap.entries()] + .map(([id, role]) => ({ + id, + name: role.name, + members: [...role.members].sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa')), + })) + .filter((role) => role.members.length >= 2) + .sort((a, b) => b.members.length - a.members.length || a.name.localeCompare(b.name, 'fa')); + for (const role of roles) { + for (const member of role.members) claimed.add(member.id); + groups.push({ key: `role:${role.id}`, kind: 'role', name: role.name, members: role.members }); + } + + const rest = people + .filter((person) => !claimed.has(person.id)) + .sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa')); + if (rest.length) { + groups.push({ + key: 'rest', + kind: 'rest', + name: groups.length ? 'سایر مسئول‌ها' : 'مسئول‌ها', + members: rest, + }); + } + return groups; +}); + const completedIds = computed(() => new Set(activity.value?.completedByIds ?? [])); + +const shareUsesGroups = computed( + () => + shareGroups.value.some((group) => group.kind !== 'rest' || group.members.length > 6), +); + +const shareDoneTotal = computed( + () => assigneePeople.value.filter((person) => completedIds.value.has(person.id)).length, +); + +function shareDoneCount(members: SharePerson[]) { + return members.filter((person) => completedIds.value.has(person.id)).length; +} + +function shareKindLabel(group: ShareGroup) { + if (group.kind === 'team' && !group.name.startsWith('تیم')) return 'تیم'; + if (group.kind === 'role' && !group.name.startsWith('نقش')) return 'نقش'; + return ''; +} + +function shareExpanded(group: ShareGroup) { + if (group.key in shareOpen.value) return shareOpen.value[group.key]; + return group.kind === 'rest' && group.members.length <= 6; +} + +function toggleShare(group: ShareGroup) { + shareOpen.value = { ...shareOpen.value, [group.key]: !shareExpanded(group) }; +} const myShareDone = computed(() => { const mine = auth.user?.id; return Boolean(mine && completedIds.value.has(mine)); @@ -278,6 +384,7 @@ async function load() { try { const { data } = await api.get(`/activities/${id.value}`); activity.value = data; + shareOpen.value = {}; await loadActivityImages(data); assignUserIds.value = data.assignees?.length ? data.assignees.map((u) => u.id) @@ -324,12 +431,16 @@ async function loadActivityImages(row: ActivityDto) { onUnmounted(clearImageUrls); async function loadUsers() { - if (!canReassign.value) return; try { - const { data } = await api.get('/users'); - users.value = data; + const [usersRes, teamsRes] = await Promise.all([ + api.get('/users').catch(() => ({ data: [] as OrgUserDto[] })), + api.get('/teams').catch(() => ({ data: [] as TeamDto[] })), + ]); + users.value = usersRes.data; + teams.value = teamsRes.data; } catch { users.value = []; + teams.value = []; } } @@ -637,6 +748,7 @@ onMounted(() => { :users="users" :disabled="saving" :min="1" + select-all @change="reassign" />