Compare commits
87
Commits
1e0b638a19
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9acb73c197 | ||
|
|
e2478e7795 | ||
|
|
c3b00ae5f8 | ||
|
|
046adf391b | ||
|
|
a455ab71ab | ||
|
|
e90f9f9538 | ||
|
|
dbb61ff870 | ||
|
|
12786d30d5 | ||
|
|
5c866e9b75 | ||
|
|
749fca6738 | ||
|
|
c185348c2d | ||
|
|
cd51439353 | ||
|
|
968252ec2f | ||
|
|
2788103488 | ||
|
|
0e961e48e6 | ||
|
|
9b0c0d55c6 | ||
|
|
ae61c321a1 | ||
|
|
5fbdb4495f | ||
|
|
de23e4d505 | ||
|
|
634af8a653 | ||
|
|
64280e85c4 | ||
|
|
abaf012342 | ||
|
|
70524f4f2c | ||
|
|
1b08ab1230 | ||
|
|
4409ded0ab | ||
|
|
3696713443 | ||
|
|
d282627af7 | ||
|
|
fb6aa77465 | ||
|
|
54d360ded8 | ||
|
|
717a41e94b | ||
|
|
f36fddc23b | ||
|
|
e04aa14b84 | ||
|
|
3c27fae626 | ||
|
|
33eeb3242a | ||
|
|
ae16e43013 | ||
|
|
7a55b84b81 | ||
|
|
a1ac677b3a | ||
|
|
b00465439e | ||
|
|
9af0e9e94e | ||
|
|
b745b6d460 | ||
|
|
fec5ece255 | ||
|
|
f4f2311ae4 | ||
|
|
57e0fdd600 | ||
|
|
b583858088 | ||
|
|
453ff1a5f6 | ||
|
|
68fcece743 | ||
|
|
de77066cb0 | ||
|
|
d23dd20237 | ||
|
|
8a4bd70ad4 | ||
|
|
d87321c7bf | ||
|
|
1a05eee46d | ||
|
|
ec9a7cf9c9 | ||
|
|
4f08ffae36 | ||
|
|
d7cb92bf81 | ||
|
|
871d7bba1a | ||
|
|
f13a1249af | ||
|
|
fdf1fbe4aa | ||
|
|
6df198321a | ||
|
|
4c8604d346 | ||
|
|
25a24772fc | ||
|
|
932dc3f1c1 | ||
|
|
5b26b9156d | ||
|
|
d12d7b91cb | ||
|
|
49459707cb | ||
|
|
ba7f942059 | ||
|
|
96105468d4 | ||
|
|
7a8007fff0 | ||
|
|
da851bd9e5 | ||
|
|
dae3ae3f7e | ||
|
|
b03d97dd9e | ||
|
|
8b8d01976d | ||
|
|
4764562bd4 | ||
|
|
0e1bc4a1fe | ||
|
|
3c9b906bd6 | ||
|
|
ef58922e13 | ||
|
|
06036b00d3 | ||
|
|
d33d88e76d | ||
|
|
5ef693990c | ||
|
|
6ebd45f2cb | ||
|
|
33f33f9521 | ||
|
|
97f00d7e6d | ||
|
|
b8c49293f7 | ||
|
|
f36711174e | ||
|
|
abb1a3a18e | ||
|
|
21d2c69227 | ||
|
|
0ca9540524 | ||
|
|
dc691c5192 |
@@ -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
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
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: 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" .
|
||||||
|
|
||||||
|
# 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
|
||||||
|
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
|
||||||
|
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 }}
|
||||||
|
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
|
||||||
|
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="✅ بیلد موفق"
|
||||||
|
elif printf '%s\n' "$STEP_OUTCOMES" | grep -q '^Build 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}"
|
||||||
@@ -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"]
|
||||||
@@ -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"]
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "VoipConnection" ADD COLUMN "provider" TEXT NOT NULL DEFAULT 'generic';
|
||||||
|
ALTER TABLE "VoipConnection" ADD COLUMN "apiTokenCiphertext" TEXT;
|
||||||
|
ALTER TABLE "VoipConnection" ADD COLUMN "apiTokenIv" TEXT;
|
||||||
|
ALTER TABLE "VoipConnection" ADD COLUMN "apiTokenTag" TEXT;
|
||||||
|
ALTER TABLE "VoipConnection" ADD COLUMN "fromNumber" TEXT;
|
||||||
|
ALTER TABLE "VoipConnection" ADD COLUMN "callerExtension" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "VoipConnection_organizationId_provider_idx" ON "VoipConnection"("organizationId", "provider");
|
||||||
@@ -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");
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "FinancialPayroll" ADD COLUMN "benefitsReason" TEXT;
|
||||||
|
ALTER TABLE "FinancialPayroll" ADD COLUMN "bonusReason" TEXT;
|
||||||
|
ALTER TABLE "FinancialPayroll" ADD COLUMN "deductionsReason" TEXT;
|
||||||
@@ -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[];
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "ActivityEditPolicy" AS ENUM ('creator', 'assignees');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Activity" ADD COLUMN "editPolicy" "ActivityEditPolicy" NOT NULL DEFAULT 'creator';
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- مسئولان اختیاری روی گروههای مشتری
|
||||||
|
CREATE TABLE IF NOT EXISTS "_CustomerGroupAssignees" (
|
||||||
|
"A" TEXT NOT NULL,
|
||||||
|
"B" TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "_CustomerGroupAssignees_AB_unique" ON "_CustomerGroupAssignees"("A", "B");
|
||||||
|
CREATE INDEX IF NOT EXISTS "_CustomerGroupAssignees_B_index" ON "_CustomerGroupAssignees"("B");
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = '_CustomerGroupAssignees_A_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE "_CustomerGroupAssignees"
|
||||||
|
ADD CONSTRAINT "_CustomerGroupAssignees_A_fkey"
|
||||||
|
FOREIGN KEY ("A") REFERENCES "CustomerGroup"("id")
|
||||||
|
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = '_CustomerGroupAssignees_B_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE "_CustomerGroupAssignees"
|
||||||
|
ADD CONSTRAINT "_CustomerGroupAssignees_B_fkey"
|
||||||
|
FOREIGN KEY ("B") REFERENCES "User"("id")
|
||||||
|
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Organization" ADD COLUMN "activityPriorities" JSONB NOT NULL DEFAULT '{}';
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Organization" ADD COLUMN "smsTemplates" JSONB NOT NULL DEFAULT '[]';
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Organization" ADD COLUMN "accountBalanceSettings" JSONB NOT NULL DEFAULT '{}';
|
||||||
|
ALTER TABLE "Organization" ADD COLUMN "accountBalanceClaimsLastSlot" TEXT;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "CustomerGroup" ADD COLUMN "assigneeIds" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
|
||||||
|
|
||||||
|
-- Backfill ordered assignee ids from existing M2M (alphabetical until re-saved)
|
||||||
|
UPDATE "CustomerGroup" AS g
|
||||||
|
SET "assigneeIds" = COALESCE((
|
||||||
|
SELECT ARRAY_AGG(link."B" ORDER BY u."fullName")
|
||||||
|
FROM "_CustomerGroupAssignees" AS link
|
||||||
|
INNER JOIN "User" AS u ON u."id" = link."B"
|
||||||
|
WHERE link."A" = g."id"
|
||||||
|
), ARRAY[]::TEXT[])
|
||||||
|
WHERE COALESCE(cardinality(g."assigneeIds"), 0) = 0;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "ActivityBoard" ADD COLUMN "systemKey" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex (NULLs allowed multiple times in PostgreSQL)
|
||||||
|
CREATE UNIQUE INDEX "ActivityBoard_organizationId_systemKey_key" ON "ActivityBoard"("organizationId", "systemKey");
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Lead" ADD COLUMN "activityExperience" TEXT;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Person" ADD COLUMN "activityExperience" TEXT;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Lead_organizationId_activityExperience_idx" ON "Lead"("organizationId", "activityExperience");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Person_organizationId_activityExperience_idx" ON "Person"("organizationId", "activityExperience");
|
||||||
@@ -33,6 +33,17 @@ enum ActivityStatus {
|
|||||||
canceled
|
canceled
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum ActivityCompletionMode {
|
||||||
|
any
|
||||||
|
all
|
||||||
|
}
|
||||||
|
|
||||||
|
/// چه کسانی میتوانند فعالیت را ویرایش/حذف کنند (علاوه بر owner/admin)
|
||||||
|
enum ActivityEditPolicy {
|
||||||
|
creator
|
||||||
|
assignees
|
||||||
|
}
|
||||||
|
|
||||||
enum ActivityPriority {
|
enum ActivityPriority {
|
||||||
low
|
low
|
||||||
medium
|
medium
|
||||||
@@ -151,6 +162,14 @@ model Organization {
|
|||||||
enabledCurrencies String[] @default(["IRR", "USD", "EUR"])
|
enabledCurrencies String[] @default(["IRR", "USD", "EUR"])
|
||||||
/// ماژولهای فعال منو برای این محیط
|
/// ماژولهای فعال منو برای این محیط
|
||||||
enabledModules String[] @default([])
|
enabledModules String[] @default([])
|
||||||
|
/// برچسب/رنگ اولویت فعالیت و روتین (کلیدهای enum ثابت؛ فقط ظاهر)
|
||||||
|
activityPriorities Json @default("{}")
|
||||||
|
/// تنظیم محدوده مانده حساب برای کاریز مطالبات
|
||||||
|
accountBalanceSettings Json @default("{}")
|
||||||
|
/// آخرین اسلات اجرای جاب مطالبات مانده (YYYY-MM-DD-HH تهران)
|
||||||
|
accountBalanceClaimsLastSlot String?
|
||||||
|
/// قالبهای آمادهٔ پیامک دستی ([{ id, name, body }, …])
|
||||||
|
smsTemplates Json @default("[]")
|
||||||
/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخابشده)؛ null = بدون فیلتر
|
/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخابشده)؛ null = بدون فیلتر
|
||||||
priorArchiveEnabledAt DateTime?
|
priorArchiveEnabledAt DateTime?
|
||||||
isActive Boolean @default(true)
|
isActive Boolean @default(true)
|
||||||
@@ -295,6 +314,7 @@ model User {
|
|||||||
ownedInvoices Invoice[] @relation("InvoiceOwner")
|
ownedInvoices Invoice[] @relation("InvoiceOwner")
|
||||||
ownedPeople Person[] @relation("PersonOwner")
|
ownedPeople Person[] @relation("PersonOwner")
|
||||||
ownedCompanies Company[] @relation("CompanyOwner")
|
ownedCompanies Company[] @relation("CompanyOwner")
|
||||||
|
assignedCustomerGroups CustomerGroup[] @relation("CustomerGroupAssignees")
|
||||||
financialPartyDocuments FinancialDocument[] @relation("FinancialDocumentParty")
|
financialPartyDocuments FinancialDocument[] @relation("FinancialDocumentParty")
|
||||||
ownedProjectCards ProjectCard[] @relation("ProjectCardOwner")
|
ownedProjectCards ProjectCard[] @relation("ProjectCardOwner")
|
||||||
activities Activity[] @relation("ActivityAssignee")
|
activities Activity[] @relation("ActivityAssignee")
|
||||||
@@ -565,6 +585,10 @@ model CustomerGroup {
|
|||||||
children CustomerGroup[] @relation("CustomerGroupTree")
|
children CustomerGroup[] @relation("CustomerGroupTree")
|
||||||
people PersonGroupLink[]
|
people PersonGroupLink[]
|
||||||
companies CompanyGroupLink[]
|
companies CompanyGroupLink[]
|
||||||
|
/// مسئولان گروه — اختیاری؛ اعضای گروه را مثل مشتریان خود میبینند
|
||||||
|
assignees User[] @relation("CustomerGroupAssignees")
|
||||||
|
/// ترتیب انتخاب مسئولان در فرم (اولین = مسئول اصلی مطالبات)
|
||||||
|
assigneeIds String[] @default([])
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@ -632,6 +656,8 @@ model Person {
|
|||||||
birthDate DateTime?
|
birthDate DateTime?
|
||||||
/// نام معرف
|
/// نام معرف
|
||||||
referrer String?
|
referrer String?
|
||||||
|
/// سابقه فعالیت (ندارم | 1 الی 2 سال | 2 الی 5 سال | بیش از 5 سال)
|
||||||
|
activityExperience String?
|
||||||
/// لیست آدرسها (JSON array of strings)
|
/// لیست آدرسها (JSON array of strings)
|
||||||
addresses Json @default("[]")
|
addresses Json @default("[]")
|
||||||
notes String?
|
notes String?
|
||||||
@@ -686,6 +712,7 @@ model Person {
|
|||||||
@@index([ownerId])
|
@@index([ownerId])
|
||||||
@@index([loyaltyTierId])
|
@@index([loyaltyTierId])
|
||||||
@@index([organizationId, discLabel])
|
@@index([organizationId, discLabel])
|
||||||
|
@@index([organizationId, activityExperience])
|
||||||
}
|
}
|
||||||
|
|
||||||
model Pipeline {
|
model Pipeline {
|
||||||
@@ -795,6 +822,8 @@ model ActivityBoard {
|
|||||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||||
name String
|
name String
|
||||||
isDefault Boolean @default(false)
|
isDefault Boolean @default(false)
|
||||||
|
/// مثلاً balance_claims — گروه سیستمی
|
||||||
|
systemKey String?
|
||||||
position Int @default(0)
|
position Int @default(0)
|
||||||
stages ActivityStage[]
|
stages ActivityStage[]
|
||||||
activities Activity[]
|
activities Activity[]
|
||||||
@@ -803,6 +832,7 @@ model ActivityBoard {
|
|||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@unique([organizationId, name])
|
@@unique([organizationId, name])
|
||||||
|
@@unique([organizationId, systemKey])
|
||||||
@@index([organizationId, position])
|
@@index([organizationId, position])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -883,6 +913,12 @@ model Activity {
|
|||||||
/// زمان ارسال یادآور؛ با تغییر reminderAt پاک میشود
|
/// زمان ارسال یادآور؛ با تغییر reminderAt پاک میشود
|
||||||
reminderSentAt DateTime?
|
reminderSentAt DateTime?
|
||||||
completedAt DateTime?
|
completedAt DateTime?
|
||||||
|
/// any = با انجام یکی بسته میشود؛ all = هر مسئول باید سهم خودش را بزند
|
||||||
|
completionMode ActivityCompletionMode @default(any)
|
||||||
|
/// مسئولانی که سهم خود را در حالت all ثبت کردهاند
|
||||||
|
completedByIds String[] @default([])
|
||||||
|
/// creator = فقط ایجادکننده؛ assignees = ایجادکننده + همهٔ مسئولان
|
||||||
|
editPolicy ActivityEditPolicy @default(creator)
|
||||||
tags String[] @default([])
|
tags String[] @default([])
|
||||||
personId String?
|
personId String?
|
||||||
person Person? @relation(fields: [personId], references: [id], onDelete: SetNull)
|
person Person? @relation(fields: [personId], references: [id], onDelete: SetNull)
|
||||||
@@ -2447,8 +2483,11 @@ model FinancialPayroll {
|
|||||||
period String
|
period String
|
||||||
baseAmount Decimal @db.Decimal(18, 2)
|
baseAmount Decimal @db.Decimal(18, 2)
|
||||||
benefits Decimal @default(0) @db.Decimal(18, 2)
|
benefits Decimal @default(0) @db.Decimal(18, 2)
|
||||||
|
benefitsReason String?
|
||||||
bonus Decimal @default(0) @db.Decimal(18, 2)
|
bonus Decimal @default(0) @db.Decimal(18, 2)
|
||||||
|
bonusReason String?
|
||||||
deductions Decimal @default(0) @db.Decimal(18, 2)
|
deductions Decimal @default(0) @db.Decimal(18, 2)
|
||||||
|
deductionsReason String?
|
||||||
payable Decimal @db.Decimal(18, 2)
|
payable Decimal @db.Decimal(18, 2)
|
||||||
dueDate DateTime
|
dueDate DateTime
|
||||||
notes String?
|
notes String?
|
||||||
@@ -2953,18 +2992,28 @@ model MontifyWebhookDelivery {
|
|||||||
@@index([connectionId, createdAt])
|
@@index([connectionId, createdAt])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// اتصال تلفن سازمانی / سانترال (وبهوک عمومی)
|
/// اتصال تلفن سازمانی / سانترال (وبهوک عمومی یا ارائهدهنده)
|
||||||
model VoipConnection {
|
model VoipConnection {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
organizationId String
|
organizationId String
|
||||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||||
label String
|
label String
|
||||||
|
/// generic | daftareshoma
|
||||||
|
provider String @default("generic")
|
||||||
enabled Boolean @default(true)
|
enabled Boolean @default(true)
|
||||||
webhookSecretCiphertext String?
|
webhookSecretCiphertext String?
|
||||||
webhookSecretIv String?
|
webhookSecretIv String?
|
||||||
webhookSecretTag String?
|
webhookSecretTag String?
|
||||||
/// قالب URL شروع تماس؛ جای {number} شماره مینشیند
|
/// قالب URL شروع تماس؛ جای {number} شماره مینشیند (generic)
|
||||||
clickToCallUrl String?
|
clickToCallUrl String?
|
||||||
|
/// توکن Bearer API دفتر شما (رمزنگاریشده)
|
||||||
|
apiTokenCiphertext String?
|
||||||
|
apiTokenIv String?
|
||||||
|
apiTokenTag String?
|
||||||
|
/// شماره مبدأ در تماس خروجی دفتر شما (from_number)
|
||||||
|
fromNumber String?
|
||||||
|
/// خط/داخلی سازمان در دفتر شما (caller_extension)
|
||||||
|
callerExtension String?
|
||||||
lastEventAt DateTime?
|
lastEventAt DateTime?
|
||||||
lastError String?
|
lastError String?
|
||||||
calls VoipCallLog[]
|
calls VoipCallLog[]
|
||||||
@@ -2972,6 +3021,7 @@ model VoipConnection {
|
|||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@index([organizationId, enabled])
|
@@index([organizationId, enabled])
|
||||||
|
@@index([organizationId, provider])
|
||||||
}
|
}
|
||||||
|
|
||||||
model VoipCallLog {
|
model VoipCallLog {
|
||||||
@@ -2986,6 +3036,8 @@ model VoipCallLog {
|
|||||||
status String @default("completed")
|
status String @default("completed")
|
||||||
fromNumber String?
|
fromNumber String?
|
||||||
toNumber String?
|
toNumber String?
|
||||||
|
/// خط/داخلی سازمان که تماس روی آن بوده (مثلاً CalleeExtension دفتر شما)
|
||||||
|
lineExtension String?
|
||||||
personId String?
|
personId String?
|
||||||
activityId String?
|
activityId String?
|
||||||
durationSec Int?
|
durationSec Int?
|
||||||
@@ -3010,6 +3062,8 @@ model VoipCallLog {
|
|||||||
|
|
||||||
@@unique([connectionId, externalCallId])
|
@@unique([connectionId, externalCallId])
|
||||||
@@index([organizationId, syncedAt])
|
@@index([organizationId, syncedAt])
|
||||||
|
@@index([organizationId, lineExtension])
|
||||||
|
@@index([organizationId, status])
|
||||||
@@index([personId])
|
@@index([personId])
|
||||||
@@index([activityId])
|
@@index([activityId])
|
||||||
@@index([summaryStatus, summaryNextAttemptAt])
|
@@index([summaryStatus, summaryNextAttemptAt])
|
||||||
@@ -3107,6 +3161,8 @@ model Lead {
|
|||||||
/// صنف
|
/// صنف
|
||||||
trade String?
|
trade String?
|
||||||
source String?
|
source String?
|
||||||
|
/// سابقه فعالیت (ندارم | 1 الی 2 سال | 2 الی 5 سال | بیش از 5 سال)
|
||||||
|
activityExperience String?
|
||||||
notes String?
|
notes String?
|
||||||
/// لوگوی فروشگاه / شرکت
|
/// لوگوی فروشگاه / شرکت
|
||||||
logoStorageKey String?
|
logoStorageKey String?
|
||||||
@@ -3144,6 +3200,7 @@ model Lead {
|
|||||||
@@index([organizationId, city])
|
@@index([organizationId, city])
|
||||||
@@index([organizationId, trade])
|
@@index([organizationId, trade])
|
||||||
@@index([organizationId, source])
|
@@index([organizationId, source])
|
||||||
|
@@index([organizationId, activityExperience])
|
||||||
}
|
}
|
||||||
|
|
||||||
model LeadEvent {
|
model LeadEvent {
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
AccountBalanceRangeDto,
|
||||||
|
AccountBalanceSettingsDto,
|
||||||
|
UpdateAccountBalanceSettingsRequest,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import {
|
||||||
|
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
|
||||||
|
parseAccountBalanceRange,
|
||||||
|
parseAccountBalanceSettings,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { BalanceClaimsService } from './balance-claims.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AccountBalanceSettingsService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly claims: BalanceClaimsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async get(organizationId: string): Promise<AccountBalanceSettingsDto> {
|
||||||
|
const row = await this.prisma.organization.findUnique({
|
||||||
|
where: { id: organizationId },
|
||||||
|
select: { accountBalanceSettings: true },
|
||||||
|
});
|
||||||
|
return parseAccountBalanceSettings(row?.accountBalanceSettings);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
organizationId: string,
|
||||||
|
dto: UpdateAccountBalanceSettingsRequest,
|
||||||
|
): Promise<AccountBalanceSettingsDto> {
|
||||||
|
const current = await this.get(organizationId);
|
||||||
|
const next: AccountBalanceSettingsDto = {
|
||||||
|
firstStageName:
|
||||||
|
dto.firstStageName !== undefined
|
||||||
|
? this.cleanStageName(dto.firstStageName)
|
||||||
|
: current.firstStageName,
|
||||||
|
rial:
|
||||||
|
dto.rial === undefined
|
||||||
|
? current.rial
|
||||||
|
: dto.rial === null
|
||||||
|
? null
|
||||||
|
: this.requireRange(dto.rial, 'بازه مالی'),
|
||||||
|
weights: { ...current.weights },
|
||||||
|
};
|
||||||
|
if (dto.weights) {
|
||||||
|
for (const [key, value] of Object.entries(dto.weights)) {
|
||||||
|
const cleanKey = key.trim();
|
||||||
|
if (!cleanKey) continue;
|
||||||
|
if (value === null) {
|
||||||
|
delete next.weights[cleanKey];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
next.weights[cleanKey] = this.requireRange(value, `بازه ${cleanKey}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.organization.update({
|
||||||
|
where: { id: organizationId },
|
||||||
|
data: {
|
||||||
|
accountBalanceSettings: next as unknown as Prisma.InputJsonValue,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.claims.ensureBoard(organizationId, next.firstStageName);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
private cleanStageName(raw: string) {
|
||||||
|
const name = raw.trim().slice(0, 80);
|
||||||
|
if (!name) return DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private requireRange(raw: AccountBalanceRangeDto, label: string): AccountBalanceRangeDto {
|
||||||
|
const range = parseAccountBalanceRange(raw);
|
||||||
|
if (!range) throw new BadRequestException(`${label} معتبر نیست.`);
|
||||||
|
if (range.mode === 'all_debtors') return { mode: 'all_debtors' };
|
||||||
|
return range;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { Body, Controller, Get, Post, Put, UseGuards } from '@nestjs/common';
|
||||||
|
import { Roles } from '../auth/roles.decorator';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
|
import { RequireOrgModule } from '../billing/org-module.decorator';
|
||||||
|
import { OrgModuleGuard } from '../billing/org-module.guard';
|
||||||
|
import { AccountBalanceSettingsService } from './account-balance-settings.service';
|
||||||
|
import { BalanceClaimsService } from './balance-claims.service';
|
||||||
|
import { EvaluateAccountBalancesDto, UpdateAccountBalanceSettingsDto } from './dto';
|
||||||
|
|
||||||
|
@Controller('account-balances')
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
|
||||||
|
@RequireOrgModule('account_balances')
|
||||||
|
export class AccountBalancesController {
|
||||||
|
constructor(
|
||||||
|
private readonly settings: AccountBalanceSettingsService,
|
||||||
|
private readonly claims: BalanceClaimsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get('settings')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
getSettings(@CurrentUser() user: Actor) {
|
||||||
|
return this.settings.get(user.organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('settings')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
updateSettings(@CurrentUser() user: Actor, @Body() dto: UpdateAccountBalanceSettingsDto) {
|
||||||
|
return this.settings.update(user.organizationId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** یک تکه از ارزیابی (حداکثر ۲۰۰۰ نفر)؛ کلاینت تکهها را پشت سر هم میزند */
|
||||||
|
@Post('evaluate')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
evaluate(@CurrentUser() user: Actor, @Body() dto: EvaluateAccountBalancesDto) {
|
||||||
|
return this.claims.evaluateOrganization(user.organizationId, {
|
||||||
|
offset: dto.offset,
|
||||||
|
limit: dto.limit,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
import { BillingModule } from '../billing/billing.module';
|
||||||
|
import { ActivitiesModule } from '../activities/activities.module';
|
||||||
|
import { TahesabModule } from '../integrations/tahesab/tahesab.module';
|
||||||
|
import { AccountBalancesController } from './account-balances.controller';
|
||||||
|
import { AccountBalanceSettingsService } from './account-balance-settings.service';
|
||||||
|
import { BalanceClaimsScheduler } from './balance-claims.scheduler';
|
||||||
|
import { BalanceClaimsService } from './balance-claims.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AuthModule, BillingModule, ActivitiesModule, TahesabModule],
|
||||||
|
controllers: [AccountBalancesController],
|
||||||
|
providers: [AccountBalanceSettingsService, BalanceClaimsService, BalanceClaimsScheduler],
|
||||||
|
exports: [AccountBalanceSettingsService, BalanceClaimsService],
|
||||||
|
})
|
||||||
|
export class AccountBalancesModule {}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { Cron } from '@nestjs/schedule';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { BalanceClaimsService } from './balance-claims.service';
|
||||||
|
import { tehranSyncSlot } from '../integrations/tahesab/customer-sync.scheduler';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class BalanceClaimsScheduler {
|
||||||
|
private readonly logger = new Logger(BalanceClaimsScheduler.name);
|
||||||
|
private busy = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly claims: BalanceClaimsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Cron('0 8,13 * * *', { timeZone: 'Asia/Tehran' })
|
||||||
|
async tick() {
|
||||||
|
if (process.env.NODE_ENV === 'test' || this.busy) return;
|
||||||
|
const { slot } = tehranSyncSlot();
|
||||||
|
|
||||||
|
this.busy = true;
|
||||||
|
try {
|
||||||
|
const orgs = await this.prisma.organization.findMany({
|
||||||
|
where: {
|
||||||
|
isActive: true,
|
||||||
|
enabledModules: { has: 'account_balances' },
|
||||||
|
OR: [
|
||||||
|
{ accountBalanceClaimsLastSlot: null },
|
||||||
|
{ accountBalanceClaimsLastSlot: { not: slot } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const org of orgs) {
|
||||||
|
const claimed = await this.prisma.organization.updateMany({
|
||||||
|
where: {
|
||||||
|
id: org.id,
|
||||||
|
OR: [
|
||||||
|
{ accountBalanceClaimsLastSlot: null },
|
||||||
|
{ accountBalanceClaimsLastSlot: { not: slot } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
data: { accountBalanceClaimsLastSlot: slot },
|
||||||
|
});
|
||||||
|
if (claimed.count !== 1) continue;
|
||||||
|
try {
|
||||||
|
await this.claims.evaluateOrganizationFully(org.id);
|
||||||
|
this.logger.log(`جاب مطالبات مانده برای «${org.name}» اجرا شد (${slot}).`);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`جاب مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this.busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,658 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ACCOUNT_BALANCE_CLAIMS_TAG,
|
||||||
|
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
|
||||||
|
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
|
||||||
|
accountBalanceMatchesCriterion,
|
||||||
|
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
|
||||||
|
parseAccountBalanceSettings,
|
||||||
|
parseAccountBalanceWeightFields,
|
||||||
|
type AccountBalanceEvaluateResultDto,
|
||||||
|
type AccountBalanceSettingsDto,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { ActivityTypesService } from '../activities/activity-types.service';
|
||||||
|
import { TahesabBalanceService } from '../integrations/tahesab/balance.service';
|
||||||
|
|
||||||
|
const BOARD_NAME = 'مطالبات';
|
||||||
|
const FOLLOW_UP_TYPE_NAME = 'پیگیری';
|
||||||
|
/** همزمانی داخل هر تکه برای ماندن زیر تایماوت */
|
||||||
|
const BATCH_CONCURRENCY = 20;
|
||||||
|
|
||||||
|
type PersonClaimContext = {
|
||||||
|
personId: string;
|
||||||
|
fullName: string;
|
||||||
|
connectionId: string;
|
||||||
|
assigneeId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class BalanceClaimsService {
|
||||||
|
private readonly logger = new Logger(BalanceClaimsService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly types: ActivityTypesService,
|
||||||
|
private readonly balances: TahesabBalanceService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async ensureFollowUpType(organizationId: string) {
|
||||||
|
await this.types.ensureDefaults(organizationId);
|
||||||
|
const existing = await this.prisma.activityTypeDef.findFirst({
|
||||||
|
where: { organizationId, name: FOLLOW_UP_TYPE_NAME },
|
||||||
|
select: { id: true, baseType: true },
|
||||||
|
});
|
||||||
|
if (existing) return existing;
|
||||||
|
const max = await this.prisma.activityTypeDef.aggregate({
|
||||||
|
where: { organizationId },
|
||||||
|
_max: { position: true },
|
||||||
|
});
|
||||||
|
return this.prisma.activityTypeDef.create({
|
||||||
|
data: {
|
||||||
|
organizationId,
|
||||||
|
name: FOLLOW_UP_TYPE_NAME,
|
||||||
|
baseType: 'call',
|
||||||
|
icon: 'bell',
|
||||||
|
color: 'orange',
|
||||||
|
position: (max._max.position ?? 0) + 1,
|
||||||
|
isSystem: false,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
key: 'followup_reason',
|
||||||
|
label: 'دلیل پیگیری',
|
||||||
|
type: 'select',
|
||||||
|
options: ['پیشفاکتور', 'پرداخت', 'ارسال کالا', 'پشتیبانی', 'تمدید قرارداد', 'سایر'],
|
||||||
|
},
|
||||||
|
{ key: 'followup_result', label: 'نتیجهٔ پیگیری', type: 'textarea' },
|
||||||
|
{ key: 'followup_next', label: 'تاریخ پیگیری بعدی', type: 'date' },
|
||||||
|
] as Prisma.InputJsonValue,
|
||||||
|
},
|
||||||
|
select: { id: true, baseType: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async ensureBoard(organizationId: string, firstStageName?: string) {
|
||||||
|
const stageName =
|
||||||
|
(firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() ||
|
||||||
|
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
|
||||||
|
|
||||||
|
let board = await this.prisma.activityBoard.findFirst({
|
||||||
|
where: { organizationId, systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!board) {
|
||||||
|
const byName = await this.prisma.activityBoard.findFirst({
|
||||||
|
where: { organizationId, name: BOARD_NAME },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
if (byName) {
|
||||||
|
board = await this.prisma.activityBoard.update({
|
||||||
|
where: { id: byName.id },
|
||||||
|
data: { systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!board) {
|
||||||
|
const max = await this.prisma.activityBoard.aggregate({
|
||||||
|
where: { organizationId },
|
||||||
|
_max: { position: true },
|
||||||
|
});
|
||||||
|
board = await this.prisma.activityBoard.create({
|
||||||
|
data: {
|
||||||
|
organizationId,
|
||||||
|
name: BOARD_NAME,
|
||||||
|
systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
|
||||||
|
position: (max._max.position ?? 0) + 1,
|
||||||
|
isDefault: false,
|
||||||
|
},
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.ensureStages(organizationId, board.id, stageName);
|
||||||
|
return board;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureStages(organizationId: string, boardId: string, firstStageName: string) {
|
||||||
|
const stages = await this.prisma.activityStage.findMany({
|
||||||
|
where: { boardId },
|
||||||
|
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
select: { id: true, name: true, kind: true, position: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!stages.length) {
|
||||||
|
await this.prisma.activityStage.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
organizationId,
|
||||||
|
boardId,
|
||||||
|
name: firstStageName,
|
||||||
|
color: 'orange',
|
||||||
|
kind: 'open',
|
||||||
|
position: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
organizationId,
|
||||||
|
boardId,
|
||||||
|
name: 'در حال انجام',
|
||||||
|
color: 'blue',
|
||||||
|
kind: 'open',
|
||||||
|
position: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
organizationId,
|
||||||
|
boardId,
|
||||||
|
name: 'انجامشده',
|
||||||
|
color: 'green',
|
||||||
|
kind: 'done',
|
||||||
|
position: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
organizationId,
|
||||||
|
boardId,
|
||||||
|
name: 'لغو شده',
|
||||||
|
color: 'rose',
|
||||||
|
kind: 'canceled',
|
||||||
|
position: 3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
skipDuplicates: true,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstOpen = stages.find((s) => s.kind === 'open') ?? stages[0];
|
||||||
|
if (firstOpen && firstOpen.name !== firstStageName) {
|
||||||
|
const clash = stages.some((s) => s.id !== firstOpen.id && s.name === firstStageName);
|
||||||
|
if (!clash) {
|
||||||
|
await this.prisma.activityStage.update({
|
||||||
|
where: { id: firstOpen.id },
|
||||||
|
data: { name: firstStageName },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async evaluateAll() {
|
||||||
|
const orgs = await this.prisma.organization.findMany({
|
||||||
|
where: {
|
||||||
|
isActive: true,
|
||||||
|
enabledModules: { has: 'account_balances' },
|
||||||
|
accountingConnections: { some: { provider: 'tahesab', enabled: true } },
|
||||||
|
},
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
for (const org of orgs) {
|
||||||
|
try {
|
||||||
|
await this.evaluateOrganizationFully(org.id);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** همهٔ تکهها پشت سر هم (برای جاب زمانبندیشده) */
|
||||||
|
async evaluateOrganizationFully(organizationId: string): Promise<AccountBalanceEvaluateResultDto> {
|
||||||
|
let offset = 0;
|
||||||
|
let merged: AccountBalanceEvaluateResultDto | null = null;
|
||||||
|
for (;;) {
|
||||||
|
const batch = await this.evaluateOrganization(organizationId, {
|
||||||
|
offset,
|
||||||
|
limit: ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
|
||||||
|
});
|
||||||
|
merged = merged ? this.mergeResults(merged, batch) : batch;
|
||||||
|
if (batch.done || batch.nextOffset == null) {
|
||||||
|
merged.message = this.summarize(merged);
|
||||||
|
this.logger.log(`مطالبات کامل ${organizationId}: ${merged.message}`);
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
offset = batch.nextOffset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async evaluateOrganization(
|
||||||
|
organizationId: string,
|
||||||
|
opts?: { offset?: number; limit?: number },
|
||||||
|
): Promise<AccountBalanceEvaluateResultDto> {
|
||||||
|
const offset = Math.max(0, Math.floor(opts?.offset ?? 0));
|
||||||
|
const limit = Math.min(
|
||||||
|
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
|
||||||
|
Math.max(1, Math.floor(opts?.limit ?? ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const empty = (message: string): AccountBalanceEvaluateResultDto => ({
|
||||||
|
linkedPeople: 0,
|
||||||
|
candidates: 0,
|
||||||
|
skippedNoAssignee: 0,
|
||||||
|
matched: 0,
|
||||||
|
created: 0,
|
||||||
|
reopened: 0,
|
||||||
|
canceled: 0,
|
||||||
|
unchanged: 0,
|
||||||
|
errors: 0,
|
||||||
|
message,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
batchProcessed: 0,
|
||||||
|
done: true,
|
||||||
|
nextOffset: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const org = await this.prisma.organization.findUnique({
|
||||||
|
where: { id: organizationId },
|
||||||
|
select: { enabledModules: true, accountBalanceSettings: true },
|
||||||
|
});
|
||||||
|
if (!org?.enabledModules.includes('account_balances')) {
|
||||||
|
return empty('ماژول مانده حساب برای این محیط فعال نیست.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const settings = parseAccountBalanceSettings(org.accountBalanceSettings);
|
||||||
|
const hasAnyRange =
|
||||||
|
Boolean(settings.rial) || Object.keys(settings.weights).length > 0;
|
||||||
|
if (!hasAnyRange) {
|
||||||
|
return empty('هیچ بازهٔ فعالی ذخیره نشده است. ابتدا محدوده را ذخیره کنید.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const board = await this.ensureBoard(organizationId, settings.firstStageName);
|
||||||
|
const typeDef = await this.ensureFollowUpType(organizationId);
|
||||||
|
const stages = await this.prisma.activityStage.findMany({
|
||||||
|
where: { boardId: board.id },
|
||||||
|
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
select: { id: true, kind: true },
|
||||||
|
});
|
||||||
|
const openStageId = stages.find((s) => s.kind === 'open')?.id;
|
||||||
|
const canceledStageId = stages.find((s) => s.kind === 'canceled')?.id;
|
||||||
|
if (!openStageId || !canceledStageId) {
|
||||||
|
return empty('ستونهای کاریز مطالبات ناقص است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { candidates, linkedPeople, skippedNoAssignee } =
|
||||||
|
await this.loadCandidates(organizationId);
|
||||||
|
|
||||||
|
const slice = candidates.slice(offset, offset + limit);
|
||||||
|
const nextOffset = offset + slice.length;
|
||||||
|
const done = nextOffset >= candidates.length;
|
||||||
|
|
||||||
|
const result: AccountBalanceEvaluateResultDto = {
|
||||||
|
linkedPeople,
|
||||||
|
candidates: candidates.length,
|
||||||
|
skippedNoAssignee,
|
||||||
|
matched: 0,
|
||||||
|
created: 0,
|
||||||
|
reopened: 0,
|
||||||
|
canceled: 0,
|
||||||
|
unchanged: 0,
|
||||||
|
errors: 0,
|
||||||
|
message: '',
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
batchProcessed: slice.length,
|
||||||
|
done,
|
||||||
|
nextOffset: done ? null : nextOffset,
|
||||||
|
};
|
||||||
|
|
||||||
|
const actions = await this.mapPool(slice, BATCH_CONCURRENCY, async (person) => {
|
||||||
|
try {
|
||||||
|
return await this.syncPerson({
|
||||||
|
organizationId,
|
||||||
|
person,
|
||||||
|
settings,
|
||||||
|
boardId: board.id,
|
||||||
|
openStageId,
|
||||||
|
canceledStageId,
|
||||||
|
typeDefId: typeDef.id,
|
||||||
|
baseType: typeDef.baseType,
|
||||||
|
preferCache: true,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`,
|
||||||
|
);
|
||||||
|
return 'error' as const;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (const action of actions) {
|
||||||
|
if (action === 'created') {
|
||||||
|
result.matched += 1;
|
||||||
|
result.created += 1;
|
||||||
|
} else if (action === 'reopened') {
|
||||||
|
result.matched += 1;
|
||||||
|
result.reopened += 1;
|
||||||
|
} else if (action === 'canceled') {
|
||||||
|
result.canceled += 1;
|
||||||
|
} else if (action === 'matched-unchanged') {
|
||||||
|
result.matched += 1;
|
||||||
|
result.unchanged += 1;
|
||||||
|
} else if (action === 'error') {
|
||||||
|
result.errors += 1;
|
||||||
|
} else {
|
||||||
|
result.unchanged += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.message = done
|
||||||
|
? this.summarize(result)
|
||||||
|
: `تکه ${offset + 1} تا ${nextOffset} از ${candidates.length} · ادامه…`;
|
||||||
|
this.logger.log(`مطالبات ${organizationId}: ${result.message}`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private mergeResults(
|
||||||
|
a: AccountBalanceEvaluateResultDto,
|
||||||
|
b: AccountBalanceEvaluateResultDto,
|
||||||
|
): AccountBalanceEvaluateResultDto {
|
||||||
|
return {
|
||||||
|
linkedPeople: Math.max(a.linkedPeople, b.linkedPeople),
|
||||||
|
candidates: Math.max(a.candidates, b.candidates),
|
||||||
|
skippedNoAssignee: Math.max(a.skippedNoAssignee, b.skippedNoAssignee),
|
||||||
|
matched: a.matched + b.matched,
|
||||||
|
created: a.created + b.created,
|
||||||
|
reopened: a.reopened + b.reopened,
|
||||||
|
canceled: a.canceled + b.canceled,
|
||||||
|
unchanged: a.unchanged + b.unchanged,
|
||||||
|
errors: a.errors + b.errors,
|
||||||
|
message: b.message,
|
||||||
|
offset: a.offset,
|
||||||
|
limit: a.limit,
|
||||||
|
batchProcessed: a.batchProcessed + b.batchProcessed,
|
||||||
|
done: b.done,
|
||||||
|
nextOffset: b.nextOffset,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async mapPool<T, R>(
|
||||||
|
items: T[],
|
||||||
|
concurrency: number,
|
||||||
|
worker: (item: T) => Promise<R>,
|
||||||
|
): Promise<R[]> {
|
||||||
|
if (!items.length) return [];
|
||||||
|
const out = new Array<R>(items.length);
|
||||||
|
let index = 0;
|
||||||
|
const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
|
||||||
|
while (index < items.length) {
|
||||||
|
const currentIndex = index++;
|
||||||
|
out[currentIndex] = await worker(items[currentIndex]!);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await Promise.all(runners);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private summarize(r: AccountBalanceEvaluateResultDto): string {
|
||||||
|
if (r.linkedPeople === 0) {
|
||||||
|
return 'هیچ مشتری لینکشده به تهحساب پیدا نشد.';
|
||||||
|
}
|
||||||
|
if (r.candidates === 0) {
|
||||||
|
return `از ${r.linkedPeople} مشتری لینکشده، هیچکدام گروه با مسئول ندارند (${r.skippedNoAssignee} بدون مسئول گروه).`;
|
||||||
|
}
|
||||||
|
if (r.matched === 0 && r.canceled === 0 && r.errors === 0) {
|
||||||
|
return `بررسی شد: ${r.candidates} نفر واجد شرایط گروه/مسئول؛ هیچکدام داخل بازهٔ ذخیرهشده نبودند.`;
|
||||||
|
}
|
||||||
|
const parts = [
|
||||||
|
`${r.candidates} واجد شرایط`,
|
||||||
|
`${r.matched} داخل بازه`,
|
||||||
|
`${r.created} ساخته`,
|
||||||
|
`${r.reopened} بازگشایی`,
|
||||||
|
`${r.canceled} خارج از بازه`,
|
||||||
|
];
|
||||||
|
if (r.errors) parts.push(`${r.errors} خطا`);
|
||||||
|
if (r.skippedNoAssignee) parts.push(`${r.skippedNoAssignee} بدون مسئول گروه`);
|
||||||
|
return parts.join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadCandidates(organizationId: string): Promise<{
|
||||||
|
candidates: PersonClaimContext[];
|
||||||
|
linkedPeople: number;
|
||||||
|
skippedNoAssignee: number;
|
||||||
|
}> {
|
||||||
|
const links = await this.prisma.personAccountingLink.findMany({
|
||||||
|
where: {
|
||||||
|
connection: { organizationId, provider: 'tahesab', enabled: true },
|
||||||
|
person: { organizationId },
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
personId: true,
|
||||||
|
connectionId: true,
|
||||||
|
linkedAt: true,
|
||||||
|
connection: { select: { isDefault: true } },
|
||||||
|
person: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
groupLinks: {
|
||||||
|
select: {
|
||||||
|
group: {
|
||||||
|
select: {
|
||||||
|
name: true,
|
||||||
|
position: true,
|
||||||
|
assigneeIds: true,
|
||||||
|
assignees: { select: { id: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const out: PersonClaimContext[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let skippedNoAssignee = 0;
|
||||||
|
const orderedLinks = [...links].sort((a, b) => {
|
||||||
|
if (a.personId !== b.personId) return a.personId.localeCompare(b.personId);
|
||||||
|
if (a.connection.isDefault !== b.connection.isDefault) {
|
||||||
|
return a.connection.isDefault ? -1 : 1;
|
||||||
|
}
|
||||||
|
return a.linkedAt.getTime() - b.linkedAt.getTime();
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const link of orderedLinks) {
|
||||||
|
if (seen.has(link.personId)) continue;
|
||||||
|
seen.add(link.personId);
|
||||||
|
|
||||||
|
const groups = [...link.person.groupLinks]
|
||||||
|
.map((g) => g.group)
|
||||||
|
.sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa'));
|
||||||
|
|
||||||
|
let assigneeId: string | null = null;
|
||||||
|
for (const group of groups) {
|
||||||
|
const fromRelation = group.assignees.map((a) => a.id);
|
||||||
|
const valid = new Set(fromRelation);
|
||||||
|
let ordered =
|
||||||
|
group.assigneeIds.length > 0
|
||||||
|
? group.assigneeIds.filter((id) => valid.has(id))
|
||||||
|
: [];
|
||||||
|
// اگر ترتیب ذخیرهشده با M2M همخوان نبود، همان مسئولان رابطه را بگیر
|
||||||
|
if (!ordered.length) ordered = fromRelation;
|
||||||
|
if (ordered.length) {
|
||||||
|
assigneeId = ordered[0]!;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!assigneeId) {
|
||||||
|
skippedNoAssignee += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push({
|
||||||
|
personId: link.person.id,
|
||||||
|
fullName: `${link.person.firstName} ${link.person.lastName}`.trim(),
|
||||||
|
connectionId: link.connectionId,
|
||||||
|
assigneeId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
candidates: out,
|
||||||
|
linkedPeople: seen.size,
|
||||||
|
skippedNoAssignee,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async syncPerson(input: {
|
||||||
|
organizationId: string;
|
||||||
|
person: PersonClaimContext;
|
||||||
|
settings: AccountBalanceSettingsDto;
|
||||||
|
boardId: string;
|
||||||
|
openStageId: string;
|
||||||
|
canceledStageId: string;
|
||||||
|
typeDefId: string;
|
||||||
|
baseType: 'call' | 'meeting' | 'task' | 'note';
|
||||||
|
/** در ارزیابی دستهای اول از کش استفاده کن تا تایماوت نشود */
|
||||||
|
preferCache?: boolean;
|
||||||
|
}): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> {
|
||||||
|
let assets;
|
||||||
|
if (input.preferCache) {
|
||||||
|
try {
|
||||||
|
assets = await this.balances.getCachedOrFetch(
|
||||||
|
input.organizationId,
|
||||||
|
input.person.personId,
|
||||||
|
input.person.connectionId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
assets = await this.balances.getAssets(
|
||||||
|
input.organizationId,
|
||||||
|
input.person.personId,
|
||||||
|
input.person.connectionId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
assets = await this.balances.getAssets(
|
||||||
|
input.organizationId,
|
||||||
|
input.person.personId,
|
||||||
|
input.person.connectionId,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
assets = await this.balances.getCachedOrFetch(
|
||||||
|
input.organizationId,
|
||||||
|
input.person.personId,
|
||||||
|
input.person.connectionId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const matched = this.matchesAnyRange(assets, input.settings);
|
||||||
|
|
||||||
|
const existing = await this.prisma.activity.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
boardId: input.boardId,
|
||||||
|
personId: input.person.personId,
|
||||||
|
tags: { has: ACCOUNT_BALANCE_CLAIMS_TAG },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
status: true,
|
||||||
|
stageId: true,
|
||||||
|
assigneeId: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const title = `مطالبه: ${input.person.fullName}`;
|
||||||
|
|
||||||
|
if (matched) {
|
||||||
|
if (!existing) {
|
||||||
|
await this.prisma.activity.create({
|
||||||
|
data: {
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
boardId: input.boardId,
|
||||||
|
stageId: input.openStageId,
|
||||||
|
status: 'open',
|
||||||
|
title,
|
||||||
|
type: input.baseType,
|
||||||
|
typeDefId: input.typeDefId,
|
||||||
|
personId: input.person.personId,
|
||||||
|
assigneeId: input.person.assigneeId,
|
||||||
|
assignees: { connect: [{ id: input.person.assigneeId }] },
|
||||||
|
tags: [ACCOUNT_BALANCE_CLAIMS_TAG],
|
||||||
|
editPolicy: 'assignees',
|
||||||
|
completionMode: 'any',
|
||||||
|
completedByIds: [],
|
||||||
|
createdById: input.person.assigneeId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return 'created';
|
||||||
|
}
|
||||||
|
|
||||||
|
// فقط بعد از خروج از بازه (لغو) دوباره از ستون اول بیاید؛
|
||||||
|
// ستونهای میانی / انجامشده حفظ میشوند.
|
||||||
|
if (existing.status === 'canceled') {
|
||||||
|
await this.prisma.activity.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: {
|
||||||
|
status: 'open',
|
||||||
|
stageId: input.openStageId,
|
||||||
|
completedAt: null,
|
||||||
|
completedByIds: [],
|
||||||
|
assigneeId: input.person.assigneeId,
|
||||||
|
assignees: { set: [{ id: input.person.assigneeId }] },
|
||||||
|
title,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return 'reopened';
|
||||||
|
}
|
||||||
|
|
||||||
|
// هنوز داخل بازه: ستون و وضعیت (در حال انجام / انجامشده) حفظ شود
|
||||||
|
await this.prisma.activity.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: {
|
||||||
|
title,
|
||||||
|
...(existing.assigneeId !== input.person.assigneeId
|
||||||
|
? {
|
||||||
|
assigneeId: input.person.assigneeId,
|
||||||
|
assignees: { set: [{ id: input.person.assigneeId }] },
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return 'matched-unchanged';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing && existing.status !== 'canceled') {
|
||||||
|
await this.prisma.activity.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: {
|
||||||
|
status: 'canceled',
|
||||||
|
stageId: input.canceledStageId,
|
||||||
|
completedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return 'canceled';
|
||||||
|
}
|
||||||
|
return 'out-unchanged';
|
||||||
|
}
|
||||||
|
|
||||||
|
private matchesAnyRange(
|
||||||
|
assets: {
|
||||||
|
rialBalance: number | null;
|
||||||
|
goldBalance: number | null;
|
||||||
|
mandehFields?: Array<{ key: string; value: string | null }>;
|
||||||
|
},
|
||||||
|
settings: AccountBalanceSettingsDto,
|
||||||
|
): boolean {
|
||||||
|
if (accountBalanceMatchesCriterion(assets.rialBalance, settings.rial)) return true;
|
||||||
|
|
||||||
|
const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields);
|
||||||
|
for (const [key, criterion] of Object.entries(settings.weights)) {
|
||||||
|
const value =
|
||||||
|
fieldMap[key] ??
|
||||||
|
(key === 'MandeyeVazni' ? assets.goldBalance : null) ??
|
||||||
|
null;
|
||||||
|
if (accountBalanceMatchesCriterion(value, criterion)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import {
|
||||||
|
IsIn,
|
||||||
|
IsInt,
|
||||||
|
IsNumber,
|
||||||
|
IsObject,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Max,
|
||||||
|
MaxLength,
|
||||||
|
Min,
|
||||||
|
ValidateIf,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
export class AccountBalanceRangeBody {
|
||||||
|
@IsIn(['all_debtors', 'range'])
|
||||||
|
mode!: 'all_debtors' | 'range';
|
||||||
|
|
||||||
|
@ValidateIf((o: AccountBalanceRangeBody) => o.mode === 'range')
|
||||||
|
@IsNumber()
|
||||||
|
min?: number;
|
||||||
|
|
||||||
|
@ValidateIf((o: AccountBalanceRangeBody) => o.mode === 'range')
|
||||||
|
@IsNumber()
|
||||||
|
max?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateAccountBalanceSettingsDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(80)
|
||||||
|
firstStageName?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateIf((_, v) => v !== null)
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => AccountBalanceRangeBody)
|
||||||
|
rial?: AccountBalanceRangeBody | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
weights?: Record<string, AccountBalanceRangeBody | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EvaluateAccountBalancesDto {
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
offset?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(2000)
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
@@ -400,6 +400,7 @@ export class ActivitiesExcelService {
|
|||||||
.join('\n'));
|
.join('\n'));
|
||||||
const dueAt = parseJalaliDateTime(row.dueDate, row.dueTime);
|
const dueAt = parseJalaliDateTime(row.dueDate, row.dueTime);
|
||||||
const doneAt = parseJalaliDateTime(row.doneDate, row.doneTime);
|
const doneAt = parseJalaliDateTime(row.doneDate, row.doneTime);
|
||||||
|
const createdAt = parseJalaliDateTime(row.createdAt);
|
||||||
const status = parseStatus(row.status);
|
const status = parseStatus(row.status);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -452,6 +453,7 @@ export class ActivitiesExcelService {
|
|||||||
dealId,
|
dealId,
|
||||||
assigneeId,
|
assigneeId,
|
||||||
createdById: creatorId,
|
createdById: creatorId,
|
||||||
|
...(createdAt ? { createdAt } : {}),
|
||||||
},
|
},
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
Query,
|
Query,
|
||||||
Res,
|
Res,
|
||||||
StreamableFile,
|
StreamableFile,
|
||||||
@@ -40,6 +41,7 @@ import {
|
|||||||
ReorderActivityTypesDto,
|
ReorderActivityTypesDto,
|
||||||
UpdateActivityBoardDto,
|
UpdateActivityBoardDto,
|
||||||
UpdateActivityDto,
|
UpdateActivityDto,
|
||||||
|
UpdateActivityPrioritiesDto,
|
||||||
UpdateActivityStageDto,
|
UpdateActivityStageDto,
|
||||||
UpdateActivityTypeDto,
|
UpdateActivityTypeDto,
|
||||||
} from './dto';
|
} from './dto';
|
||||||
@@ -139,6 +141,18 @@ export class ActivitiesController {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('priorities')
|
||||||
|
listPriorities(@CurrentUser() user: Actor) {
|
||||||
|
return this.typesService.listPriorities(user.organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('priorities')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
updatePriorities(@CurrentUser() user: Actor, @Body() dto: UpdateActivityPrioritiesDto) {
|
||||||
|
return this.typesService.updatePriorities(user.organizationId, dto.items);
|
||||||
|
}
|
||||||
|
|
||||||
@Get('types')
|
@Get('types')
|
||||||
listTypes(@CurrentUser() user: Actor) {
|
listTypes(@CurrentUser() user: Actor) {
|
||||||
return this.typesService.list(user.organizationId);
|
return this.typesService.list(user.organizationId);
|
||||||
@@ -196,6 +210,7 @@ export class ActivitiesController {
|
|||||||
title: query.title,
|
title: query.title,
|
||||||
customer: query.customer,
|
customer: query.customer,
|
||||||
due: query.due,
|
due: query.due,
|
||||||
|
priority: query.priority,
|
||||||
boardId: query.boardId,
|
boardId: query.boardId,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -232,6 +247,7 @@ export class ActivitiesController {
|
|||||||
title: query.title,
|
title: query.title,
|
||||||
customer: query.customer,
|
customer: query.customer,
|
||||||
due: query.due,
|
due: query.due,
|
||||||
|
priority: query.priority,
|
||||||
boardId: query.boardId,
|
boardId: query.boardId,
|
||||||
},
|
},
|
||||||
query.stageId ? { stageId: query.stageId } : undefined,
|
query.stageId ? { stageId: query.stageId } : undefined,
|
||||||
@@ -265,6 +281,7 @@ export class ActivitiesController {
|
|||||||
title: query.title,
|
title: query.title,
|
||||||
customer: query.customer,
|
customer: query.customer,
|
||||||
due: query.due,
|
due: query.due,
|
||||||
|
priority: query.priority,
|
||||||
boardId: query.boardId,
|
boardId: query.boardId,
|
||||||
},
|
},
|
||||||
query.stageId ? { stageId: query.stageId } : undefined,
|
query.stageId ? { stageId: query.stageId } : undefined,
|
||||||
@@ -438,8 +455,16 @@ export class ActivitiesController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/complete')
|
@Patch(':id/complete')
|
||||||
complete(@CurrentUser() user: Actor, @Param('id') id: string) {
|
complete(
|
||||||
return this.activitiesService.complete(user.organizationId, id, user);
|
@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')
|
@Delete(':id')
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type {
|
import type {
|
||||||
|
ActivityAccountBalanceDto,
|
||||||
ActivityDto,
|
ActivityDto,
|
||||||
ActivityFieldValues,
|
ActivityFieldValues,
|
||||||
ActivityFilter,
|
ActivityFilter,
|
||||||
@@ -15,6 +16,12 @@ import type {
|
|||||||
PaginatedResponse,
|
PaginatedResponse,
|
||||||
UpdateActivityRequest,
|
UpdateActivityRequest,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
|
import {
|
||||||
|
ACCOUNT_BALANCE_CLAIMS_TAG,
|
||||||
|
ACCOUNT_BALANCE_WEIGHT_KEYS,
|
||||||
|
ACCOUNT_BALANCE_WEIGHT_LABELS,
|
||||||
|
parseAccountBalanceWeightFields,
|
||||||
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import * as path from 'node:path';
|
import * as path from 'node:path';
|
||||||
@@ -38,6 +45,7 @@ import { tehranDayKey } from '../routines/routine-dates';
|
|||||||
import { buildSearchWhere, ci } from '../common/search';
|
import { buildSearchWhere, ci } from '../common/search';
|
||||||
import { activityPriorWhere } from '../common/prior-archive';
|
import { activityPriorWhere } from '../common/prior-archive';
|
||||||
import { leadsDeepWhere } from '../common/data-access';
|
import { leadsDeepWhere } from '../common/data-access';
|
||||||
|
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
|
||||||
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
|
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
|
||||||
import {
|
import {
|
||||||
ActivityTypesService,
|
ActivityTypesService,
|
||||||
@@ -52,6 +60,65 @@ type ActivityActor = Pick<
|
|||||||
'userId' | 'role' | 'priorLens' | 'priorCutoff' | 'leadsAccess' | 'teamPeerIds'
|
'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 canMutateActivity(
|
||||||
|
actor: { userId: string; role: string },
|
||||||
|
row: {
|
||||||
|
createdById?: string | null;
|
||||||
|
editPolicy?: 'creator' | 'assignees' | null;
|
||||||
|
assigneeId?: string | null;
|
||||||
|
assignees?: Array<{ id: string }>;
|
||||||
|
},
|
||||||
|
): boolean {
|
||||||
|
if (actor.role === 'owner' || actor.role === 'admin') return true;
|
||||||
|
if (row.createdById && actor.userId === row.createdById) return true;
|
||||||
|
if ((row.editPolicy ?? 'creator') !== 'assignees') return false;
|
||||||
|
return assigneeIdList(row).includes(actor.userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ثبت نظر / تعویق — برای همهٔ مسئولان، حتی وقتی ویرایش فقط با ایجادکننده است */
|
||||||
|
function canCollaborateActivity(
|
||||||
|
actor: { userId: string; role: string },
|
||||||
|
row: {
|
||||||
|
createdById?: string | null;
|
||||||
|
assigneeId?: string | null;
|
||||||
|
assignees?: Array<{ id: string }>;
|
||||||
|
},
|
||||||
|
): boolean {
|
||||||
|
if (actor.role === 'owner' || actor.role === 'admin') return true;
|
||||||
|
if (row.createdById && actor.userId === row.createdById) return true;
|
||||||
|
return assigneeIdList(row).includes(actor.userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** فقط dueAt / description → تعویق و ثبت نظر */
|
||||||
|
function isCollaboratorPatch(dto: UpdateActivityRequest): boolean {
|
||||||
|
const keys = Object.keys(dto).filter(
|
||||||
|
(key) => (dto as Record<string, unknown>)[key] !== undefined,
|
||||||
|
);
|
||||||
|
return keys.length > 0 && keys.every((key) => key === 'dueAt' || key === 'description');
|
||||||
|
}
|
||||||
|
|
||||||
|
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'؛ وقتی ست باشد فیلتر زمانی وضعیت را تحمیل نمیکند (جز عقبافتاده) */
|
/** stageId = شناسهٔ مرحله یا 'all'؛ وقتی ست باشد فیلتر زمانی وضعیت را تحمیل نمیکند (جز عقبافتاده) */
|
||||||
type StageScope = { stageId: string };
|
type StageScope = { stageId: string };
|
||||||
|
|
||||||
@@ -64,6 +131,7 @@ type ListFacets = {
|
|||||||
customer?: string;
|
customer?: string;
|
||||||
/** set = زمان شروع دارد، unset = ندارد */
|
/** set = زمان شروع دارد، unset = ندارد */
|
||||||
due?: 'set' | 'unset';
|
due?: 'set' | 'unset';
|
||||||
|
priority?: ActivityDto['priority'];
|
||||||
/** گروه فعالیت؛ خالی = همهٔ گروهها */
|
/** گروه فعالیت؛ خالی = همهٔ گروهها */
|
||||||
boardId?: string;
|
boardId?: string;
|
||||||
};
|
};
|
||||||
@@ -82,6 +150,9 @@ type ActivityRow = {
|
|||||||
reminderNotifySms: boolean;
|
reminderNotifySms: boolean;
|
||||||
reminderSentAt: Date | null;
|
reminderSentAt: Date | null;
|
||||||
completedAt: Date | null;
|
completedAt: Date | null;
|
||||||
|
completionMode?: 'any' | 'all';
|
||||||
|
completedByIds?: string[];
|
||||||
|
editPolicy?: 'creator' | 'assignees';
|
||||||
importSource?: string;
|
importSource?: string;
|
||||||
promotedFromPriorAt?: Date | null;
|
promotedFromPriorAt?: Date | null;
|
||||||
tags: string[];
|
tags: string[];
|
||||||
@@ -186,22 +257,39 @@ export class ActivitiesService {
|
|||||||
return { stages, types };
|
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(
|
async summary(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
desk?: 'mine' | 'team',
|
desk?: 'mine' | 'team',
|
||||||
): Promise<ActivitySummaryDto> {
|
): Promise<ActivitySummaryDto> {
|
||||||
const { start, end } = dayBounds();
|
const { start, end } = dayBounds();
|
||||||
const scope: Prisma.ActivityWhereInput =
|
const scope = this.deskScope(actor, desk);
|
||||||
desk === 'mine'
|
|
||||||
? {
|
|
||||||
OR: [
|
|
||||||
{ assigneeId: actor.userId },
|
|
||||||
{ assignees: { some: { id: actor.userId } } },
|
|
||||||
{ participantIds: { has: actor.userId } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
: activityAccessWhere(actor);
|
|
||||||
const prior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
|
const prior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
|
||||||
const [todayCount, overdueCount] = await Promise.all([
|
const [todayCount, overdueCount] = await Promise.all([
|
||||||
this.prisma.activity.count({
|
this.prisma.activity.count({
|
||||||
@@ -283,10 +371,24 @@ export class ActivitiesService {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const ctx = await this.ctx(organizationId);
|
const ctx = await this.ctx(organizationId);
|
||||||
|
const [todayDto, overdueDto, upcomingDto] = await Promise.all([
|
||||||
|
this.withAccountBalances(
|
||||||
|
organizationId,
|
||||||
|
today.map((row) => this.toDto(row, ctx)),
|
||||||
|
),
|
||||||
|
this.withAccountBalances(
|
||||||
|
organizationId,
|
||||||
|
overdue.map((row) => this.toDto(row, ctx)),
|
||||||
|
),
|
||||||
|
this.withAccountBalances(
|
||||||
|
organizationId,
|
||||||
|
upcoming.map((row) => this.toDto(row, ctx)),
|
||||||
|
),
|
||||||
|
]);
|
||||||
return {
|
return {
|
||||||
today: today.map((row) => this.toDto(row, ctx)),
|
today: todayDto,
|
||||||
overdue: overdue.map((row) => this.toDto(row, ctx)),
|
overdue: overdueDto,
|
||||||
upcoming: upcoming.map((row) => this.toDto(row, ctx)),
|
upcoming: upcomingDto,
|
||||||
todayCount,
|
todayCount,
|
||||||
overdueCount,
|
overdueCount,
|
||||||
};
|
};
|
||||||
@@ -338,7 +440,10 @@ export class ActivitiesService {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: rows.map((row) => this.toDto(row, ctx)),
|
items: await this.withAccountBalances(
|
||||||
|
organizationId,
|
||||||
|
rows.map((row) => this.toDto(row, ctx)),
|
||||||
|
),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
limit: take,
|
limit: take,
|
||||||
@@ -534,8 +639,24 @@ export class ActivitiesService {
|
|||||||
const stage = await this.stages.get(organizationId, stageId);
|
const stage = await this.stages.get(organizationId, stageId);
|
||||||
const existing = await this.prisma.activity.findFirst({
|
const existing = await this.prisma.activity.findFirst({
|
||||||
where: { id, organizationId },
|
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({
|
const row = await this.prisma.activity.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
@@ -550,6 +671,9 @@ export class ActivitiesService {
|
|||||||
: stage.kind === 'open'
|
: stage.kind === 'open'
|
||||||
? null
|
? null
|
||||||
: undefined,
|
: undefined,
|
||||||
|
...(stage.kind === 'open' && existing?.status !== 'open'
|
||||||
|
? { completedByIds: [] }
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
include,
|
include,
|
||||||
});
|
});
|
||||||
@@ -590,7 +714,8 @@ export class ActivitiesService {
|
|||||||
orderBy: { fullName: 'asc' },
|
orderBy: { fullName: 'asc' },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return dto;
|
const [enriched] = await this.withAccountBalances(organizationId, [dto]);
|
||||||
|
return enriched;
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(
|
async create(
|
||||||
@@ -675,6 +800,9 @@ export class ActivitiesService {
|
|||||||
assignees: assigneeIds.length
|
assignees: assigneeIds.length
|
||||||
? { connect: assigneeIds.map((id) => ({ id })) }
|
? { connect: assigneeIds.map((id) => ({ id })) }
|
||||||
: undefined,
|
: undefined,
|
||||||
|
completionMode: dto.completionMode === 'all' ? 'all' : 'any',
|
||||||
|
completedByIds: [],
|
||||||
|
editPolicy: dto.editPolicy === 'assignees' ? 'assignees' : 'creator',
|
||||||
createdById: userId,
|
createdById: userId,
|
||||||
},
|
},
|
||||||
include,
|
include,
|
||||||
@@ -743,8 +871,31 @@ export class ActivitiesService {
|
|||||||
|
|
||||||
const existing = await this.prisma.activity.findFirst({
|
const existing = await this.prisma.activity.findFirst({
|
||||||
where: { id, organizationId },
|
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,
|
||||||
|
editPolicy: true,
|
||||||
|
createdById: true,
|
||||||
|
assigneeId: true,
|
||||||
|
assignees: { select: { id: true } },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
if (!existing) {
|
||||||
|
throw new ForbiddenException('شما مجوز ویرایش این فعالیت را ندارید');
|
||||||
|
}
|
||||||
|
const collabOnly = isCollaboratorPatch(dto);
|
||||||
|
if (collabOnly) {
|
||||||
|
if (!canCollaborateActivity(actor, existing)) {
|
||||||
|
throw new ForbiddenException('شما مجوز ثبت نظر یا تعویق این فعالیت را ندارید');
|
||||||
|
}
|
||||||
|
} else if (!canMutateActivity(actor, existing)) {
|
||||||
|
throw new ForbiddenException('شما مجوز ویرایش این فعالیت را ندارید');
|
||||||
|
}
|
||||||
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
||||||
if (dto.title !== undefined) data.title = dto.title.trim();
|
if (dto.title !== undefined) data.title = dto.title.trim();
|
||||||
if ('boardId' in dto) {
|
if ('boardId' in dto) {
|
||||||
@@ -812,6 +963,7 @@ export class ActivitiesService {
|
|||||||
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
|
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
|
||||||
if ('leadId' in dto) data.leadId = emptyToNull(dto.leadId ?? null);
|
if ('leadId' in dto) data.leadId = emptyToNull(dto.leadId ?? null);
|
||||||
let assigneeConnect: Array<{ id: string }> | undefined;
|
let assigneeConnect: Array<{ id: string }> | undefined;
|
||||||
|
let nextAssigneeIds: string[] | undefined;
|
||||||
if (dto.assigneeIds !== undefined || 'assigneeId' in dto) {
|
if (dto.assigneeIds !== undefined || 'assigneeId' in dto) {
|
||||||
const current = await this.prisma.activity.findFirst({
|
const current = await this.prisma.activity.findFirst({
|
||||||
where: { id, organizationId },
|
where: { id, organizationId },
|
||||||
@@ -839,6 +991,7 @@ export class ActivitiesService {
|
|||||||
);
|
);
|
||||||
data.assigneeId = assigneeIds[0]!;
|
data.assigneeId = assigneeIds[0]!;
|
||||||
assigneeConnect = assigneeIds.map((uid) => ({ id: uid }));
|
assigneeConnect = assigneeIds.map((uid) => ({ id: uid }));
|
||||||
|
nextAssigneeIds = assigneeIds;
|
||||||
} else {
|
} else {
|
||||||
const assigneeId = emptyToNull(dto.assigneeId ?? null);
|
const assigneeId = emptyToNull(dto.assigneeId ?? null);
|
||||||
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
||||||
@@ -852,12 +1005,44 @@ export class ActivitiesService {
|
|||||||
data.assigneeId = assigneeId;
|
data.assigneeId = assigneeId;
|
||||||
if (assigneeId) assigneeConnect = [{ id: assigneeId }];
|
if (assigneeId) assigneeConnect = [{ id: assigneeId }];
|
||||||
else assigneeConnect = [];
|
else assigneeConnect = [];
|
||||||
|
nextAssigneeIds = assigneeId ? [assigneeId] : [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (dto.status !== undefined) {
|
const modeChanged = dto.completionMode === 'any' || dto.completionMode === 'all';
|
||||||
data.status = dto.status;
|
const nextMode = modeChanged ? dto.completionMode! : (existing?.completionMode ?? 'any');
|
||||||
data.completedAt =
|
if (modeChanged) data.completionMode = nextMode;
|
||||||
dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined;
|
if (dto.editPolicy === 'creator' || dto.editPolicy === 'assignees') {
|
||||||
|
data.editPolicy = dto.editPolicy;
|
||||||
|
}
|
||||||
|
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({
|
const row = await this.prisma.activity.update({
|
||||||
@@ -881,7 +1066,7 @@ export class ActivitiesService {
|
|||||||
addedParticipants.filter((uid) => !assigneeSet.has(uid)),
|
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);
|
await this.fireDone(organizationId, row);
|
||||||
}
|
}
|
||||||
return this.toDto(row, await this.ctx(organizationId));
|
return this.toDto(row, await this.ctx(organizationId));
|
||||||
@@ -891,18 +1076,74 @@ export class ActivitiesService {
|
|||||||
organizationId: string,
|
organizationId: string,
|
||||||
id: string,
|
id: string,
|
||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
|
options: { force?: boolean; undo?: boolean } = {},
|
||||||
): Promise<ActivityDto> {
|
): Promise<ActivityDto> {
|
||||||
await this.ensureExists(organizationId, id, actor);
|
await this.ensureExists(organizationId, id, actor);
|
||||||
const existing = await this.prisma.activity.findFirst({
|
const existing = await this.prisma.activity.findFirst({
|
||||||
where: { id, organizationId },
|
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({
|
const row = await this.prisma.activity.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { status: 'done', completedAt: new Date() },
|
data: {
|
||||||
|
completedByIds: reconciled.completedByIds,
|
||||||
|
status: reconciled.status,
|
||||||
|
completedAt: reconciled.status === 'done' ? new Date() : null,
|
||||||
|
},
|
||||||
include,
|
include,
|
||||||
});
|
});
|
||||||
if (existing?.status !== 'done') {
|
if (reconciled.status === 'done' && existing.status !== 'done') {
|
||||||
await this.fireDone(organizationId, row);
|
await this.fireDone(organizationId, row);
|
||||||
}
|
}
|
||||||
return this.toDto(row, await this.ctx(organizationId));
|
return this.toDto(row, await this.ctx(organizationId));
|
||||||
@@ -946,6 +1187,18 @@ export class ActivitiesService {
|
|||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await this.ensureExists(organizationId, id, actor);
|
await this.ensureExists(organizationId, id, actor);
|
||||||
|
const existing = await this.prisma.activity.findFirst({
|
||||||
|
where: { id, organizationId },
|
||||||
|
select: {
|
||||||
|
createdById: true,
|
||||||
|
editPolicy: true,
|
||||||
|
assigneeId: true,
|
||||||
|
assignees: { select: { id: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!existing || !canMutateActivity(actor, existing)) {
|
||||||
|
throw new ForbiddenException('شما مجوز حذف این فعالیت را ندارید');
|
||||||
|
}
|
||||||
const images = await this.prisma.activityImage.findMany({
|
const images = await this.prisma.activityImage.findMany({
|
||||||
where: { activityId: id, organizationId },
|
where: { activityId: id, organizationId },
|
||||||
select: { storageKey: true, sizeBytes: true },
|
select: { storageKey: true, sizeBytes: true },
|
||||||
@@ -966,6 +1219,19 @@ export class ActivitiesService {
|
|||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
): Promise<ActivityImageDto> {
|
): Promise<ActivityImageDto> {
|
||||||
await this.ensureExists(organizationId, activityId, actor);
|
await this.ensureExists(organizationId, activityId, actor);
|
||||||
|
const gate = await this.prisma.activity.findFirst({
|
||||||
|
where: { id: activityId, organizationId },
|
||||||
|
select: {
|
||||||
|
createdById: true,
|
||||||
|
editPolicy: true,
|
||||||
|
assigneeId: true,
|
||||||
|
assignees: { select: { id: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// پیوست در مسیر ثبت نظر — مسئولان هم مجازند حتی با editPolicy=creator
|
||||||
|
if (!gate || !canCollaborateActivity(actor, gate)) {
|
||||||
|
throw new ForbiddenException('شما مجوز ثبت نظر یا پیوست برای این فعالیت را ندارید');
|
||||||
|
}
|
||||||
if (!file?.buffer?.length) {
|
if (!file?.buffer?.length) {
|
||||||
throw new BadRequestException('فایلی ارسال نشده است');
|
throw new BadRequestException('فایلی ارسال نشده است');
|
||||||
}
|
}
|
||||||
@@ -1060,10 +1326,27 @@ export class ActivitiesService {
|
|||||||
actor: ActivityActor,
|
actor: ActivityActor,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await this.ensureExists(organizationId, activityId, actor);
|
await this.ensureExists(organizationId, activityId, actor);
|
||||||
|
const gate = await this.prisma.activity.findFirst({
|
||||||
|
where: { id: activityId, organizationId },
|
||||||
|
select: {
|
||||||
|
createdById: true,
|
||||||
|
editPolicy: true,
|
||||||
|
assigneeId: true,
|
||||||
|
assignees: { select: { id: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
const row = await this.prisma.activityImage.findFirst({
|
const row = await this.prisma.activityImage.findFirst({
|
||||||
where: { id: imageId, activityId, organizationId },
|
where: { id: imageId, activityId, organizationId },
|
||||||
});
|
});
|
||||||
if (!row) throw new NotFoundException('فایل پیدا نشد');
|
if (!row) throw new NotFoundException('فایل پیدا نشد');
|
||||||
|
const canMutate = !!gate && canMutateActivity(actor, gate);
|
||||||
|
const canRemoveOwn =
|
||||||
|
!!gate &&
|
||||||
|
canCollaborateActivity(actor, gate) &&
|
||||||
|
row.uploadedById === actor.userId;
|
||||||
|
if (!canMutate && !canRemoveOwn) {
|
||||||
|
throw new ForbiddenException('شما مجوز حذف این پیوست را ندارید');
|
||||||
|
}
|
||||||
await this.files.remove(row.storageKey);
|
await this.files.remove(row.storageKey);
|
||||||
await this.prisma.activityImage.delete({ where: { id: row.id } });
|
await this.prisma.activityImage.delete({ where: { id: row.id } });
|
||||||
await this.storage.addLocal(organizationId, -row.sizeBytes);
|
await this.storage.addLocal(organizationId, -row.sizeBytes);
|
||||||
@@ -1108,25 +1391,18 @@ export class ActivitiesService {
|
|||||||
typeRows: TypeRow[] = [],
|
typeRows: TypeRow[] = [],
|
||||||
): Prisma.ActivityWhereInput {
|
): Prisma.ActivityWhereInput {
|
||||||
const { start, end } = dayBounds();
|
const { start, end } = dayBounds();
|
||||||
const scope: Prisma.ActivityWhereInput =
|
const scope = this.deskScope(actor, desk);
|
||||||
desk === 'mine'
|
|
||||||
? {
|
|
||||||
OR: [
|
|
||||||
{ assigneeId: actor.userId },
|
|
||||||
{ assignees: { some: { id: actor.userId } } },
|
|
||||||
{ participantIds: { has: actor.userId } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
: activityAccessWhere(actor);
|
|
||||||
const facetAssignee = facets?.assigneeId?.trim();
|
const facetAssignee = facets?.assigneeId?.trim();
|
||||||
const facetTypeDef = facets?.typeDefId?.trim();
|
const facetTypeDef = facets?.typeDefId?.trim();
|
||||||
const facetTitle = facets?.title?.trim();
|
const facetTitle = facets?.title?.trim();
|
||||||
const facetCustomer = facets?.customer?.trim();
|
const facetCustomer = facets?.customer?.trim();
|
||||||
|
const facetPriority = facets?.priority;
|
||||||
const andParts: Prisma.ActivityWhereInput[] = [
|
const andParts: Prisma.ActivityWhereInput[] = [
|
||||||
scope,
|
scope,
|
||||||
...(facets?.type ? [{ type: facets.type }] : []),
|
...(facets?.type ? [{ type: facets.type }] : []),
|
||||||
...(facetTypeDef ? [this.types.whereForType(typeRows, facetTypeDef)] : []),
|
...(facetTypeDef ? [this.types.whereForType(typeRows, facetTypeDef)] : []),
|
||||||
...(facets?.status ? [{ status: facets.status }] : []),
|
...(facets?.status ? [{ status: facets.status }] : []),
|
||||||
|
...(facetPriority ? [{ priority: facetPriority }] : []),
|
||||||
...(facetTitle ? [{ title: ci(facetTitle) }] : []),
|
...(facetTitle ? [{ title: ci(facetTitle) }] : []),
|
||||||
...(facetCustomer ? [this.customerWhere(facetCustomer)] : []),
|
...(facetCustomer ? [this.customerWhere(facetCustomer)] : []),
|
||||||
...(facetAssignee
|
...(facetAssignee
|
||||||
@@ -1385,6 +1661,105 @@ export class ActivitiesService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** فقط فعالیتهای تگ مطالبات؛ مانده از کش تهحساب بدون فراخوانی زنده */
|
||||||
|
private async withAccountBalances(
|
||||||
|
organizationId: string,
|
||||||
|
items: ActivityDto[],
|
||||||
|
): Promise<ActivityDto[]> {
|
||||||
|
if (!items.length) return items;
|
||||||
|
const claimItems = items.filter((item) =>
|
||||||
|
(item.tags ?? []).includes(ACCOUNT_BALANCE_CLAIMS_TAG),
|
||||||
|
);
|
||||||
|
if (!claimItems.length) return items;
|
||||||
|
|
||||||
|
const personIds = [
|
||||||
|
...new Set(
|
||||||
|
claimItems
|
||||||
|
.map((item) => item.person?.id)
|
||||||
|
.filter((id): id is string => Boolean(id)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
const balanceByPerson = new Map<string, ActivityAccountBalanceDto | null>();
|
||||||
|
if (personIds.length) {
|
||||||
|
const links = await this.prisma.personAccountingLink.findMany({
|
||||||
|
where: {
|
||||||
|
personId: { in: personIds },
|
||||||
|
person: { organizationId },
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
balanceCache: true,
|
||||||
|
connection: { select: { isDefault: true } },
|
||||||
|
},
|
||||||
|
orderBy: [{ linkedAt: 'desc' }],
|
||||||
|
});
|
||||||
|
const bestByPerson = new Map<string, (typeof links)[number]>();
|
||||||
|
for (const link of links) {
|
||||||
|
const prev = bestByPerson.get(link.personId);
|
||||||
|
if (!prev) {
|
||||||
|
bestByPerson.set(link.personId, link);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const prevScore =
|
||||||
|
(prev.balanceCache ? 2 : 0) + (prev.connection.isDefault ? 1 : 0);
|
||||||
|
const nextScore =
|
||||||
|
(link.balanceCache ? 2 : 0) + (link.connection.isDefault ? 1 : 0);
|
||||||
|
if (nextScore > prevScore) bestByPerson.set(link.personId, link);
|
||||||
|
}
|
||||||
|
for (const personId of personIds) {
|
||||||
|
const link = bestByPerson.get(personId);
|
||||||
|
balanceByPerson.set(
|
||||||
|
personId,
|
||||||
|
link?.balanceCache
|
||||||
|
? this.cacheToAccountBalance(link.balanceCache)
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return items.map((item) => {
|
||||||
|
if (!(item.tags ?? []).includes(ACCOUNT_BALANCE_CLAIMS_TAG)) return item;
|
||||||
|
const personId = item.person?.id;
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
accountBalance: personId
|
||||||
|
? (balanceByPerson.get(personId) ?? null)
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private cacheToAccountBalance(cache: {
|
||||||
|
rialBalance: number | null;
|
||||||
|
goldBalance: number | null;
|
||||||
|
rawResponse: unknown;
|
||||||
|
fetchedAt: Date;
|
||||||
|
}): ActivityAccountBalanceDto {
|
||||||
|
const fields = parseAccountBalanceWeightFields(
|
||||||
|
extractMandehRaw(cache.rawResponse).fields,
|
||||||
|
);
|
||||||
|
const weights = ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => {
|
||||||
|
const value =
|
||||||
|
fields[key] ??
|
||||||
|
(key === 'MandeyeVazni' ? cache.goldBalance : null) ??
|
||||||
|
null;
|
||||||
|
if (value == null || !Number.isFinite(value)) return null;
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label: ACCOUNT_BALANCE_WEIGHT_LABELS[key] ?? key,
|
||||||
|
value,
|
||||||
|
};
|
||||||
|
}).filter((row): row is NonNullable<typeof row> => row != null);
|
||||||
|
|
||||||
|
return {
|
||||||
|
rialBalance:
|
||||||
|
cache.rialBalance != null && Number.isFinite(cache.rialBalance)
|
||||||
|
? cache.rialBalance
|
||||||
|
: null,
|
||||||
|
weights,
|
||||||
|
fetchedAt: cache.fetchedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private toDto(row: ActivityRow, ctx?: DtoContext): ActivityDto {
|
private toDto(row: ActivityRow, ctx?: DtoContext): ActivityDto {
|
||||||
const fields =
|
const fields =
|
||||||
row.fields && typeof row.fields === 'object' && !Array.isArray(row.fields)
|
row.fields && typeof row.fields === 'object' && !Array.isArray(row.fields)
|
||||||
@@ -1418,6 +1793,9 @@ export class ActivitiesService {
|
|||||||
reminderNotifySms: row.reminderNotifySms,
|
reminderNotifySms: row.reminderNotifySms,
|
||||||
reminderSentAt: row.reminderSentAt?.toISOString() ?? null,
|
reminderSentAt: row.reminderSentAt?.toISOString() ?? null,
|
||||||
completedAt: row.completedAt?.toISOString() ?? null,
|
completedAt: row.completedAt?.toISOString() ?? null,
|
||||||
|
completionMode: row.completionMode ?? 'any',
|
||||||
|
completedByIds: row.completedByIds ?? [],
|
||||||
|
editPolicy: row.editPolicy ?? 'creator',
|
||||||
importSource: row.importSource ?? 'manual',
|
importSource: row.importSource ?? 'manual',
|
||||||
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
|
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
|
||||||
tags: row.tags ?? [],
|
tags: row.tags ?? [],
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ import type {
|
|||||||
ActivityStageDto,
|
ActivityStageDto,
|
||||||
ActivityStatus,
|
ActivityStatus,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { ACTIVITY_STAGE_COLORS } from '@mento/shared';
|
import {
|
||||||
|
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
|
||||||
|
ACTIVITY_STAGE_COLORS,
|
||||||
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
@@ -39,6 +42,7 @@ type BoardRow = {
|
|||||||
name: string;
|
name: string;
|
||||||
isDefault: boolean;
|
isDefault: boolean;
|
||||||
position: number;
|
position: number;
|
||||||
|
systemKey: string | null;
|
||||||
members: Array<{ userId: string }>;
|
members: Array<{ userId: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -49,6 +53,7 @@ function toBoardDto(row: BoardRow): ActivityBoardDto {
|
|||||||
isDefault: row.isDefault,
|
isDefault: row.isDefault,
|
||||||
position: row.position,
|
position: row.position,
|
||||||
memberIds: row.members.map((member) => member.userId),
|
memberIds: row.members.map((member) => member.userId),
|
||||||
|
systemKey: row.systemKey,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,6 +74,7 @@ const BOARD_SELECT = {
|
|||||||
id: true,
|
id: true,
|
||||||
name: true,
|
name: true,
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
|
systemKey: true,
|
||||||
position: true,
|
position: true,
|
||||||
members: { select: { userId: true } },
|
members: { select: { userId: true } },
|
||||||
} satisfies Prisma.ActivityBoardSelect;
|
} satisfies Prisma.ActivityBoardSelect;
|
||||||
@@ -142,9 +148,35 @@ export class ActivityStagesService {
|
|||||||
});
|
});
|
||||||
const boards = rows.map(toBoardDto);
|
const boards = rows.map(toBoardDto);
|
||||||
if (!actor || managesAllBoards(actor.role)) return boards;
|
if (!actor || managesAllBoards(actor.role)) return boards;
|
||||||
return boards.filter(
|
|
||||||
(board) => board.memberIds.length === 0 || board.memberIds.includes(actor.userId),
|
const claimBoardIds = boards
|
||||||
);
|
.filter((b) => b.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS)
|
||||||
|
.map((b) => b.id);
|
||||||
|
const assignedClaimBoardIds = new Set<string>();
|
||||||
|
if (claimBoardIds.length) {
|
||||||
|
const assigned = await this.prisma.activity.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId,
|
||||||
|
boardId: { in: claimBoardIds },
|
||||||
|
OR: [
|
||||||
|
{ assigneeId: actor.userId },
|
||||||
|
{ assignees: { some: { id: actor.userId } } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: { boardId: true },
|
||||||
|
distinct: ['boardId'],
|
||||||
|
});
|
||||||
|
for (const row of assigned) {
|
||||||
|
if (row.boardId) assignedClaimBoardIds.add(row.boardId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return boards.filter((board) => {
|
||||||
|
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
|
||||||
|
return assignedClaimBoardIds.has(board.id);
|
||||||
|
}
|
||||||
|
return board.memberIds.length === 0 || board.memberIds.includes(actor.userId);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** گروه بدون عضو برای همه باز است؛ مالک و مدیر همهٔ گروهها را میبینند */
|
/** گروه بدون عضو برای همه باز است؛ مالک و مدیر همهٔ گروهها را میبینند */
|
||||||
@@ -154,6 +186,25 @@ export class ActivityStagesService {
|
|||||||
actor: { userId: string; role: string },
|
actor: { userId: string; role: string },
|
||||||
) {
|
) {
|
||||||
if (managesAllBoards(actor.role)) return;
|
if (managesAllBoards(actor.role)) return;
|
||||||
|
const board = await this.prisma.activityBoard.findFirst({
|
||||||
|
where: { id: boardId, organizationId },
|
||||||
|
select: { systemKey: true },
|
||||||
|
});
|
||||||
|
if (!board) throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
|
||||||
|
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
|
||||||
|
const hit = await this.prisma.activity.count({
|
||||||
|
where: {
|
||||||
|
organizationId,
|
||||||
|
boardId,
|
||||||
|
OR: [
|
||||||
|
{ assigneeId: actor.userId },
|
||||||
|
{ assignees: { some: { id: actor.userId } } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (hit > 0) return;
|
||||||
|
throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
|
||||||
|
}
|
||||||
const members = await this.prisma.activityBoardMember.findMany({
|
const members = await this.prisma.activityBoardMember.findMany({
|
||||||
where: { boardId, board: { organizationId } },
|
where: { boardId, board: { organizationId } },
|
||||||
select: { userId: true },
|
select: { userId: true },
|
||||||
@@ -206,7 +257,13 @@ export class ActivityStagesService {
|
|||||||
id: string,
|
id: string,
|
||||||
dto: { name?: string; memberIds?: string[] },
|
dto: { name?: string; memberIds?: string[] },
|
||||||
): Promise<ActivityBoardDto> {
|
): Promise<ActivityBoardDto> {
|
||||||
await this.getBoard(organizationId, id);
|
const board = await this.getBoard(organizationId, id);
|
||||||
|
if (board.systemKey && dto.name != null) {
|
||||||
|
throw new BadRequestException('نام این گروه سیستمی قابل تغییر نیست');
|
||||||
|
}
|
||||||
|
if (board.systemKey && dto.memberIds !== undefined) {
|
||||||
|
throw new BadRequestException('اعضای این گروه سیستمی از اینجا قابل تغییر نیست');
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
if (dto.name != null) {
|
if (dto.name != null) {
|
||||||
await this.prisma.activityBoard.update({
|
await this.prisma.activityBoard.update({
|
||||||
@@ -255,6 +312,9 @@ export class ActivityStagesService {
|
|||||||
if (board.isDefault) {
|
if (board.isDefault) {
|
||||||
throw new BadRequestException('گروه پیشفرض قابل حذف نیست');
|
throw new BadRequestException('گروه پیشفرض قابل حذف نیست');
|
||||||
}
|
}
|
||||||
|
if (board.systemKey) {
|
||||||
|
throw new BadRequestException('گروه سیستمی قابل حذف نیست');
|
||||||
|
}
|
||||||
await this.prisma.$transaction([
|
await this.prisma.$transaction([
|
||||||
this.prisma.activity.updateMany({
|
this.prisma.activity.updateMany({
|
||||||
where: { organizationId, boardId: id },
|
where: { organizationId, boardId: id },
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import type {
|
|||||||
ActivityFieldValue,
|
ActivityFieldValue,
|
||||||
ActivityFieldValues,
|
ActivityFieldValues,
|
||||||
ActivityParticipantsValue,
|
ActivityParticipantsValue,
|
||||||
|
ActivityPriority,
|
||||||
|
ActivityPrioritySetting,
|
||||||
ActivityStageColor,
|
ActivityStageColor,
|
||||||
ActivityType,
|
ActivityType,
|
||||||
ActivityTypeDefDto,
|
ActivityTypeDefDto,
|
||||||
@@ -17,8 +19,11 @@ import type {
|
|||||||
import {
|
import {
|
||||||
ACTIVITY_FIELD_TYPES,
|
ACTIVITY_FIELD_TYPES,
|
||||||
ACTIVITY_FIELD_TYPES_WITH_OPTIONS,
|
ACTIVITY_FIELD_TYPES_WITH_OPTIONS,
|
||||||
|
ACTIVITY_PRIORITY_KEYS,
|
||||||
ACTIVITY_STAGE_COLORS,
|
ACTIVITY_STAGE_COLORS,
|
||||||
ACTIVITY_TYPE_ICONS,
|
ACTIVITY_TYPE_ICONS,
|
||||||
|
DEFAULT_ACTIVITY_PRIORITY_SETTINGS,
|
||||||
|
parseActivityPrioritySettings,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
@@ -619,6 +624,43 @@ export class ActivityTypesService {
|
|||||||
: 'green';
|
: 'green';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async listPriorities(organizationId: string): Promise<ActivityPrioritySetting[]> {
|
||||||
|
const row = await this.prisma.organization.findUnique({
|
||||||
|
where: { id: organizationId },
|
||||||
|
select: { activityPriorities: true },
|
||||||
|
});
|
||||||
|
return parseActivityPrioritySettings(row?.activityPriorities);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePriorities(
|
||||||
|
organizationId: string,
|
||||||
|
items: Array<{ key: ActivityPriority; label: string; color: string }>,
|
||||||
|
): Promise<ActivityPrioritySetting[]> {
|
||||||
|
const byKey = new Map(items.map((i) => [i.key, i]));
|
||||||
|
if (ACTIVITY_PRIORITY_KEYS.some((k) => !byKey.has(k))) {
|
||||||
|
throw new BadRequestException('هر پنج سطح اولویت باید ارسال شوند');
|
||||||
|
}
|
||||||
|
const hex = /^#[0-9a-fA-F]{6}$/;
|
||||||
|
const stored: Record<string, { label: string; color: string }> = {};
|
||||||
|
for (const key of ACTIVITY_PRIORITY_KEYS) {
|
||||||
|
const item = byKey.get(key)!;
|
||||||
|
const label = item.label.trim().slice(0, 40);
|
||||||
|
const color = item.color.trim();
|
||||||
|
if (!label) throw new BadRequestException(`عنوان اولویت «${key}» خالی است`);
|
||||||
|
if (!hex.test(color)) throw new BadRequestException(`رنگ اولویت «${key}» نامعتبر است`);
|
||||||
|
const def = DEFAULT_ACTIVITY_PRIORITY_SETTINGS.find((d) => d.key === key)!;
|
||||||
|
// فقط تفاوت با پیشفرض را نگه میداریم تا JSON جمعوجور بماند
|
||||||
|
if (label !== def.label || color.toLowerCase() !== def.color.toLowerCase()) {
|
||||||
|
stored[key] = { label, color };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await this.prisma.organization.update({
|
||||||
|
where: { id: organizationId },
|
||||||
|
data: { activityPriorities: stored as Prisma.InputJsonValue },
|
||||||
|
});
|
||||||
|
return parseActivityPrioritySettings(stored);
|
||||||
|
}
|
||||||
|
|
||||||
private mapError(e: unknown) {
|
private mapError(e: unknown) {
|
||||||
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
|
||||||
return new BadRequestException('نوع فعالیتی با این نام وجود دارد');
|
return new BadRequestException('نوع فعالیتی با این نام وجود دارد');
|
||||||
|
|||||||
@@ -9,11 +9,13 @@ import {
|
|||||||
IsObject,
|
IsObject,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
|
Matches,
|
||||||
Max,
|
Max,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
Min,
|
Min,
|
||||||
MinLength,
|
MinLength,
|
||||||
ValidateIf,
|
ValidateIf,
|
||||||
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import type { ActivityFieldDef, ActivityFieldValues, ActivityTypeIcon } from '@mento/shared';
|
import type { ActivityFieldDef, ActivityFieldValues, ActivityTypeIcon } from '@mento/shared';
|
||||||
import { ACTIVITY_TYPE_ICONS } from '@mento/shared';
|
import { ACTIVITY_TYPE_ICONS } from '@mento/shared';
|
||||||
@@ -91,6 +93,11 @@ export class ListActivitiesQueryDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
typeDefId?: string;
|
typeDefId?: string;
|
||||||
|
|
||||||
|
/** اولویت فعالیت (کلید ثابت؛ برچسب در تنظیمات سازمان) */
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(ACTIVITY_PRIORITIES)
|
||||||
|
priority?: (typeof ACTIVITY_PRIORITIES)[number];
|
||||||
|
|
||||||
/** شناسهٔ مرحله یا 'all' — حالت تب/کانبان مراحل */
|
/** شناسهٔ مرحله یا 'all' — حالت تب/کانبان مراحل */
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -384,6 +391,14 @@ export class CreateActivityDto {
|
|||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
assigneeIds?: string[];
|
assigneeIds?: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['any', 'all'])
|
||||||
|
completionMode?: 'any' | 'all';
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['creator', 'assignees'])
|
||||||
|
editPolicy?: 'creator' | 'assignees';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UpdateActivityDto {
|
export class UpdateActivityDto {
|
||||||
@@ -484,4 +499,35 @@ export class UpdateActivityDto {
|
|||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
assigneeIds?: string[];
|
assigneeIds?: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['any', 'all'])
|
||||||
|
completionMode?: 'any' | 'all';
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['creator', 'assignees'])
|
||||||
|
editPolicy?: 'creator' | 'assignees';
|
||||||
|
}
|
||||||
|
|
||||||
|
const PRIORITY_KEYS = ['very_low', 'low', 'medium', 'high', 'very_high'] as const;
|
||||||
|
|
||||||
|
export class ActivityPriorityItemDto {
|
||||||
|
@IsIn(PRIORITY_KEYS)
|
||||||
|
key!: (typeof PRIORITY_KEYS)[number];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(40)
|
||||||
|
label!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@Matches(/^#[0-9a-fA-F]{6}$/)
|
||||||
|
color!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateActivityPrioritiesDto {
|
||||||
|
@IsArray()
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => ActivityPriorityItemDto)
|
||||||
|
items!: ActivityPriorityItemDto[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { OrganizationsModule } from './organizations/organizations.module';
|
|||||||
import { ContactsModule } from './contacts/contacts.module';
|
import { ContactsModule } from './contacts/contacts.module';
|
||||||
import { PipelinesModule } from './pipelines/pipelines.module';
|
import { PipelinesModule } from './pipelines/pipelines.module';
|
||||||
import { ActivitiesModule } from './activities/activities.module';
|
import { ActivitiesModule } from './activities/activities.module';
|
||||||
|
import { AccountBalancesModule } from './account-balances/account-balances.module';
|
||||||
import { NotesModule } from './notes/notes.module';
|
import { NotesModule } from './notes/notes.module';
|
||||||
import { CustomFieldsModule } from './custom-fields/custom-fields.module';
|
import { CustomFieldsModule } from './custom-fields/custom-fields.module';
|
||||||
import { ProductsModule } from './products/products.module';
|
import { ProductsModule } from './products/products.module';
|
||||||
@@ -67,6 +68,7 @@ import { CustomerGroupsModule } from './customer-groups/customer-groups.module';
|
|||||||
PrismaModule,
|
PrismaModule,
|
||||||
SmsBillingModule,
|
SmsBillingModule,
|
||||||
CustomerGroupsModule,
|
CustomerGroupsModule,
|
||||||
|
AccountBalancesModule,
|
||||||
OutboundSmsModule,
|
OutboundSmsModule,
|
||||||
StorageModule,
|
StorageModule,
|
||||||
HealthModule,
|
HealthModule,
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ import type {
|
|||||||
StorageUsageDto,
|
StorageUsageDto,
|
||||||
SubscriptionSummaryDto,
|
SubscriptionSummaryDto,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
|
import {
|
||||||
|
parseUserTreasuryAccess,
|
||||||
|
permissionsWithTreasuryOverride,
|
||||||
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
/** Ensures Express.Multer.File augmentation is loaded for saveAvatar. */
|
/** Ensures Express.Multer.File augmentation is loaded for saveAvatar. */
|
||||||
import type {} from 'multer';
|
import type {} from 'multer';
|
||||||
@@ -848,6 +852,9 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const role = membership?.role ?? user.role;
|
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 orgName = membership?.organization.name;
|
||||||
const sub =
|
const sub =
|
||||||
subscription ??
|
subscription ??
|
||||||
@@ -879,9 +886,10 @@ export class AuthService {
|
|||||||
storage,
|
storage,
|
||||||
isOrgOwner: role === 'owner',
|
isOrgOwner: role === 'owner',
|
||||||
priorArchive: this.priorArchiveFor(membership),
|
priorArchive: this.priorArchiveFor(membership),
|
||||||
permissions: (Array.isArray(membership?.orgRole?.permissions)
|
permissions: permissionsWithTreasuryOverride(
|
||||||
? membership.orgRole.permissions.filter((item) => typeof item === 'string')
|
rolePermissions,
|
||||||
: []) as AuthUserDto['permissions'],
|
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
|
||||||
|
) as AuthUserDto['permissions'],
|
||||||
...(viewAs ? { viewAs } : {}),
|
...(viewAs ? { viewAs } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,6 +195,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
const peers = await this.prisma.teamMember.findMany({
|
const peers = await this.prisma.teamMember.findMany({
|
||||||
where: {
|
where: {
|
||||||
teamId: { in: memberships.map((m) => m.teamId) },
|
teamId: { in: memberships.map((m) => m.teamId) },
|
||||||
|
team: { organizationId },
|
||||||
|
user: {
|
||||||
|
memberships: { some: { organizationId, isActive: true } },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
select: { userId: true },
|
select: { userId: true },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -416,7 +416,10 @@ export class AutomationsService {
|
|||||||
await this.syncLeadAssigneeFromActivity(ctx, type === 'call' ? assigneeId : null);
|
await this.syncLeadAssigneeFromActivity(ctx, type === 'call' ? assigneeId : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** سرنخ تازهای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس را میگیرد. */
|
/**
|
||||||
|
* سرنخ تازهای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس اتوماسیون را میگیرد.
|
||||||
|
* مالک سازمان بهعنوان fallback ست نمیشود — فقط مسئول صریح فعالیت.
|
||||||
|
*/
|
||||||
private async syncLeadAssigneeFromActivity(
|
private async syncLeadAssigneeFromActivity(
|
||||||
ctx: AutomationContext,
|
ctx: AutomationContext,
|
||||||
activityAssigneeId: string | null,
|
activityAssigneeId: string | null,
|
||||||
@@ -468,6 +471,7 @@ export class AutomationsService {
|
|||||||
ctx: AutomationContext,
|
ctx: AutomationContext,
|
||||||
ref: StepRef,
|
ref: StepRef,
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
|
/** مسئول فعلی رکورد؛ هرگز مالک سازمان را بهصورت ضمنی اضافه نکن */
|
||||||
const fallback = ctx.assigneeId || ctx.ownerId || null;
|
const fallback = ctx.assigneeId || ctx.ownerId || null;
|
||||||
const mode = config.assignMode ?? (config.assigneeId ? 'user' : 'owner');
|
const mode = config.assignMode ?? (config.assigneeId ? 'user' : 'owner');
|
||||||
|
|
||||||
@@ -502,6 +506,7 @@ export class AutomationsService {
|
|||||||
return pickRoundRobin(valid, cursor.counter) ?? fallback;
|
return pickRoundRobin(valid, cursor.counter) ?? fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mode === 'owner' → مسئول فعلی رکورد؛ اگر نباشد فعالیت بدون مسئول میماند
|
||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ import {
|
|||||||
defaultEnabledModules,
|
defaultEnabledModules,
|
||||||
isPermanentBillingPlan,
|
isPermanentBillingPlan,
|
||||||
isOrgModuleKey,
|
isOrgModuleKey,
|
||||||
|
modulesForProductPlan,
|
||||||
|
PRODUCT_PLAN_LIMITS,
|
||||||
|
type ProductPlanCode,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { PlatformAdminAlertService } from './platform-admin-alert.service';
|
import { PlatformAdminAlertService } from './platform-admin-alert.service';
|
||||||
@@ -414,7 +417,37 @@ export class BillingService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
defaultModulesForNewOrg(): OrgModuleKey[] {
|
defaultModulesForNewOrg(): OrgModuleKey[] {
|
||||||
return defaultEnabledModules();
|
return modulesForProductPlan('core');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** سطح امکانات را روی همهٔ محیطهای مالک میگذارد و سقف هسته/تیم/سازمان را هم تنظیم میکند. */
|
||||||
|
async applyProductPlan(organizationId: string, code: ProductPlanCode) {
|
||||||
|
const modules = modulesForProductPlan(code);
|
||||||
|
const owner = await this.prisma.membership.findFirst({
|
||||||
|
where: { organizationId, role: 'owner', isActive: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { userId: true },
|
||||||
|
});
|
||||||
|
const orgIds = owner ? await this.ownedOrganizationIds(owner.userId) : [organizationId];
|
||||||
|
for (const id of orgIds) {
|
||||||
|
await this.setOrgModules(id, modules);
|
||||||
|
}
|
||||||
|
const limits = PRODUCT_PLAN_LIMITS[code];
|
||||||
|
if (owner && (limits.maxUsers != null || limits.maxOrganizations != null)) {
|
||||||
|
const account = await this.getByOwnerUserId(owner.userId);
|
||||||
|
if (account) {
|
||||||
|
await this.prisma.billingAccount.update({
|
||||||
|
where: { id: account.id },
|
||||||
|
data: {
|
||||||
|
...(limits.maxUsers != null ? { maxUsers: limits.maxUsers } : {}),
|
||||||
|
...(limits.maxOrganizations != null
|
||||||
|
? { maxOrganizations: limits.maxOrganizations }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return modules;
|
||||||
}
|
}
|
||||||
|
|
||||||
async countExpiringSoon() {
|
async countExpiringSoon() {
|
||||||
|
|||||||
+138
-109
@@ -105,29 +105,33 @@ export function resolveAllSectionAccess(input: {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** ابعاد پرشدهٔ یک قانون با OR؛ خالی = null */
|
||||||
|
function unionFacets<T>(facets: T[]): T | { OR: T[] } | null {
|
||||||
|
if (!facets.length) return null;
|
||||||
|
return facets.length === 1 ? facets[0]! : { OR: facets };
|
||||||
|
}
|
||||||
|
|
||||||
export function buildContactRuleWhere(
|
export function buildContactRuleWhere(
|
||||||
rule: DataAccessRule,
|
rule: DataAccessRule,
|
||||||
ctx: { userId: string; teamPeerIds: string[] | null },
|
ctx: { userId: string; teamPeerIds: string[] | null },
|
||||||
): Prisma.PersonWhereInput | null {
|
): Prisma.PersonWhereInput | null {
|
||||||
const and: Prisma.PersonWhereInput[] = [];
|
const facets: Prisma.PersonWhereInput[] = [];
|
||||||
const ids = ownerIdList(rule, ctx);
|
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
if (!ids.length) return null;
|
const ids = ownerIdList(rule, ctx);
|
||||||
and.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } });
|
if (ids.length) {
|
||||||
}
|
facets.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } });
|
||||||
if (rule.groupIds?.length) {
|
}
|
||||||
and.push({ groupLinks: { some: { groupId: { in: rule.groupIds } } } });
|
|
||||||
}
|
}
|
||||||
|
// groupIds دیگر فیلتر دسترسی نیست؛ دید گروه فقط از مسئولگروه (personViaGroupAssignee)
|
||||||
if (rule.sources?.length) {
|
if (rule.sources?.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }],
|
OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (rule.moods?.length) {
|
if (rule.moods?.length) {
|
||||||
and.push({ mood: { in: rule.moods } });
|
facets.push({ mood: { in: rule.moods } });
|
||||||
}
|
}
|
||||||
if (!and.length) return null;
|
return unionFacets(facets);
|
||||||
return and.length === 1 ? and[0]! : { AND: and };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function orParts<T>(parts: T[]): T | { OR: T[] } | { id: string } {
|
function orParts<T>(parts: T[]): T | { OR: T[] } | { id: string } {
|
||||||
@@ -135,6 +139,23 @@ function orParts<T>(parts: T[]): T | { OR: T[] } | { id: string } {
|
|||||||
return parts.length === 1 ? parts[0]! : { OR: parts };
|
return parts.length === 1 ? parts[0]! : { OR: parts };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** اعضای گروههایی که کاربر مسئولشان است */
|
||||||
|
function personViaGroupAssignee(userId: string): Prisma.PersonWhereInput {
|
||||||
|
return {
|
||||||
|
groupLinks: {
|
||||||
|
some: { group: { assignees: { some: { id: userId } } } },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function companyViaGroupAssignee(userId: string): Prisma.CompanyWhereInput {
|
||||||
|
return {
|
||||||
|
groupLinks: {
|
||||||
|
some: { group: { assignees: { some: { id: userId } } } },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function customersPersonWhere(
|
export function customersPersonWhere(
|
||||||
actor: Pick<Actor, 'userId' | 'role' | 'customersAccess' | 'teamPeerIds'>,
|
actor: Pick<Actor, 'userId' | 'role' | 'customersAccess' | 'teamPeerIds'>,
|
||||||
): Prisma.PersonWhereInput {
|
): Prisma.PersonWhereInput {
|
||||||
@@ -149,6 +170,8 @@ export function customersPersonWhere(
|
|||||||
});
|
});
|
||||||
if (w) parts.push(w);
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
|
// مسئول گروه: اتحاد با محدودیت نقش (مالک خودم یا عضو گروه تحت مسئولیت)
|
||||||
|
parts.push(personViaGroupAssignee(actor.userId));
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,34 +183,28 @@ export function customersCompanyWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.CompanyWhereInput[] = [];
|
const parts: Prisma.CompanyWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.CompanyWhereInput[] = [];
|
// حال مشتری روی شرکت معنا ندارد؛ فقط مالک/منبع
|
||||||
|
if (rule.moods?.length && !rule.owners?.length && !rule.sources?.length) continue;
|
||||||
|
const facets: Prisma.CompanyWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } });
|
facets.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } });
|
||||||
}
|
}
|
||||||
if (rule.groupIds?.length) {
|
|
||||||
and.push({ groupLinks: { some: { groupId: { in: rule.groupIds } } } });
|
|
||||||
}
|
}
|
||||||
|
// groupIds دیگر فیلتر دسترسی نیست؛ دید گروه فقط از مسئولگروه (companyViaGroupAssignee)
|
||||||
if (rule.sources?.length) {
|
if (rule.sources?.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }],
|
OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (
|
const w = unionFacets(facets);
|
||||||
rule.moods?.length &&
|
if (w) parts.push(w);
|
||||||
!rule.owners?.length &&
|
|
||||||
!rule.groupIds?.length &&
|
|
||||||
!rule.sources?.length
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!and.length) continue;
|
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
|
||||||
}
|
}
|
||||||
|
parts.push(companyViaGroupAssignee(actor.userId));
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,27 +216,28 @@ export function leadsDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.LeadWhereInput[] = [];
|
const parts: Prisma.LeadWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.LeadWhereInput[] = [];
|
const facets: Prisma.LeadWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } });
|
facets.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (rule.stageIds?.length) {
|
if (rule.stageIds?.length) {
|
||||||
and.push({ stageId: { in: rule.stageIds } });
|
facets.push({ stageId: { in: rule.stageIds } });
|
||||||
}
|
}
|
||||||
if (rule.sources?.length) {
|
if (rule.sources?.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: rule.sources.map((s) => ({
|
OR: rule.sources.map((s) => ({
|
||||||
source: { equals: s, mode: 'insensitive' as const },
|
source: { equals: s, mode: 'insensitive' as const },
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
@@ -232,28 +250,29 @@ export function dealsDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.DealWhereInput[] = [];
|
const parts: Prisma.DealWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.DealWhereInput[] = [];
|
const facets: Prisma.DealWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [
|
OR: [
|
||||||
{ ownerId: { in: ids } },
|
{ ownerId: { in: ids } },
|
||||||
{ assignees: { some: { id: { in: ids } } } },
|
{ assignees: { some: { id: { in: ids } } } },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (rule.pipelineIds?.length) {
|
if (rule.pipelineIds?.length) {
|
||||||
and.push({ pipelineId: { in: rule.pipelineIds } });
|
facets.push({ pipelineId: { in: rule.pipelineIds } });
|
||||||
}
|
}
|
||||||
if (rule.stageIds?.length) {
|
if (rule.stageIds?.length) {
|
||||||
and.push({ stageId: { in: rule.stageIds } });
|
facets.push({ stageId: { in: rule.stageIds } });
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
@@ -266,32 +285,33 @@ export function activitiesDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.ActivityWhereInput[] = [];
|
const parts: Prisma.ActivityWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.ActivityWhereInput[] = [];
|
const facets: Prisma.ActivityWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [
|
OR: [
|
||||||
{ assigneeId: { in: ids } },
|
{ assigneeId: { in: ids } },
|
||||||
{ assignees: { some: { id: { in: ids } } } },
|
{ assignees: { some: { id: { in: ids } } } },
|
||||||
{ participantIds: { hasSome: ids } },
|
{ participantIds: { hasSome: ids } },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (rule.boardIds?.length) {
|
if (rule.boardIds?.length) {
|
||||||
and.push({ boardId: { in: rule.boardIds } });
|
facets.push({ boardId: { in: rule.boardIds } });
|
||||||
}
|
}
|
||||||
if (rule.stageIds?.length) {
|
if (rule.stageIds?.length) {
|
||||||
and.push({ stageId: { in: rule.stageIds } });
|
facets.push({ stageId: { in: rule.stageIds } });
|
||||||
}
|
}
|
||||||
if (rule.typeIds?.length) {
|
if (rule.typeIds?.length) {
|
||||||
and.push({ typeDefId: { in: rule.typeIds } });
|
facets.push({ typeDefId: { in: rule.typeIds } });
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
@@ -310,34 +330,35 @@ export function notesDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return personalGate;
|
if (!sectionHasDataAccessLimits(section)) return personalGate;
|
||||||
const parts: Prisma.NoteWhereInput[] = [];
|
const parts: Prisma.NoteWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.NoteWhereInput[] = [];
|
const facets: Prisma.NoteWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [
|
OR: [
|
||||||
{ authorId: { in: ids } },
|
{ authorId: { in: ids } },
|
||||||
{
|
{
|
||||||
deal: {
|
deal: {
|
||||||
OR: [
|
OR: [
|
||||||
{ ownerId: { in: ids } },
|
{ ownerId: { in: ids } },
|
||||||
{ assignees: { some: { id: { in: ids } } } },
|
{ assignees: { some: { id: { in: ids } } } },
|
||||||
],
|
],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{ person: { ownerId: { in: ids } } },
|
||||||
{ person: { ownerId: { in: ids } } },
|
{ company: { ownerId: { in: ids } } },
|
||||||
{ company: { ownerId: { in: ids } } },
|
],
|
||||||
],
|
});
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
if (rule.sources?.length) {
|
if (rule.sources?.length) {
|
||||||
and.push({ noteType: { in: rule.sources } });
|
facets.push({ noteType: { in: rule.sources } });
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
AND: [personalGate, orParts(parts)],
|
AND: [personalGate, orParts(parts)],
|
||||||
@@ -352,26 +373,27 @@ export function ticketsDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.TicketWhereInput[] = [];
|
const parts: Prisma.TicketWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.TicketWhereInput[] = [];
|
const facets: Prisma.TicketWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [{ assigneeId: { in: ids } }, { reporterId: { in: ids } }],
|
OR: [{ assigneeId: { in: ids } }, { reporterId: { in: ids } }],
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (rule.sources?.length) {
|
if (rule.sources?.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
status: {
|
status: {
|
||||||
in: rule.sources as Array<'open' | 'in_progress' | 'waiting' | 'resolved' | 'closed'>,
|
in: rule.sources as Array<'open' | 'in_progress' | 'waiting' | 'resolved' | 'closed'>,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
@@ -384,28 +406,29 @@ export function projectsDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.ProjectCardWhereInput[] = [];
|
const parts: Prisma.ProjectCardWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.ProjectCardWhereInput[] = [];
|
const facets: Prisma.ProjectCardWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push({
|
facets.push({
|
||||||
OR: [
|
OR: [
|
||||||
{ ownerId: { in: ids } },
|
{ ownerId: { in: ids } },
|
||||||
{ assignees: { some: { id: { in: ids } } } },
|
{ assignees: { some: { id: { in: ids } } } },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (rule.boardIds?.length) {
|
if (rule.boardIds?.length) {
|
||||||
and.push({ boardId: { in: rule.boardIds } });
|
facets.push({ boardId: { in: rule.boardIds } });
|
||||||
}
|
}
|
||||||
if (rule.stageIds?.length) {
|
if (rule.stageIds?.length) {
|
||||||
and.push({ stageId: { in: rule.stageIds } });
|
facets.push({ stageId: { in: rule.stageIds } });
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
@@ -418,20 +441,21 @@ export function routinesDeepWhere(
|
|||||||
if (!sectionHasDataAccessLimits(section)) return {};
|
if (!sectionHasDataAccessLimits(section)) return {};
|
||||||
const parts: Prisma.RoutineTaskWhereInput[] = [];
|
const parts: Prisma.RoutineTaskWhereInput[] = [];
|
||||||
for (const rule of section.rules ?? []) {
|
for (const rule of section.rules ?? []) {
|
||||||
const and: Prisma.RoutineTaskWhereInput[] = [];
|
const facets: Prisma.RoutineTaskWhereInput[] = [];
|
||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
const ids = ownerIdList(rule, {
|
const ids = ownerIdList(rule, {
|
||||||
userId: actor.userId,
|
userId: actor.userId,
|
||||||
teamPeerIds: actor.teamPeerIds ?? null,
|
teamPeerIds: actor.teamPeerIds ?? null,
|
||||||
});
|
});
|
||||||
if (!ids.length) continue;
|
if (ids.length) {
|
||||||
and.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } });
|
facets.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (rule.typeIds?.length) {
|
if (rule.typeIds?.length) {
|
||||||
and.push({ categoryId: { in: rule.typeIds } });
|
facets.push({ categoryId: { in: rule.typeIds } });
|
||||||
}
|
}
|
||||||
if (!and.length) continue;
|
const w = unionFacets(facets);
|
||||||
parts.push(and.length === 1 ? and[0]! : { AND: and });
|
if (w) parts.push(w);
|
||||||
}
|
}
|
||||||
return orParts(parts);
|
return orParts(parts);
|
||||||
}
|
}
|
||||||
@@ -449,9 +473,14 @@ export function sectionOwnerIdUnion(
|
|||||||
if (rule.owners?.length) {
|
if (rule.owners?.length) {
|
||||||
sawOwnerRule = true;
|
sawOwnerRule = true;
|
||||||
for (const id of ownerIdList(rule, ctx)) ids.add(id);
|
for (const id of ownerIdList(rule, ctx)) ids.add(id);
|
||||||
} else if (rule.groupIds?.length || rule.sources?.length || rule.moods?.length ||
|
} else if (
|
||||||
rule.stageIds?.length || rule.pipelineIds?.length || rule.boardIds?.length ||
|
rule.sources?.length ||
|
||||||
rule.typeIds?.length) {
|
rule.moods?.length ||
|
||||||
|
rule.stageIds?.length ||
|
||||||
|
rule.pipelineIds?.length ||
|
||||||
|
rule.boardIds?.length ||
|
||||||
|
rule.typeIds?.length
|
||||||
|
) {
|
||||||
sawNonOwnerRule = true;
|
sawNonOwnerRule = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type {
|
|||||||
SectionDataAccess,
|
SectionDataAccess,
|
||||||
UserRole,
|
UserRole,
|
||||||
} from '@mento/shared';
|
} 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 type { Prisma } from '@prisma/client';
|
||||||
import {
|
import {
|
||||||
activitiesDeepWhere,
|
activitiesDeepWhere,
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
notesDeepWhere,
|
notesDeepWhere,
|
||||||
projectsDeepWhere,
|
projectsDeepWhere,
|
||||||
routinesDeepWhere,
|
routinesDeepWhere,
|
||||||
|
sectionOwnerIdUnion,
|
||||||
ticketsDeepWhere,
|
ticketsDeepWhere,
|
||||||
} from './data-access';
|
} from './data-access';
|
||||||
|
|
||||||
@@ -60,6 +61,65 @@ export type Actor = {
|
|||||||
|
|
||||||
export type ScopedActor = Pick<Actor, 'userId' | 'role' | 'dataVisibility' | 'visibleUserIds' | 'scopes'>;
|
export type ScopedActor = Pick<Actor, 'userId' | 'role' | 'dataVisibility' | 'visibleUserIds' | 'scopes'>;
|
||||||
|
|
||||||
|
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 با سطح دید مخصوص یک بخش (اگر تنظیم شده باشد). */
|
/** Actor با سطح دید مخصوص یک بخش (اگر تنظیم شده باشد). */
|
||||||
export function forScope<T extends ScopedActor>(actor: T, scope: DataScope): T {
|
export function forScope<T extends ScopedActor>(actor: T, scope: DataScope): T {
|
||||||
const s = actor.scopes?.[scope];
|
const s = actor.scopes?.[scope];
|
||||||
@@ -109,9 +169,16 @@ export function scopedOwnerIds(
|
|||||||
|
|
||||||
/** فیلتر مالکیت؛ پیشفرض بخش «مشتریان» (Person / Company). برای فاکتور/پیشفاکتور scope=finance. */
|
/** فیلتر مالکیت؛ پیشفرض بخش «مشتریان» (Person / Company). برای فاکتور/پیشفاکتور scope=finance. */
|
||||||
export function ownerWhere(
|
export function ownerWhere(
|
||||||
actor: ScopedActor,
|
actor: DeepAccessActor,
|
||||||
scope: DataScope = 'contacts',
|
scope: DataScope = 'contacts',
|
||||||
): { ownerId: string } | { ownerId: { in: string[] } } | Record<string, never> {
|
): { ownerId: string } | { ownerId: { in: string[] } } | Record<string, never> {
|
||||||
|
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);
|
const ids = scopedOwnerIds(actor, scope);
|
||||||
if (!ids) return {};
|
if (!ids) return {};
|
||||||
if (ids.length === 1) return { ownerId: ids[0]! };
|
if (ids.length === 1) return { ownerId: ids[0]! };
|
||||||
@@ -153,11 +220,16 @@ export function projectCardAccessWhere(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** فعالیتها بر اساس مسئول اصلی یا مسئولان مشترک */
|
/** فعالیتها بر اساس مسئول اصلی یا مسئولان مشترک */
|
||||||
export function assigneeWhere(
|
export function assigneeWhere(actor: DeepAccessActor): Prisma.ActivityWhereInput {
|
||||||
actor: ScopedActor,
|
const deep = deepOwnerIds(actor, 'activities');
|
||||||
): Prisma.ActivityWhereInput {
|
const ids =
|
||||||
const ids = scopedOwnerIds(actor, 'activities');
|
deep.kind === 'open'
|
||||||
|
? null
|
||||||
|
: deep.kind === 'ids'
|
||||||
|
? deep.ids
|
||||||
|
: scopedOwnerIds(actor, 'activities');
|
||||||
if (!ids) return {};
|
if (!ids) return {};
|
||||||
|
if (!ids.length) return { assigneeId: '__no_access__' };
|
||||||
return {
|
return {
|
||||||
OR: [
|
OR: [
|
||||||
{ assigneeId: { in: ids } },
|
{ assigneeId: { in: ids } },
|
||||||
|
|||||||
@@ -21,15 +21,82 @@ function tehranJalaliLong(d: Date) {
|
|||||||
return `${toFaDigits(j.jd)} ${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`;
|
return `${toFaDigits(j.jd)} ${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** قالب بس/بد مثل UI تهحساب — برای توکنهای مانده در پیامک */
|
||||||
|
export function formatSmsBedBes(v: unknown, maximumFractionDigits = 3): string {
|
||||||
|
if (v == null) return '';
|
||||||
|
const s = String(v).trim();
|
||||||
|
if (!s || s === 'null' || s === 'undefined' || s === 'NaN') return '';
|
||||||
|
const n = Number(s.replace(/,/g, ''));
|
||||||
|
if (!Number.isFinite(n)) return toFaDigits(s);
|
||||||
|
const abs = toFaDigits(
|
||||||
|
new Intl.NumberFormat('en-US', { maximumFractionDigits }).format(Math.abs(n)),
|
||||||
|
);
|
||||||
|
if (n === 0) return abs;
|
||||||
|
return `${abs} ${n < 0 ? 'بد' : 'بس'}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const METAL_FIELD_LABELS: Record<string, string> = {
|
||||||
|
MandeyeVazni: 'طلا',
|
||||||
|
MandeyeVazniNoghre: 'نقره',
|
||||||
|
MandeyeKolBeTALA: 'کل به طلا',
|
||||||
|
MandeMenhayeSeke: 'منهای سکه',
|
||||||
|
};
|
||||||
|
|
||||||
|
function isMetalMandehKey(key: string) {
|
||||||
|
if (METAL_FIELD_LABELS[key]) return true;
|
||||||
|
if (key.startsWith('Seke_')) return true;
|
||||||
|
return /Vazni|طلا|نقره|فلز|Gold|Silver/i.test(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function metalFieldLabel(key: string) {
|
||||||
|
if (METAL_FIELD_LABELS[key]) return METAL_FIELD_LABELS[key]!;
|
||||||
|
if (key.startsWith('Seke_')) return `سکه ${key.slice(5)}`;
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** از فیلدهای مانده تهحساب، متن مانده ریالی و فلزی میسازد */
|
||||||
|
export function smsBalanceTexts(input: {
|
||||||
|
mandehFields?: Array<{ key: string; value: string | null }> | null;
|
||||||
|
rialBalance?: number | null;
|
||||||
|
goldBalance?: number | null;
|
||||||
|
}): { rialBalance: string; metalBalance: string } {
|
||||||
|
const fields = input.mandehFields ?? [];
|
||||||
|
const mali = fields.find((f) => f.key === 'MandeyeMali' || f.key === 'MandeyeKolBePool');
|
||||||
|
const rial =
|
||||||
|
formatSmsBedBes(mali?.value ?? input.rialBalance) ||
|
||||||
|
formatSmsBedBes(input.rialBalance);
|
||||||
|
const metalParts = fields
|
||||||
|
.filter((f) => isMetalMandehKey(f.key) && f.value != null && String(f.value).trim() !== '')
|
||||||
|
.map((f) => `${metalFieldLabel(f.key)} ${formatSmsBedBes(f.value)}`.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const metal =
|
||||||
|
metalParts.join('، ') ||
|
||||||
|
(input.goldBalance != null && formatSmsBedBes(input.goldBalance)
|
||||||
|
? `طلا ${formatSmsBedBes(input.goldBalance)}`
|
||||||
|
: '');
|
||||||
|
return { rialBalance: rial, metalBalance: metal };
|
||||||
|
}
|
||||||
|
|
||||||
export function renderSmsText(
|
export function renderSmsText(
|
||||||
text: string,
|
text: string,
|
||||||
vars: { name?: string; phone?: string; title?: string; company?: string },
|
vars: {
|
||||||
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
|
title?: string;
|
||||||
|
company?: string;
|
||||||
|
from?: string;
|
||||||
|
rialBalance?: string;
|
||||||
|
metalBalance?: string;
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
return applyMessageTemplate(text, {
|
return applyMessageTemplate(text, {
|
||||||
name: vars.name,
|
name: vars.name,
|
||||||
phone: vars.phone,
|
phone: vars.phone,
|
||||||
title: vars.title,
|
title: vars.title,
|
||||||
company: vars.company,
|
company: vars.company,
|
||||||
|
from: vars.from,
|
||||||
|
rialBalance: vars.rialBalance,
|
||||||
|
metalBalance: vars.metalBalance,
|
||||||
date: tehranJalaliLong(new Date()),
|
date: tehranJalaliLong(new Date()),
|
||||||
}).trim();
|
}).trim();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ export function selectMonthBirthdays(people: BirthdayRow[], now = new Date(), pr
|
|||||||
const upcoming = matched.filter((row) => row.day >= today.jd).sort(byDay);
|
const upcoming = matched.filter((row) => row.day >= today.jd).sort(byDay);
|
||||||
const passed = matched.filter((row) => row.day < today.jd).sort(byDay);
|
const passed = matched.filter((row) => row.day < today.jd).sort(byDay);
|
||||||
return {
|
return {
|
||||||
|
year: today.jy,
|
||||||
month: today.jm,
|
month: today.jm,
|
||||||
monthName: jalaliMonthName(today.jm),
|
monthName: jalaliMonthName(today.jm),
|
||||||
today: today.jd,
|
today: today.jd,
|
||||||
|
|||||||
@@ -112,9 +112,13 @@ export class CompaniesService {
|
|||||||
...(groupIds.length ? [{ groupLinks: { some: { groupId: { in: groupIds } } } }] : []),
|
...(groupIds.length ? [{ groupLinks: { some: { groupId: { in: groupIds } } } }] : []),
|
||||||
];
|
];
|
||||||
const where: Prisma.CompanyWhereInput = {
|
const where: Prisma.CompanyWhereInput = {
|
||||||
organizationId: actor.organizationId,
|
AND: [
|
||||||
...customersCompanyWhere(actor),
|
{
|
||||||
...(and.length ? { AND: and } : {}),
|
organizationId: actor.organizationId,
|
||||||
|
...customersCompanyWhere(actor),
|
||||||
|
},
|
||||||
|
...and,
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const [rows, total] = await this.prisma.$transaction([
|
const [rows, total] = await this.prisma.$transaction([
|
||||||
@@ -165,6 +169,7 @@ export class CompaniesService {
|
|||||||
fromTahesab: Boolean(g.tahesabGid),
|
fromTahesab: Boolean(g.tahesabGid),
|
||||||
personCount: 0,
|
personCount: 0,
|
||||||
companyCount: countMap.get(g.id) ?? 0,
|
companyCount: countMap.get(g.id) ?? 0,
|
||||||
|
assignees: [],
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { LoyaltyModule } from '../loyalty/loyalty.module';
|
|||||||
import { AutomationsModule } from '../automations/automations.module';
|
import { AutomationsModule } from '../automations/automations.module';
|
||||||
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
|
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
|
||||||
import { PublicApiModule } from '../public-api/public-api.module';
|
import { PublicApiModule } from '../public-api/public-api.module';
|
||||||
|
import { NotificationsModule } from '../notifications/notifications.module';
|
||||||
import { CompaniesController } from './companies.controller';
|
import { CompaniesController } from './companies.controller';
|
||||||
import { CompaniesService } from './companies.service';
|
import { CompaniesService } from './companies.service';
|
||||||
import { PeopleController } from './people.controller';
|
import { PeopleController } from './people.controller';
|
||||||
@@ -20,6 +21,7 @@ import { CustomerGroupsModule } from '../customer-groups/customer-groups.module'
|
|||||||
PublicApiModule,
|
PublicApiModule,
|
||||||
BehaviorModule,
|
BehaviorModule,
|
||||||
CustomerGroupsModule,
|
CustomerGroupsModule,
|
||||||
|
NotificationsModule,
|
||||||
],
|
],
|
||||||
controllers: [PeopleController, CompaniesController],
|
controllers: [PeopleController, CompaniesController],
|
||||||
providers: [PeopleService, CompaniesService, ContactsExcelService, SameMobileMergeService],
|
providers: [PeopleService, CompaniesService, ContactsExcelService, SameMobileMergeService],
|
||||||
|
|||||||
@@ -23,6 +23,11 @@ export class BirthdaySmsDto {
|
|||||||
@MinLength(1)
|
@MinLength(1)
|
||||||
@MaxLength(500)
|
@MaxLength(500)
|
||||||
text!: string;
|
text!: string;
|
||||||
|
|
||||||
|
/** تأیید ارسال مجدد وقتی قبلاً مسئول دیگری تبریک فرستاده */
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
force?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BulkDeletePeopleDto {
|
export class BulkDeletePeopleDto {
|
||||||
@@ -95,6 +100,12 @@ export class ListQueryDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
@MaxLength(2000)
|
@MaxLength(2000)
|
||||||
groupId?: string;
|
groupId?: string;
|
||||||
|
|
||||||
|
/** فیلتر سابقه فعالیت؛ چندتایی با کاما */
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(400)
|
||||||
|
activityExperience?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
class CompanyExtraFieldsDto {
|
class CompanyExtraFieldsDto {
|
||||||
@@ -355,6 +366,11 @@ export class CreatePersonDto {
|
|||||||
@MaxLength(120)
|
@MaxLength(120)
|
||||||
referrer?: string;
|
referrer?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(80)
|
||||||
|
activityExperience?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
@@ -481,6 +497,11 @@ export class UpdatePersonDto {
|
|||||||
@MaxLength(120)
|
@MaxLength(120)
|
||||||
referrer?: string;
|
referrer?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(80)
|
||||||
|
activityExperience?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ export class PeopleController {
|
|||||||
hasMobile,
|
hasMobile,
|
||||||
disc: query.disc,
|
disc: query.disc,
|
||||||
groupId: query.groupId,
|
groupId: query.groupId,
|
||||||
|
activityExperience: query.activityExperience,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -81,6 +82,7 @@ export class PeopleController {
|
|||||||
hasMobile,
|
hasMobile,
|
||||||
disc: query.disc,
|
disc: query.disc,
|
||||||
groupId: query.groupId,
|
groupId: query.groupId,
|
||||||
|
activityExperience: query.activityExperience,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,6 +141,7 @@ export class PeopleController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get('birthdays')
|
@Get('birthdays')
|
||||||
|
@RequirePermission('customers', { reads: true })
|
||||||
birthdays(@CurrentUser() user: Actor) {
|
birthdays(@CurrentUser() user: Actor) {
|
||||||
return this.peopleService.birthdaysThisMonth(user);
|
return this.peopleService.birthdaysThisMonth(user);
|
||||||
}
|
}
|
||||||
@@ -171,7 +174,7 @@ export class PeopleController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() dto: BirthdaySmsDto,
|
@Body() dto: BirthdaySmsDto,
|
||||||
) {
|
) {
|
||||||
return this.peopleService.sendBirthdaySms(user, id, dto.text);
|
return this.peopleService.sendBirthdaySms(user, id, dto.text, Boolean(dto.force));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ import {
|
|||||||
FILTERED_IDS_MAX,
|
FILTERED_IDS_MAX,
|
||||||
PERSON_MOODS,
|
PERSON_MOODS,
|
||||||
applyPersonGenderTitle,
|
applyPersonGenderTitle,
|
||||||
|
canViewAllRecords,
|
||||||
|
extractActivityExperienceFromNotes,
|
||||||
|
normalizeActivityExperience,
|
||||||
splitPersonHonorific,
|
splitPersonHonorific,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
@@ -48,13 +51,15 @@ import {
|
|||||||
import { actorCanAssignToOthers, assertAssigneeSet } from '../common/assign-access';
|
import { actorCanAssignToOthers, assertAssigneeSet } from '../common/assign-access';
|
||||||
import { LoyaltyService } from '../loyalty/loyalty.service';
|
import { LoyaltyService } from '../loyalty/loyalty.service';
|
||||||
import { AutomationsService } from '../automations/automations.service';
|
import { AutomationsService } from '../automations/automations.service';
|
||||||
|
import { NotificationsService } from '../notifications/notifications.service';
|
||||||
import { MessageAutomationsService } from '../message-automations/message-automations.service';
|
import { MessageAutomationsService } from '../message-automations/message-automations.service';
|
||||||
import { WebhooksService } from '../public-api/webhooks.service';
|
import { WebhooksService } from '../public-api/webhooks.service';
|
||||||
import { GamificationService } from '../gamification/gamification.service';
|
import { GamificationService } from '../gamification/gamification.service';
|
||||||
import { parseBirthDate } from '../common/excel';
|
import { parseBirthDate } from '../common/excel';
|
||||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||||
import { selectMonthBirthdays } from './birthday-month';
|
import { selectMonthBirthdays } from './birthday-month';
|
||||||
import { renderSmsText } from '../common/sms-text';
|
import { renderSmsText, smsBalanceTexts } from '../common/sms-text';
|
||||||
|
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
|
||||||
import { normalizeTags } from '../common/tags';
|
import { normalizeTags } from '../common/tags';
|
||||||
import { buildSearchWhere, ci, splitCsv } from '../common/search';
|
import { buildSearchWhere, ci, splitCsv } from '../common/search';
|
||||||
import {
|
import {
|
||||||
@@ -99,6 +104,7 @@ type PersonRow = {
|
|||||||
instagram: string | null;
|
instagram: string | null;
|
||||||
birthDate: Date | null;
|
birthDate: Date | null;
|
||||||
referrer: string | null;
|
referrer: string | null;
|
||||||
|
activityExperience: string | null;
|
||||||
addresses: unknown;
|
addresses: unknown;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
mood: PersonMood;
|
mood: PersonMood;
|
||||||
@@ -157,6 +163,7 @@ export class PeopleService implements OnModuleInit {
|
|||||||
private readonly outboundSms: OutboundSmsLogService,
|
private readonly outboundSms: OutboundSmsLogService,
|
||||||
private readonly behaviorAccess: BehaviorAccessService,
|
private readonly behaviorAccess: BehaviorAccessService,
|
||||||
private readonly groups: CustomerGroupsService,
|
private readonly groups: CustomerGroupsService,
|
||||||
|
private readonly notifications: NotificationsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private personListWhere(
|
private personListWhere(
|
||||||
@@ -170,6 +177,7 @@ export class PeopleService implements OnModuleInit {
|
|||||||
hasMobile?: boolean;
|
hasMobile?: boolean;
|
||||||
disc?: string;
|
disc?: string;
|
||||||
groupId?: string;
|
groupId?: string;
|
||||||
|
activityExperience?: string;
|
||||||
},
|
},
|
||||||
): Prisma.PersonWhereInput {
|
): Prisma.PersonWhereInput {
|
||||||
const sources = [...new Set(splitCsv(opts?.importSource).map(normalizePersonImportSource))];
|
const sources = [...new Set(splitCsv(opts?.importSource).map(normalizePersonImportSource))];
|
||||||
@@ -177,6 +185,13 @@ export class PeopleService implements OnModuleInit {
|
|||||||
(PERSON_MOODS as readonly string[]).includes(m),
|
(PERSON_MOODS as readonly string[]).includes(m),
|
||||||
);
|
);
|
||||||
const groupIds = splitCsv(opts?.groupId);
|
const groupIds = splitCsv(opts?.groupId);
|
||||||
|
const experiences = [
|
||||||
|
...new Set(
|
||||||
|
splitCsv(opts?.activityExperience)
|
||||||
|
.map((v) => normalizeActivityExperience(v) ?? v)
|
||||||
|
.filter(Boolean),
|
||||||
|
),
|
||||||
|
];
|
||||||
const search = buildSearchWhere<Prisma.PersonWhereInput>(q, (t) => [
|
const search = buildSearchWhere<Prisma.PersonWhereInput>(q, (t) => [
|
||||||
{ firstName: ci(t) },
|
{ firstName: ci(t) },
|
||||||
{ lastName: ci(t) },
|
{ lastName: ci(t) },
|
||||||
@@ -216,13 +231,30 @@ export class PeopleService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
const disc = discFilter(opts?.disc);
|
const disc = discFilter(opts?.disc);
|
||||||
if (disc) and.push(disc);
|
if (disc) and.push(disc);
|
||||||
if (groupIds.length) and.push({ groupLinks: { some: { groupId: { in: groupIds } } } });
|
// گروه / منبع / حال: اتحاد (هر بُعد کافی است)؛ داخل هر بُعد چند مقدار با in = OR
|
||||||
|
const facets: Prisma.PersonWhereInput[] = [];
|
||||||
|
if (groupIds.length) {
|
||||||
|
facets.push({ groupLinks: { some: { groupId: { in: groupIds } } } });
|
||||||
|
}
|
||||||
|
if (moods.length) {
|
||||||
|
facets.push({ mood: { in: moods } });
|
||||||
|
}
|
||||||
|
if (sources.length) {
|
||||||
|
facets.push({ importSource: { in: sources } });
|
||||||
|
}
|
||||||
|
if (experiences.length) {
|
||||||
|
facets.push({ activityExperience: { in: experiences } });
|
||||||
|
}
|
||||||
|
if (facets.length === 1) and.push(facets[0]!);
|
||||||
|
else if (facets.length > 1) and.push({ OR: facets });
|
||||||
return {
|
return {
|
||||||
organizationId: actor.organizationId,
|
AND: [
|
||||||
...customersPersonWhere(actor),
|
{
|
||||||
...(moods.length ? { mood: { in: moods } } : {}),
|
organizationId: actor.organizationId,
|
||||||
...(sources.length ? { importSource: { in: sources } } : {}),
|
...customersPersonWhere(actor),
|
||||||
...(and.length ? { AND: and } : {}),
|
},
|
||||||
|
...and,
|
||||||
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,6 +272,7 @@ export class PeopleService implements OnModuleInit {
|
|||||||
hasMobile?: boolean;
|
hasMobile?: boolean;
|
||||||
disc?: string;
|
disc?: string;
|
||||||
groupId?: string;
|
groupId?: string;
|
||||||
|
activityExperience?: string;
|
||||||
},
|
},
|
||||||
): Promise<PaginatedResponse<PersonDto>> {
|
): Promise<PaginatedResponse<PersonDto>> {
|
||||||
const seeDisc = await this.behaviorAccess.canView(actor);
|
const seeDisc = await this.behaviorAccess.canView(actor);
|
||||||
@@ -278,6 +311,7 @@ export class PeopleService implements OnModuleInit {
|
|||||||
hasMobile?: boolean;
|
hasMobile?: boolean;
|
||||||
disc?: string;
|
disc?: string;
|
||||||
groupId?: string;
|
groupId?: string;
|
||||||
|
activityExperience?: string;
|
||||||
},
|
},
|
||||||
max = FILTERED_IDS_MAX,
|
max = FILTERED_IDS_MAX,
|
||||||
): Promise<FilteredIdsResponse> {
|
): Promise<FilteredIdsResponse> {
|
||||||
@@ -345,11 +379,44 @@ export class PeopleService implements OnModuleInit {
|
|||||||
fromTahesab: Boolean(g.tahesabGid),
|
fromTahesab: Boolean(g.tahesabGid),
|
||||||
personCount: countMap.get(g.id) ?? 0,
|
personCount: countMap.get(g.id) ?? 0,
|
||||||
companyCount: 0,
|
companyCount: 0,
|
||||||
|
assignees: [],
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
onModuleInit() {
|
onModuleInit() {
|
||||||
void this.backfillStoredBirthDates();
|
void this.backfillStoredBirthDates();
|
||||||
|
void this.backfillActivityExperienceFromNotes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** سابقه فعالیت قدیمی که فقط در یادداشت بود، روی ستون مشتری مینشیند. */
|
||||||
|
async backfillActivityExperienceFromNotes() {
|
||||||
|
try {
|
||||||
|
const rows = await this.prisma.person.findMany({
|
||||||
|
where: {
|
||||||
|
activityExperience: null,
|
||||||
|
notes: { contains: 'سابقه' },
|
||||||
|
},
|
||||||
|
select: { id: true, notes: true },
|
||||||
|
take: 20000,
|
||||||
|
});
|
||||||
|
let filled = 0;
|
||||||
|
for (const row of rows) {
|
||||||
|
const value = extractActivityExperienceFromNotes(row.notes);
|
||||||
|
if (!value) continue;
|
||||||
|
const updated = await this.prisma.person.updateMany({
|
||||||
|
where: { id: row.id, activityExperience: null },
|
||||||
|
data: { activityExperience: value },
|
||||||
|
});
|
||||||
|
filled += updated.count;
|
||||||
|
}
|
||||||
|
if (filled) {
|
||||||
|
this.logger.log(`سابقه فعالیت ${filled} مشتری از یادداشت پر شد`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`پر کردن سابقه فعالیت مشتریان ناموفق بود: ${err instanceof Error ? err.message : err}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** تاریخ تولدی که قبلاً در فیلد اضافی دیدار/اکسل یا پروفایل مونتیفای مانده، روی شخص مینشیند. */
|
/** تاریخ تولدی که قبلاً در فیلد اضافی دیدار/اکسل یا پروفایل مونتیفای مانده، روی شخص مینشیند. */
|
||||||
@@ -456,6 +523,9 @@ export class PeopleService implements OnModuleInit {
|
|||||||
instagram: emptyToNull(dto.instagram),
|
instagram: emptyToNull(dto.instagram),
|
||||||
birthDate: parseBirthDate(dto.birthDate),
|
birthDate: parseBirthDate(dto.birthDate),
|
||||||
referrer: emptyToNull(dto.referrer),
|
referrer: emptyToNull(dto.referrer),
|
||||||
|
activityExperience:
|
||||||
|
normalizeActivityExperience(dto.activityExperience) ??
|
||||||
|
emptyToNull(dto.activityExperience),
|
||||||
addresses: toJsonAddresses(dto.addresses),
|
addresses: toJsonAddresses(dto.addresses),
|
||||||
notes: emptyToNull(dto.notes),
|
notes: emptyToNull(dto.notes),
|
||||||
mood: dto.mood ?? 'newcomer',
|
mood: dto.mood ?? 'newcomer',
|
||||||
@@ -568,6 +638,11 @@ export class PeopleService implements OnModuleInit {
|
|||||||
if ('instagram' in dto) data.instagram = emptyToNull(dto.instagram);
|
if ('instagram' in dto) data.instagram = emptyToNull(dto.instagram);
|
||||||
if ('birthDate' in dto) data.birthDate = parseBirthDate(dto.birthDate);
|
if ('birthDate' in dto) data.birthDate = parseBirthDate(dto.birthDate);
|
||||||
if ('referrer' in dto) data.referrer = emptyToNull(dto.referrer);
|
if ('referrer' in dto) data.referrer = emptyToNull(dto.referrer);
|
||||||
|
if ('activityExperience' in dto) {
|
||||||
|
data.activityExperience =
|
||||||
|
normalizeActivityExperience(dto.activityExperience) ??
|
||||||
|
emptyToNull(dto.activityExperience);
|
||||||
|
}
|
||||||
if ('addresses' in dto) data.addresses = toJsonAddresses(dto.addresses);
|
if ('addresses' in dto) data.addresses = toJsonAddresses(dto.addresses);
|
||||||
if ('notes' in dto) data.notes = emptyToNull(dto.notes);
|
if ('notes' in dto) data.notes = emptyToNull(dto.notes);
|
||||||
if (dto.mood !== undefined) data.mood = dto.mood;
|
if (dto.mood !== undefined) data.mood = dto.mood;
|
||||||
@@ -680,8 +755,8 @@ export class PeopleService implements OnModuleInit {
|
|||||||
const rows = await this.prisma.person.findMany({
|
const rows = await this.prisma.person.findMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
ownerId: actor.userId,
|
|
||||||
birthDate: { not: null },
|
birthDate: { not: null },
|
||||||
|
...customersPersonWhere(actor),
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@@ -728,27 +803,50 @@ export class PeopleService implements OnModuleInit {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendBirthdaySms(actor: Actor, personId: string, text: string) {
|
async sendBirthdaySms(actor: Actor, personId: string, text: string, force = false) {
|
||||||
const body = text.trim();
|
const body = text.trim();
|
||||||
if (!body || body.length > 500) {
|
if (!body || body.length > 500) {
|
||||||
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
|
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
|
||||||
}
|
}
|
||||||
const person = await this.prisma.person.findFirst({
|
const person = await this.prisma.person.findFirst({
|
||||||
where: { id: personId, organizationId: actor.organizationId },
|
where: {
|
||||||
|
id: personId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
...customersPersonWhere(actor),
|
||||||
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
firstName: true,
|
firstName: true,
|
||||||
lastName: true,
|
lastName: true,
|
||||||
mobile: true,
|
mobile: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
|
position: true,
|
||||||
ownerId: true,
|
ownerId: true,
|
||||||
birthDate: true,
|
birthDate: true,
|
||||||
company: { select: { name: true } },
|
company: { select: { name: true } },
|
||||||
|
groupLinks: {
|
||||||
|
select: {
|
||||||
|
group: {
|
||||||
|
select: {
|
||||||
|
assignees: { select: { id: true, fullName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!person) throw new NotFoundException('مشتری پیدا نشد');
|
if (!person) throw new NotFoundException('مشتری پیدا نشد');
|
||||||
if (person.ownerId !== actor.userId) {
|
const assigneeIds = new Set(
|
||||||
throw new ForbiddenException('فقط مسئول این مشتری میتواند پیامک تبریک بفرستد.');
|
person.groupLinks.flatMap((link) => link.group.assignees.map((a) => a.id)),
|
||||||
|
);
|
||||||
|
const canSend =
|
||||||
|
canViewAllRecords(actor.role) ||
|
||||||
|
person.ownerId === actor.userId ||
|
||||||
|
assigneeIds.has(actor.userId);
|
||||||
|
if (!canSend) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'فقط مالک مشتری یا مسئول گروه او میتواند پیامک تبریک بفرستد.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!person.birthDate) {
|
if (!person.birthDate) {
|
||||||
throw new BadRequestException('برای این مشتری تاریخ تولد ثبت نشده است.');
|
throw new BadRequestException('برای این مشتری تاریخ تولد ثبت نشده است.');
|
||||||
@@ -770,12 +868,110 @@ export class PeopleService implements OnModuleInit {
|
|||||||
const mobile = person.mobile || person.phone;
|
const mobile = person.mobile || person.phone;
|
||||||
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
|
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
|
||||||
const fullName = `${person.firstName} ${person.lastName}`.trim();
|
const fullName = `${person.firstName} ${person.lastName}`.trim();
|
||||||
const message = renderSmsText(body, {
|
const birthdayKey = `birthday:${inMonth.year}-${inMonth.month}`;
|
||||||
name: fullName,
|
if (!force) {
|
||||||
|
const prior = await this.prisma.outboundSmsLog.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
personId: person.id,
|
||||||
|
status: 'sent',
|
||||||
|
sourceId: birthdayKey,
|
||||||
|
NOT: { actorUserId: actor.userId },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
select: { actorUserId: true },
|
||||||
|
});
|
||||||
|
if (prior) {
|
||||||
|
const priorUser = prior.actorUserId
|
||||||
|
? await this.prisma.user.findFirst({
|
||||||
|
where: { id: prior.actorUserId },
|
||||||
|
select: { fullName: true },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
const who = priorUser?.fullName?.trim() || 'مسئول دیگری';
|
||||||
|
throw new ConflictException(
|
||||||
|
`${who} قبلاً پیامک تبریک این مشتری را فرستاده است. آیا میخواهید دوباره بفرستید؟`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const message = renderSmsText(
|
||||||
|
body,
|
||||||
|
await this.personSmsVars(actor.organizationId, person.id, {
|
||||||
|
name: fullName,
|
||||||
|
phone: mobile,
|
||||||
|
title: person.position?.trim() || '',
|
||||||
|
company: person.company?.name ?? '',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
||||||
|
const result = await this.sms.send({
|
||||||
|
organizationId: actor.organizationId,
|
||||||
phone: mobile,
|
phone: mobile,
|
||||||
title: fullName,
|
text: message,
|
||||||
company: person.company?.name ?? '',
|
source: 'manual',
|
||||||
});
|
});
|
||||||
|
await this.outboundSms.record({
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
personId: person.id,
|
||||||
|
mobile,
|
||||||
|
body: message,
|
||||||
|
source: 'manual',
|
||||||
|
sourceId: birthdayKey,
|
||||||
|
status: result.ok ? 'sent' : 'failed',
|
||||||
|
error: result.ok ? null : result.reason,
|
||||||
|
actorUserId: actor.userId,
|
||||||
|
});
|
||||||
|
if (!result.ok) {
|
||||||
|
throw new ServiceUnavailableException(
|
||||||
|
result.blocked
|
||||||
|
? 'ارسال پیامک بهخاطر محدودیت اعتبار مسدود است.'
|
||||||
|
: result.reason === 'SMS not configured'
|
||||||
|
? 'ارسال پیامک روی سرور فعال نیست.'
|
||||||
|
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const senderName = (
|
||||||
|
await this.prisma.user.findFirst({
|
||||||
|
where: { id: actor.userId },
|
||||||
|
select: { fullName: true },
|
||||||
|
})
|
||||||
|
)?.fullName?.trim() || 'یکی از مسئولان';
|
||||||
|
const peers = [...assigneeIds].filter((id) => id !== actor.userId);
|
||||||
|
await Promise.all(
|
||||||
|
peers.map((userId) =>
|
||||||
|
this.notifications.create({
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
userId,
|
||||||
|
type: 'birthday_sms_sent',
|
||||||
|
title: 'پیامک تبریک تولد ارسال شد',
|
||||||
|
body: `${senderName} برای «${fullName}» پیامک تبریک فرستاد. اگر لازم است میتوانید دوباره بفرستید.`,
|
||||||
|
link: `/contacts/people/${person.id}`,
|
||||||
|
entityType: 'person',
|
||||||
|
entityId: person.id,
|
||||||
|
dedupe: false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendSms(actor: Actor, personId: string, text: string) {
|
||||||
|
const body = text.trim();
|
||||||
|
if (!body || body.length > 500) {
|
||||||
|
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
|
||||||
|
}
|
||||||
|
const person = await this.get(actor, personId);
|
||||||
|
const mobile = person.mobile || person.phone;
|
||||||
|
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
|
||||||
|
const message = renderSmsText(
|
||||||
|
body,
|
||||||
|
await this.personSmsVars(actor.organizationId, person.id, {
|
||||||
|
name: person.fullName,
|
||||||
|
phone: mobile,
|
||||||
|
title: person.position?.trim() || '',
|
||||||
|
company: person.company?.name ?? '',
|
||||||
|
}),
|
||||||
|
);
|
||||||
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
||||||
const result = await this.sms.send({
|
const result = await this.sms.send({
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
@@ -805,47 +1001,50 @@ export class PeopleService implements OnModuleInit {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendSms(actor: Actor, personId: string, text: string) {
|
/** نام سازمان + ماندههای کششدهٔ تهحساب برای توکنهای پیامک */
|
||||||
const body = text.trim();
|
private async personSmsVars(
|
||||||
if (!body || body.length > 500) {
|
organizationId: string,
|
||||||
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
|
personId: string,
|
||||||
|
base: {
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
title: string;
|
||||||
|
company: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const [org, link] = await Promise.all([
|
||||||
|
this.prisma.organization.findUnique({
|
||||||
|
where: { id: organizationId },
|
||||||
|
select: { name: true },
|
||||||
|
}),
|
||||||
|
this.prisma.personAccountingLink.findFirst({
|
||||||
|
where: { personId, connection: { organizationId } },
|
||||||
|
orderBy: [
|
||||||
|
{ connection: { isDefault: 'desc' } },
|
||||||
|
{ linkedAt: 'desc' },
|
||||||
|
],
|
||||||
|
include: { balanceCache: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
let rialBalance = '';
|
||||||
|
let metalBalance = '';
|
||||||
|
const cache = link?.balanceCache;
|
||||||
|
if (cache) {
|
||||||
|
const rawView = extractMandehRaw(cache.rawResponse);
|
||||||
|
const bal = smsBalanceTexts({
|
||||||
|
mandehFields: rawView.fields,
|
||||||
|
rialBalance: cache.rialBalance,
|
||||||
|
goldBalance: cache.goldBalance,
|
||||||
|
});
|
||||||
|
rialBalance = bal.rialBalance;
|
||||||
|
metalBalance = bal.metalBalance;
|
||||||
}
|
}
|
||||||
const person = await this.get(actor, personId);
|
return {
|
||||||
const mobile = person.mobile || person.phone;
|
...base,
|
||||||
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
|
from: org?.name?.trim() || '',
|
||||||
const message = renderSmsText(body, {
|
rialBalance,
|
||||||
name: person.fullName,
|
metalBalance,
|
||||||
phone: mobile,
|
};
|
||||||
title: person.fullName,
|
|
||||||
company: person.company?.name ?? '',
|
|
||||||
});
|
|
||||||
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
|
||||||
const result = await this.sms.send({
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
phone: mobile,
|
|
||||||
text: message,
|
|
||||||
source: 'manual',
|
|
||||||
});
|
|
||||||
await this.outboundSms.record({
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
personId: person.id,
|
|
||||||
mobile,
|
|
||||||
body: message,
|
|
||||||
source: 'manual',
|
|
||||||
status: result.ok ? 'sent' : 'failed',
|
|
||||||
error: result.ok ? null : result.reason,
|
|
||||||
actorUserId: actor.userId,
|
|
||||||
});
|
|
||||||
if (!result.ok) {
|
|
||||||
throw new ServiceUnavailableException(
|
|
||||||
result.blocked
|
|
||||||
? 'ارسال پیامک بهخاطر محدودیت اعتبار مسدود است.'
|
|
||||||
: result.reason === 'SMS not configured'
|
|
||||||
? 'ارسال پیامک روی سرور فعال نیست.'
|
|
||||||
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return { ok: true };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
listSmsHistory(actor: Actor, personId: string, limit?: number) {
|
listSmsHistory(actor: Actor, personId: string, limit?: number) {
|
||||||
@@ -879,6 +1078,9 @@ export class PeopleService implements OnModuleInit {
|
|||||||
instagram: row.instagram,
|
instagram: row.instagram,
|
||||||
birthDate: row.birthDate?.toISOString() ?? null,
|
birthDate: row.birthDate?.toISOString() ?? null,
|
||||||
referrer: row.referrer,
|
referrer: row.referrer,
|
||||||
|
activityExperience:
|
||||||
|
row.activityExperience ||
|
||||||
|
extractActivityExperienceFromNotes(row.notes),
|
||||||
addresses: (() => {
|
addresses: (() => {
|
||||||
const fromCol = asAddresses(row.addresses);
|
const fromCol = asAddresses(row.addresses);
|
||||||
if (fromCol.length) return fromCol;
|
if (fromCol.length) return fromCol;
|
||||||
|
|||||||
@@ -8,7 +8,14 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { IsIn, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsIn,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
import { CUSTOMER_GROUP_COLORS, type CustomerGroupColor } from '@mento/shared';
|
import { CUSTOMER_GROUP_COLORS, type CustomerGroupColor } from '@mento/shared';
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
import { RolesGuard } from '../auth/roles.guard';
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
@@ -26,6 +33,11 @@ class CreateCustomerGroupDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn([...CUSTOMER_GROUP_COLORS])
|
@IsIn([...CUSTOMER_GROUP_COLORS])
|
||||||
color?: CustomerGroupColor;
|
color?: CustomerGroupColor;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
assigneeIds?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
class UpdateCustomerGroupDto {
|
class UpdateCustomerGroupDto {
|
||||||
@@ -43,6 +55,11 @@ class UpdateCustomerGroupDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
parentId?: string | null;
|
parentId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
assigneeIds?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@Controller('customer-groups')
|
@Controller('customer-groups')
|
||||||
|
|||||||
@@ -51,26 +51,21 @@ export class CustomerGroupsService {
|
|||||||
include: {
|
include: {
|
||||||
_count: { select: { people: true, companies: true } },
|
_count: { select: { people: true, companies: true } },
|
||||||
parent: { select: { name: true } },
|
parent: { select: { name: true } },
|
||||||
|
assignees: { select: { id: true, fullName: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return rows.map((r) => ({
|
return rows.map((r) => this.toDto(r));
|
||||||
id: r.id,
|
|
||||||
name: r.name,
|
|
||||||
color: r.color,
|
|
||||||
position: r.position,
|
|
||||||
fromTahesab: Boolean(r.tahesabGid),
|
|
||||||
personCount: r._count.people,
|
|
||||||
companyCount: r._count.companies,
|
|
||||||
parentId: r.parentId,
|
|
||||||
parentName: r.parent?.name ?? null,
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(
|
async create(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
dto: { name: string; color?: CustomerGroupColor },
|
dto: { name: string; color?: CustomerGroupColor; assigneeIds?: string[] },
|
||||||
): Promise<CustomerGroupDto> {
|
): Promise<CustomerGroupDto> {
|
||||||
const name = this.cleanName(dto.name);
|
const name = this.cleanName(dto.name);
|
||||||
|
const assigneeIds =
|
||||||
|
dto.assigneeIds !== undefined
|
||||||
|
? await this.validAssigneeIds(organizationId, dto.assigneeIds)
|
||||||
|
: [];
|
||||||
const max = await this.prisma.customerGroup.aggregate({
|
const max = await this.prisma.customerGroup.aggregate({
|
||||||
where: { organizationId },
|
where: { organizationId },
|
||||||
_max: { position: true },
|
_max: { position: true },
|
||||||
@@ -82,6 +77,10 @@ export class CustomerGroupsService {
|
|||||||
name,
|
name,
|
||||||
color: this.cleanColor(dto.color),
|
color: this.cleanColor(dto.color),
|
||||||
position: (max._max.position ?? -1) + 1,
|
position: (max._max.position ?? -1) + 1,
|
||||||
|
assigneeIds,
|
||||||
|
...(assigneeIds.length
|
||||||
|
? { assignees: { connect: assigneeIds.map((id) => ({ id })) } }
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -93,7 +92,12 @@ export class CustomerGroupsService {
|
|||||||
async update(
|
async update(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
id: string,
|
id: string,
|
||||||
dto: { name?: string; color?: CustomerGroupColor; parentId?: string | null },
|
dto: {
|
||||||
|
name?: string;
|
||||||
|
color?: CustomerGroupColor;
|
||||||
|
parentId?: string | null;
|
||||||
|
assigneeIds?: string[];
|
||||||
|
},
|
||||||
): Promise<CustomerGroupDto> {
|
): Promise<CustomerGroupDto> {
|
||||||
await this.require(organizationId, id);
|
await this.require(organizationId, id);
|
||||||
const parentId =
|
const parentId =
|
||||||
@@ -101,6 +105,10 @@ export class CustomerGroupsService {
|
|||||||
if (parentId !== undefined) {
|
if (parentId !== undefined) {
|
||||||
await this.assertParent(organizationId, id, parentId);
|
await this.assertParent(organizationId, id, parentId);
|
||||||
}
|
}
|
||||||
|
const assigneeIds =
|
||||||
|
dto.assigneeIds !== undefined
|
||||||
|
? await this.validAssigneeIds(organizationId, dto.assigneeIds)
|
||||||
|
: undefined;
|
||||||
try {
|
try {
|
||||||
await this.prisma.customerGroup.update({
|
await this.prisma.customerGroup.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
@@ -108,6 +116,12 @@ export class CustomerGroupsService {
|
|||||||
...(dto.name != null ? { name: this.cleanName(dto.name) } : {}),
|
...(dto.name != null ? { name: this.cleanName(dto.name) } : {}),
|
||||||
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
|
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
|
||||||
...(parentId !== undefined ? { parentId } : {}),
|
...(parentId !== undefined ? { parentId } : {}),
|
||||||
|
...(assigneeIds !== undefined
|
||||||
|
? {
|
||||||
|
assigneeIds,
|
||||||
|
assignees: { set: assigneeIds.map((uid) => ({ id: uid })) },
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -317,6 +331,57 @@ export class CustomerGroupsService {
|
|||||||
return link?.group.name ?? null;
|
return link?.group.name ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private toDto(r: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
color: string;
|
||||||
|
position: number;
|
||||||
|
tahesabGid: string | null;
|
||||||
|
parentId: string | null;
|
||||||
|
parent?: { name: string } | null;
|
||||||
|
_count: { people: number; companies: number };
|
||||||
|
assigneeIds: string[];
|
||||||
|
assignees: Array<{ id: string; fullName: string }>;
|
||||||
|
}): CustomerGroupDto {
|
||||||
|
const order = new Map(r.assigneeIds.map((id, index) => [id, index]));
|
||||||
|
const assignees = [...r.assignees].sort((a, b) => {
|
||||||
|
const ai = order.get(a.id) ?? Number.MAX_SAFE_INTEGER;
|
||||||
|
const bi = order.get(b.id) ?? Number.MAX_SAFE_INTEGER;
|
||||||
|
return ai - bi || a.fullName.localeCompare(b.fullName, 'fa');
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: r.id,
|
||||||
|
name: r.name,
|
||||||
|
color: r.color,
|
||||||
|
position: r.position,
|
||||||
|
fromTahesab: Boolean(r.tahesabGid),
|
||||||
|
personCount: r._count.people,
|
||||||
|
companyCount: r._count.companies,
|
||||||
|
parentId: r.parentId,
|
||||||
|
parentName: r.parent?.name ?? null,
|
||||||
|
assigneeIds: assignees.map((a) => a.id),
|
||||||
|
assignees: assignees.map((a) => ({ id: a.id, fullName: a.fullName })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async validAssigneeIds(organizationId: string, ids: string[]): Promise<string[]> {
|
||||||
|
const unique = [...new Set((ids ?? []).map((id) => id?.trim()).filter(Boolean))];
|
||||||
|
if (!unique.length) return [];
|
||||||
|
const rows = await this.prisma.user.findMany({
|
||||||
|
where: {
|
||||||
|
id: { in: unique },
|
||||||
|
isActive: true,
|
||||||
|
memberships: { some: { organizationId, isActive: true } },
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (rows.length !== unique.length) {
|
||||||
|
throw new BadRequestException('یکی از مسئولان انتخابشده معتبر نیست');
|
||||||
|
}
|
||||||
|
const found = new Set(rows.map((r) => r.id));
|
||||||
|
return unique.filter((id) => found.has(id));
|
||||||
|
}
|
||||||
|
|
||||||
private async require(organizationId: string, id: string) {
|
private async require(organizationId: string, id: string) {
|
||||||
const row = await this.prisma.customerGroup.findFirst({
|
const row = await this.prisma.customerGroup.findFirst({
|
||||||
where: { id, organizationId },
|
where: { id, organizationId },
|
||||||
|
|||||||
@@ -1,4 +1,11 @@
|
|||||||
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
|
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
|
||||||
|
import {
|
||||||
|
pickAddress,
|
||||||
|
pickCity,
|
||||||
|
pickNationalId,
|
||||||
|
pickRasteh,
|
||||||
|
tahesabProfilePatch,
|
||||||
|
} from '../moshtari-profile';
|
||||||
import {
|
import {
|
||||||
assertFactorCode,
|
assertFactorCode,
|
||||||
buildFactorCode,
|
buildFactorCode,
|
||||||
@@ -116,12 +123,52 @@ function testSanadBuilders() {
|
|||||||
assert(bank[12] === fc, 'bank factor index');
|
assert(bank[12] === fc, 'bank factor index');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function testMoshtariProfile() {
|
||||||
|
const row = {
|
||||||
|
CodeMelli: '00112312311',
|
||||||
|
Address: 'خیابان ولیعصر',
|
||||||
|
City: 'تهران',
|
||||||
|
Rasteh: 2,
|
||||||
|
BDate: null,
|
||||||
|
};
|
||||||
|
assert(pickNationalId(row) === '00112312311', 'national id');
|
||||||
|
assert(pickAddress(row) === 'خیابان ولیعصر', 'address');
|
||||||
|
assert(pickCity(row) === 'تهران', 'city');
|
||||||
|
assert(pickRasteh(row) === 2, 'rasteh');
|
||||||
|
assert(pickNationalId({ CodeMelli: '-1' }) == null, 'skip -1 national');
|
||||||
|
|
||||||
|
const patch = tahesabProfilePatch(row, {
|
||||||
|
birthDate: null,
|
||||||
|
addresses: [],
|
||||||
|
customFields: { keep: true },
|
||||||
|
});
|
||||||
|
assert(Array.isArray(patch.addresses) && patch.addresses[0] === 'خیابان ولیعصر، تهران', 'addr+city');
|
||||||
|
const fields = patch.customFields as Record<string, unknown>;
|
||||||
|
assert(fields.nationalId === '00112312311', 'cf national');
|
||||||
|
assert(fields.city === 'تهران', 'cf city');
|
||||||
|
assert(fields.rasteh === 2, 'cf rasteh');
|
||||||
|
assert(fields.keep === true, 'cf merge');
|
||||||
|
|
||||||
|
const emptyKeep = tahesabProfilePatch(
|
||||||
|
{ CodeMelli: '', Address: '', City: '', Rasteh: '' },
|
||||||
|
{
|
||||||
|
birthDate: new Date('2000-01-01'),
|
||||||
|
addresses: ['قدیمی'],
|
||||||
|
customFields: { nationalId: '111' },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert(emptyKeep.addresses == null, 'empty does not wipe address');
|
||||||
|
assert(emptyKeep.customFields == null, 'empty does not wipe custom');
|
||||||
|
assert(emptyKeep.birthDate == null, 'existing birth kept');
|
||||||
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
testCryptoRoundtrip();
|
testCryptoRoundtrip();
|
||||||
testFactorCode();
|
testFactorCode();
|
||||||
testMobile();
|
testMobile();
|
||||||
testMandehNormalize();
|
testMandehNormalize();
|
||||||
testSanadBuilders();
|
testSanadBuilders();
|
||||||
|
testMoshtariProfile();
|
||||||
console.log('tahesab unit checks: OK');
|
console.log('tahesab unit checks: OK');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -205,6 +205,12 @@ export class SyncGroupsPageDto {
|
|||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** اجرای دستی همگامسازی همهٔ مشتریان (وارد + بهروز کردن لینکشدهها) */
|
||||||
|
export class SyncAllCustomersDto {
|
||||||
|
@IsString()
|
||||||
|
connectionId!: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class ExportPeopleToTahesabDto {
|
export class ExportPeopleToTahesabDto {
|
||||||
@IsString()
|
@IsString()
|
||||||
connectionId!: string;
|
connectionId!: string;
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { parseBirthDate } from '../../common/excel';
|
||||||
|
|
||||||
|
export function pickBirthDate(row: Record<string, unknown>): Date | null {
|
||||||
|
const raw =
|
||||||
|
row.BDate ??
|
||||||
|
row.bDate ??
|
||||||
|
row.Tarikh_Tavalod ??
|
||||||
|
row.tarikh_tavalod ??
|
||||||
|
row.BirthDate;
|
||||||
|
if (raw == null) return null;
|
||||||
|
return parseBirthDate(String(raw));
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimStr(raw: unknown): string | null {
|
||||||
|
if (raw == null) return null;
|
||||||
|
const s = String(raw).trim();
|
||||||
|
if (!s || s === '-1') return null;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** کد ملی از پاسخ لیست مشتری تهحساب */
|
||||||
|
export function pickNationalId(row: Record<string, unknown>): string | null {
|
||||||
|
return (
|
||||||
|
trimStr(row.CodeMelli) ??
|
||||||
|
trimStr(row.CodeMeli) ??
|
||||||
|
trimStr(row.codeMeli) ??
|
||||||
|
trimStr(row.NationalId) ??
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pickAddress(row: Record<string, unknown>): string | null {
|
||||||
|
return trimStr(row.Address) ?? trimStr(row.address) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pickCity(row: Record<string, unknown>): string | null {
|
||||||
|
return trimStr(row.City) ?? trimStr(row.city) ?? trimStr(row.Shahr) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** رسته حساب در تهحساب (عدد یا رشته) */
|
||||||
|
export function pickRasteh(row: Record<string, unknown>): string | number | null {
|
||||||
|
const raw = row.Rasteh ?? row.rasteh ?? row.Raste;
|
||||||
|
if (raw == null || raw === '') return null;
|
||||||
|
if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
|
||||||
|
const s = String(raw).trim();
|
||||||
|
if (!s || s === '-1') return null;
|
||||||
|
const n = Number(s);
|
||||||
|
return Number.isFinite(n) && String(n) === s ? n : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asCustomFieldRecord(raw: unknown): Record<string, unknown> {
|
||||||
|
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||||
|
return { ...(raw as Record<string, unknown>) };
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function asAddressList(raw: unknown): string[] {
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
return raw
|
||||||
|
.map((a) => (typeof a === 'string' ? a.trim() : ''))
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* فیلدهای پروفایل قابلدریافت از DoListMoshtari را روی شخص مینشاند.
|
||||||
|
* مقدار خالی تهحساب، دادهٔ موجود CRM را پاک نمیکند.
|
||||||
|
*/
|
||||||
|
export function tahesabProfilePatch(
|
||||||
|
row: Record<string, unknown>,
|
||||||
|
existing: {
|
||||||
|
birthDate: Date | null;
|
||||||
|
addresses: unknown;
|
||||||
|
customFields: unknown;
|
||||||
|
},
|
||||||
|
): Prisma.PersonUpdateInput {
|
||||||
|
const data: Prisma.PersonUpdateInput = {};
|
||||||
|
const birthDate = pickBirthDate(row);
|
||||||
|
if (!existing.birthDate && birthDate) data.birthDate = birthDate;
|
||||||
|
|
||||||
|
const address = pickAddress(row);
|
||||||
|
const city = pickCity(row);
|
||||||
|
if (address) {
|
||||||
|
const line = city ? `${address}، ${city}` : address;
|
||||||
|
data.addresses = [line] as Prisma.InputJsonValue;
|
||||||
|
} else if (city && asAddressList(existing.addresses).length === 0) {
|
||||||
|
data.addresses = [city] as Prisma.InputJsonValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fields = asCustomFieldRecord(existing.customFields);
|
||||||
|
let fieldsChanged = false;
|
||||||
|
const nationalId = pickNationalId(row);
|
||||||
|
if (nationalId) {
|
||||||
|
fields.nationalId = nationalId;
|
||||||
|
fieldsChanged = true;
|
||||||
|
}
|
||||||
|
if (city) {
|
||||||
|
fields.city = city;
|
||||||
|
fieldsChanged = true;
|
||||||
|
}
|
||||||
|
if (address) {
|
||||||
|
fields.address = address;
|
||||||
|
fieldsChanged = true;
|
||||||
|
}
|
||||||
|
const rasteh = pickRasteh(row);
|
||||||
|
if (rasteh != null) {
|
||||||
|
fields.rasteh = rasteh;
|
||||||
|
fieldsChanged = true;
|
||||||
|
}
|
||||||
|
if (fieldsChanged) data.customFields = fields as Prisma.InputJsonValue;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@@ -26,8 +26,9 @@ import {
|
|||||||
SearchTahesabDto,
|
SearchTahesabDto,
|
||||||
SyncGroupsPageDto,
|
SyncGroupsPageDto,
|
||||||
} from './dto';
|
} from './dto';
|
||||||
import { formatJalaliDate, parseBirthDate } from '../../common/excel';
|
import { formatJalaliDate } from '../../common/excel';
|
||||||
import { CustomerGroupsService } from '../../customer-groups/customer-groups.service';
|
import { CustomerGroupsService } from '../../customer-groups/customer-groups.service';
|
||||||
|
import { pickBirthDate, tahesabProfilePatch } from './moshtari-profile';
|
||||||
import { normalizeIranMobile, SanadBuilders, type TahesabApi } from './tahesab-methods';
|
import { normalizeIranMobile, SanadBuilders, type TahesabApi } from './tahesab-methods';
|
||||||
|
|
||||||
/** موبایل تهحساب را به شکل 0912… ذخیره میکند، حتی اگر قبلاً 912… یا +98912… بوده باشد. */
|
/** موبایل تهحساب را به شکل 0912… ذخیره میکند، حتی اگر قبلاً 912… یا +98912… بوده باشد. */
|
||||||
@@ -83,17 +84,6 @@ function pickTel(row: Record<string, unknown>): string {
|
|||||||
return String(row.Tel ?? row.Phone ?? row.Mobile ?? row.tel ?? '');
|
return String(row.Tel ?? row.Phone ?? row.Mobile ?? row.tel ?? '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickBirthDate(row: Record<string, unknown>): Date | null {
|
|
||||||
const raw =
|
|
||||||
row.BDate ??
|
|
||||||
row.bDate ??
|
|
||||||
row.Tarikh_Tavalod ??
|
|
||||||
row.tarikh_tavalod ??
|
|
||||||
row.BirthDate;
|
|
||||||
if (raw == null) return null;
|
|
||||||
return parseBirthDate(String(raw));
|
|
||||||
}
|
|
||||||
|
|
||||||
function firstAddress(raw: unknown): string | undefined {
|
function firstAddress(raw: unknown): string | undefined {
|
||||||
if (!Array.isArray(raw)) return undefined;
|
if (!Array.isArray(raw)) return undefined;
|
||||||
const first = raw.find((a) => typeof a === 'string' && a.trim());
|
const first = raw.find((a) => typeof a === 'string' && a.trim());
|
||||||
@@ -438,6 +428,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) {
|
async search(organizationId: string, dto: SearchTahesabDto) {
|
||||||
const { api } = await this.connections.getApi(
|
const { api } = await this.connections.getApi(
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -516,7 +577,7 @@ export class TahesabPersonLinkService {
|
|||||||
});
|
});
|
||||||
const byCode = new Map(existing.map((e) => [e.moshtariCode, e]));
|
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;
|
const link = row.moshtariCode != null ? byCode.get(row.moshtariCode) : undefined;
|
||||||
return {
|
return {
|
||||||
...row,
|
...row,
|
||||||
@@ -527,6 +588,22 @@ export class TahesabPersonLinkService {
|
|||||||
: null,
|
: 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({
|
await this.prisma.accountingSyncJob.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -601,7 +678,6 @@ export class TahesabPersonLinkService {
|
|||||||
const sourceRef = String(dto.moshtariCode);
|
const sourceRef = String(dto.moshtariCode);
|
||||||
|
|
||||||
let personId = dto.personId;
|
let personId = dto.personId;
|
||||||
let preserveExistingLink = false;
|
|
||||||
if (personId) {
|
if (personId) {
|
||||||
const existing = await this.getPerson(organizationId, personId);
|
const existing = await this.getPerson(organizationId, personId);
|
||||||
const prevFirst = existing.firstName;
|
const prevFirst = existing.firstName;
|
||||||
@@ -624,14 +700,14 @@ export class TahesabPersonLinkService {
|
|||||||
...carryPreviousSource(existing, 'tahesab'),
|
...carryPreviousSource(existing, 'tahesab'),
|
||||||
importSource: 'tahesab',
|
importSource: 'tahesab',
|
||||||
sourceRef,
|
sourceRef,
|
||||||
...(!existing.birthDate && pickBirthDate(row) ? { birthDate: pickBirthDate(row) } : {}),
|
|
||||||
...canonicalMobileUpdate(mobile, existing),
|
...canonicalMobileUpdate(mobile, existing),
|
||||||
|
...tahesabProfilePatch(row, existing),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// اگر موبایل تکراری است → همان شخص؛ نام قبلی حفظ و نام تهحساب جایگزین.
|
// اگر موبایل تکراری است → همان شخص؛ نام قبلی حفظ و نام تهحساب جایگزین.
|
||||||
// اگر همان شخص قبلاً به کد دیگری از این اتصال لینک شده، لینک جابهجا نمیشود
|
// اگر همان شخص قبلاً به کد دیگری از این اتصال لینک شده، نام و لینک دست نمیخورند
|
||||||
// تا کد قبلی دوباره «واردنشده» نشود و مشتری تکراری ساخته نشود.
|
// تا کد قبلی جابهجا نشود و این کد هم مشتری تکراری نسازد.
|
||||||
const mobileKeys = phoneIdentityKeys(mobile);
|
const mobileKeys = phoneIdentityKeys(mobile);
|
||||||
const matches = mobileKeys.length
|
const matches = mobileKeys.length
|
||||||
? await this.prisma.person.findMany({
|
? await this.prisma.person.findMany({
|
||||||
@@ -651,7 +727,22 @@ export class TahesabPersonLinkService {
|
|||||||
const byMobile = matches.find((person) => person.importSource === 'tahesab') ?? matches[0] ?? null;
|
const byMobile = matches.find((person) => person.importSource === 'tahesab') ?? matches[0] ?? null;
|
||||||
if (byMobile) {
|
if (byMobile) {
|
||||||
const linkedCode = byMobile.accountingLinks[0]?.moshtariCode;
|
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 =
|
const nameChanged =
|
||||||
`${byMobile.firstName} ${byMobile.lastName}`.trim() !==
|
`${byMobile.firstName} ${byMobile.lastName}`.trim() !==
|
||||||
`${firstName} ${lastName}`.trim();
|
`${firstName} ${lastName}`.trim();
|
||||||
@@ -670,13 +761,18 @@ export class TahesabPersonLinkService {
|
|||||||
: {}),
|
: {}),
|
||||||
...carryPreviousSource(byMobile, 'tahesab'),
|
...carryPreviousSource(byMobile, 'tahesab'),
|
||||||
importSource: 'tahesab',
|
importSource: 'tahesab',
|
||||||
sourceRef: preserveExistingLink ? String(linkedCode) : sourceRef,
|
sourceRef,
|
||||||
...(!byMobile.birthDate && pickBirthDate(row) ? { birthDate: pickBirthDate(row) } : {}),
|
|
||||||
...canonicalMobileUpdate(mobile, byMobile),
|
...canonicalMobileUpdate(mobile, byMobile),
|
||||||
|
...tahesabProfilePatch(row, byMobile),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
personId = byMobile.id;
|
personId = byMobile.id;
|
||||||
} else {
|
} else {
|
||||||
|
const profile = tahesabProfilePatch(row, {
|
||||||
|
birthDate: null,
|
||||||
|
addresses: [],
|
||||||
|
customFields: {},
|
||||||
|
});
|
||||||
const created = await this.prisma.person.create({
|
const created = await this.prisma.person.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -689,39 +785,15 @@ export class TahesabPersonLinkService {
|
|||||||
notes: `واردشده از تهحساب (کد ${dto.moshtariCode})`,
|
notes: `واردشده از تهحساب (کد ${dto.moshtariCode})`,
|
||||||
importSource: 'tahesab',
|
importSource: 'tahesab',
|
||||||
sourceRef,
|
sourceRef,
|
||||||
birthDate: pickBirthDate(row),
|
birthDate: (profile.birthDate as Date | undefined) ?? null,
|
||||||
|
addresses: (profile.addresses as Prisma.InputJsonValue) ?? [],
|
||||||
|
customFields: (profile.customFields as Prisma.InputJsonValue) ?? {},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
personId = created.id;
|
personId = created.id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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({
|
const link = await this.prisma.personAccountingLink.upsert({
|
||||||
where: {
|
where: {
|
||||||
personId_connectionId: {
|
personId_connectionId: {
|
||||||
@@ -762,7 +834,7 @@ export class TahesabPersonLinkService {
|
|||||||
return { personId, link: this.linkDto(link) };
|
return { personId, link: this.linkDto(link) };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** نام، موبایل و گروه مشتریِ از قبل لینکشده را با ردیف تهحساب تازه میکند. */
|
/** پروفایل و گروه مشتریِ از قبل لینکشده را با ردیف تهحساب تازه میکند. */
|
||||||
private async refreshLinkedCustomer(
|
private async refreshLinkedCustomer(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
connectionId: string,
|
connectionId: string,
|
||||||
@@ -803,10 +875,8 @@ export class TahesabPersonLinkService {
|
|||||||
...carryPreviousSource(existing, 'tahesab'),
|
...carryPreviousSource(existing, 'tahesab'),
|
||||||
importSource: 'tahesab',
|
importSource: 'tahesab',
|
||||||
sourceRef: String(moshtariCode),
|
sourceRef: String(moshtariCode),
|
||||||
...(!existing.birthDate && pickBirthDate(row)
|
|
||||||
? { birthDate: pickBirthDate(row) }
|
|
||||||
: {}),
|
|
||||||
...canonicalMobileUpdate(storedPhoneNumber(pickTel(row)), existing),
|
...canonicalMobileUpdate(storedPhoneNumber(pickTel(row)), existing),
|
||||||
|
...tahesabProfilePatch(row, existing),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
await this.applyTahesabGroup(organizationId, connectionId, personId, row);
|
await this.applyTahesabGroup(organizationId, connectionId, personId, row);
|
||||||
@@ -822,6 +892,7 @@ export class TahesabPersonLinkService {
|
|||||||
let emptyStreak = 0;
|
let emptyStreak = 0;
|
||||||
let imported = 0;
|
let imported = 0;
|
||||||
let updated = 0;
|
let updated = 0;
|
||||||
|
let duplicate = 0;
|
||||||
let failed = 0;
|
let failed = 0;
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
const maxPages = 300;
|
const maxPages = 300;
|
||||||
@@ -869,13 +940,14 @@ export class TahesabPersonLinkService {
|
|||||||
);
|
);
|
||||||
updated += 1;
|
updated += 1;
|
||||||
} else {
|
} else {
|
||||||
await this.importFromTahesab(
|
const created = await this.importFromTahesab(
|
||||||
organizationId,
|
organizationId,
|
||||||
{ connectionId, moshtariCode: code },
|
{ connectionId, moshtariCode: code },
|
||||||
{ api, row },
|
{ api, row },
|
||||||
{ skipJob: true },
|
{ skipJob: true },
|
||||||
);
|
);
|
||||||
imported += 1;
|
if (created.duplicateOf) duplicate += 1;
|
||||||
|
else imported += 1;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
failed += 1;
|
failed += 1;
|
||||||
@@ -891,23 +963,38 @@ export class TahesabPersonLinkService {
|
|||||||
errors.push('فهرست مشتریان از سقف خواندن خودکار بیشتر بود.');
|
errors.push('فهرست مشتریان از سقف خواندن خودکار بیشتر بود.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const summary = `${imported} وارد شد، ${updated} بهروز شد، ${failed} خطا`;
|
const summary = [
|
||||||
|
`${imported} وارد شد`,
|
||||||
|
`${updated} بهروز شد`,
|
||||||
|
...(duplicate ? [`${duplicate} شماره تکراری`] : []),
|
||||||
|
`${failed} خطا`,
|
||||||
|
].join('، ');
|
||||||
|
const error = errors.length ? errors.join('؛ ') : null;
|
||||||
await this.prisma.accountingSyncJob.create({
|
await this.prisma.accountingSyncJob.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId,
|
organizationId,
|
||||||
connectionId,
|
connectionId,
|
||||||
kind: 'customer-sync',
|
kind: 'customer-sync',
|
||||||
status: !imported && !updated && (failed > 0 || errors.length > 0) ? 'error' : 'success',
|
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,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.prisma.accountingConnection.update({
|
||||||
|
where: { id: connectionId },
|
||||||
|
data: {
|
||||||
|
customerSyncLastRunAt: new Date(),
|
||||||
|
customerSyncLastSummary: summary,
|
||||||
|
customerSyncLastError: error,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
this.logger.log(`همگامسازی مشتریان تهحساب ${connectionId}: ${summary}`);
|
this.logger.log(`همگامسازی مشتریان تهحساب ${connectionId}: ${summary}`);
|
||||||
return {
|
return {
|
||||||
imported,
|
imported,
|
||||||
updated,
|
updated,
|
||||||
|
duplicate,
|
||||||
failed,
|
failed,
|
||||||
summary,
|
summary,
|
||||||
error: errors.length ? errors.join('؛ ') : null,
|
error,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1003,19 +1090,16 @@ export class TahesabPersonLinkService {
|
|||||||
try {
|
try {
|
||||||
const linkedPersonId = linkedByCode.get(moshtariCode);
|
const linkedPersonId = linkedByCode.get(moshtariCode);
|
||||||
if (linkedPersonId) {
|
if (linkedPersonId) {
|
||||||
const birthDate = pickBirthDate(rowsByCode.get(moshtariCode) ?? {});
|
const row = rowsByCode.get(moshtariCode);
|
||||||
if (birthDate) {
|
if (row) {
|
||||||
await this.prisma.person.updateMany({
|
await this.refreshLinkedCustomer(
|
||||||
where: { id: linkedPersonId, birthDate: null },
|
organizationId,
|
||||||
data: { birthDate },
|
dto.connectionId,
|
||||||
});
|
linkedPersonId,
|
||||||
|
moshtariCode,
|
||||||
|
row,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
await this.applyTahesabGroup(
|
|
||||||
organizationId,
|
|
||||||
dto.connectionId,
|
|
||||||
linkedPersonId,
|
|
||||||
rowsByCode.get(moshtariCode),
|
|
||||||
);
|
|
||||||
items.push({
|
items.push({
|
||||||
moshtariCode,
|
moshtariCode,
|
||||||
ok: true,
|
ok: true,
|
||||||
@@ -1029,6 +1113,16 @@ export class TahesabPersonLinkService {
|
|||||||
{ connectionId: dto.connectionId, moshtariCode },
|
{ connectionId: dto.connectionId, moshtariCode },
|
||||||
bulkApi ? { api: bulkApi, row: rowsByCode.get(moshtariCode) } : undefined,
|
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 });
|
items.push({ moshtariCode, ok: true, personId: r.personId });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const message =
|
const message =
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import {
|
|||||||
SearchTahesabDto,
|
SearchTahesabDto,
|
||||||
SearchTahesabProductsDto,
|
SearchTahesabProductsDto,
|
||||||
SyncAsnadReportDto,
|
SyncAsnadReportDto,
|
||||||
|
SyncAllCustomersDto,
|
||||||
SyncGroupsPageDto,
|
SyncGroupsPageDto,
|
||||||
UpdateTahesabConnectionDto,
|
UpdateTahesabConnectionDto,
|
||||||
UpdateTahesabInvoiceSettingsDto,
|
UpdateTahesabInvoiceSettingsDto,
|
||||||
@@ -237,6 +238,16 @@ export class TahesabController {
|
|||||||
return this.links.syncGroupsPage(user.organizationId, dto);
|
return this.links.syncGroupsPage(user.organizationId, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** همهٔ مشتریان تهحساب: تازهها وارد، لینکشدهها (نام/موبایل/کدملی/آدرس/شهر/رسته/گروه) بهروز */
|
||||||
|
@Post('sync/customers-now')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
syncCustomersNow(
|
||||||
|
@CurrentUser() user: { organizationId: string },
|
||||||
|
@Body() dto: SyncAllCustomersDto,
|
||||||
|
) {
|
||||||
|
return this.links.syncAllCustomers(user.organizationId, dto.connectionId);
|
||||||
|
}
|
||||||
|
|
||||||
@Get('sync/unlinked-people')
|
@Get('sync/unlinked-people')
|
||||||
@Roles('owner', 'admin')
|
@Roles('owner', 'admin')
|
||||||
unlinkedPeople(
|
unlinkedPeople(
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ import { Cron } from '@nestjs/schedule';
|
|||||||
import { AiService } from '../../ai/ai.service';
|
import { AiService } from '../../ai/ai.service';
|
||||||
import { NotesService } from '../../notes/notes.service';
|
import { NotesService } from '../../notes/notes.service';
|
||||||
import { PrismaService } from '../../prisma/prisma.service';
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { VoipConnectionsService } from './connections.service';
|
||||||
|
import { DaftaresomaClient } from './daftareshoma-client';
|
||||||
|
import { parseDaftaresomaRecordingRef } from './daftareshoma-webhook';
|
||||||
import { SttClientService } from './stt-client.service';
|
import { SttClientService } from './stt-client.service';
|
||||||
|
|
||||||
const MAX_ATTEMPTS = 3;
|
const MAX_ATTEMPTS = 3;
|
||||||
@@ -17,6 +20,8 @@ export class CallSummaryService {
|
|||||||
private readonly stt: SttClientService,
|
private readonly stt: SttClientService,
|
||||||
private readonly ai: AiService,
|
private readonly ai: AiService,
|
||||||
private readonly notes: NotesService,
|
private readonly notes: NotesService,
|
||||||
|
private readonly connections: VoipConnectionsService,
|
||||||
|
private readonly daftareshoma: DaftaresomaClient,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Cron('*/1 * * * *')
|
@Cron('*/1 * * * *')
|
||||||
@@ -74,7 +79,31 @@ export class CallSummaryService {
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
transcript = await this.stt.downloadAndTranscribe(row.recordingUrl);
|
const daftId = parseDaftaresomaRecordingRef(row.recordingUrl);
|
||||||
|
if (daftId) {
|
||||||
|
const conn = await this.prisma.voipConnection.findFirst({
|
||||||
|
where: { id: row.connectionId },
|
||||||
|
});
|
||||||
|
const token = conn
|
||||||
|
? await this.connections.decryptApiToken(conn)
|
||||||
|
: null;
|
||||||
|
if (!token) {
|
||||||
|
await this.markFailed(
|
||||||
|
id,
|
||||||
|
row.summaryAttempts,
|
||||||
|
'توکن API دفتر شما برای دانلود ضبط موجود نیست',
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const audio = await this.daftareshoma.downloadRecording(
|
||||||
|
token,
|
||||||
|
daftId,
|
||||||
|
);
|
||||||
|
transcript = await this.stt.transcribeAudio(audio);
|
||||||
|
} else {
|
||||||
|
transcript = await this.stt.downloadAndTranscribe(row.recordingUrl);
|
||||||
|
}
|
||||||
await this.prisma.voipCallLog.update({
|
await this.prisma.voipCallLog.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { transcript },
|
data: { transcript },
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ import { PrismaService } from '../../prisma/prisma.service';
|
|||||||
import { NotificationsService } from '../../notifications/notifications.service';
|
import { NotificationsService } from '../../notifications/notifications.service';
|
||||||
import { iranMobileLookupKeys, normalizePhone } from '../../contacts/normalize';
|
import { iranMobileLookupKeys, normalizePhone } from '../../contacts/normalize';
|
||||||
import { VoipConnectionsService } from './connections.service';
|
import { VoipConnectionsService } from './connections.service';
|
||||||
|
import { DaftaresomaClient } from './daftareshoma-client';
|
||||||
|
import {
|
||||||
|
daftareshomaRecordingRef,
|
||||||
|
parseDaftaresomaRecordingRef,
|
||||||
|
} from './daftareshoma-webhook';
|
||||||
|
|
||||||
function digitsOnly(value: string | null | undefined): string {
|
function digitsOnly(value: string | null | undefined): string {
|
||||||
return (value ?? '').replace(/\D/g, '');
|
return (value ?? '').replace(/\D/g, '');
|
||||||
@@ -57,19 +62,32 @@ export class VoipCallsService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly connections: VoipConnectionsService,
|
private readonly connections: VoipConnectionsService,
|
||||||
private readonly notifications: NotificationsService,
|
private readonly notifications: NotificationsService,
|
||||||
|
private readonly daftareshoma: DaftaresomaClient,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async listRecent(
|
async listRecent(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
connectionId?: string,
|
opts?: {
|
||||||
|
connectionId?: string;
|
||||||
|
direction?: string;
|
||||||
|
status?: string;
|
||||||
|
lineExtension?: string;
|
||||||
|
},
|
||||||
): Promise<VoipCallLogDto[]> {
|
): Promise<VoipCallLogDto[]> {
|
||||||
const rows = await this.prisma.voipCallLog.findMany({
|
const rows = await this.prisma.voipCallLog.findMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId,
|
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' },
|
orderBy: { syncedAt: 'desc' },
|
||||||
take: 50,
|
take: 100,
|
||||||
});
|
});
|
||||||
const personIds = rows
|
const personIds = rows
|
||||||
.map((r) => r.personId)
|
.map((r) => r.personId)
|
||||||
@@ -91,6 +109,7 @@ export class VoipCallsService {
|
|||||||
status: r.status,
|
status: r.status,
|
||||||
fromNumber: r.fromNumber,
|
fromNumber: r.fromNumber,
|
||||||
toNumber: r.toNumber,
|
toNumber: r.toNumber,
|
||||||
|
lineExtension: r.lineExtension ?? null,
|
||||||
personId: r.personId,
|
personId: r.personId,
|
||||||
personName: r.personId ? (nameById.get(r.personId) ?? null) : null,
|
personName: r.personId ? (nameById.get(r.personId) ?? null) : null,
|
||||||
activityId: r.activityId,
|
activityId: r.activityId,
|
||||||
@@ -127,6 +146,9 @@ export class VoipCallsService {
|
|||||||
const toDigits = digitsOnly(event.to ?? event.callee);
|
const toDigits = digitsOnly(event.to ?? event.callee);
|
||||||
const fromNumber = fromNormalized || fromDigits || null;
|
const fromNumber = fromNormalized || fromDigits || null;
|
||||||
const toNumber = toNormalized || toDigits || 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 matchNumber = direction === 'inbound' ? fromNumber : toNumber;
|
||||||
const personId = await this.findPersonId(
|
const personId = await this.findPersonId(
|
||||||
conn.organizationId,
|
conn.organizationId,
|
||||||
@@ -193,6 +215,7 @@ export class VoipCallsService {
|
|||||||
status,
|
status,
|
||||||
fromNumber,
|
fromNumber,
|
||||||
toNumber,
|
toNumber,
|
||||||
|
lineExtension: lineExtension ?? existing.lineExtension,
|
||||||
personId: personId ?? existing.personId,
|
personId: personId ?? existing.personId,
|
||||||
activityId: activityId ?? existing.activityId,
|
activityId: activityId ?? existing.activityId,
|
||||||
durationSec,
|
durationSec,
|
||||||
@@ -213,6 +236,7 @@ export class VoipCallsService {
|
|||||||
status,
|
status,
|
||||||
fromNumber,
|
fromNumber,
|
||||||
toNumber,
|
toNumber,
|
||||||
|
lineExtension,
|
||||||
personId,
|
personId,
|
||||||
activityId,
|
activityId,
|
||||||
durationSec,
|
durationSec,
|
||||||
@@ -240,6 +264,17 @@ export class VoipCallsService {
|
|||||||
await this.notifyIncoming(conn.organizationId, personId, fromNumber);
|
await this.notifyIncoming(conn.organizationId, personId, fromNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
conn.provider === 'daftareshoma' &&
|
||||||
|
['completed', 'answered', 'missed'].includes(status)
|
||||||
|
) {
|
||||||
|
void this.enrichDaftaresomaRecording(connectionId, callId).catch((e) => {
|
||||||
|
this.logger.warn(
|
||||||
|
`daftareshoma recording enrich failed: ${e instanceof Error ? e.message : e}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const link = await this.prisma.voipCallLog.findUnique({
|
const link = await this.prisma.voipCallLog.findUnique({
|
||||||
where: {
|
where: {
|
||||||
connectionId_externalCallId: {
|
connectionId_externalCallId: {
|
||||||
@@ -261,10 +296,67 @@ export class VoipCallsService {
|
|||||||
userId: string,
|
userId: string,
|
||||||
number: string,
|
number: string,
|
||||||
personId?: string,
|
personId?: string,
|
||||||
): Promise<{ ok: true; mode: 'url' | 'tel'; dialUrl: string }> {
|
): Promise<{ ok: true; mode: 'url' | 'tel' | 'daftareshoma'; dialUrl: string }> {
|
||||||
const phone = normalizePhone(number) ?? digitsOnly(number);
|
const phone = normalizePhone(number) ?? digitsOnly(number);
|
||||||
if (!phone) throw new BadRequestException('شماره معتبر نیست');
|
if (!phone) throw new BadRequestException('شماره معتبر نیست');
|
||||||
|
|
||||||
|
const daftareshomaConn = await this.prisma.voipConnection.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId,
|
||||||
|
enabled: true,
|
||||||
|
provider: 'daftareshoma',
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (daftareshomaConn) {
|
||||||
|
const token = await this.connections.decryptApiToken(daftareshomaConn);
|
||||||
|
const fromNumber = daftareshomaConn.fromNumber?.trim();
|
||||||
|
const callerExtension = daftareshomaConn.callerExtension?.trim();
|
||||||
|
if (!token || !fromNumber || !callerExtension) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'اتصال دفتر شما ناقص است؛ توکن، شماره مبدأ و خط را تکمیل کنید',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const toE164 = this.toPlusDigits(phone);
|
||||||
|
const fromE164 = this.toPlusDigits(fromNumber);
|
||||||
|
const extE164 = this.toPlusDigits(callerExtension);
|
||||||
|
try {
|
||||||
|
await this.daftareshoma.outgoingCall(token, {
|
||||||
|
fromNumber: fromE164,
|
||||||
|
toNumber: toE164,
|
||||||
|
callerExtension: extE164,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : 'خطا';
|
||||||
|
await this.prisma.voipConnection.update({
|
||||||
|
where: { id: daftareshomaConn.id },
|
||||||
|
data: { lastError: msg.slice(0, 400) },
|
||||||
|
});
|
||||||
|
throw new BadRequestException(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.voipCallLog.create({
|
||||||
|
data: {
|
||||||
|
organizationId,
|
||||||
|
connectionId: daftareshomaConn.id,
|
||||||
|
externalCallId: `ctc-${Date.now()}-${userId.slice(0, 6)}`,
|
||||||
|
direction: 'outbound',
|
||||||
|
status: 'ringing',
|
||||||
|
fromNumber: fromE164,
|
||||||
|
toNumber: toE164,
|
||||||
|
personId: personId ?? null,
|
||||||
|
startedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
mode: 'daftareshoma',
|
||||||
|
dialUrl: `daftareshoma:${toE164}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const conn = await this.prisma.voipConnection.findFirst({
|
const conn = await this.prisma.voipConnection.findFirst({
|
||||||
where: {
|
where: {
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -318,6 +410,69 @@ export class VoipCallsService {
|
|||||||
return { ok: true, mode: 'tel', dialUrl: `tel:${phone}` };
|
return { ok: true, mode: 'tel', dialUrl: `tel:${phone}` };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private toPlusDigits(raw: string): string {
|
||||||
|
const d = digitsOnly(raw);
|
||||||
|
if (!d) return raw.trim();
|
||||||
|
if (raw.trim().startsWith('+')) return `+${d}`;
|
||||||
|
if (d.startsWith('98')) return `+${d}`;
|
||||||
|
if (d.startsWith('0') && d.length >= 10) return `+98${d.slice(1)}`;
|
||||||
|
if (d.length === 10 && d.startsWith('9')) return `+98${d}`;
|
||||||
|
return `+${d}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async enrichDaftaresomaRecording(
|
||||||
|
connectionId: string,
|
||||||
|
callId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const conn = await this.prisma.voipConnection.findFirst({
|
||||||
|
where: { id: connectionId, provider: 'daftareshoma', enabled: true },
|
||||||
|
});
|
||||||
|
if (!conn) return;
|
||||||
|
const log = await this.prisma.voipCallLog.findUnique({
|
||||||
|
where: {
|
||||||
|
connectionId_externalCallId: { connectionId, externalCallId: callId },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!log) return;
|
||||||
|
if (parseDaftaresomaRecordingRef(log.recordingUrl) || log.recordingUrl) {
|
||||||
|
if (
|
||||||
|
parseDaftaresomaRecordingRef(log.recordingUrl) &&
|
||||||
|
!['done', 'pending', 'processing'].includes(log.summaryStatus)
|
||||||
|
) {
|
||||||
|
await this.prisma.voipCallLog.update({
|
||||||
|
where: { id: log.id },
|
||||||
|
data: {
|
||||||
|
summaryStatus: 'pending',
|
||||||
|
summaryError: null,
|
||||||
|
summaryNextAttemptAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await this.connections.decryptApiToken(conn);
|
||||||
|
if (!token) return;
|
||||||
|
const row = await this.daftareshoma.findCallById(token, callId);
|
||||||
|
const recordingId = row?.recordingId?.trim();
|
||||||
|
if (!recordingId) return;
|
||||||
|
|
||||||
|
const ref = daftareshomaRecordingRef(recordingId);
|
||||||
|
await this.prisma.voipCallLog.update({
|
||||||
|
where: { id: log.id },
|
||||||
|
data: {
|
||||||
|
recordingUrl: ref,
|
||||||
|
summaryStatus: ['done', 'pending', 'processing'].includes(
|
||||||
|
log.summaryStatus,
|
||||||
|
)
|
||||||
|
? log.summaryStatus
|
||||||
|
: 'pending',
|
||||||
|
summaryError: null,
|
||||||
|
summaryNextAttemptAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private shouldCreateActivity(status: string): boolean {
|
private shouldCreateActivity(status: string): boolean {
|
||||||
return ['answered', 'completed', 'missed', 'failed'].includes(status);
|
return ['answered', 'completed', 'missed', 'failed'].includes(status);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,12 +7,17 @@ import type {
|
|||||||
CreateVoipConnectionRequest,
|
CreateVoipConnectionRequest,
|
||||||
UpdateVoipConnectionRequest,
|
UpdateVoipConnectionRequest,
|
||||||
VoipConnectionDto,
|
VoipConnectionDto,
|
||||||
|
VoipProvider,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { createHmac } from 'crypto';
|
import { createHmac } from 'crypto';
|
||||||
import { PrismaService } from '../../prisma/prisma.service';
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
import { TahesabCryptoService } from '../tahesab/tahesab-crypto.service';
|
import { TahesabCryptoService } from '../tahesab/tahesab-crypto.service';
|
||||||
|
|
||||||
|
function asProvider(value: string | null | undefined): VoipProvider {
|
||||||
|
return value === 'daftareshoma' ? 'daftareshoma' : 'generic';
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class VoipConnectionsService {
|
export class VoipConnectionsService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -43,19 +48,35 @@ export class VoipConnectionsService {
|
|||||||
): Promise<VoipConnectionDto> {
|
): Promise<VoipConnectionDto> {
|
||||||
const label = dto.label?.trim();
|
const label = dto.label?.trim();
|
||||||
if (!label) throw new BadRequestException('نام اتصال الزامی است');
|
if (!label) throw new BadRequestException('نام اتصال الزامی است');
|
||||||
|
const provider = asProvider(dto.provider);
|
||||||
|
if (provider === 'daftareshoma') {
|
||||||
|
const token = dto.apiToken?.trim();
|
||||||
|
if (!token) throw new BadRequestException('توکن API دفتر شما الزامی است');
|
||||||
|
// fromNumber / callerExtension فقط برای تماس خروجی از CRM لازماند؛ ثبت وبهوک بدون آنها ممکن است
|
||||||
|
}
|
||||||
|
|
||||||
const secret = dto.webhookSecret?.trim();
|
const secret = dto.webhookSecret?.trim();
|
||||||
const secretEnc = secret ? this.crypto.encrypt(secret) : null;
|
const secretEnc = secret ? this.crypto.encrypt(secret) : null;
|
||||||
const clickToCallUrl = this.normalizeClickUrl(dto.clickToCallUrl);
|
const token = dto.apiToken?.trim();
|
||||||
|
const tokenEnc = token ? this.crypto.encrypt(token) : null;
|
||||||
|
const clickToCallUrl =
|
||||||
|
provider === 'generic' ? this.normalizeClickUrl(dto.clickToCallUrl) : null;
|
||||||
|
|
||||||
const row = await this.prisma.voipConnection.create({
|
const row = await this.prisma.voipConnection.create({
|
||||||
data: {
|
data: {
|
||||||
organizationId,
|
organizationId,
|
||||||
label,
|
label,
|
||||||
|
provider,
|
||||||
enabled: dto.enabled ?? true,
|
enabled: dto.enabled ?? true,
|
||||||
clickToCallUrl,
|
clickToCallUrl,
|
||||||
|
fromNumber: dto.fromNumber?.trim() || null,
|
||||||
|
callerExtension: dto.callerExtension?.trim() || null,
|
||||||
webhookSecretCiphertext: secretEnc?.ciphertext,
|
webhookSecretCiphertext: secretEnc?.ciphertext,
|
||||||
webhookSecretIv: secretEnc?.iv,
|
webhookSecretIv: secretEnc?.iv,
|
||||||
webhookSecretTag: secretEnc?.tag,
|
webhookSecretTag: secretEnc?.tag,
|
||||||
|
apiTokenCiphertext: tokenEnc?.ciphertext,
|
||||||
|
apiTokenIv: tokenEnc?.iv,
|
||||||
|
apiTokenTag: tokenEnc?.tag,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return this.toDto(row, 0);
|
return this.toDto(row, 0);
|
||||||
@@ -77,6 +98,12 @@ export class VoipConnectionsService {
|
|||||||
if (dto.clickToCallUrl !== undefined) {
|
if (dto.clickToCallUrl !== undefined) {
|
||||||
data.clickToCallUrl = this.normalizeClickUrl(dto.clickToCallUrl);
|
data.clickToCallUrl = this.normalizeClickUrl(dto.clickToCallUrl);
|
||||||
}
|
}
|
||||||
|
if (dto.fromNumber !== undefined) {
|
||||||
|
data.fromNumber = dto.fromNumber?.trim() || null;
|
||||||
|
}
|
||||||
|
if (dto.callerExtension !== undefined) {
|
||||||
|
data.callerExtension = dto.callerExtension?.trim() || null;
|
||||||
|
}
|
||||||
if (dto.webhookSecret !== undefined) {
|
if (dto.webhookSecret !== undefined) {
|
||||||
const wh = dto.webhookSecret?.trim();
|
const wh = dto.webhookSecret?.trim();
|
||||||
if (!wh) {
|
if (!wh) {
|
||||||
@@ -90,6 +117,19 @@ export class VoipConnectionsService {
|
|||||||
data.webhookSecretTag = enc.tag;
|
data.webhookSecretTag = enc.tag;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (dto.apiToken !== undefined) {
|
||||||
|
const tok = dto.apiToken?.trim();
|
||||||
|
if (!tok) {
|
||||||
|
data.apiTokenCiphertext = null;
|
||||||
|
data.apiTokenIv = null;
|
||||||
|
data.apiTokenTag = null;
|
||||||
|
} else {
|
||||||
|
const enc = this.crypto.encrypt(tok);
|
||||||
|
data.apiTokenCiphertext = enc.ciphertext;
|
||||||
|
data.apiTokenIv = enc.iv;
|
||||||
|
data.apiTokenTag = enc.tag;
|
||||||
|
}
|
||||||
|
}
|
||||||
const row = await this.prisma.voipConnection.update({
|
const row = await this.prisma.voipConnection.update({
|
||||||
where: { id: existing.id },
|
where: { id: existing.id },
|
||||||
data,
|
data,
|
||||||
@@ -124,6 +164,21 @@ export class VoipConnectionsService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async decryptApiToken(row: {
|
||||||
|
apiTokenCiphertext: string | null;
|
||||||
|
apiTokenIv: string | null;
|
||||||
|
apiTokenTag: string | null;
|
||||||
|
}): Promise<string | null> {
|
||||||
|
if (!row.apiTokenCiphertext || !row.apiTokenIv || !row.apiTokenTag) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.crypto.decrypt({
|
||||||
|
ciphertext: row.apiTokenCiphertext,
|
||||||
|
iv: row.apiTokenIv,
|
||||||
|
tag: row.apiTokenTag,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
verifySignature(
|
verifySignature(
|
||||||
rawBody: string | Buffer,
|
rawBody: string | Buffer,
|
||||||
signature: string | undefined,
|
signature: string | undefined,
|
||||||
@@ -153,9 +208,13 @@ export class VoipConnectionsService {
|
|||||||
row: {
|
row: {
|
||||||
id: string;
|
id: string;
|
||||||
label: string;
|
label: string;
|
||||||
|
provider?: string | null;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
webhookSecretCiphertext: string | null;
|
webhookSecretCiphertext: string | null;
|
||||||
|
apiTokenCiphertext?: string | null;
|
||||||
clickToCallUrl: string | null;
|
clickToCallUrl: string | null;
|
||||||
|
fromNumber?: string | null;
|
||||||
|
callerExtension?: string | null;
|
||||||
lastEventAt: Date | null;
|
lastEventAt: Date | null;
|
||||||
lastError: string | null;
|
lastError: string | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
@@ -166,9 +225,13 @@ export class VoipConnectionsService {
|
|||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
label: row.label,
|
label: row.label,
|
||||||
|
provider: asProvider(row.provider),
|
||||||
enabled: row.enabled,
|
enabled: row.enabled,
|
||||||
webhookSecretSet: Boolean(row.webhookSecretCiphertext),
|
webhookSecretSet: Boolean(row.webhookSecretCiphertext),
|
||||||
|
apiTokenSet: Boolean(row.apiTokenCiphertext),
|
||||||
clickToCallUrl: row.clickToCallUrl,
|
clickToCallUrl: row.clickToCallUrl,
|
||||||
|
fromNumber: row.fromNumber ?? null,
|
||||||
|
callerExtension: row.callerExtension ?? null,
|
||||||
lastEventAt: row.lastEventAt?.toISOString() ?? null,
|
lastEventAt: row.lastEventAt?.toISOString() ?? null,
|
||||||
lastError: row.lastError,
|
lastError: row.lastError,
|
||||||
callCount,
|
callCount,
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
|
||||||
|
const BASE_URL = 'https://coreapi.daftareshoma.com/api/Customize';
|
||||||
|
const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
export type DaftaresomaOutgoingCallInput = {
|
||||||
|
fromNumber: string;
|
||||||
|
toNumber: string;
|
||||||
|
callerExtension: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DaftaresomaCallSearchRow = {
|
||||||
|
id?: string;
|
||||||
|
fromNumber?: string;
|
||||||
|
toNumber?: string;
|
||||||
|
recordingId?: string | null;
|
||||||
|
direction?: string;
|
||||||
|
reportDispositionType?: string;
|
||||||
|
startTime?: string;
|
||||||
|
endTime?: string;
|
||||||
|
duration?: string;
|
||||||
|
extension?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DaftaresomaClient {
|
||||||
|
private readonly logger = new Logger(DaftaresomaClient.name);
|
||||||
|
|
||||||
|
async outgoingCall(
|
||||||
|
apiToken: string,
|
||||||
|
input: DaftaresomaOutgoingCallInput,
|
||||||
|
): Promise<void> {
|
||||||
|
const res = await fetch(`${BASE_URL}/OutgoingCall`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
from_number: input.fromNumber,
|
||||||
|
to_number: input.toNumber,
|
||||||
|
caller_extension: input.callerExtension,
|
||||||
|
}),
|
||||||
|
signal: AbortSignal.timeout(15000),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text().catch(() => '');
|
||||||
|
this.logger.warn(
|
||||||
|
`OutgoingCall failed (${res.status}): ${text.slice(0, 300)}`,
|
||||||
|
);
|
||||||
|
throw new Error(
|
||||||
|
text.trim()
|
||||||
|
? `تماس خروجی دفتر شما ناموفق بود (${res.status}): ${text.slice(0, 200)}`
|
||||||
|
: `تماس خروجی دفتر شما ناموفق بود (${res.status})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async findCallById(
|
||||||
|
apiToken: string,
|
||||||
|
callId: string,
|
||||||
|
): Promise<DaftaresomaCallSearchRow | null> {
|
||||||
|
const res = await fetch(`${BASE_URL}/CustomerCallSearch`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ id: callId, limit: 1, pagination: 1 }),
|
||||||
|
signal: AbortSignal.timeout(20000),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text().catch(() => '');
|
||||||
|
this.logger.warn(
|
||||||
|
`CustomerCallSearch failed (${res.status}): ${text.slice(0, 200)}`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const json = (await res.json()) as {
|
||||||
|
data?: DaftaresomaCallSearchRow[];
|
||||||
|
};
|
||||||
|
const row = Array.isArray(json.data) ? json.data[0] : null;
|
||||||
|
return row ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async downloadRecording(
|
||||||
|
apiToken: string,
|
||||||
|
recordingId: string,
|
||||||
|
): Promise<{ buffer: ArrayBuffer; contentType: string; filename: string }> {
|
||||||
|
const url = new URL(`${BASE_URL}/GetCallRecording`);
|
||||||
|
url.searchParams.set('recordingId', recordingId);
|
||||||
|
const res = await fetch(url.toString(), {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiToken}`,
|
||||||
|
Accept: '*/*',
|
||||||
|
'User-Agent': 'MontactCRM-VoIP/1.0',
|
||||||
|
},
|
||||||
|
signal: AbortSignal.timeout(60000),
|
||||||
|
redirect: 'follow',
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text().catch(() => '');
|
||||||
|
throw new Error(
|
||||||
|
`دانلود ضبط دفتر شما ناموفق بود (${res.status})${text ? `: ${text.slice(0, 160)}` : ''}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const contentLength = Number(res.headers.get('content-length') || 0);
|
||||||
|
if (contentLength > MAX_AUDIO_BYTES) {
|
||||||
|
throw new Error('حجم فایل ضبط بیش از حد مجاز است');
|
||||||
|
}
|
||||||
|
const buffer = await res.arrayBuffer();
|
||||||
|
if (buffer.byteLength > MAX_AUDIO_BYTES) {
|
||||||
|
throw new Error('حجم فایل ضبط بیش از حد مجاز است');
|
||||||
|
}
|
||||||
|
if (!buffer.byteLength) {
|
||||||
|
throw new Error('فایل ضبط خالی است');
|
||||||
|
}
|
||||||
|
const contentType =
|
||||||
|
res.headers.get('content-type')?.split(';')[0]?.trim() || 'audio/wav';
|
||||||
|
const filename = `daftareshoma-${recordingId}.wav`;
|
||||||
|
return { buffer, contentType, filename };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import type { VoipWebhookEvent } from '@mento/shared';
|
||||||
|
|
||||||
|
/** پیشوند ذخیرهشده در recordingUrl برای واکشی بعدی با توکن API */
|
||||||
|
export const DAFTARESHOMA_RECORDING_PREFIX = 'daftareshoma-recording:';
|
||||||
|
|
||||||
|
export function daftareshomaRecordingRef(recordingId: string): string {
|
||||||
|
return `${DAFTARESHOMA_RECORDING_PREFIX}${recordingId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseDaftaresomaRecordingRef(
|
||||||
|
value: string | null | undefined,
|
||||||
|
): string | null {
|
||||||
|
const raw = String(value ?? '').trim();
|
||||||
|
if (!raw.startsWith(DAFTARESHOMA_RECORDING_PREFIX)) return null;
|
||||||
|
const id = raw.slice(DAFTARESHOMA_RECORDING_PREFIX.length).trim();
|
||||||
|
return id || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Loose = Record<string, unknown>;
|
||||||
|
|
||||||
|
function str(v: unknown): string {
|
||||||
|
return v == null ? '' : String(v).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(obj: Loose, ...keys: string[]): string {
|
||||||
|
for (const k of keys) {
|
||||||
|
const v = str(obj[k]);
|
||||||
|
if (v) return v;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDurationSec(raw: unknown): number | undefined {
|
||||||
|
if (raw == null || raw === '') return undefined;
|
||||||
|
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
||||||
|
return Math.max(0, Math.round(raw));
|
||||||
|
}
|
||||||
|
const s = String(raw).trim();
|
||||||
|
if (!s) return undefined;
|
||||||
|
if (/^\d+(\.\d+)?$/.test(s)) return Math.max(0, Math.round(Number(s)));
|
||||||
|
const parts = s.split(':').map((p) => Number(p));
|
||||||
|
if (parts.some((n) => !Number.isFinite(n))) return undefined;
|
||||||
|
if (parts.length === 3) {
|
||||||
|
return Math.max(0, Math.round(parts[0]! * 3600 + parts[1]! * 60 + parts[2]!));
|
||||||
|
}
|
||||||
|
if (parts.length === 2) {
|
||||||
|
return Math.max(0, Math.round(parts[0]! * 60 + parts[1]!));
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* رویداد وبهوک دفتر شما را به VoipWebhookEvent تبدیل میکند.
|
||||||
|
* اگر payload از قبل فرمت Montact باشد، همان را برمیگرداند.
|
||||||
|
*/
|
||||||
|
export function mapDaftaresomaWebhook(
|
||||||
|
body: unknown,
|
||||||
|
): VoipWebhookEvent | null {
|
||||||
|
if (!body || typeof body !== 'object') return null;
|
||||||
|
const obj = body as Loose;
|
||||||
|
|
||||||
|
const legacyCallId = pick(obj, 'callId');
|
||||||
|
if (legacyCallId && (obj.direction || obj.status || obj.from || obj.to)) {
|
||||||
|
return body as VoipWebhookEvent;
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventType = pick(obj, 'EventType', 'eventType', 'event');
|
||||||
|
const callId = pick(obj, 'CallId', 'callId', 'Id', 'id');
|
||||||
|
if (!callId) return null;
|
||||||
|
|
||||||
|
const caller = pick(
|
||||||
|
obj,
|
||||||
|
'CallerNumber',
|
||||||
|
'callerNumber',
|
||||||
|
'from',
|
||||||
|
'From',
|
||||||
|
'fromNumber',
|
||||||
|
);
|
||||||
|
/** خط سازمانی که تماس روی آن آمده/رفته */
|
||||||
|
const lineExtension =
|
||||||
|
pick(obj, 'CalleeExtension', 'calleeExtension', 'Extension', 'extension') ||
|
||||||
|
undefined;
|
||||||
|
/** مقصد انتقال / شماره طرف مقابل روی خط */
|
||||||
|
const transferred = pick(
|
||||||
|
obj,
|
||||||
|
'TransferredToNumber',
|
||||||
|
'transferredToNumber',
|
||||||
|
);
|
||||||
|
|
||||||
|
const startedAt =
|
||||||
|
pick(obj, 'StartDateTime', 'startDateTime', 'startedAt') || undefined;
|
||||||
|
const endedAt =
|
||||||
|
pick(obj, 'EndDateTime', 'endDateTime', 'endedAt', 'DateTime') ||
|
||||||
|
undefined;
|
||||||
|
const durationSec = parseDurationSec(
|
||||||
|
obj.DurationInSeconds ?? obj.durationInSeconds ?? obj.durationSec,
|
||||||
|
);
|
||||||
|
|
||||||
|
const lower = eventType.toLowerCase();
|
||||||
|
const isOutbound = lower.includes('outgoing') || lower.includes('outbound');
|
||||||
|
const isStarted =
|
||||||
|
lower.includes('started') ||
|
||||||
|
lower.includes('ringing') ||
|
||||||
|
lower.includes('transferstarted');
|
||||||
|
const isEnded =
|
||||||
|
lower.includes('ended') ||
|
||||||
|
lower.includes('completed') ||
|
||||||
|
lower.includes('hangup');
|
||||||
|
|
||||||
|
let status: string = 'completed';
|
||||||
|
if (isStarted && !isEnded) {
|
||||||
|
status = 'ringing';
|
||||||
|
} else if (isEnded) {
|
||||||
|
const result = obj.Result ?? obj.result;
|
||||||
|
if (result === false || result === 'false' || result === 0) {
|
||||||
|
status = durationSec && durationSec > 0 ? 'completed' : 'missed';
|
||||||
|
} else if (result === true || result === 'true' || result === 1) {
|
||||||
|
status = 'completed';
|
||||||
|
} else {
|
||||||
|
status = 'completed';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const recordingId = pick(
|
||||||
|
obj,
|
||||||
|
'RecordingId',
|
||||||
|
'recordingId',
|
||||||
|
'RecordId',
|
||||||
|
'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,
|
||||||
|
to,
|
||||||
|
lineExtension,
|
||||||
|
startedAt,
|
||||||
|
endedAt,
|
||||||
|
durationSec,
|
||||||
|
caller: from,
|
||||||
|
callee: to,
|
||||||
|
};
|
||||||
|
if (recordingId) {
|
||||||
|
event.recordingUrl = daftareshomaRecordingRef(recordingId);
|
||||||
|
}
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDaftaresomaWebhookPayload(body: unknown): boolean {
|
||||||
|
if (!body || typeof body !== 'object') return false;
|
||||||
|
const obj = body as Loose;
|
||||||
|
return Boolean(
|
||||||
|
pick(obj, 'EventType', 'eventType') ||
|
||||||
|
(pick(obj, 'CallId') && pick(obj, 'CallerNumber', 'callerNumber')),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
IsBoolean,
|
IsBoolean,
|
||||||
|
IsIn,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
@@ -12,6 +13,10 @@ export class CreateVoipConnectionDto {
|
|||||||
@MaxLength(80)
|
@MaxLength(80)
|
||||||
label!: string;
|
label!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['generic', 'daftareshoma'])
|
||||||
|
provider?: 'generic' | 'daftareshoma';
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@MaxLength(200)
|
@MaxLength(200)
|
||||||
@@ -22,6 +27,21 @@ export class CreateVoipConnectionDto {
|
|||||||
@MaxLength(500)
|
@MaxLength(500)
|
||||||
clickToCallUrl?: string | null;
|
clickToCallUrl?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(500)
|
||||||
|
apiToken?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(40)
|
||||||
|
fromNumber?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(40)
|
||||||
|
callerExtension?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
@@ -44,6 +64,21 @@ export class UpdateVoipConnectionDto {
|
|||||||
@MaxLength(500)
|
@MaxLength(500)
|
||||||
clickToCallUrl?: string | null;
|
clickToCallUrl?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(500)
|
||||||
|
apiToken?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(40)
|
||||||
|
fromNumber?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(40)
|
||||||
|
callerExtension?: string | null;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
|
|||||||
@@ -18,17 +18,31 @@ export class SttClientService {
|
|||||||
throw new ServiceUnavailableException('سرویس تبدیل گفتار فعال نیست');
|
throw new ServiceUnavailableException('سرویس تبدیل گفتار فعال نیست');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const timeoutMs = Number(
|
||||||
|
this.config.get<string>('STT_TIMEOUT_MS') || 180000,
|
||||||
|
);
|
||||||
|
const audio = await this.downloadAudio(recordingUrl, timeoutMs);
|
||||||
|
return this.transcribeAudio(audio, timeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
async transcribeAudio(
|
||||||
|
audio: { buffer: ArrayBuffer; contentType: string; filename: string },
|
||||||
|
timeoutMs?: number,
|
||||||
|
): Promise<string> {
|
||||||
|
if (!this.isEnabled()) {
|
||||||
|
throw new ServiceUnavailableException('سرویس تبدیل گفتار فعال نیست');
|
||||||
|
}
|
||||||
|
|
||||||
const baseUrl = this.config.get<string>('STT_URL')?.trim();
|
const baseUrl = this.config.get<string>('STT_URL')?.trim();
|
||||||
if (!baseUrl) {
|
if (!baseUrl) {
|
||||||
throw new ServiceUnavailableException('آدرس سرویس STT تنظیم نشده');
|
throw new ServiceUnavailableException('آدرس سرویس STT تنظیم نشده');
|
||||||
}
|
}
|
||||||
|
|
||||||
const timeoutMs = Number(
|
const waitMs = timeoutMs ?? Number(
|
||||||
this.config.get<string>('STT_TIMEOUT_MS') || 180000,
|
this.config.get<string>('STT_TIMEOUT_MS') || 180000,
|
||||||
);
|
);
|
||||||
const token = this.config.get<string>('STT_INTERNAL_TOKEN')?.trim() || '';
|
const token = this.config.get<string>('STT_INTERNAL_TOKEN')?.trim() || '';
|
||||||
|
|
||||||
const audio = await this.downloadAudio(recordingUrl, timeoutMs);
|
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
const blob = new Blob([new Uint8Array(audio.buffer)], {
|
const blob = new Blob([new Uint8Array(audio.buffer)], {
|
||||||
type: audio.contentType,
|
type: audio.contentType,
|
||||||
@@ -39,7 +53,7 @@ export class SttClientService {
|
|||||||
if (token) headers['X-STT-Token'] = token;
|
if (token) headers['X-STT-Token'] = token;
|
||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
const timer = setTimeout(() => controller.abort(), waitMs);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${baseUrl.replace(/\/$/, '')}/transcribe`, {
|
const res = await fetch(`${baseUrl.replace(/\/$/, '')}/transcribe`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -28,6 +28,10 @@ import {
|
|||||||
UpdateVoipConnectionDto,
|
UpdateVoipConnectionDto,
|
||||||
VoipClickToCallDto,
|
VoipClickToCallDto,
|
||||||
} from './dto';
|
} from './dto';
|
||||||
|
import {
|
||||||
|
isDaftaresomaWebhookPayload,
|
||||||
|
mapDaftaresomaWebhook,
|
||||||
|
} from './daftareshoma-webhook';
|
||||||
|
|
||||||
@Controller('integrations/voip')
|
@Controller('integrations/voip')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
|
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
|
||||||
@@ -78,8 +82,16 @@ export class VoipController {
|
|||||||
recent(
|
recent(
|
||||||
@CurrentUser() user: { organizationId: string },
|
@CurrentUser() user: { organizationId: string },
|
||||||
@Query('connectionId') connectionId?: 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')
|
@Post('click-to-call')
|
||||||
@@ -129,11 +141,21 @@ export class VoipWebhookController {
|
|||||||
if (!ok) throw new UnauthorizedException('امضای وبهوک نامعتبر است');
|
if (!ok) throw new UnauthorizedException('امضای وبهوک نامعتبر است');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!body?.callId) {
|
let event: VoipWebhookEvent | null = null;
|
||||||
|
if (
|
||||||
|
row.provider === 'daftareshoma' ||
|
||||||
|
isDaftaresomaWebhookPayload(body)
|
||||||
|
) {
|
||||||
|
event = mapDaftaresomaWebhook(body);
|
||||||
|
} else if (body?.callId) {
|
||||||
|
event = body;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!event?.callId) {
|
||||||
return { ok: false, error: 'callId required' };
|
return { ok: false, error: 'callId required' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await this.calls.ingestWebhook(connectionId, body);
|
const result = await this.calls.ingestWebhook(connectionId, event);
|
||||||
return { ok: true, ...result };
|
return { ok: true, ...result };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { TahesabCryptoService } from '../tahesab/tahesab-crypto.service';
|
|||||||
import { CallSummaryService } from './call-summary.service';
|
import { CallSummaryService } from './call-summary.service';
|
||||||
import { VoipConnectionsService } from './connections.service';
|
import { VoipConnectionsService } from './connections.service';
|
||||||
import { VoipCallsService } from './calls.service';
|
import { VoipCallsService } from './calls.service';
|
||||||
|
import { DaftaresomaClient } from './daftareshoma-client';
|
||||||
import { SttClientService } from './stt-client.service';
|
import { SttClientService } from './stt-client.service';
|
||||||
import { VoipController, VoipWebhookController } from './voip.controller';
|
import { VoipController, VoipWebhookController } from './voip.controller';
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ import { VoipController, VoipWebhookController } from './voip.controller';
|
|||||||
TahesabCryptoService,
|
TahesabCryptoService,
|
||||||
VoipConnectionsService,
|
VoipConnectionsService,
|
||||||
VoipCallsService,
|
VoipCallsService,
|
||||||
|
DaftaresomaClient,
|
||||||
SttClientService,
|
SttClientService,
|
||||||
CallSummaryService,
|
CallSummaryService,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -30,9 +30,11 @@ const MAP_TO = [
|
|||||||
'lead.city',
|
'lead.city',
|
||||||
'lead.region',
|
'lead.region',
|
||||||
'lead.trade',
|
'lead.trade',
|
||||||
|
'lead.activityExperience',
|
||||||
'lead.notes',
|
'lead.notes',
|
||||||
'lead.source',
|
'lead.source',
|
||||||
'lead.gender',
|
'lead.gender',
|
||||||
|
'person.activityExperience',
|
||||||
'person.gender',
|
'person.gender',
|
||||||
'notes',
|
'notes',
|
||||||
'custom',
|
'custom',
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ import type {
|
|||||||
SubmitLeadFormResponse,
|
SubmitLeadFormResponse,
|
||||||
UpdateLeadFormRequest,
|
UpdateLeadFormRequest,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { isGenderQuestionLabel, parsePersonGenderAnswer } from '@mento/shared';
|
import {
|
||||||
|
isActivityExperienceLabel,
|
||||||
|
isGenderQuestionLabel,
|
||||||
|
normalizeActivityExperience,
|
||||||
|
parsePersonGenderAnswer,
|
||||||
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { LocalFileStorage } from '../storage/local-file.storage';
|
import { LocalFileStorage } from '../storage/local-file.storage';
|
||||||
@@ -298,14 +303,20 @@ export class LeadFormsService {
|
|||||||
mapped.notes = [mapped.notes, utmNote].filter(Boolean).join('\n');
|
mapped.notes = [mapped.notes, utmNote].filter(Boolean).join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
const ownerId = await this.nextAssignee(form);
|
/** فقط از لیست صریح «توزیع نوبتی»؛ بدون fallback به مالک سازمان */
|
||||||
|
const formAssigneeId = await this.nextAssignee(form);
|
||||||
|
/** فقط برای createdBy / رویدادها — مسئول لید نمیشود */
|
||||||
const actorId =
|
const actorId =
|
||||||
ownerId ??
|
formAssigneeId ??
|
||||||
(
|
(
|
||||||
await this.prisma.user.findFirst({
|
await this.prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
memberships: {
|
memberships: {
|
||||||
some: { organizationId: form.organizationId, role: 'owner' },
|
some: {
|
||||||
|
organizationId: form.organizationId,
|
||||||
|
role: { in: ['owner', 'admin'] },
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
@@ -324,7 +335,7 @@ export class LeadFormsService {
|
|||||||
let message: string | null = null;
|
let message: string | null = null;
|
||||||
|
|
||||||
if (form.createLead) {
|
if (form.createLead) {
|
||||||
const result = await this.upsertLead(form, mapped, ownerId ?? actorId, actorId);
|
const result = await this.upsertLead(form, mapped, formAssigneeId, actorId);
|
||||||
leadId = result.leadId;
|
leadId = result.leadId;
|
||||||
status = result.status;
|
status = result.status;
|
||||||
leadCreated = result.created;
|
leadCreated = result.created;
|
||||||
@@ -344,12 +355,12 @@ export class LeadFormsService {
|
|||||||
personId = await this.upsertPerson(
|
personId = await this.upsertPerson(
|
||||||
form.organizationId,
|
form.organizationId,
|
||||||
mapped,
|
mapped,
|
||||||
ownerId ?? actorId,
|
formAssigneeId ?? actorId,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (form.createDeal) {
|
if (form.createDeal) {
|
||||||
await this.createDeal(form, mapped, personId, actorId, ownerId);
|
await this.createDeal(form, mapped, personId, actorId, formAssigneeId);
|
||||||
} else if (personId && mapped.notes && !form.createLead) {
|
} else if (personId && mapped.notes && !form.createLead) {
|
||||||
await this.prisma.person.update({
|
await this.prisma.person.update({
|
||||||
where: { id: personId },
|
where: { id: personId },
|
||||||
@@ -394,7 +405,9 @@ export class LeadFormsService {
|
|||||||
entityId: personId ?? leadId ?? form.id,
|
entityId: personId ?? leadId ?? form.id,
|
||||||
title,
|
title,
|
||||||
personId,
|
personId,
|
||||||
ownerId: ownerId ?? actorId,
|
/** فقط مسئول صریح فرم؛ مالک سازمان بهعنوان fallback ست نمیشود */
|
||||||
|
ownerId: formAssigneeId,
|
||||||
|
assigneeId: formAssigneeId,
|
||||||
};
|
};
|
||||||
await this.automations.runTrigger('lead_submitted', {
|
await this.automations.runTrigger('lead_submitted', {
|
||||||
...leadCtx,
|
...leadCtx,
|
||||||
@@ -402,7 +415,7 @@ export class LeadFormsService {
|
|||||||
sourceId: form.id,
|
sourceId: form.id,
|
||||||
sourceType: 'lead_form',
|
sourceType: 'lead_form',
|
||||||
leadId,
|
leadId,
|
||||||
syncLeadAssignee: !ownerId && leadCreated && !!leadId,
|
syncLeadAssignee: !formAssigneeId && leadCreated && !!leadId,
|
||||||
mobile: mapped.mobile ?? mapped.phone ?? null,
|
mobile: mapped.mobile ?? mapped.phone ?? null,
|
||||||
formName: form.name,
|
formName: form.name,
|
||||||
formValues: values,
|
formValues: values,
|
||||||
@@ -437,7 +450,7 @@ export class LeadFormsService {
|
|||||||
private async upsertLead(
|
private async upsertLead(
|
||||||
form: FormRow,
|
form: FormRow,
|
||||||
mapped: MappedValues,
|
mapped: MappedValues,
|
||||||
assigneeId: string,
|
assigneeId: string | null,
|
||||||
actorId: string,
|
actorId: string,
|
||||||
): Promise<{
|
): Promise<{
|
||||||
leadId: string | null;
|
leadId: string | null;
|
||||||
@@ -561,6 +574,9 @@ export class LeadFormsService {
|
|||||||
region: emptyToNull(mapped.region) ?? existingLead.region,
|
region: emptyToNull(mapped.region) ?? existingLead.region,
|
||||||
trade: emptyToNull(mapped.trade) ?? existingLead.trade,
|
trade: emptyToNull(mapped.trade) ?? existingLead.trade,
|
||||||
source: source ?? existingLead.source,
|
source: source ?? existingLead.source,
|
||||||
|
activityExperience:
|
||||||
|
emptyToNull(mapped.activityExperience) ??
|
||||||
|
existingLead.activityExperience,
|
||||||
notes: emptyToNull(mapped.notes) ?? existingLead.notes,
|
notes: emptyToNull(mapped.notes) ?? existingLead.notes,
|
||||||
...(mapped.gender ? { gender: mapped.gender } : {}),
|
...(mapped.gender ? { gender: mapped.gender } : {}),
|
||||||
assigneeId: existingLead.assigneeId ?? assigneeId,
|
assigneeId: existingLead.assigneeId ?? assigneeId,
|
||||||
@@ -587,7 +603,9 @@ export class LeadFormsService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const stages = await this.leadStages.list(form.organizationId);
|
const stages = await this.leadStages.list(form.organizationId, {
|
||||||
|
withLeadCounts: false,
|
||||||
|
});
|
||||||
const stageId =
|
const stageId =
|
||||||
(form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) ||
|
(form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) ||
|
||||||
stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id ||
|
stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id ||
|
||||||
@@ -610,6 +628,7 @@ export class LeadFormsService {
|
|||||||
region: emptyToNull(mapped.region),
|
region: emptyToNull(mapped.region),
|
||||||
trade: emptyToNull(mapped.trade),
|
trade: emptyToNull(mapped.trade),
|
||||||
source,
|
source,
|
||||||
|
activityExperience: emptyToNull(mapped.activityExperience),
|
||||||
notes: emptyToNull(mapped.notes),
|
notes: emptyToNull(mapped.notes),
|
||||||
gender: mapped.gender ?? 'none',
|
gender: mapped.gender ?? 'none',
|
||||||
stageId,
|
stageId,
|
||||||
@@ -674,6 +693,8 @@ export class LeadFormsService {
|
|||||||
phone: phone ?? existing.phone,
|
phone: phone ?? existing.phone,
|
||||||
position: emptyToNull(mapped.position) ?? existing.position,
|
position: emptyToNull(mapped.position) ?? existing.position,
|
||||||
notes: emptyToNull(mapped.notes) ?? existing.notes,
|
notes: emptyToNull(mapped.notes) ?? existing.notes,
|
||||||
|
activityExperience:
|
||||||
|
emptyToNull(mapped.activityExperience) ?? existing.activityExperience,
|
||||||
...(mapped.gender ? { gender: mapped.gender } : {}),
|
...(mapped.gender ? { gender: mapped.gender } : {}),
|
||||||
ownerId: existing.ownerId ?? ownerId,
|
ownerId: existing.ownerId ?? ownerId,
|
||||||
},
|
},
|
||||||
@@ -691,6 +712,7 @@ export class LeadFormsService {
|
|||||||
phone,
|
phone,
|
||||||
position: emptyToNull(mapped.position),
|
position: emptyToNull(mapped.position),
|
||||||
notes: emptyToNull(mapped.notes),
|
notes: emptyToNull(mapped.notes),
|
||||||
|
activityExperience: emptyToNull(mapped.activityExperience),
|
||||||
gender: mapped.gender ?? 'none',
|
gender: mapped.gender ?? 'none',
|
||||||
ownerId,
|
ownerId,
|
||||||
},
|
},
|
||||||
@@ -954,6 +976,7 @@ type MappedValues = {
|
|||||||
city?: string;
|
city?: string;
|
||||||
region?: string;
|
region?: string;
|
||||||
trade?: string;
|
trade?: string;
|
||||||
|
activityExperience?: string;
|
||||||
leadSource?: string;
|
leadSource?: string;
|
||||||
gender?: 'male' | 'female' | 'none';
|
gender?: 'male' | 'female' | 'none';
|
||||||
};
|
};
|
||||||
@@ -985,6 +1008,15 @@ function mapValues(
|
|||||||
if (gender) mapped.gender = gender;
|
if (gender) mapped.gender = gender;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
field.mapTo === 'lead.activityExperience' ||
|
||||||
|
field.mapTo === 'person.activityExperience' ||
|
||||||
|
isActivityExperienceLabel(field.label)
|
||||||
|
) {
|
||||||
|
mapped.activityExperience =
|
||||||
|
normalizeActivityExperience(raw) ?? raw;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
switch (field.mapTo) {
|
switch (field.mapTo) {
|
||||||
case 'person.fullName': {
|
case 'person.fullName': {
|
||||||
const parts = raw.split(/\s+/).filter(Boolean);
|
const parts = raw.split(/\s+/).filter(Boolean);
|
||||||
@@ -1038,6 +1070,11 @@ function mapValues(
|
|||||||
case 'lead.trade':
|
case 'lead.trade':
|
||||||
mapped.trade = raw;
|
mapped.trade = raw;
|
||||||
break;
|
break;
|
||||||
|
case 'lead.activityExperience':
|
||||||
|
case 'person.activityExperience':
|
||||||
|
mapped.activityExperience =
|
||||||
|
normalizeActivityExperience(raw) ?? raw;
|
||||||
|
break;
|
||||||
case 'lead.notes':
|
case 'lead.notes':
|
||||||
mapped.notes = raw;
|
mapped.notes = raw;
|
||||||
break;
|
break;
|
||||||
@@ -1108,7 +1145,9 @@ function collectExtras(
|
|||||||
for (const field of fields) {
|
for (const field of fields) {
|
||||||
if (field.fieldType === 'heading' || field.mapTo !== 'custom') continue;
|
if (field.fieldType === 'heading' || field.mapTo !== 'custom') continue;
|
||||||
const raw = (values?.[field.key] ?? '').toString().trim();
|
const raw = (values?.[field.key] ?? '').toString().trim();
|
||||||
if (!raw || (isGenderQuestionLabel(field.label) && parsePersonGenderAnswer(raw))) continue;
|
if (!raw) continue;
|
||||||
|
if (isGenderQuestionLabel(field.label) && parsePersonGenderAnswer(raw)) continue;
|
||||||
|
if (isActivityExperienceLabel(field.label)) continue;
|
||||||
lines.push(`${field.label}: ${raw}`);
|
lines.push(`${field.label}: ${raw}`);
|
||||||
}
|
}
|
||||||
return lines.join('\n');
|
return lines.join('\n');
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ export class CreateLeadDto {
|
|||||||
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
|
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
|
||||||
@IsOptional() @IsString() trade?: string;
|
@IsOptional() @IsString() trade?: string;
|
||||||
@IsOptional() @IsString() source?: string;
|
@IsOptional() @IsString() source?: string;
|
||||||
|
@IsOptional() @IsString() activityExperience?: string | null;
|
||||||
@IsOptional() @IsString() notes?: string;
|
@IsOptional() @IsString() notes?: string;
|
||||||
@IsOptional() @IsNumber() estimatedValue?: number;
|
@IsOptional() @IsNumber() estimatedValue?: number;
|
||||||
@IsOptional() @IsString() stageId?: string;
|
@IsOptional() @IsString() stageId?: string;
|
||||||
@@ -60,9 +61,12 @@ export class UpdateLeadDto {
|
|||||||
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
|
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
|
||||||
@IsOptional() @IsString() trade?: string | null;
|
@IsOptional() @IsString() trade?: string | null;
|
||||||
@IsOptional() @IsString() source?: string | null;
|
@IsOptional() @IsString() source?: string | null;
|
||||||
|
@IsOptional() @IsString() activityExperience?: string | null;
|
||||||
@IsOptional() @IsString() notes?: string | null;
|
@IsOptional() @IsString() notes?: string | null;
|
||||||
@IsOptional() @IsNumber() estimatedValue?: number | null;
|
@IsOptional() @IsNumber() estimatedValue?: number | null;
|
||||||
@IsOptional() @IsString() stageId?: string;
|
@IsOptional() @IsString() stageId?: string;
|
||||||
|
/** الزامی هنگام تغییر ستون؛ در جدول زمانی لید ثبت میشود */
|
||||||
|
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
|
||||||
@IsOptional() @IsString() assigneeId?: string | null;
|
@IsOptional() @IsString() assigneeId?: string | null;
|
||||||
@IsOptional() @IsString() nextFollowUpAt?: string | null;
|
@IsOptional() @IsString() nextFollowUpAt?: string | null;
|
||||||
@IsOptional() @IsString() lastContactAt?: string | null;
|
@IsOptional() @IsString() lastContactAt?: string | null;
|
||||||
@@ -71,6 +75,7 @@ export class UpdateLeadDto {
|
|||||||
export class MoveLeadDto {
|
export class MoveLeadDto {
|
||||||
@IsString() stageId!: string;
|
@IsString() stageId!: string;
|
||||||
@IsOptional() @IsNumber() position?: number;
|
@IsOptional() @IsNumber() position?: number;
|
||||||
|
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AssignLeadsDto {
|
export class AssignLeadsDto {
|
||||||
@@ -81,6 +86,7 @@ export class AssignLeadsDto {
|
|||||||
export class BulkLeadStageDto {
|
export class BulkLeadStageDto {
|
||||||
@IsArray() @IsString({ each: true }) leadIds!: string[];
|
@IsArray() @IsString({ each: true }) leadIds!: string[];
|
||||||
@IsString() stageId!: string;
|
@IsString() stageId!: string;
|
||||||
|
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AutoAssignLeadsDto {
|
export class AutoAssignLeadsDto {
|
||||||
|
|||||||
@@ -43,18 +43,26 @@ export class LeadStagesService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async list(organizationId: string): Promise<LeadStageDto[]> {
|
async list(
|
||||||
|
organizationId: string,
|
||||||
|
opts: { withLeadCounts?: boolean } = {},
|
||||||
|
): Promise<LeadStageDto[]> {
|
||||||
|
const withLeadCounts = opts.withLeadCounts !== false;
|
||||||
await this.ensureDefaults(organizationId);
|
await this.ensureDefaults(organizationId);
|
||||||
const rows = await this.prisma.leadStage.findMany({
|
const rows = await this.prisma.leadStage.findMany({
|
||||||
where: { organizationId },
|
where: { organizationId },
|
||||||
orderBy: { position: 'asc' },
|
orderBy: { position: 'asc' },
|
||||||
include: {
|
...(withLeadCounts
|
||||||
_count: {
|
? {
|
||||||
select: {
|
include: {
|
||||||
leads: { where: { archivedAt: null } },
|
_count: {
|
||||||
},
|
select: {
|
||||||
},
|
leads: { where: { archivedAt: null } },
|
||||||
},
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
});
|
});
|
||||||
return rows.map((r) => this.toDto(r));
|
return rows.map((r) => this.toDto(r));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -181,7 +181,9 @@ export class LeadsImportService {
|
|||||||
const job = await this.prisma.leadImportJob.findUnique({ where: { id } });
|
const job = await this.prisma.leadImportJob.findUnique({ where: { id } });
|
||||||
if (!job) return;
|
if (!job) return;
|
||||||
|
|
||||||
const stages = await this.stages.list(job.organizationId);
|
const stages = await this.stages.list(job.organizationId, {
|
||||||
|
withLeadCounts: false,
|
||||||
|
});
|
||||||
const defaultStageId = stages[0]?.id;
|
const defaultStageId = stages[0]?.id;
|
||||||
if (!defaultStageId) {
|
if (!defaultStageId) {
|
||||||
await this.prisma.leadImportJob.update({
|
await this.prisma.leadImportJob.update({
|
||||||
|
|||||||
@@ -70,8 +70,13 @@ export class LeadsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get('stages')
|
@Get('stages')
|
||||||
listStages(@CurrentUser() user: Actor) {
|
listStages(
|
||||||
return this.stages.list(user.organizationId);
|
@CurrentUser() user: Actor,
|
||||||
|
@Query('counts') counts?: string,
|
||||||
|
) {
|
||||||
|
return this.stages.list(user.organizationId, {
|
||||||
|
withLeadCounts: counts !== '0' && counts !== 'false',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('stages')
|
@Post('stages')
|
||||||
@@ -244,9 +249,14 @@ export class LeadsController {
|
|||||||
@Query('region') region?: string,
|
@Query('region') region?: string,
|
||||||
@Query('trade') trade?: string,
|
@Query('trade') trade?: string,
|
||||||
@Query('source') source?: string,
|
@Query('source') source?: string,
|
||||||
|
@Query('activityExperience') activityExperience?: string,
|
||||||
@Query('unassigned') unassigned?: string,
|
@Query('unassigned') unassigned?: string,
|
||||||
@Query('archived') archived?: string,
|
@Query('archived') archived?: string,
|
||||||
|
@Query('converted') converted?: string,
|
||||||
@Query('hasMobile') hasMobile?: string,
|
@Query('hasMobile') hasMobile?: string,
|
||||||
|
@Query('followUp') followUp?: string,
|
||||||
|
@Query('createdFrom') createdFrom?: string,
|
||||||
|
@Query('createdTo') createdTo?: string,
|
||||||
) {
|
) {
|
||||||
return this.leads.listIds(user, {
|
return this.leads.listIds(user, {
|
||||||
q,
|
q,
|
||||||
@@ -256,9 +266,14 @@ export class LeadsController {
|
|||||||
region,
|
region,
|
||||||
trade,
|
trade,
|
||||||
source,
|
source,
|
||||||
|
activityExperience,
|
||||||
unassigned: unassigned === '1' || unassigned === 'true',
|
unassigned: unassigned === '1' || unassigned === 'true',
|
||||||
archived: archived === '1' || archived === 'true',
|
archived: archived === '1' || archived === 'true',
|
||||||
|
converted: converted === '1' || converted === 'true',
|
||||||
hasMobile: hasMobile === '1' || hasMobile === 'true',
|
hasMobile: hasMobile === '1' || hasMobile === 'true',
|
||||||
|
followUp,
|
||||||
|
createdFrom,
|
||||||
|
createdTo,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,10 +289,15 @@ export class LeadsController {
|
|||||||
@Query('region') region?: string,
|
@Query('region') region?: string,
|
||||||
@Query('trade') trade?: string,
|
@Query('trade') trade?: string,
|
||||||
@Query('source') source?: string,
|
@Query('source') source?: string,
|
||||||
|
@Query('activityExperience') activityExperience?: string,
|
||||||
@Query('unassigned') unassigned?: string,
|
@Query('unassigned') unassigned?: string,
|
||||||
@Query('archived') archived?: string,
|
@Query('archived') archived?: string,
|
||||||
|
@Query('converted') converted?: string,
|
||||||
@Query('sort') sort?: string,
|
@Query('sort') sort?: string,
|
||||||
@Query('hasMobile') hasMobile?: string,
|
@Query('hasMobile') hasMobile?: string,
|
||||||
|
@Query('followUp') followUp?: string,
|
||||||
|
@Query('createdFrom') createdFrom?: string,
|
||||||
|
@Query('createdTo') createdTo?: string,
|
||||||
) {
|
) {
|
||||||
return this.leads.list(user, {
|
return this.leads.list(user, {
|
||||||
q,
|
q,
|
||||||
@@ -289,10 +309,15 @@ export class LeadsController {
|
|||||||
region,
|
region,
|
||||||
trade,
|
trade,
|
||||||
source,
|
source,
|
||||||
|
activityExperience,
|
||||||
unassigned: unassigned === '1' || unassigned === 'true',
|
unassigned: unassigned === '1' || unassigned === 'true',
|
||||||
archived: archived === '1' || archived === 'true',
|
archived: archived === '1' || archived === 'true',
|
||||||
|
converted: converted === '1' || converted === 'true',
|
||||||
sort,
|
sort,
|
||||||
hasMobile: hasMobile === '1' || hasMobile === 'true',
|
hasMobile: hasMobile === '1' || hasMobile === 'true',
|
||||||
|
followUp,
|
||||||
|
createdFrom,
|
||||||
|
createdTo,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -313,7 +338,7 @@ export class LeadsController {
|
|||||||
@Roles('owner', 'admin')
|
@Roles('owner', 'admin')
|
||||||
bulkStage(@CurrentUser() user: Actor, @Body() dto: BulkLeadStageDto) {
|
bulkStage(@CurrentUser() user: Actor, @Body() dto: BulkLeadStageDto) {
|
||||||
return this.leads
|
return this.leads
|
||||||
.bulkStage(user, dto.leadIds, dto.stageId)
|
.bulkStage(user, dto.leadIds, dto.stageId, dto.reason)
|
||||||
.then((count) => ({ count }));
|
.then((count) => ({ count }));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,7 +402,7 @@ export class LeadsController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() dto: MoveLeadDto,
|
@Body() dto: MoveLeadDto,
|
||||||
) {
|
) {
|
||||||
return this.leads.move(user, id, dto.stageId, dto.position);
|
return this.leads.move(user, id, dto.stageId, dto.position, dto.reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id/sms-history')
|
@Get(':id/sms-history')
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import {
|
|||||||
BadRequestException,
|
BadRequestException,
|
||||||
ConflictException,
|
ConflictException,
|
||||||
Injectable,
|
Injectable,
|
||||||
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
ServiceUnavailableException,
|
ServiceUnavailableException,
|
||||||
|
type OnModuleInit,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { parseBirthDate } from '../common/excel';
|
import { parseBirthDate } from '../common/excel';
|
||||||
@@ -20,7 +22,12 @@ import type {
|
|||||||
PaginatedResponse,
|
PaginatedResponse,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { FILTERED_IDS_MAX } from '@mento/shared';
|
import { FILTERED_IDS_MAX } from '@mento/shared';
|
||||||
import { applyLeadGenderName, applyPersonGenderTitle } from '@mento/shared';
|
import {
|
||||||
|
applyLeadGenderName,
|
||||||
|
applyPersonGenderTitle,
|
||||||
|
extractActivityExperienceFromNotes,
|
||||||
|
normalizeActivityExperience,
|
||||||
|
} from '@mento/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
|
||||||
import { renderSmsText } from '../common/sms-text';
|
import { renderSmsText } from '../common/sms-text';
|
||||||
@@ -49,6 +56,12 @@ import { StorageQuotaService } from '../billing/storage-quota.service';
|
|||||||
import { LeadStagesService } from './lead-stages.service';
|
import { LeadStagesService } from './lead-stages.service';
|
||||||
import { buildSearchWhere, ci } from '../common/search';
|
import { buildSearchWhere, ci } from '../common/search';
|
||||||
import { GamificationService } from '../gamification/gamification.service';
|
import { GamificationService } from '../gamification/gamification.service';
|
||||||
|
import {
|
||||||
|
addDays,
|
||||||
|
isDayKey,
|
||||||
|
tehranDayKey,
|
||||||
|
tehranDayStart,
|
||||||
|
} from '../routines/routine-dates';
|
||||||
|
|
||||||
const LOGO_MAX_BYTES = 2 * 1024 * 1024;
|
const LOGO_MAX_BYTES = 2 * 1024 * 1024;
|
||||||
const LOGO_EXT: Record<string, string> = {
|
const LOGO_EXT: Record<string, string> = {
|
||||||
@@ -98,10 +111,44 @@ const leadInclude = {
|
|||||||
assignee: { select: { id: true, fullName: true } },
|
assignee: { select: { id: true, fullName: true } },
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
/** فیلدهای لازم برای کارت مسیر لیدها — بدون notes/addresses حجیم و بدون join مرحله */
|
||||||
|
const boardLeadSelect = {
|
||||||
|
id: true,
|
||||||
|
title: true,
|
||||||
|
contactName: true,
|
||||||
|
gender: true,
|
||||||
|
showGenderInName: true,
|
||||||
|
mobile: true,
|
||||||
|
phone: true,
|
||||||
|
city: true,
|
||||||
|
region: true,
|
||||||
|
instagram: true,
|
||||||
|
birthDate: true,
|
||||||
|
trade: true,
|
||||||
|
source: true,
|
||||||
|
activityExperience: true,
|
||||||
|
logoStorageKey: true,
|
||||||
|
estimatedValue: true,
|
||||||
|
stageId: true,
|
||||||
|
position: true,
|
||||||
|
assigneeId: true,
|
||||||
|
lastContactAt: true,
|
||||||
|
nextFollowUpAt: true,
|
||||||
|
convertedPersonId: true,
|
||||||
|
convertedAt: true,
|
||||||
|
archivedAt: true,
|
||||||
|
createdAt: true,
|
||||||
|
updatedAt: true,
|
||||||
|
assignee: { select: { id: true, fullName: true } },
|
||||||
|
} as const;
|
||||||
|
|
||||||
type LeadRow = Prisma.LeadGetPayload<{ include: typeof leadInclude }>;
|
type LeadRow = Prisma.LeadGetPayload<{ include: typeof leadInclude }>;
|
||||||
|
type BoardLeadRow = Prisma.LeadGetPayload<{ select: typeof boardLeadSelect }>;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class LeadsService {
|
export class LeadsService implements OnModuleInit {
|
||||||
|
private readonly logger = new Logger(LeadsService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly stages: LeadStagesService,
|
private readonly stages: LeadStagesService,
|
||||||
@@ -112,6 +159,41 @@ export class LeadsService {
|
|||||||
private readonly outboundSms: OutboundSmsLogService,
|
private readonly outboundSms: OutboundSmsLogService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
onModuleInit() {
|
||||||
|
void this.backfillActivityExperienceFromNotes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** سابقه فعالیت قدیمی که فقط در یادداشت فرم بود، روی ستون لید مینشیند. */
|
||||||
|
async backfillActivityExperienceFromNotes() {
|
||||||
|
try {
|
||||||
|
const rows = await this.prisma.lead.findMany({
|
||||||
|
where: {
|
||||||
|
activityExperience: null,
|
||||||
|
notes: { contains: 'سابقه' },
|
||||||
|
},
|
||||||
|
select: { id: true, notes: true },
|
||||||
|
take: 20000,
|
||||||
|
});
|
||||||
|
let filled = 0;
|
||||||
|
for (const row of rows) {
|
||||||
|
const value = extractActivityExperienceFromNotes(row.notes);
|
||||||
|
if (!value) continue;
|
||||||
|
const updated = await this.prisma.lead.updateMany({
|
||||||
|
where: { id: row.id, activityExperience: null },
|
||||||
|
data: { activityExperience: value },
|
||||||
|
});
|
||||||
|
filled += updated.count;
|
||||||
|
}
|
||||||
|
if (filled) {
|
||||||
|
this.logger.log(`سابقه فعالیت ${filled} لید از یادداشت فرم پر شد`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`پر کردن سابقه فعالیت لیدها ناموفق بود: ${err instanceof Error ? err.message : err}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private gameEvent(
|
private gameEvent(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
event: Parameters<GamificationService['emit']>[0]['event'],
|
event: Parameters<GamificationService['emit']>[0]['event'],
|
||||||
@@ -140,9 +222,14 @@ export class LeadsService {
|
|||||||
region?: string;
|
region?: string;
|
||||||
trade?: string;
|
trade?: string;
|
||||||
source?: string;
|
source?: string;
|
||||||
|
activityExperience?: string;
|
||||||
unassigned?: boolean;
|
unassigned?: boolean;
|
||||||
archived?: boolean;
|
archived?: boolean;
|
||||||
|
converted?: boolean;
|
||||||
hasMobile?: boolean;
|
hasMobile?: boolean;
|
||||||
|
followUp?: string;
|
||||||
|
createdFrom?: string;
|
||||||
|
createdTo?: string;
|
||||||
},
|
},
|
||||||
): Prisma.LeadWhereInput {
|
): Prisma.LeadWhereInput {
|
||||||
const search = buildSearchWhere<Prisma.LeadWhereInput>(opts.q, (t) => [
|
const search = buildSearchWhere<Prisma.LeadWhereInput>(opts.q, (t) => [
|
||||||
@@ -155,28 +242,91 @@ export class LeadsService {
|
|||||||
{ trade: ci(t) },
|
{ trade: ci(t) },
|
||||||
{ instagram: ci(t) },
|
{ instagram: ci(t) },
|
||||||
{ source: ci(t) },
|
{ source: ci(t) },
|
||||||
|
{ activityExperience: ci(t) },
|
||||||
]);
|
]);
|
||||||
const and: Prisma.LeadWhereInput[] = [];
|
const and: Prisma.LeadWhereInput[] = [];
|
||||||
if (search) and.push(search);
|
if (search) and.push(search);
|
||||||
if (opts.hasMobile) {
|
if (opts.hasMobile) {
|
||||||
and.push({ mobile: { not: '' } });
|
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 {
|
return {
|
||||||
organizationId: actor.organizationId,
|
AND: [
|
||||||
...leadAccessWhere(actor),
|
{
|
||||||
archivedAt: opts.archived ? { not: null } : null,
|
organizationId: actor.organizationId,
|
||||||
...(opts.stageId ? { stageId: opts.stageId } : {}),
|
...leadAccessWhere(actor),
|
||||||
...(opts.assigneeId ? { assigneeId: opts.assigneeId } : {}),
|
archivedAt: opts.archived ? { not: null } : null,
|
||||||
...(opts.unassigned ? { assigneeId: null } : {}),
|
...(opts.converted ? { convertedPersonId: { not: null } } : {}),
|
||||||
...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}),
|
...(opts.stageId ? { stageId: opts.stageId } : {}),
|
||||||
...(opts.region
|
...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}),
|
||||||
? { region: { contains: opts.region, mode: 'insensitive' } }
|
...(opts.region
|
||||||
: {}),
|
? { region: { contains: opts.region, mode: 'insensitive' } }
|
||||||
...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}),
|
: {}),
|
||||||
...(opts.source
|
...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}),
|
||||||
? { source: { contains: opts.source, mode: 'insensitive' } }
|
...(opts.source
|
||||||
: {}),
|
? { source: { contains: opts.source, mode: 'insensitive' } }
|
||||||
...(and.length ? { AND: and } : {}),
|
: {}),
|
||||||
|
...(opts.activityExperience
|
||||||
|
? {
|
||||||
|
activityExperience:
|
||||||
|
normalizeActivityExperience(opts.activityExperience) ??
|
||||||
|
opts.activityExperience,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
...(opts.unassigned ? [{ assigneeId: null }] : []),
|
||||||
|
...(opts.assigneeId && !opts.unassigned ? [{ assigneeId: opts.assigneeId }] : []),
|
||||||
|
...and,
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** مرز روز به وقت تهران برای فیلترهای «امروز». */
|
||||||
|
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 } : {}),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,10 +342,15 @@ export class LeadsService {
|
|||||||
region?: string;
|
region?: string;
|
||||||
trade?: string;
|
trade?: string;
|
||||||
source?: string;
|
source?: string;
|
||||||
|
activityExperience?: string;
|
||||||
unassigned?: boolean;
|
unassigned?: boolean;
|
||||||
archived?: boolean;
|
archived?: boolean;
|
||||||
|
converted?: boolean;
|
||||||
sort?: string;
|
sort?: string;
|
||||||
hasMobile?: boolean;
|
hasMobile?: boolean;
|
||||||
|
followUp?: string;
|
||||||
|
createdFrom?: string;
|
||||||
|
createdTo?: string;
|
||||||
},
|
},
|
||||||
): Promise<PaginatedResponse<LeadDto>> {
|
): Promise<PaginatedResponse<LeadDto>> {
|
||||||
await this.stages.ensureDefaults(actor.organizationId);
|
await this.stages.ensureDefaults(actor.organizationId);
|
||||||
@@ -241,9 +396,14 @@ export class LeadsService {
|
|||||||
region?: string;
|
region?: string;
|
||||||
trade?: string;
|
trade?: string;
|
||||||
source?: string;
|
source?: string;
|
||||||
|
activityExperience?: string;
|
||||||
unassigned?: boolean;
|
unassigned?: boolean;
|
||||||
archived?: boolean;
|
archived?: boolean;
|
||||||
|
converted?: boolean;
|
||||||
hasMobile?: boolean;
|
hasMobile?: boolean;
|
||||||
|
followUp?: string;
|
||||||
|
createdFrom?: string;
|
||||||
|
createdTo?: string;
|
||||||
},
|
},
|
||||||
max = FILTERED_IDS_MAX,
|
max = FILTERED_IDS_MAX,
|
||||||
): Promise<FilteredIdsResponse> {
|
): Promise<FilteredIdsResponse> {
|
||||||
@@ -265,33 +425,56 @@ export class LeadsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async board(actor: Actor): Promise<LeadBoardColumnDto[]> {
|
async board(actor: Actor): Promise<LeadBoardColumnDto[]> {
|
||||||
const stages = await this.stages.list(actor.organizationId);
|
// بدون شمارش لید روی هر مرحله — شمارش را یکبار با groupBy میگیریم
|
||||||
|
const stages = await this.stages.list(actor.organizationId, {
|
||||||
|
withLeadCounts: false,
|
||||||
|
});
|
||||||
const boardStages = stages.filter((s) => s.showOnBoard);
|
const boardStages = stages.filter((s) => s.showOnBoard);
|
||||||
const whereBase = {
|
if (!boardStages.length) return [];
|
||||||
|
|
||||||
|
const access = leadAccessWhere(actor);
|
||||||
|
const stageIds = boardStages.map((s) => s.id);
|
||||||
|
const whereBase: Prisma.LeadWhereInput = {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
...leadAccessWhere(actor),
|
...access,
|
||||||
archivedAt: null,
|
archivedAt: null,
|
||||||
|
stageId: { in: stageIds },
|
||||||
};
|
};
|
||||||
const perColumn = 120;
|
const perColumn = 120;
|
||||||
return Promise.all(
|
|
||||||
boardStages.map(async (stage) => {
|
const [counts, ...columnRows] = await Promise.all([
|
||||||
const where = { ...whereBase, stageId: stage.id };
|
this.prisma.lead.groupBy({
|
||||||
const [total, rows] = await Promise.all([
|
by: ['stageId'],
|
||||||
this.prisma.lead.count({ where }),
|
where: whereBase,
|
||||||
this.prisma.lead.findMany({
|
_count: { _all: true },
|
||||||
where,
|
|
||||||
include: leadInclude,
|
|
||||||
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
|
|
||||||
take: perColumn,
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
return {
|
|
||||||
stage,
|
|
||||||
total,
|
|
||||||
leads: rows.map((row) => this.toDto(row)),
|
|
||||||
};
|
|
||||||
}),
|
}),
|
||||||
|
...boardStages.map((stage) =>
|
||||||
|
this.prisma.lead.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
...access,
|
||||||
|
archivedAt: null,
|
||||||
|
stageId: stage.id,
|
||||||
|
},
|
||||||
|
// کارت بورد به join مرحله نیاز ندارد؛ اسم مرحله را از ستون میگذاریم
|
||||||
|
select: boardLeadSelect,
|
||||||
|
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
|
||||||
|
take: perColumn,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const totalByStage = new Map(
|
||||||
|
counts.map((row) => [row.stageId, row._count._all]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return boardStages.map((stage, index) => ({
|
||||||
|
stage,
|
||||||
|
total: totalByStage.get(stage.id) ?? 0,
|
||||||
|
leads: (columnRows[index] ?? []).map((row) =>
|
||||||
|
this.toBoardDto(row, stage.name),
|
||||||
|
),
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(actor: Actor, id: string): Promise<LeadDto & { events: LeadEventDto[] }> {
|
async get(actor: Actor, id: string): Promise<LeadDto & { events: LeadEventDto[] }> {
|
||||||
@@ -365,6 +548,7 @@ export class LeadsService {
|
|||||||
addresses?: string[];
|
addresses?: string[];
|
||||||
trade?: string | null;
|
trade?: string | null;
|
||||||
source?: string | null;
|
source?: string | null;
|
||||||
|
activityExperience?: string | null;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
estimatedValue?: number | null;
|
estimatedValue?: number | null;
|
||||||
stageId?: string;
|
stageId?: string;
|
||||||
@@ -386,7 +570,9 @@ export class LeadsService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const stages = await this.stages.list(actor.organizationId);
|
const stages = await this.stages.list(actor.organizationId, {
|
||||||
|
withLeadCounts: false,
|
||||||
|
});
|
||||||
const stageId = dto.stageId || stages[0]?.id;
|
const stageId = dto.stageId || stages[0]?.id;
|
||||||
if (!stageId) throw new BadRequestException('مرحلهای تعریف نشده');
|
if (!stageId) throw new BadRequestException('مرحلهای تعریف نشده');
|
||||||
|
|
||||||
@@ -424,6 +610,9 @@ export class LeadsService {
|
|||||||
addresses: toJsonAddresses(dto.addresses),
|
addresses: toJsonAddresses(dto.addresses),
|
||||||
trade: emptyToNull(dto.trade),
|
trade: emptyToNull(dto.trade),
|
||||||
source: emptyToNull(dto.source),
|
source: emptyToNull(dto.source),
|
||||||
|
activityExperience:
|
||||||
|
normalizeActivityExperience(dto.activityExperience) ??
|
||||||
|
emptyToNull(dto.activityExperience),
|
||||||
notes: emptyToNull(dto.notes),
|
notes: emptyToNull(dto.notes),
|
||||||
estimatedValue:
|
estimatedValue:
|
||||||
dto.estimatedValue != null
|
dto.estimatedValue != null
|
||||||
@@ -442,7 +631,10 @@ export class LeadsService {
|
|||||||
include: leadInclude,
|
include: leadInclude,
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null);
|
await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null, {
|
||||||
|
stageId: row.stageId,
|
||||||
|
stageName: row.stage.name,
|
||||||
|
});
|
||||||
if (assigneeId) {
|
if (assigneeId) {
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
@@ -552,6 +744,13 @@ export class LeadsService {
|
|||||||
...(dto.source !== undefined
|
...(dto.source !== undefined
|
||||||
? { source: emptyToNull(dto.source as string) }
|
? { source: emptyToNull(dto.source as string) }
|
||||||
: {}),
|
: {}),
|
||||||
|
...(dto.activityExperience !== undefined
|
||||||
|
? {
|
||||||
|
activityExperience:
|
||||||
|
normalizeActivityExperience(dto.activityExperience as string | null) ??
|
||||||
|
emptyToNull(dto.activityExperience as string),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
...(dto.notes !== undefined
|
...(dto.notes !== undefined
|
||||||
? { notes: emptyToNull(dto.notes as string) }
|
? { notes: emptyToNull(dto.notes as string) }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -597,11 +796,22 @@ export class LeadsService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (typeof dto.stageId === 'string' && dto.stageId !== existing.stageId) {
|
if (typeof dto.stageId === 'string' && dto.stageId !== existing.stageId) {
|
||||||
|
const reason = this.requireStageReason(
|
||||||
|
typeof dto.reason === 'string' ? dto.reason : null,
|
||||||
|
);
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
id,
|
id,
|
||||||
'stage_changed',
|
'stage_changed',
|
||||||
`وضعیت به «${row.stage.name}» تغییر کرد`,
|
`وضعیت به «${row.stage.name}» تغییر کرد`,
|
||||||
|
reason,
|
||||||
|
{
|
||||||
|
fromStageId: existing.stageId,
|
||||||
|
fromStageName: existing.stage?.name ?? null,
|
||||||
|
toStageId: row.stageId,
|
||||||
|
toStageName: row.stage.name,
|
||||||
|
reason,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
||||||
eventKey: `${id}:${row.stageId}`,
|
eventKey: `${id}:${row.stageId}`,
|
||||||
@@ -616,6 +826,7 @@ export class LeadsService {
|
|||||||
id: string,
|
id: string,
|
||||||
stageId: string,
|
stageId: string,
|
||||||
position?: number,
|
position?: number,
|
||||||
|
reasonRaw?: string | null,
|
||||||
): Promise<LeadDto> {
|
): Promise<LeadDto> {
|
||||||
const before = await this.findAccessible(actor, id);
|
const before = await this.findAccessible(actor, id);
|
||||||
const stage = await this.prisma.leadStage.findFirst({
|
const stage = await this.prisma.leadStage.findFirst({
|
||||||
@@ -623,6 +834,9 @@ export class LeadsService {
|
|||||||
});
|
});
|
||||||
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
|
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
|
||||||
|
|
||||||
|
const stageChanged = before.stageId !== stageId;
|
||||||
|
const reason = stageChanged ? this.requireStageReason(reasonRaw) : null;
|
||||||
|
|
||||||
let placedIds: string[] | null = null;
|
let placedIds: string[] | null = null;
|
||||||
let nextPosition = position ?? 0;
|
let nextPosition = position ?? 0;
|
||||||
if (position != null) {
|
if (position != null) {
|
||||||
@@ -653,12 +867,20 @@ export class LeadsService {
|
|||||||
this.prisma.lead.update({ where: { id: leadId }, data: { position: leadPosition } }),
|
this.prisma.lead.update({ where: { id: leadId }, data: { position: leadPosition } }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (before.stageId !== stageId) {
|
if (stageChanged && reason) {
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
id,
|
id,
|
||||||
'stage_changed',
|
'stage_changed',
|
||||||
`به مرحله «${stage.name}» منتقل شد`,
|
`به مرحله «${stage.name}» منتقل شد`,
|
||||||
|
reason,
|
||||||
|
{
|
||||||
|
fromStageId: before.stageId,
|
||||||
|
fromStageName: before.stage?.name ?? null,
|
||||||
|
toStageId: stageId,
|
||||||
|
toStageName: stage.name,
|
||||||
|
reason,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
|
||||||
eventKey: `${id}:${stageId}`,
|
eventKey: `${id}:${stageId}`,
|
||||||
@@ -709,7 +931,9 @@ export class LeadsService {
|
|||||||
actor: Actor,
|
actor: Actor,
|
||||||
leadIds: string[],
|
leadIds: string[],
|
||||||
stageId: string,
|
stageId: string,
|
||||||
|
reasonRaw?: string | null,
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
|
const reason = this.requireStageReason(reasonRaw);
|
||||||
if (!elevated(actor.role)) {
|
if (!elevated(actor.role)) {
|
||||||
throw new BadRequestException('فقط مدیر میتواند وضعیت گروهی تغییر دهد');
|
throw new BadRequestException('فقط مدیر میتواند وضعیت گروهی تغییر دهد');
|
||||||
}
|
}
|
||||||
@@ -717,6 +941,18 @@ export class LeadsService {
|
|||||||
where: { id: stageId, organizationId: actor.organizationId },
|
where: { id: stageId, organizationId: actor.organizationId },
|
||||||
});
|
});
|
||||||
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
|
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
|
||||||
|
const beforeRows = await this.prisma.lead.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
id: { in: leadIds },
|
||||||
|
archivedAt: null,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
stageId: true,
|
||||||
|
stage: { select: { name: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
const result = await this.prisma.lead.updateMany({
|
const result = await this.prisma.lead.updateMany({
|
||||||
where: {
|
where: {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
@@ -725,12 +961,21 @@ export class LeadsService {
|
|||||||
},
|
},
|
||||||
data: { stageId },
|
data: { stageId },
|
||||||
});
|
});
|
||||||
for (const leadId of leadIds) {
|
for (const lead of beforeRows) {
|
||||||
|
if (lead.stageId === stageId) continue;
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
leadId,
|
lead.id,
|
||||||
'stage_changed',
|
'stage_changed',
|
||||||
`وضعیت گروهی به «${stage.name}»`,
|
`وضعیت گروهی به «${stage.name}»`,
|
||||||
|
reason,
|
||||||
|
{
|
||||||
|
fromStageId: lead.stageId,
|
||||||
|
fromStageName: lead.stage.name,
|
||||||
|
toStageId: stageId,
|
||||||
|
toStageName: stage.name,
|
||||||
|
reason,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return result.count;
|
return result.count;
|
||||||
@@ -1016,6 +1261,7 @@ export class LeadsService {
|
|||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join('\n'),
|
.join('\n'),
|
||||||
|
activityExperience: lead.activityExperience,
|
||||||
ownerId: lead.assigneeId ?? actor.userId,
|
ownerId: lead.assigneeId ?? actor.userId,
|
||||||
createdAt: lead.createdAt,
|
createdAt: lead.createdAt,
|
||||||
importSource: 'lead_form',
|
importSource: 'lead_form',
|
||||||
@@ -1023,11 +1269,23 @@ export class LeadsService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
createdPerson = true;
|
createdPerson = true;
|
||||||
} else if (!person.birthDate && lead.birthDate) {
|
} else {
|
||||||
await this.prisma.person.update({
|
const personPatch: {
|
||||||
where: { id: person.id },
|
birthDate?: Date | null;
|
||||||
data: { birthDate: lead.birthDate },
|
activityExperience?: string | null;
|
||||||
});
|
} = {};
|
||||||
|
if (!person.birthDate && lead.birthDate) {
|
||||||
|
personPatch.birthDate = lead.birthDate;
|
||||||
|
}
|
||||||
|
if (!person.activityExperience && lead.activityExperience) {
|
||||||
|
personPatch.activityExperience = lead.activityExperience;
|
||||||
|
}
|
||||||
|
if (Object.keys(personPatch).length) {
|
||||||
|
await this.prisma.person.update({
|
||||||
|
where: { id: person.id },
|
||||||
|
data: personPatch,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const convertedStage = await this.prisma.leadStage.findFirst({
|
const convertedStage = await this.prisma.leadStage.findFirst({
|
||||||
@@ -1045,6 +1303,22 @@ export class LeadsService {
|
|||||||
include: leadInclude,
|
include: leadInclude,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (convertedStage && convertedStage.id !== lead.stageId) {
|
||||||
|
await this.addEvent(
|
||||||
|
actor,
|
||||||
|
id,
|
||||||
|
'stage_changed',
|
||||||
|
`وضعیت به «${convertedStage.name}» تغییر کرد`,
|
||||||
|
null,
|
||||||
|
{
|
||||||
|
fromStageId: lead.stageId,
|
||||||
|
fromStageName: lead.stage?.name ?? null,
|
||||||
|
toStageId: convertedStage.id,
|
||||||
|
toStageName: convertedStage.name,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
await this.addEvent(
|
await this.addEvent(
|
||||||
actor,
|
actor,
|
||||||
id,
|
id,
|
||||||
@@ -1094,7 +1368,9 @@ export class LeadsService {
|
|||||||
...leadAccessWhere(actor),
|
...leadAccessWhere(actor),
|
||||||
archivedAt: null,
|
archivedAt: null,
|
||||||
};
|
};
|
||||||
const stages = await this.stages.list(actor.organizationId);
|
const stages = await this.stages.list(actor.organizationId, {
|
||||||
|
withLeadCounts: false,
|
||||||
|
});
|
||||||
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
|
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
|
||||||
const lostIds = stages.filter((s) => s.isLost).map((s) => s.id);
|
const lostIds = stages.filter((s) => s.isLost).map((s) => s.id);
|
||||||
// همان مقصد فرم و ورود از اکسل: اولین ستون باز، مستقل از اسم «جدید»
|
// همان مقصد فرم و ورود از اکسل: اولین ستون باز، مستقل از اسم «جدید»
|
||||||
@@ -1116,7 +1392,7 @@ export class LeadsService {
|
|||||||
newStage
|
newStage
|
||||||
? this.prisma.lead.count({ where: { ...base, stageId: newStage.id } })
|
? this.prisma.lead.count({ where: { ...base, stageId: newStage.id } })
|
||||||
: Promise.resolve(0),
|
: Promise.resolve(0),
|
||||||
this.prisma.lead.count({ where: { ...base, assigneeId: null } }),
|
this.prisma.lead.count({ where: { AND: [base, { assigneeId: null }] } }),
|
||||||
convertedIds.length
|
convertedIds.length
|
||||||
? this.prisma.lead.count({
|
? this.prisma.lead.count({
|
||||||
where: { ...base, stageId: { in: convertedIds } },
|
where: { ...base, stageId: { in: convertedIds } },
|
||||||
@@ -1236,7 +1512,9 @@ export class LeadsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.stages.ensureDefaults(input.organizationId);
|
await this.stages.ensureDefaults(input.organizationId);
|
||||||
const stages = await this.stages.list(input.organizationId);
|
const stages = await this.stages.list(input.organizationId, {
|
||||||
|
withLeadCounts: false,
|
||||||
|
});
|
||||||
const stageId = stages[0]?.id;
|
const stageId = stages[0]?.id;
|
||||||
if (!stageId) throw new BadRequestException('مرحلهای تعریف نشده');
|
if (!stageId) throw new BadRequestException('مرحلهای تعریف نشده');
|
||||||
|
|
||||||
@@ -1374,6 +1652,17 @@ export class LeadsService {
|
|||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private requireStageReason(raw: string | null | undefined): string {
|
||||||
|
const reason = String(raw ?? '').trim();
|
||||||
|
if (!reason) {
|
||||||
|
throw new BadRequestException('دلیل تغییر ستون الزامی است.');
|
||||||
|
}
|
||||||
|
if (reason.length > 1000) {
|
||||||
|
throw new BadRequestException('دلیل تغییر ستون نباید بیش از ۱۰۰۰ کاراکتر باشد.');
|
||||||
|
}
|
||||||
|
return reason;
|
||||||
|
}
|
||||||
|
|
||||||
private async addEvent(
|
private async addEvent(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
leadId: string,
|
leadId: string,
|
||||||
@@ -1417,6 +1706,9 @@ export class LeadsService {
|
|||||||
addresses: asAddresses(row.addresses),
|
addresses: asAddresses(row.addresses),
|
||||||
trade: row.trade,
|
trade: row.trade,
|
||||||
source: row.source,
|
source: row.source,
|
||||||
|
activityExperience:
|
||||||
|
row.activityExperience ||
|
||||||
|
extractActivityExperienceFromNotes(row.notes),
|
||||||
notes: row.notes,
|
notes: row.notes,
|
||||||
estimatedValue:
|
estimatedValue:
|
||||||
row.estimatedValue != null ? Number(row.estimatedValue) : null,
|
row.estimatedValue != null ? Number(row.estimatedValue) : null,
|
||||||
@@ -1437,6 +1729,49 @@ export class LeadsService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private toBoardDto(row: BoardLeadRow, stageName: string): LeadDto {
|
||||||
|
const daysInStage = Math.max(
|
||||||
|
0,
|
||||||
|
Math.floor(
|
||||||
|
(Date.now() - row.updatedAt.getTime()) / (24 * 60 * 60 * 1000),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
contactName: row.contactName,
|
||||||
|
gender: row.gender === 'male' || row.gender === 'female' ? row.gender : 'none',
|
||||||
|
showGenderInName: row.showGenderInName,
|
||||||
|
mobile: row.mobile,
|
||||||
|
phone: row.phone,
|
||||||
|
city: row.city,
|
||||||
|
region: row.region,
|
||||||
|
instagram: row.instagram,
|
||||||
|
birthDate: row.birthDate?.toISOString() ?? null,
|
||||||
|
addresses: [],
|
||||||
|
trade: row.trade,
|
||||||
|
source: row.source,
|
||||||
|
activityExperience: row.activityExperience,
|
||||||
|
notes: null,
|
||||||
|
estimatedValue:
|
||||||
|
row.estimatedValue != null ? Number(row.estimatedValue) : null,
|
||||||
|
stageId: row.stageId,
|
||||||
|
stageName,
|
||||||
|
position: row.position,
|
||||||
|
assigneeId: row.assigneeId,
|
||||||
|
assigneeName: row.assignee?.fullName ?? null,
|
||||||
|
lastContactAt: row.lastContactAt?.toISOString() ?? null,
|
||||||
|
nextFollowUpAt: row.nextFollowUpAt?.toISOString() ?? null,
|
||||||
|
convertedPersonId: row.convertedPersonId,
|
||||||
|
convertedAt: row.convertedAt?.toISOString() ?? null,
|
||||||
|
archivedAt: row.archivedAt?.toISOString() ?? null,
|
||||||
|
daysInStage,
|
||||||
|
hasLogo: Boolean(row.logoStorageKey),
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async saveLogo(
|
async saveLogo(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
id: string,
|
id: string,
|
||||||
@@ -1499,11 +1834,16 @@ export class LeadsService {
|
|||||||
const mobile = lead.mobile || lead.phone;
|
const mobile = lead.mobile || lead.phone;
|
||||||
if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.');
|
if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.');
|
||||||
const name = (lead.contactName || lead.title).trim();
|
const name = (lead.contactName || lead.title).trim();
|
||||||
|
const org = await this.prisma.organization.findUnique({
|
||||||
|
where: { id: actor.organizationId },
|
||||||
|
select: { name: true },
|
||||||
|
});
|
||||||
const message = renderSmsText(body, {
|
const message = renderSmsText(body, {
|
||||||
name,
|
name,
|
||||||
phone: mobile,
|
phone: mobile,
|
||||||
title: lead.title,
|
title: lead.title,
|
||||||
company: lead.contactName ? lead.title : '',
|
company: lead.trade?.trim() || '',
|
||||||
|
from: org?.name?.trim() || '',
|
||||||
});
|
});
|
||||||
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
if (!message) throw new BadRequestException('متن پیامک خالی است.');
|
||||||
const result = await this.sms.send({
|
const result = await this.sms.send({
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
ForbiddenException,
|
ForbiddenException,
|
||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
@@ -70,6 +71,16 @@ export class MembershipsService {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** هر محیط یک مالک فعال دارد: همان کسی که محیط را ثبت کرده. */
|
||||||
|
async assertSoleOwner(organizationId: string, userId: string) {
|
||||||
|
const others = await this.countActiveOwners(organizationId, userId);
|
||||||
|
if (others > 0) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'هر محیط فقط یک مالک دارد و مالک همان کسی است که ثبتنام کرده. برای دسترسی کامل نقش مدیر را انتخاب کنید.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async createMembership(data: {
|
async createMembership(data: {
|
||||||
userId: string;
|
userId: string;
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
@@ -78,6 +89,9 @@ export class MembershipsService {
|
|||||||
commissionPercent?: number;
|
commissionPercent?: number;
|
||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
}) {
|
}) {
|
||||||
|
if (data.role === 'owner' && data.isActive !== false) {
|
||||||
|
await this.assertSoleOwner(data.organizationId, data.userId);
|
||||||
|
}
|
||||||
return this.prisma.membership.create({
|
return this.prisma.membership.create({
|
||||||
data: {
|
data: {
|
||||||
userId: data.userId,
|
userId: data.userId,
|
||||||
|
|||||||
@@ -56,7 +56,19 @@ function testTemplate() {
|
|||||||
}) === 'سلام علی 0912',
|
}) === 'سلام علی 0912',
|
||||||
'name phone vars',
|
'name phone vars',
|
||||||
);
|
);
|
||||||
assert(clipSms('الف'.repeat(200)).length === 200, 'sms is not clipped');
|
assert(
|
||||||
|
applyMessageTemplate('تبریک {از طرف}', { from: 'هنراندیشه' }) ===
|
||||||
|
'تبریک هنراندیشه',
|
||||||
|
'from org var',
|
||||||
|
);
|
||||||
|
assert(
|
||||||
|
applyMessageTemplate('مانده {مانده ریالی} / {مانده فلزی}', {
|
||||||
|
rialBalance: '۱۰۰۰ بس',
|
||||||
|
metalBalance: 'طلا ۲',
|
||||||
|
}) === 'مانده ۱۰۰۰ بس / طلا ۲',
|
||||||
|
'balance vars',
|
||||||
|
);
|
||||||
|
assert(clipSms('ا'.repeat(200)).length === 200, 'sms is not clipped');
|
||||||
}
|
}
|
||||||
|
|
||||||
testDelay();
|
testDelay();
|
||||||
|
|||||||
@@ -77,6 +77,17 @@ export function buildSendAts(
|
|||||||
return times;
|
return times;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** یکسانسازی کلید توکنهای قالب (فاصله/ZWNJ/ی عربی). */
|
||||||
|
export function normalizeTemplateKey(key: string): string {
|
||||||
|
return String(key ?? '')
|
||||||
|
.normalize('NFKC')
|
||||||
|
.replace(/[\u200c\u200d\u200e\u200f\ufeff]/g, '')
|
||||||
|
.replace(/ي/g, 'ی')
|
||||||
|
.replace(/ك/g, 'ک')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
export function applyMessageTemplate(
|
export function applyMessageTemplate(
|
||||||
text: string,
|
text: string,
|
||||||
vars: {
|
vars: {
|
||||||
@@ -85,22 +96,44 @@ export function applyMessageTemplate(
|
|||||||
phone?: string;
|
phone?: string;
|
||||||
date?: string;
|
date?: string;
|
||||||
company?: string;
|
company?: string;
|
||||||
|
/** نام سازمان فرستنده */
|
||||||
|
from?: string;
|
||||||
|
/** مانده مالی قالببندیشده */
|
||||||
|
rialBalance?: string;
|
||||||
|
/** ماندههای وزنی/فلزی قالببندیشده */
|
||||||
|
metalBalance?: string;
|
||||||
},
|
},
|
||||||
): string {
|
): string {
|
||||||
const map: Record<string, string> = {
|
const from = vars.from ?? '';
|
||||||
title: vars.title ?? '',
|
const rial = vars.rialBalance ?? '';
|
||||||
عنوان: vars.title ?? '',
|
const metal = vars.metalBalance ?? '';
|
||||||
نام: vars.name ?? '',
|
const entries: Array<[string, string]> = [
|
||||||
name: vars.name ?? '',
|
['title', vars.title ?? ''],
|
||||||
شماره: vars.phone ?? '',
|
['عنوان', vars.title ?? ''],
|
||||||
phone: vars.phone ?? '',
|
['نام', vars.name ?? ''],
|
||||||
تاریخ: vars.date ?? '',
|
['name', vars.name ?? ''],
|
||||||
date: vars.date ?? '',
|
['شماره', vars.phone ?? ''],
|
||||||
شرکت: vars.company ?? '',
|
['phone', vars.phone ?? ''],
|
||||||
company: vars.company ?? '',
|
['تاریخ', vars.date ?? ''],
|
||||||
};
|
['date', vars.date ?? ''],
|
||||||
|
['شرکت', vars.company ?? ''],
|
||||||
|
['company', vars.company ?? ''],
|
||||||
|
['از طرف', from],
|
||||||
|
['ازطرف', from],
|
||||||
|
['from', from],
|
||||||
|
['مانده ریالی', rial],
|
||||||
|
['ماندهریالی', rial],
|
||||||
|
['rialBalance', rial],
|
||||||
|
['مانده فلزی', metal],
|
||||||
|
['ماندهفلزی', metal],
|
||||||
|
['metalBalance', metal],
|
||||||
|
];
|
||||||
|
const map: Record<string, string> = {};
|
||||||
|
for (const [key, value] of entries) {
|
||||||
|
map[normalizeTemplateKey(key)] = value;
|
||||||
|
}
|
||||||
return text.replace(/\{([^}]+)\}/g, (full, key: string) => {
|
return text.replace(/\{([^}]+)\}/g, (full, key: string) => {
|
||||||
const next = map[key.trim()];
|
const next = map[normalizeTemplateKey(key)];
|
||||||
return next === undefined ? full : next;
|
return next === undefined ? full : next;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -356,6 +356,10 @@ export class MessageAutomationsService {
|
|||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
const lead = await this.lookupLead(job);
|
const lead = await this.lookupLead(job);
|
||||||
|
const org = await this.prisma.organization.findUnique({
|
||||||
|
where: { id: job.organizationId },
|
||||||
|
select: { name: true },
|
||||||
|
});
|
||||||
const personName = person
|
const personName = person
|
||||||
? [person.firstName, person.lastName].filter(Boolean).join(' ').trim()
|
? [person.firstName, person.lastName].filter(Boolean).join(' ').trim()
|
||||||
: '';
|
: '';
|
||||||
@@ -366,6 +370,7 @@ export class MessageAutomationsService {
|
|||||||
phone,
|
phone,
|
||||||
date: formatJalaliDayFa(new Date()),
|
date: formatJalaliDayFa(new Date()),
|
||||||
company: person?.company?.name ?? '',
|
company: person?.company?.name ?? '',
|
||||||
|
from: org?.name?.trim() || '',
|
||||||
};
|
};
|
||||||
const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200);
|
const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200);
|
||||||
const body = applyMessageTemplate(job.rule.body, vars);
|
const body = applyMessageTemplate(job.rule.body, vars);
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { OutboundSmsLogService } from './outbound-sms-log.service';
|
import { OutboundSmsLogService } from './outbound-sms-log.service';
|
||||||
|
import { SmsTemplatesController } from './sms-templates.controller';
|
||||||
|
import { SmsTemplatesService } from './sms-templates.service';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
providers: [OutboundSmsLogService],
|
controllers: [SmsTemplatesController],
|
||||||
exports: [OutboundSmsLogService],
|
providers: [OutboundSmsLogService, SmsTemplatesService],
|
||||||
|
exports: [OutboundSmsLogService, SmsTemplatesService],
|
||||||
})
|
})
|
||||||
export class OutboundSmsModule {}
|
export class OutboundSmsModule {}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
|
import type { Actor } from '../common/record-scope';
|
||||||
|
import {
|
||||||
|
CreateSmsTemplateDto,
|
||||||
|
UpdateSmsTemplateDto,
|
||||||
|
} from './sms-templates.dto';
|
||||||
|
import { SmsTemplatesService } from './sms-templates.service';
|
||||||
|
|
||||||
|
@Controller('sms-templates')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
export class SmsTemplatesController {
|
||||||
|
constructor(private readonly templates: SmsTemplatesService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
list(@CurrentUser() user: Actor) {
|
||||||
|
return this.templates.list(user.organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
create(@CurrentUser() user: Actor, @Body() dto: CreateSmsTemplateDto) {
|
||||||
|
return this.templates.create(user.organizationId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
update(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateSmsTemplateDto,
|
||||||
|
) {
|
||||||
|
return this.templates.update(user.organizationId, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
remove(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
|
return this.templates.remove(user.organizationId, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
import { SMS_TEMPLATE_BODY_MAX, SMS_TEMPLATE_NAME_MAX } from '@mento/shared';
|
||||||
|
|
||||||
|
export class CreateSmsTemplateDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(SMS_TEMPLATE_NAME_MAX)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(SMS_TEMPLATE_BODY_MAX)
|
||||||
|
body!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateSmsTemplateDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(SMS_TEMPLATE_NAME_MAX)
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(SMS_TEMPLATE_BODY_MAX)
|
||||||
|
body?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import type { Prisma } from '@prisma/client';
|
||||||
|
import {
|
||||||
|
parseSmsTemplates,
|
||||||
|
SMS_TEMPLATE_MAX,
|
||||||
|
type SmsTemplateDto,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import type {
|
||||||
|
CreateSmsTemplateDto,
|
||||||
|
UpdateSmsTemplateDto,
|
||||||
|
} from './sms-templates.dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SmsTemplatesService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async list(organizationId: string): Promise<SmsTemplateDto[]> {
|
||||||
|
const row = await this.prisma.organization.findUnique({
|
||||||
|
where: { id: organizationId },
|
||||||
|
select: { smsTemplates: true },
|
||||||
|
});
|
||||||
|
return parseSmsTemplates(row?.smsTemplates);
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(
|
||||||
|
organizationId: string,
|
||||||
|
dto: CreateSmsTemplateDto,
|
||||||
|
): Promise<SmsTemplateDto[]> {
|
||||||
|
const current = await this.list(organizationId);
|
||||||
|
if (current.length >= SMS_TEMPLATE_MAX) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`حداکثر ${SMS_TEMPLATE_MAX} پیامک آماده میتوانید داشته باشید.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const next: SmsTemplateDto[] = [
|
||||||
|
...current,
|
||||||
|
{
|
||||||
|
id: randomUUID(),
|
||||||
|
name: dto.name.trim(),
|
||||||
|
body: dto.body.trim(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return this.persist(organizationId, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
organizationId: string,
|
||||||
|
id: string,
|
||||||
|
dto: UpdateSmsTemplateDto,
|
||||||
|
): Promise<SmsTemplateDto[]> {
|
||||||
|
const current = await this.list(organizationId);
|
||||||
|
const idx = current.findIndex((item) => item.id === id);
|
||||||
|
if (idx < 0) throw new NotFoundException('پیامک آماده پیدا نشد.');
|
||||||
|
const prev = current[idx]!;
|
||||||
|
const next = [...current];
|
||||||
|
next[idx] = {
|
||||||
|
id: prev.id,
|
||||||
|
name: dto.name !== undefined ? dto.name.trim() : prev.name,
|
||||||
|
body: dto.body !== undefined ? dto.body.trim() : prev.body,
|
||||||
|
};
|
||||||
|
return this.persist(organizationId, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(organizationId: string, id: string): Promise<SmsTemplateDto[]> {
|
||||||
|
const current = await this.list(organizationId);
|
||||||
|
if (!current.some((item) => item.id === id)) {
|
||||||
|
throw new NotFoundException('پیامک آماده پیدا نشد.');
|
||||||
|
}
|
||||||
|
return this.persist(
|
||||||
|
organizationId,
|
||||||
|
current.filter((item) => item.id !== id),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async persist(
|
||||||
|
organizationId: string,
|
||||||
|
items: SmsTemplateDto[],
|
||||||
|
): Promise<SmsTemplateDto[]> {
|
||||||
|
const stored = parseSmsTemplates(items);
|
||||||
|
await this.prisma.organization.update({
|
||||||
|
where: { id: organizationId },
|
||||||
|
data: { smsTemplates: stored as unknown as Prisma.InputJsonValue },
|
||||||
|
});
|
||||||
|
return stored;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,8 +31,11 @@ export class PipelinesController {
|
|||||||
constructor(private readonly pipelinesService: PipelinesService) {}
|
constructor(private readonly pipelinesService: PipelinesService) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
list(@CurrentUser() user: { organizationId: string }) {
|
list(
|
||||||
return this.pipelinesService.list(user.organizationId);
|
@CurrentUser() user: Actor,
|
||||||
|
@Query('forLens') forLens?: string,
|
||||||
|
) {
|
||||||
|
return this.pipelinesService.list(user, forLens === '1');
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('board')
|
@Get('board')
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type {
|
import type {
|
||||||
|
ActivityStatus,
|
||||||
|
ActivityType,
|
||||||
|
DealActivityCue,
|
||||||
|
DealActivitySummaryDto,
|
||||||
DealDto,
|
DealDto,
|
||||||
MergePipelineResultDto,
|
MergePipelineResultDto,
|
||||||
PipelineBoardDto,
|
PipelineBoardDto,
|
||||||
@@ -102,24 +106,55 @@ export class PipelinesService {
|
|||||||
return this.toPipelineDto(created);
|
return this.toPipelineDto(created);
|
||||||
}
|
}
|
||||||
|
|
||||||
async list(organizationId: string): Promise<PipelineDto[]> {
|
async list(actorOrOrgId: Actor | string, forLens = false): Promise<PipelineDto[]> {
|
||||||
|
const organizationId =
|
||||||
|
typeof actorOrOrgId === 'string' ? actorOrOrgId : actorOrOrgId.organizationId;
|
||||||
|
const actor = typeof actorOrOrgId === 'string' ? undefined : actorOrOrgId;
|
||||||
await this.ensureDefaultPipeline(organizationId);
|
await this.ensureDefaultPipeline(organizationId);
|
||||||
const rows = await this.prisma.pipeline.findMany({
|
const rows = await this.prisma.pipeline.findMany({
|
||||||
where: { organizationId },
|
where: { organizationId },
|
||||||
include: { stages: { orderBy: { position: 'asc' } } },
|
include: { stages: { orderBy: { position: 'asc' } } },
|
||||||
orderBy: [{ isDefault: 'desc' }, { name: 'asc' }],
|
orderBy: [{ isDefault: 'desc' }, { name: 'asc' }],
|
||||||
});
|
});
|
||||||
const counts = await this.prisma.deal.groupBy({
|
const lens = actor?.priorLens;
|
||||||
by: ['pipelineId'],
|
const lensActive = forLens && (lens === 'current' || lens === 'archive');
|
||||||
where: { organizationId },
|
const access = actor ? dealAccessWhere(actor) : {};
|
||||||
_count: { _all: true },
|
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(
|
const dealCountByPipeline = new Map(
|
||||||
counts.map((row) => [row.pipelineId, row._count._all]),
|
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),
|
...this.toPipelineDto(row),
|
||||||
dealCount: dealCountByPipeline.get(row.id) ?? 0,
|
dealCount: lensActive
|
||||||
|
? (lensCountByPipeline.get(row.id) ?? 0)
|
||||||
|
: (dealCountByPipeline.get(row.id) ?? 0),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,12 +378,23 @@ export class PipelinesService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const rateMap = await loadOrgRates(this.prisma, organizationId);
|
const rateMap = await loadOrgRates(this.prisma, organizationId);
|
||||||
|
const activityHints = await this.loadDealActivityHints(
|
||||||
|
organizationId,
|
||||||
|
deals.map((deal) => deal.id),
|
||||||
|
);
|
||||||
|
|
||||||
const byStage = new Map<string, DealDto[]>();
|
const byStage = new Map<string, DealDto[]>();
|
||||||
for (const stage of resolved.stages) byStage.set(stage.id, []);
|
for (const stage of resolved.stages) byStage.set(stage.id, []);
|
||||||
for (const deal of deals) {
|
for (const deal of deals) {
|
||||||
const list = byStage.get(deal.stageId);
|
const list = byStage.get(deal.stageId);
|
||||||
if (list) list.push(this.toDealDto(deal));
|
if (list) {
|
||||||
|
const hint = activityHints.get(deal.id);
|
||||||
|
list.push({
|
||||||
|
...this.toDealDto(deal),
|
||||||
|
activityCue: hint?.cue ?? 'none',
|
||||||
|
activitySummaries: hint?.summaries ?? [],
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -566,6 +612,105 @@ export class PipelinesService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async loadDealActivityHints(
|
||||||
|
organizationId: string,
|
||||||
|
dealIds: string[],
|
||||||
|
): Promise<
|
||||||
|
Map<string, { cue: DealActivityCue; summaries: DealActivitySummaryDto[] }>
|
||||||
|
> {
|
||||||
|
const hints = new Map<
|
||||||
|
string,
|
||||||
|
{ cue: DealActivityCue; summaries: DealActivitySummaryDto[] }
|
||||||
|
>();
|
||||||
|
if (!dealIds.length) return hints;
|
||||||
|
|
||||||
|
const rows = await this.prisma.activity.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId,
|
||||||
|
dealId: { in: dealIds },
|
||||||
|
status: { in: ['open', 'done'] },
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
dealId: true,
|
||||||
|
title: true,
|
||||||
|
type: true,
|
||||||
|
status: true,
|
||||||
|
dueAt: true,
|
||||||
|
completedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
type Row = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
type: string;
|
||||||
|
status: 'open' | 'done';
|
||||||
|
dueAt: Date | null;
|
||||||
|
completedAt: Date | null;
|
||||||
|
};
|
||||||
|
const byDeal = new Map<string, Row[]>();
|
||||||
|
for (const row of rows) {
|
||||||
|
if (!row.dealId) continue;
|
||||||
|
const list = byDeal.get(row.dealId) ?? [];
|
||||||
|
list.push({
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
type: row.type,
|
||||||
|
status: row.status === 'done' ? 'done' : 'open',
|
||||||
|
dueAt: row.dueAt,
|
||||||
|
completedAt: row.completedAt,
|
||||||
|
});
|
||||||
|
byDeal.set(row.dealId, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const cueOf = (item: Row): Exclude<DealActivityCue, 'none'> => {
|
||||||
|
if (item.status === 'done') return 'done';
|
||||||
|
if (item.dueAt && item.dueAt.getTime() < now) return 'overdue';
|
||||||
|
return 'upcoming';
|
||||||
|
};
|
||||||
|
const rank = (cue: Exclude<DealActivityCue, 'none'>) =>
|
||||||
|
cue === 'overdue' ? 0 : cue === 'upcoming' ? 1 : 2;
|
||||||
|
|
||||||
|
for (const dealId of dealIds) {
|
||||||
|
const list = byDeal.get(dealId) ?? [];
|
||||||
|
const summaries = list
|
||||||
|
.map((item) => {
|
||||||
|
const cue = cueOf(item);
|
||||||
|
return {
|
||||||
|
id: item.id,
|
||||||
|
title: item.title,
|
||||||
|
type: item.type as ActivityType,
|
||||||
|
status: item.status as ActivityStatus,
|
||||||
|
dueAt: item.dueAt?.toISOString() ?? null,
|
||||||
|
cue,
|
||||||
|
_due: item.dueAt?.getTime() ?? Number.POSITIVE_INFINITY,
|
||||||
|
_done: item.completedAt?.getTime() ?? 0,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) => {
|
||||||
|
const byRank = rank(a.cue) - rank(b.cue);
|
||||||
|
if (byRank) return byRank;
|
||||||
|
if (a.cue === 'done' && b.cue === 'done') return b._done - a._done;
|
||||||
|
return a._due - b._due;
|
||||||
|
})
|
||||||
|
.map(({ _due: _d, _done: _c, ...summary }) => summary);
|
||||||
|
|
||||||
|
const open = list.filter((item) => item.status === 'open');
|
||||||
|
let cue: DealActivityCue = 'none';
|
||||||
|
if (open.some((item) => item.dueAt && item.dueAt.getTime() < now)) {
|
||||||
|
cue = 'overdue';
|
||||||
|
} else if (open.length) {
|
||||||
|
cue = 'upcoming';
|
||||||
|
} else if (list.some((item) => item.status === 'done')) {
|
||||||
|
cue = 'done';
|
||||||
|
}
|
||||||
|
hints.set(dealId, { cue, summaries });
|
||||||
|
}
|
||||||
|
return hints;
|
||||||
|
}
|
||||||
|
|
||||||
toDealDto(row: DealRow): DealDto {
|
toDealDto(row: DealRow): DealDto {
|
||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
MinLength,
|
MinLength,
|
||||||
ValidateIf,
|
ValidateIf,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { USER_ROLES, type UserRole } from '@mento/shared';
|
import { PRODUCT_PLAN_CODES, USER_ROLES, type ProductPlanCode, type UserRole } from '@mento/shared';
|
||||||
|
|
||||||
export class PlatformLoginDto {
|
export class PlatformLoginDto {
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -189,6 +189,11 @@ export class SetStorageQuotaDto {
|
|||||||
quotaGb!: number | null;
|
quotaGb!: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class ApplyProductPlanDto {
|
||||||
|
@IsIn(PRODUCT_PLAN_CODES)
|
||||||
|
planCode!: ProductPlanCode;
|
||||||
|
}
|
||||||
|
|
||||||
export class UpdateOrgModulesDto {
|
export class UpdateOrgModulesDto {
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
import {
|
import {
|
||||||
ApplyBillingPlanDto,
|
ApplyBillingPlanDto,
|
||||||
|
ApplyProductPlanDto,
|
||||||
SetStorageQuotaDto,
|
SetStorageQuotaDto,
|
||||||
SetUserCapDto,
|
SetUserCapDto,
|
||||||
CreatePlatformAdminDto,
|
CreatePlatformAdminDto,
|
||||||
@@ -168,6 +169,11 @@ export class PlatformController {
|
|||||||
return this.platform.setUserCap(id, dto.maxUsers);
|
return this.platform.setUserCap(id, dto.maxUsers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('organizations/:id/product-plan')
|
||||||
|
applyProductPlan(@Param('id') id: string, @Body() dto: ApplyProductPlanDto) {
|
||||||
|
return this.platform.applyProductPlan(id, dto.planCode);
|
||||||
|
}
|
||||||
|
|
||||||
@Patch('organizations/:id/modules')
|
@Patch('organizations/:id/modules')
|
||||||
updateOrganizationModules(
|
updateOrganizationModules(
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
PlatformOrganizationDto,
|
PlatformOrganizationDto,
|
||||||
PlatformStatsDto,
|
PlatformStatsDto,
|
||||||
PlatformUserDto,
|
PlatformUserDto,
|
||||||
|
ProductPlanCode,
|
||||||
UserRole,
|
UserRole,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { isBusinessField } from '@mento/shared';
|
import { isBusinessField } from '@mento/shared';
|
||||||
@@ -472,6 +473,16 @@ export class PlatformService {
|
|||||||
return this.getUser(userId);
|
return this.getUser(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async applyProductPlan(id: string, planCode: ProductPlanCode) {
|
||||||
|
const existing = await this.prisma.organization.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!existing) throw new NotFoundException('محیط پیدا نشد');
|
||||||
|
await this.billing.applyProductPlan(id, planCode);
|
||||||
|
return this.getOrganization(id);
|
||||||
|
}
|
||||||
|
|
||||||
async updateOrganizationModules(id: string, dto: UpdateOrgModulesDto) {
|
async updateOrganizationModules(id: string, dto: UpdateOrgModulesDto) {
|
||||||
const existing = await this.prisma.organization.findUnique({
|
const existing = await this.prisma.organization.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
@@ -532,6 +543,9 @@ export class PlatformService {
|
|||||||
});
|
});
|
||||||
if (!row) throw new NotFoundException('عضویت پیدا نشد');
|
if (!row) throw new NotFoundException('عضویت پیدا نشد');
|
||||||
if (isActive && !row.isActive) {
|
if (isActive && !row.isActive) {
|
||||||
|
if (row.role === 'owner') {
|
||||||
|
await this.memberships.assertSoleOwner(row.organizationId, row.userId);
|
||||||
|
}
|
||||||
await this.billing.assertSeatAvailable(row.organizationId, row.userId);
|
await this.billing.assertSeatAvailable(row.organizationId, row.userId);
|
||||||
}
|
}
|
||||||
if (!isActive && row.role === 'owner') {
|
if (!isActive && row.role === 'owner') {
|
||||||
@@ -562,6 +576,9 @@ export class PlatformService {
|
|||||||
});
|
});
|
||||||
if (!row) throw new NotFoundException('عضویت پیدا نشد');
|
if (!row) throw new NotFoundException('عضویت پیدا نشد');
|
||||||
|
|
||||||
|
if (role === 'owner' && row.role !== 'owner') {
|
||||||
|
await this.memberships.assertSoleOwner(row.organizationId, row.userId);
|
||||||
|
}
|
||||||
if (row.role === 'owner' && role !== 'owner') {
|
if (row.role === 'owner' && role !== 'owner') {
|
||||||
const owners = await this.memberships.countActiveOwners(
|
const owners = await this.memberships.countActiveOwners(
|
||||||
row.organizationId,
|
row.organizationId,
|
||||||
@@ -569,7 +586,7 @@ export class PlatformService {
|
|||||||
);
|
);
|
||||||
if (owners < 1) {
|
if (owners < 1) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'حداقل یک مالک برای سازمان لازم است؛ ابتدا مالک دیگری تعیین کنید',
|
'مالک محیط همان کسی است که ثبتنام کرده و نمیتوان نقش او را عوض کرد',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/** بازهٔ ماندن یک لید در یک مرحله */
|
||||||
|
export type LeadStageStay = {
|
||||||
|
stageId: string;
|
||||||
|
fromMs: number;
|
||||||
|
toMs: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type StageChangeMeta = {
|
||||||
|
fromStageId?: string | null;
|
||||||
|
toStageId?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function asMeta(raw: unknown): StageChangeMeta {
|
||||||
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||||
|
const obj = raw as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
fromStageId:
|
||||||
|
typeof obj.fromStageId === 'string' ? obj.fromStageId : null,
|
||||||
|
toStageId: typeof obj.toStageId === 'string' ? obj.toStageId : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* از رویدادهای لید، بازههای ماندن در هر مرحله را میسازد.
|
||||||
|
* برای دادهٔ قدیمی بدون meta، فقط toStage از meta یا ترتیب رویدادها استفاده میشود.
|
||||||
|
*/
|
||||||
|
export function buildLeadStageStays(input: {
|
||||||
|
leadId: string;
|
||||||
|
currentStageId: string;
|
||||||
|
createdAt: Date;
|
||||||
|
convertedAt: Date | null;
|
||||||
|
archivedAt: Date | null;
|
||||||
|
events: Array<{ type: string; createdAt: Date; meta: unknown }>;
|
||||||
|
nowMs?: number;
|
||||||
|
}): LeadStageStay[] {
|
||||||
|
const nowMs = input.nowMs ?? Date.now();
|
||||||
|
const endCap = Math.min(
|
||||||
|
nowMs,
|
||||||
|
input.convertedAt?.getTime() ?? Number.POSITIVE_INFINITY,
|
||||||
|
input.archivedAt?.getTime() ?? Number.POSITIVE_INFINITY,
|
||||||
|
);
|
||||||
|
|
||||||
|
type Point = { at: number; stageId: string | null };
|
||||||
|
const points: Point[] = [{ at: input.createdAt.getTime(), stageId: null }];
|
||||||
|
|
||||||
|
const timeline = [...input.events].sort(
|
||||||
|
(a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
|
||||||
|
);
|
||||||
|
for (const ev of timeline) {
|
||||||
|
if (ev.type === 'created') {
|
||||||
|
const meta = asMeta(ev.meta);
|
||||||
|
const rawStage =
|
||||||
|
meta.toStageId ||
|
||||||
|
(ev.meta &&
|
||||||
|
typeof ev.meta === 'object' &&
|
||||||
|
!Array.isArray(ev.meta) &&
|
||||||
|
typeof (ev.meta as { stageId?: unknown }).stageId === 'string'
|
||||||
|
? String((ev.meta as { stageId: string }).stageId)
|
||||||
|
: null);
|
||||||
|
if (rawStage) {
|
||||||
|
points[0] = { at: ev.createdAt.getTime(), stageId: rawStage };
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ev.type !== 'stage_changed') continue;
|
||||||
|
const meta = asMeta(ev.meta);
|
||||||
|
const toStageId = meta.toStageId;
|
||||||
|
if (!toStageId) continue;
|
||||||
|
points.push({ at: ev.createdAt.getTime(), stageId: toStageId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// اگر نقطهٔ اول stage نداشت، از اولین stage_changed یا مرحلهٔ فعلی استفاده کن
|
||||||
|
if (!points[0]?.stageId) {
|
||||||
|
const firstKnown = points.find((p) => p.stageId);
|
||||||
|
points[0]!.stageId = firstKnown?.stageId ?? input.currentStageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// آخرین مرحله تا endCap ادامه دارد
|
||||||
|
const last = points[points.length - 1]!;
|
||||||
|
if (last.stageId !== input.currentStageId && !input.convertedAt && !input.archivedAt) {
|
||||||
|
// مرحلهٔ فعلی ممکن است بدون رویداد باشد (دادهٔ قدیمی)
|
||||||
|
points.push({ at: endCap, stageId: input.currentStageId });
|
||||||
|
}
|
||||||
|
|
||||||
|
const stays: LeadStageStay[] = [];
|
||||||
|
for (let i = 0; i < points.length; i++) {
|
||||||
|
const cur = points[i]!;
|
||||||
|
if (!cur.stageId) continue;
|
||||||
|
const nextAt = points[i + 1]?.at ?? endCap;
|
||||||
|
const toMs = Math.min(nextAt, endCap);
|
||||||
|
if (toMs <= cur.at) continue;
|
||||||
|
stays.push({ stageId: cur.stageId, fromMs: cur.at, toMs });
|
||||||
|
}
|
||||||
|
return stays;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hoursBetween(fromMs: number, toMs: number): number {
|
||||||
|
return Math.max(0, (toMs - fromMs) / (1000 * 60 * 60));
|
||||||
|
}
|
||||||
@@ -97,6 +97,15 @@ export class ReportsController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** قیف لید، تبدیل بینمرحلهای و میانگین ماندن در ستونها */
|
||||||
|
@Get('leads')
|
||||||
|
leads(@CurrentUser() user: Actor, @Query() query: ReportsQueryDto) {
|
||||||
|
return this.reportsService.leadsAnalytics(user, {
|
||||||
|
from: query.from,
|
||||||
|
to: query.to,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** داشبورد صفحهٔ خانه برای همه باز است */
|
/** داشبورد صفحهٔ خانه برای همه باز است */
|
||||||
@Get('home')
|
@Get('home')
|
||||||
@RequirePermission('reports', { reads: false })
|
@RequirePermission('reports', { reads: false })
|
||||||
|
|||||||
@@ -10,18 +10,22 @@ import type {
|
|||||||
ReportsDrillKind,
|
ReportsDrillKind,
|
||||||
ReportsDrilldownDto,
|
ReportsDrilldownDto,
|
||||||
ReportsFunnelStageDto,
|
ReportsFunnelStageDto,
|
||||||
|
ReportsLeadsAnalyticsDto,
|
||||||
ReportsPeriodCompareRowDto,
|
ReportsPeriodCompareRowDto,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import {
|
import {
|
||||||
|
isReportsLeadBuilderMetric,
|
||||||
REPORTS_BUILDER_DIMENSION_LABELS,
|
REPORTS_BUILDER_DIMENSION_LABELS,
|
||||||
REPORTS_BUILDER_METRIC_LABELS,
|
REPORTS_BUILDER_METRIC_LABELS,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { customersPersonWhere, leadsDeepWhere } from '../common/data-access';
|
||||||
import {
|
import {
|
||||||
type Actor,
|
type Actor,
|
||||||
assigneeWhere,
|
assigneeWhere,
|
||||||
elevated,
|
elevated,
|
||||||
|
forScope,
|
||||||
ownerWhere,
|
ownerWhere,
|
||||||
ticketAccessWhere,
|
ticketAccessWhere,
|
||||||
} from '../common/record-scope';
|
} from '../common/record-scope';
|
||||||
@@ -37,6 +41,10 @@ import {
|
|||||||
jalaliMonthName,
|
jalaliMonthName,
|
||||||
startOfJalaliMonth,
|
startOfJalaliMonth,
|
||||||
} from '../common/jalali';
|
} from '../common/jalali';
|
||||||
|
import {
|
||||||
|
buildLeadStageStays,
|
||||||
|
hoursBetween,
|
||||||
|
} from './leads-analytics.util';
|
||||||
|
|
||||||
const DRILL_LIMIT = 50;
|
const DRILL_LIMIT = 50;
|
||||||
|
|
||||||
@@ -54,7 +62,7 @@ export class ReportsService {
|
|||||||
const invoiceScope = ownerWhere(actor, 'finance');
|
const invoiceScope = ownerWhere(actor, 'finance');
|
||||||
const activityScope = assigneeWhere(actor);
|
const activityScope = assigneeWhere(actor);
|
||||||
const ticketScope = ticketAccessWhere(actor);
|
const ticketScope = ticketAccessWhere(actor);
|
||||||
const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId };
|
const personScope = customersPersonWhere(actor);
|
||||||
|
|
||||||
const durationMs = end.getTime() - start.getTime();
|
const durationMs = end.getTime() - start.getTime();
|
||||||
const prevEnd = new Date(start.getTime() - 1);
|
const prevEnd = new Date(start.getTime() - 1);
|
||||||
@@ -1204,6 +1212,230 @@ export class ReportsService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async leadsAnalytics(
|
||||||
|
actor: Actor,
|
||||||
|
opts: { from?: string; to?: string },
|
||||||
|
): Promise<ReportsLeadsAnalyticsDto> {
|
||||||
|
const { start, end } = resolveRange(opts.from, opts.to);
|
||||||
|
const orgId = actor.organizationId;
|
||||||
|
const access = this.leadAccessWhere(actor);
|
||||||
|
|
||||||
|
const stages = await this.prisma.leadStage.findMany({
|
||||||
|
where: { organizationId: orgId },
|
||||||
|
orderBy: { position: 'asc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
position: true,
|
||||||
|
isConverted: true,
|
||||||
|
isLost: true,
|
||||||
|
isUnqualified: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const stageName = new Map(stages.map((s) => [s.id, s.name]));
|
||||||
|
const lostIds = new Set(
|
||||||
|
stages.filter((s) => s.isLost || s.isUnqualified).map((s) => s.id),
|
||||||
|
);
|
||||||
|
const convertedIds = new Set(
|
||||||
|
stages.filter((s) => s.isConverted).map((s) => s.id),
|
||||||
|
);
|
||||||
|
|
||||||
|
const [created, converted, lost, activeLeads, stageEvents] =
|
||||||
|
await Promise.all([
|
||||||
|
this.prisma.lead.count({
|
||||||
|
where: {
|
||||||
|
organizationId: orgId,
|
||||||
|
...access,
|
||||||
|
createdAt: { gte: start, lte: end },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.lead.count({
|
||||||
|
where: {
|
||||||
|
organizationId: orgId,
|
||||||
|
...access,
|
||||||
|
convertedAt: { gte: start, lte: end },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.lead.count({
|
||||||
|
where: {
|
||||||
|
organizationId: orgId,
|
||||||
|
...access,
|
||||||
|
archivedAt: null,
|
||||||
|
stageId: { in: [...lostIds] },
|
||||||
|
updatedAt: { gte: start, lte: end },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.lead.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: orgId,
|
||||||
|
...access,
|
||||||
|
archivedAt: null,
|
||||||
|
convertedAt: null,
|
||||||
|
stageId: { notIn: [...lostIds, ...convertedIds] },
|
||||||
|
},
|
||||||
|
select: { id: true, stageId: true },
|
||||||
|
}),
|
||||||
|
this.prisma.leadEvent.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: orgId,
|
||||||
|
type: { in: ['created', 'stage_changed'] },
|
||||||
|
createdAt: { gte: start, lte: end },
|
||||||
|
lead: { ...access },
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
leadId: true,
|
||||||
|
type: true,
|
||||||
|
createdAt: true,
|
||||||
|
meta: true,
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const active = activeLeads.length;
|
||||||
|
const byStageCount = new Map<string, number>();
|
||||||
|
for (const lead of activeLeads) {
|
||||||
|
byStageCount.set(lead.stageId, (byStageCount.get(lead.stageId) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
const funnelTotal = active || 1;
|
||||||
|
let prevCount: number | null = null;
|
||||||
|
|
||||||
|
// ماندگاری و انتقالها از رویدادها + وضعیت فعلی لیدهای درگیر
|
||||||
|
const leadIds = [
|
||||||
|
...new Set([
|
||||||
|
...stageEvents.map((e) => e.leadId),
|
||||||
|
...activeLeads.map((l) => l.id),
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
const leadsForDwell = leadIds.length
|
||||||
|
? await this.prisma.lead.findMany({
|
||||||
|
where: { id: { in: leadIds }, organizationId: orgId, ...access },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
stageId: true,
|
||||||
|
createdAt: true,
|
||||||
|
convertedAt: true,
|
||||||
|
archivedAt: true,
|
||||||
|
events: {
|
||||||
|
where: { type: { in: ['created', 'stage_changed'] } },
|
||||||
|
select: { type: true, createdAt: true, meta: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const dwellSum = new Map<string, { hours: number; n: number }>();
|
||||||
|
const transitionCount = new Map<string, number>();
|
||||||
|
const leftFromCount = new Map<string, number>();
|
||||||
|
|
||||||
|
for (const lead of leadsForDwell) {
|
||||||
|
const stays = buildLeadStageStays({
|
||||||
|
leadId: lead.id,
|
||||||
|
currentStageId: lead.stageId,
|
||||||
|
createdAt: lead.createdAt,
|
||||||
|
convertedAt: lead.convertedAt,
|
||||||
|
archivedAt: lead.archivedAt,
|
||||||
|
events: lead.events,
|
||||||
|
});
|
||||||
|
for (const stay of stays) {
|
||||||
|
// فقط بازههایی که با بازهٔ گزارش همپوشانی دارند
|
||||||
|
const fromMs = Math.max(stay.fromMs, start.getTime());
|
||||||
|
const toMs = Math.min(stay.toMs, end.getTime());
|
||||||
|
if (toMs <= fromMs) continue;
|
||||||
|
const hours = hoursBetween(fromMs, toMs);
|
||||||
|
const cur = dwellSum.get(stay.stageId) ?? { hours: 0, n: 0 };
|
||||||
|
cur.hours += hours;
|
||||||
|
cur.n += 1;
|
||||||
|
dwellSum.set(stay.stageId, cur);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const ev of lead.events) {
|
||||||
|
if (ev.type !== 'stage_changed') continue;
|
||||||
|
if (ev.createdAt < start || ev.createdAt > end) continue;
|
||||||
|
const meta =
|
||||||
|
ev.meta && typeof ev.meta === 'object' && !Array.isArray(ev.meta)
|
||||||
|
? (ev.meta as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
const fromId =
|
||||||
|
typeof meta.fromStageId === 'string' ? meta.fromStageId : null;
|
||||||
|
const toId = typeof meta.toStageId === 'string' ? meta.toStageId : null;
|
||||||
|
if (!fromId || !toId || fromId === toId) continue;
|
||||||
|
const key = `${fromId}→${toId}`;
|
||||||
|
transitionCount.set(key, (transitionCount.get(key) ?? 0) + 1);
|
||||||
|
leftFromCount.set(fromId, (leftFromCount.get(fromId) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const funnel = stages.map((s) => {
|
||||||
|
const count = byStageCount.get(s.id) ?? 0;
|
||||||
|
const conversionFromPrevPercent =
|
||||||
|
prevCount == null
|
||||||
|
? null
|
||||||
|
: prevCount === 0
|
||||||
|
? count > 0
|
||||||
|
? 100
|
||||||
|
: 0
|
||||||
|
: Math.round((count / prevCount) * 1000) / 10;
|
||||||
|
prevCount = count;
|
||||||
|
const dwell = dwellSum.get(s.id);
|
||||||
|
return {
|
||||||
|
stageId: s.id,
|
||||||
|
stageName: s.name,
|
||||||
|
count,
|
||||||
|
sharePercent: Math.round((count / funnelTotal) * 1000) / 10,
|
||||||
|
conversionFromPrevPercent,
|
||||||
|
avgDwellHours: dwell
|
||||||
|
? Math.round((dwell.hours / dwell.n) * 10) / 10
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const transitions = [...transitionCount.entries()]
|
||||||
|
.map(([key, count]) => {
|
||||||
|
const [fromStageId, toStageId] = key.split('→');
|
||||||
|
const left = leftFromCount.get(fromStageId!) ?? 0;
|
||||||
|
return {
|
||||||
|
fromStageId: fromStageId!,
|
||||||
|
fromStageName: stageName.get(fromStageId!) ?? fromStageId!,
|
||||||
|
toStageId: toStageId!,
|
||||||
|
toStageName: stageName.get(toStageId!) ?? toStageId!,
|
||||||
|
count,
|
||||||
|
conversionPercent:
|
||||||
|
left > 0 ? Math.round((count / left) * 1000) / 10 : 0,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.count - a.count);
|
||||||
|
|
||||||
|
const dwellByStage = stages
|
||||||
|
.map((s) => {
|
||||||
|
const d = dwellSum.get(s.id);
|
||||||
|
if (!d || d.n === 0) return null;
|
||||||
|
return {
|
||||||
|
stageId: s.id,
|
||||||
|
stageName: s.name,
|
||||||
|
avgHours: Math.round((d.hours / d.n) * 10) / 10,
|
||||||
|
sampleCount: d.n,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((row): row is NonNullable<typeof row> => row != null);
|
||||||
|
|
||||||
|
const closed = converted + lost;
|
||||||
|
return {
|
||||||
|
from: start.toISOString(),
|
||||||
|
to: end.toISOString(),
|
||||||
|
created,
|
||||||
|
converted,
|
||||||
|
lost,
|
||||||
|
active,
|
||||||
|
conversionRate:
|
||||||
|
closed > 0 ? Math.round((converted / closed) * 1000) / 10 : 0,
|
||||||
|
funnel,
|
||||||
|
transitions,
|
||||||
|
dwellByStage,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async builder(
|
async builder(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
query: ReportsBuilderQuery,
|
query: ReportsBuilderQuery,
|
||||||
@@ -1225,11 +1457,16 @@ export class ReportsService {
|
|||||||
'invoice_amount',
|
'invoice_amount',
|
||||||
'invoice_count',
|
'invoice_count',
|
||||||
]);
|
]);
|
||||||
|
const leadMetric = isReportsLeadBuilderMetric(metric);
|
||||||
|
|
||||||
if (
|
if (leadMetric) {
|
||||||
|
if (dimension === 'stage') dimension = 'lead_stage';
|
||||||
|
if (dimension === 'status') dimension = 'none';
|
||||||
|
} else if (
|
||||||
!dealMetrics.has(metric) &&
|
!dealMetrics.has(metric) &&
|
||||||
(dimension === 'source' ||
|
(dimension === 'source' ||
|
||||||
dimension === 'stage' ||
|
dimension === 'stage' ||
|
||||||
|
dimension === 'lead_stage' ||
|
||||||
dimension === 'status')
|
dimension === 'status')
|
||||||
) {
|
) {
|
||||||
dimension = 'none';
|
dimension = 'none';
|
||||||
@@ -1245,6 +1482,7 @@ export class ReportsService {
|
|||||||
const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, {
|
const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, {
|
||||||
userId: query.userId,
|
userId: query.userId,
|
||||||
teamId: query.teamId,
|
teamId: query.teamId,
|
||||||
|
scope: leadMetric ? 'leads' : 'deals',
|
||||||
});
|
});
|
||||||
if (ownerFilterIds && ownerFilterIds.length === 0) {
|
if (ownerFilterIds && ownerFilterIds.length === 0) {
|
||||||
return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format);
|
return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format);
|
||||||
@@ -1309,7 +1547,7 @@ export class ReportsService {
|
|||||||
const label = normalizeSource(opts.source);
|
const label = normalizeSource(opts.source);
|
||||||
return { key: label, label };
|
return { key: label, label };
|
||||||
}
|
}
|
||||||
if (dimension === 'stage') {
|
if (dimension === 'stage' || dimension === 'lead_stage') {
|
||||||
const id = opts.stageId || 'none';
|
const id = opts.stageId || 'none';
|
||||||
return { key: id, label: opts.stageName || 'بدون مرحله' };
|
return { key: id, label: opts.stageName || 'بدون مرحله' };
|
||||||
}
|
}
|
||||||
@@ -1436,13 +1674,174 @@ export class ReportsService {
|
|||||||
add(dim.key, dim.label, amount);
|
add(dim.key, dim.label, amount);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else if (leadMetric) {
|
||||||
|
const leadAccess = this.leadAccessWhere(actor);
|
||||||
|
const assigneeFilter =
|
||||||
|
ownerFilterIds == null
|
||||||
|
? {}
|
||||||
|
: { assigneeId: { in: ownerFilterIds } };
|
||||||
|
|
||||||
|
const stages = await this.prisma.leadStage.findMany({
|
||||||
|
where: { organizationId: orgId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
isConverted: true,
|
||||||
|
isLost: true,
|
||||||
|
isUnqualified: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const lostIds = stages
|
||||||
|
.filter((s) => s.isLost || s.isUnqualified)
|
||||||
|
.map((s) => s.id);
|
||||||
|
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
|
||||||
|
|
||||||
|
if (metric === 'leads_avg_dwell_hours') {
|
||||||
|
const leads = await this.prisma.lead.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: orgId,
|
||||||
|
...leadAccess,
|
||||||
|
...assigneeFilter,
|
||||||
|
OR: [
|
||||||
|
{ createdAt: { gte: start, lte: end } },
|
||||||
|
{ updatedAt: { gte: start, lte: end } },
|
||||||
|
{ convertedAt: { gte: start, lte: end } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
stageId: true,
|
||||||
|
assigneeId: true,
|
||||||
|
source: true,
|
||||||
|
createdAt: true,
|
||||||
|
convertedAt: true,
|
||||||
|
archivedAt: true,
|
||||||
|
events: {
|
||||||
|
where: { type: { in: ['created', 'stage_changed'] } },
|
||||||
|
select: { type: true, createdAt: true, meta: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const sum = new Map<string, { hours: number; n: number; label: string }>();
|
||||||
|
for (const lead of leads) {
|
||||||
|
const stays = buildLeadStageStays({
|
||||||
|
leadId: lead.id,
|
||||||
|
currentStageId: lead.stageId,
|
||||||
|
createdAt: lead.createdAt,
|
||||||
|
convertedAt: lead.convertedAt,
|
||||||
|
archivedAt: lead.archivedAt,
|
||||||
|
events: lead.events,
|
||||||
|
});
|
||||||
|
for (const stay of stays) {
|
||||||
|
const fromMs = Math.max(stay.fromMs, start.getTime());
|
||||||
|
const toMs = Math.min(stay.toMs, end.getTime());
|
||||||
|
if (toMs <= fromMs) continue;
|
||||||
|
const hours = hoursBetween(fromMs, toMs);
|
||||||
|
if (dimension === 'lead_stage' || dimension === 'stage') {
|
||||||
|
const name =
|
||||||
|
stages.find((s) => s.id === stay.stageId)?.name ?? stay.stageId;
|
||||||
|
const cur = sum.get(stay.stageId) ?? {
|
||||||
|
hours: 0,
|
||||||
|
n: 0,
|
||||||
|
label: name,
|
||||||
|
};
|
||||||
|
cur.hours += hours;
|
||||||
|
cur.n += 1;
|
||||||
|
sum.set(stay.stageId, cur);
|
||||||
|
} else {
|
||||||
|
const dim = await dimKey({
|
||||||
|
ownerId: lead.assigneeId,
|
||||||
|
source: lead.source,
|
||||||
|
stageId: stay.stageId,
|
||||||
|
stageName:
|
||||||
|
stages.find((s) => s.id === stay.stageId)?.name ?? null,
|
||||||
|
at: new Date(stay.fromMs),
|
||||||
|
});
|
||||||
|
const cur = sum.get(dim.key) ?? {
|
||||||
|
hours: 0,
|
||||||
|
n: 0,
|
||||||
|
label: dim.label,
|
||||||
|
};
|
||||||
|
cur.hours += hours;
|
||||||
|
cur.n += 1;
|
||||||
|
sum.set(dim.key, cur);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [key, row] of sum.entries()) {
|
||||||
|
if (row.n <= 0) continue;
|
||||||
|
add(key, row.label, Math.round((row.hours / row.n) * 10) / 10);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let where: Prisma.LeadWhereInput = {
|
||||||
|
organizationId: orgId,
|
||||||
|
...leadAccess,
|
||||||
|
...assigneeFilter,
|
||||||
|
};
|
||||||
|
if (metric === 'leads_created') {
|
||||||
|
where = { ...where, createdAt: { gte: start, lte: end } };
|
||||||
|
} else if (metric === 'leads_converted') {
|
||||||
|
where = { ...where, convertedAt: { gte: start, lte: end } };
|
||||||
|
} else if (metric === 'leads_lost') {
|
||||||
|
where = {
|
||||||
|
...where,
|
||||||
|
archivedAt: null,
|
||||||
|
stageId: { in: lostIds.length ? lostIds : ['__none__'] },
|
||||||
|
updatedAt: { gte: start, lte: end },
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// leads_active
|
||||||
|
where = {
|
||||||
|
...where,
|
||||||
|
archivedAt: null,
|
||||||
|
convertedAt: null,
|
||||||
|
stageId: {
|
||||||
|
notIn: [...lostIds, ...convertedIds],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const leads = await this.prisma.lead.findMany({
|
||||||
|
where,
|
||||||
|
select: {
|
||||||
|
assigneeId: true,
|
||||||
|
source: true,
|
||||||
|
stageId: true,
|
||||||
|
stage: { select: { name: true } },
|
||||||
|
createdAt: true,
|
||||||
|
updatedAt: true,
|
||||||
|
convertedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const lead of leads) {
|
||||||
|
const at =
|
||||||
|
metric === 'leads_converted'
|
||||||
|
? lead.convertedAt ?? lead.updatedAt
|
||||||
|
: metric === 'leads_created'
|
||||||
|
? lead.createdAt
|
||||||
|
: lead.updatedAt;
|
||||||
|
const dim = await dimKey({
|
||||||
|
ownerId: lead.assigneeId,
|
||||||
|
source: lead.source,
|
||||||
|
stageId: lead.stageId,
|
||||||
|
stageName: lead.stage?.name,
|
||||||
|
at,
|
||||||
|
});
|
||||||
|
add(dim.key, dim.label, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const rows: ReportsBuilderRowDto[] = [...buckets.entries()]
|
const rows: ReportsBuilderRowDto[] = [...buckets.entries()]
|
||||||
.map(([key, row]) => ({
|
.map(([key, row]) => ({
|
||||||
key,
|
key,
|
||||||
label: row.label,
|
label: row.label,
|
||||||
value: Math.round(row.value * (format === 'money' ? 1 : 1)),
|
value:
|
||||||
|
metric === 'leads_avg_dwell_hours'
|
||||||
|
? Math.round(row.value * 10) / 10
|
||||||
|
: Math.round(row.value * (format === 'money' ? 1 : 1)),
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => b.value - a.value);
|
.sort((a, b) => b.value - a.value);
|
||||||
|
|
||||||
@@ -1470,21 +1869,52 @@ export class ReportsService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private leadAccessWhere(actor: Actor): Prisma.LeadWhereInput {
|
||||||
|
if (actor.leadsAccess !== undefined) {
|
||||||
|
return leadsDeepWhere(actor);
|
||||||
|
}
|
||||||
|
const scoped = forScope(actor, 'leads');
|
||||||
|
if (elevated(scoped.role)) return {};
|
||||||
|
if (scoped.dataVisibility === 'org') return {};
|
||||||
|
if (
|
||||||
|
scoped.dataVisibility === 'team' &&
|
||||||
|
scoped.visibleUserIds &&
|
||||||
|
scoped.visibleUserIds.length
|
||||||
|
) {
|
||||||
|
return { assigneeId: { in: scoped.visibleUserIds } };
|
||||||
|
}
|
||||||
|
return { assigneeId: scoped.userId };
|
||||||
|
}
|
||||||
|
|
||||||
private async resolveBuilderOwnerIds(
|
private async resolveBuilderOwnerIds(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
opts: { userId?: string; teamId?: string },
|
opts: { userId?: string; teamId?: string; scope?: 'deals' | 'leads' },
|
||||||
): Promise<string[] | null> {
|
): Promise<string[] | null> {
|
||||||
const scope = ownerWhere(actor, 'deals');
|
|
||||||
let allowed: string[] | null = null;
|
let allowed: string[] | null = null;
|
||||||
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
|
if (opts.scope === 'leads') {
|
||||||
allowed = [scope.ownerId];
|
const scoped = forScope(actor, 'leads');
|
||||||
} else if (
|
if (elevated(scoped.role) || scoped.dataVisibility === 'org') {
|
||||||
'ownerId' in scope &&
|
allowed = null;
|
||||||
scope.ownerId &&
|
} else if (
|
||||||
typeof scope.ownerId === 'object' &&
|
scoped.dataVisibility === 'team' &&
|
||||||
'in' in scope.ownerId
|
scoped.visibleUserIds?.length
|
||||||
) {
|
) {
|
||||||
allowed = [...scope.ownerId.in];
|
allowed = [...scoped.visibleUserIds];
|
||||||
|
} else {
|
||||||
|
allowed = [scoped.userId];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const scope = ownerWhere(actor, 'deals');
|
||||||
|
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
|
||||||
|
allowed = [scope.ownerId];
|
||||||
|
} else if (
|
||||||
|
'ownerId' in scope &&
|
||||||
|
scope.ownerId &&
|
||||||
|
typeof scope.ownerId === 'object' &&
|
||||||
|
'in' in scope.ownerId
|
||||||
|
) {
|
||||||
|
allowed = [...scope.ownerId.in];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let ids: string[] | null = null;
|
let ids: string[] | null = null;
|
||||||
@@ -1534,7 +1964,7 @@ export class ReportsService {
|
|||||||
const orgId = actor.organizationId;
|
const orgId = actor.organizationId;
|
||||||
const dealScope = ownerWhere(actor, 'deals');
|
const dealScope = ownerWhere(actor, 'deals');
|
||||||
const activityScope = assigneeWhere(actor);
|
const activityScope = assigneeWhere(actor);
|
||||||
const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId };
|
const personScope = customersPersonWhere(actor);
|
||||||
const rates = await loadOrgRates(this.prisma, orgId);
|
const rates = await loadOrgRates(this.prisma, orgId);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const { jy, jm } = dateToJalali(now);
|
const { jy, jm } = dateToJalali(now);
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export type RoutineTaskRow = Prisma.RoutineTaskGetPayload<{
|
|||||||
export const routineInclude = {
|
export const routineInclude = {
|
||||||
category: true,
|
category: true,
|
||||||
assignee: userSelect,
|
assignee: userSelect,
|
||||||
|
createdBy: userSelect,
|
||||||
team: { select: { id: true, name: true } },
|
team: { select: { id: true, name: true } },
|
||||||
} satisfies Prisma.RoutineInclude;
|
} satisfies Prisma.RoutineInclude;
|
||||||
|
|
||||||
@@ -186,6 +187,7 @@ export function toRoutineDto(
|
|||||||
reminderMinutesBefore: row.reminderMinutesBefore,
|
reminderMinutesBefore: row.reminderMinutesBefore,
|
||||||
isActive: row.isActive,
|
isActive: row.isActive,
|
||||||
createdById: row.createdById,
|
createdById: row.createdById,
|
||||||
|
createdBy: row.createdBy,
|
||||||
recurrenceLabel: describeRecurrence(rule),
|
recurrenceLabel: describeRecurrence(rule),
|
||||||
executionRate: execution.total ? Math.round((execution.done / execution.total) * 100) : null,
|
executionRate: execution.total ? Math.round((execution.done / execution.total) * 100) : null,
|
||||||
executionTotal: execution.total,
|
executionTotal: execution.total,
|
||||||
|
|||||||
@@ -273,6 +273,7 @@ export class RoutinesService {
|
|||||||
category: _cat,
|
category: _cat,
|
||||||
assignee: _a,
|
assignee: _a,
|
||||||
team: _t,
|
team: _t,
|
||||||
|
createdBy: _cb,
|
||||||
deletedAt: _d,
|
deletedAt: _d,
|
||||||
...rest
|
...rest
|
||||||
} = src;
|
} = src;
|
||||||
|
|||||||
@@ -511,7 +511,7 @@ export class SmsCampaignsService {
|
|||||||
const leadIds = batch
|
const leadIds = batch
|
||||||
.map((r) => r.leadId)
|
.map((r) => r.leadId)
|
||||||
.filter((id): id is string => Boolean(id));
|
.filter((id): id is string => Boolean(id));
|
||||||
const [people, leads] = await Promise.all([
|
const [people, leads, org] = await Promise.all([
|
||||||
personIds.length
|
personIds.length
|
||||||
? this.prisma.person.findMany({
|
? this.prisma.person.findMany({
|
||||||
where: { id: { in: personIds } },
|
where: { id: { in: personIds } },
|
||||||
@@ -535,9 +535,14 @@ export class SmsCampaignsService {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
: Promise.resolve([]),
|
: Promise.resolve([]),
|
||||||
|
this.prisma.organization.findUnique({
|
||||||
|
where: { id: campaign.organizationId },
|
||||||
|
select: { name: true },
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
const personMap = new Map(people.map((p) => [p.id, p]));
|
const personMap = new Map(people.map((p) => [p.id, p]));
|
||||||
const leadMap = new Map(leads.map((l) => [l.id, l]));
|
const leadMap = new Map(leads.map((l) => [l.id, l]));
|
||||||
|
const fromOrg = org?.name?.trim() || '';
|
||||||
|
|
||||||
let sent = 0;
|
let sent = 0;
|
||||||
let failed = 0;
|
let failed = 0;
|
||||||
@@ -572,6 +577,7 @@ export class SmsCampaignsService {
|
|||||||
phone: recipient.mobile,
|
phone: recipient.mobile,
|
||||||
title,
|
title,
|
||||||
company,
|
company,
|
||||||
|
from: fromOrg,
|
||||||
});
|
});
|
||||||
|
|
||||||
const personalized = await this.tracking.personalizeSmsBody({
|
const personalized = await this.tracking.personalizeSmsBody({
|
||||||
|
|||||||
@@ -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<InvoicePartyPosition[]> {
|
||||||
|
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<string, Bucket>();
|
||||||
|
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),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
parseUserTreasuryAccess,
|
parseUserTreasuryAccess,
|
||||||
|
permissionsWithTreasuryOverride,
|
||||||
treasurySectionAllowed,
|
treasurySectionAllowed,
|
||||||
type TreasurySectionKey,
|
type TreasurySectionKey,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
@@ -16,7 +17,12 @@ export class TreasuryAccessGuard implements CanActivate {
|
|||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
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;
|
const actor = req.user;
|
||||||
if (!actor) throw new ForbiddenException('دسترسی مالی مجاز نیست.');
|
if (!actor) throw new ForbiddenException('دسترسی مالی مجاز نیست.');
|
||||||
if (actor.role === 'owner' || actor.role === 'admin') return true;
|
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)
|
const rolePermissions = Array.isArray(membership?.orgRole?.permissions)
|
||||||
? membership.orgRole.permissions.map(String)
|
? membership.orgRole.permissions.map(String)
|
||||||
: [];
|
: [];
|
||||||
const permissions = permissionsForTreasury(
|
const permissions = permissionsWithTreasuryOverride(
|
||||||
rolePermissions,
|
rolePermissions,
|
||||||
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
|
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
|
||||||
);
|
);
|
||||||
|
const method = (req.method || 'GET').toUpperCase();
|
||||||
const url = req.originalUrl || req.url || '';
|
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))) {
|
if (!treasurySectionAllowed(actor.role, permissions, sectionForUrl(url))) {
|
||||||
throw new ForbiddenException('به این بخش مدیریت مالی دسترسی ندارید.');
|
throw new ForbiddenException('به این بخش مدیریت مالی دسترسی ندارید.');
|
||||||
}
|
}
|
||||||
@@ -42,14 +55,11 @@ export class TreasuryAccessGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function permissionsForTreasury(
|
/** فهرست حساب و دسته برای ثبت سند لازم است؛ صفحهٔ مدیریتشان جدا میماند. */
|
||||||
rolePermissions: string[],
|
function isLookupForDocuments(method: string, url: string): boolean {
|
||||||
override: ReturnType<typeof parseUserTreasuryAccess>,
|
if (method !== 'GET' && method !== 'HEAD') return false;
|
||||||
): string[] {
|
const path = (url.split('?')[0] || '').replace(/\/+$/, '');
|
||||||
if (!override) return rolePermissions;
|
return path.endsWith('/treasury/accounts') || path.endsWith('/treasury/categories');
|
||||||
const rest = rolePermissions.filter((key) => key !== 'treasury' && !key.startsWith('treasury_'));
|
|
||||||
if (!override.enabled) return rest;
|
|
||||||
return ['treasury', ...override.sections, ...rest];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function sectionForUrl(url: string): TreasurySectionKey | 'treasury_documents' {
|
function sectionForUrl(url: string): TreasurySectionKey | 'treasury_documents' {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import ExcelJS from 'exceljs';
|
|||||||
import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import type { Actor } from '../common/record-scope';
|
import type { Actor } from '../common/record-scope';
|
||||||
|
import { invoiceSalesInPeriod } from './invoice-ledger';
|
||||||
|
|
||||||
function dec(value: Prisma.Decimal | number | string | null | undefined) {
|
function dec(value: Prisma.Decimal | number | string | null | undefined) {
|
||||||
return new Prisma.Decimal(value ?? 0);
|
return new Prisma.Decimal(value ?? 0);
|
||||||
@@ -12,11 +13,20 @@ function dec(value: Prisma.Decimal | number | string | null | undefined) {
|
|||||||
function money(value: Prisma.Decimal | number | string) {
|
function money(value: Prisma.Decimal | number | string) {
|
||||||
return new Prisma.Decimal(value).toFixed(2);
|
return new Prisma.Decimal(value).toFixed(2);
|
||||||
}
|
}
|
||||||
|
function reasonText(value?: string | null) {
|
||||||
|
const text = value?.trim() ?? '';
|
||||||
|
return text ? text.slice(0, 500) : null;
|
||||||
|
}
|
||||||
function parseDate(iso?: string | null) {
|
function parseDate(iso?: string | null) {
|
||||||
if (!iso) return null;
|
if (!iso) return null;
|
||||||
const d = new Date(iso);
|
const d = new Date(iso);
|
||||||
return Number.isNaN(d.getTime()) ? null : d;
|
return Number.isNaN(d.getTime()) ? null : d;
|
||||||
}
|
}
|
||||||
|
function payrollStatus(payable: Prisma.Decimal, paid: Prisma.Decimal) {
|
||||||
|
if (paid.lessThanOrEqualTo(0)) return 'open';
|
||||||
|
if (paid.greaterThanOrEqualTo(payable)) return 'settled';
|
||||||
|
return 'partial';
|
||||||
|
}
|
||||||
function periodKey(date: Date) {
|
function periodKey(date: Date) {
|
||||||
return date.toISOString().slice(0, 10);
|
return date.toISOString().slice(0, 10);
|
||||||
}
|
}
|
||||||
@@ -36,9 +46,15 @@ export class TreasuryOpsService {
|
|||||||
async listPayroll(actor: Actor) {
|
async listPayroll(actor: Actor) {
|
||||||
const rows = await this.prisma.financialPayroll.findMany({
|
const rows = await this.prisma.financialPayroll.findMany({
|
||||||
where: { organizationId: actor.organizationId },
|
where: { organizationId: actor.organizationId },
|
||||||
include: { movements: true },
|
include: {
|
||||||
|
movements: {
|
||||||
|
where: { voidedAt: null },
|
||||||
|
include: { account: { select: { name: true } } },
|
||||||
|
orderBy: { occurredAt: 'desc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
orderBy: { dueDate: 'desc' },
|
orderBy: { dueDate: 'desc' },
|
||||||
take: 100,
|
take: 500,
|
||||||
});
|
});
|
||||||
const users = await this.prisma.user.findMany({
|
const users = await this.prisma.user.findMany({
|
||||||
where: { id: { in: rows.map((row) => row.userId) } },
|
where: { id: { in: rows.map((row) => row.userId) } },
|
||||||
@@ -55,8 +71,11 @@ export class TreasuryOpsService {
|
|||||||
period: string;
|
period: string;
|
||||||
baseAmount: string | number;
|
baseAmount: string | number;
|
||||||
benefits?: string | number;
|
benefits?: string | number;
|
||||||
|
benefitsReason?: string | null;
|
||||||
bonus?: string | number;
|
bonus?: string | number;
|
||||||
|
bonusReason?: string | null;
|
||||||
deductions?: string | number;
|
deductions?: string | number;
|
||||||
|
deductionsReason?: string | null;
|
||||||
dueDate?: string;
|
dueDate?: string;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
},
|
},
|
||||||
@@ -81,14 +100,23 @@ export class TreasuryOpsService {
|
|||||||
period: input.period.trim(),
|
period: input.period.trim(),
|
||||||
baseAmount: base,
|
baseAmount: base,
|
||||||
benefits,
|
benefits,
|
||||||
|
benefitsReason: benefits.greaterThan(0) ? reasonText(input.benefitsReason) : null,
|
||||||
bonus,
|
bonus,
|
||||||
|
bonusReason: bonus.greaterThan(0) ? reasonText(input.bonusReason) : null,
|
||||||
deductions,
|
deductions,
|
||||||
|
deductionsReason: deductions.greaterThan(0) ? reasonText(input.deductionsReason) : null,
|
||||||
payable,
|
payable,
|
||||||
dueDate: parseDate(input.dueDate) ?? new Date(),
|
dueDate: parseDate(input.dueDate) ?? new Date(),
|
||||||
notes: input.notes?.trim() || null,
|
notes: input.notes?.trim() || null,
|
||||||
createdById: actor.userId,
|
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 } });
|
const user = await this.prisma.user.findUnique({ where: { id: row.userId }, select: { fullName: true } });
|
||||||
return this.payrollDto(row, user?.fullName ?? '');
|
return this.payrollDto(row, user?.fullName ?? '');
|
||||||
@@ -124,7 +152,7 @@ export class TreasuryOpsService {
|
|||||||
if (!account) throw new BadRequestException('حساب پرداخت پیدا نشد.');
|
if (!account) throw new BadRequestException('حساب پرداخت پیدا نشد.');
|
||||||
const balance = await this.balance(account.id);
|
const balance = await this.balance(account.id);
|
||||||
if (balance.lessThan(amount)) throw new BadRequestException('موجودی حساب کافی نیست.');
|
if (balance.lessThan(amount)) throw new BadRequestException('موجودی حساب کافی نیست.');
|
||||||
const status = paid.plus(amount).equals(row.payable) ? 'settled' : 'partial';
|
const status = payrollStatus(row.payable, paid.plus(amount));
|
||||||
await this.prisma.$transaction([
|
await this.prisma.$transaction([
|
||||||
this.prisma.financialMovement.create({
|
this.prisma.financialMovement.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -145,6 +173,123 @@ export class TreasuryOpsService {
|
|||||||
return this.listPayroll(actor);
|
return this.listPayroll(actor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updatePayroll(
|
||||||
|
actor: Actor,
|
||||||
|
id: string,
|
||||||
|
input: {
|
||||||
|
userId: string;
|
||||||
|
period: string;
|
||||||
|
baseAmount: string | number;
|
||||||
|
benefits?: string | number;
|
||||||
|
benefitsReason?: string | null;
|
||||||
|
bonus?: string | number;
|
||||||
|
bonusReason?: string | null;
|
||||||
|
deductions?: string | number;
|
||||||
|
deductionsReason?: string | null;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const row = await this.prisma.financialPayroll.findFirst({
|
||||||
|
where: { id, organizationId: actor.organizationId },
|
||||||
|
include: { movements: true },
|
||||||
|
});
|
||||||
|
if (!row || row.voidedAt || row.status === 'void') {
|
||||||
|
throw new NotFoundException('رکورد حقوق برای ویرایش پیدا نشد.');
|
||||||
|
}
|
||||||
|
const base = dec(input.baseAmount);
|
||||||
|
const benefits = dec(input.benefits ?? 0);
|
||||||
|
const bonus = dec(input.bonus ?? 0);
|
||||||
|
const deductions = dec(input.deductions ?? 0);
|
||||||
|
const payable = base.plus(benefits).plus(bonus).minus(deductions);
|
||||||
|
if (!input.userId || !input.period?.trim()) {
|
||||||
|
throw new BadRequestException('پرسنل و دوره حقوق لازم است.');
|
||||||
|
}
|
||||||
|
if (!payable.greaterThan(0)) throw new BadRequestException('مبلغ قابل پرداخت باید بزرگتر از صفر باشد.');
|
||||||
|
const paid = this.paidOf(row.movements);
|
||||||
|
if (payable.lessThan(paid)) {
|
||||||
|
throw new BadRequestException('مبلغ قابل پرداخت از پرداختهای ثبتشده کمتر است.');
|
||||||
|
}
|
||||||
|
const member = await this.prisma.membership.findFirst({
|
||||||
|
where: { organizationId: actor.organizationId, userId: input.userId, isActive: true },
|
||||||
|
});
|
||||||
|
if (!member) throw new BadRequestException('این کاربر عضو محیط نیست.');
|
||||||
|
try {
|
||||||
|
await this.prisma.financialPayroll.update({
|
||||||
|
where: { id: row.id },
|
||||||
|
data: {
|
||||||
|
userId: input.userId,
|
||||||
|
period: input.period.trim(),
|
||||||
|
baseAmount: base,
|
||||||
|
benefits,
|
||||||
|
benefitsReason: benefits.greaterThan(0) ? reasonText(input.benefitsReason) : null,
|
||||||
|
bonus,
|
||||||
|
bonusReason: bonus.greaterThan(0) ? reasonText(input.bonusReason) : null,
|
||||||
|
deductions,
|
||||||
|
deductionsReason: deductions.greaterThan(0) ? reasonText(input.deductionsReason) : null,
|
||||||
|
payable,
|
||||||
|
status: payrollStatus(payable, paid),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
|
||||||
|
throw new BadRequestException('برای این پرسنل در این دوره حقوق ثبت شده است.');
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return this.listPayroll(actor);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePayrollPayment(
|
||||||
|
actor: Actor,
|
||||||
|
payrollId: string,
|
||||||
|
movementId: string,
|
||||||
|
input: { amount: string | number; accountId: string; occurredAt?: string },
|
||||||
|
) {
|
||||||
|
const movement = await this.prisma.financialMovement.findFirst({
|
||||||
|
where: {
|
||||||
|
id: movementId,
|
||||||
|
payrollId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
voidedAt: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const payroll = await this.prisma.financialPayroll.findFirst({
|
||||||
|
where: { id: payrollId, organizationId: actor.organizationId },
|
||||||
|
include: { movements: true },
|
||||||
|
});
|
||||||
|
if (!movement || !payroll || payroll.voidedAt || payroll.status === 'void') {
|
||||||
|
throw new NotFoundException('پرداخت حقوق برای ویرایش پیدا نشد.');
|
||||||
|
}
|
||||||
|
const amount = dec(input.amount);
|
||||||
|
const otherPaid = this.paidOf(payroll.movements.filter((item) => item.id !== movement.id));
|
||||||
|
if (!amount.greaterThan(0) || otherPaid.plus(amount).greaterThan(payroll.payable)) {
|
||||||
|
throw new BadRequestException('مبلغ پرداخت حقوق نامعتبر است.');
|
||||||
|
}
|
||||||
|
const account = await this.prisma.financialAccount.findFirst({
|
||||||
|
where: { id: input.accountId, organizationId: actor.organizationId },
|
||||||
|
});
|
||||||
|
if (!account || (!account.isActive && account.id !== movement.accountId)) {
|
||||||
|
throw new BadRequestException('حساب پرداخت پیدا نشد.');
|
||||||
|
}
|
||||||
|
const available = await this.balance(account.id);
|
||||||
|
const room = account.id === movement.accountId ? available.plus(movement.amount) : available;
|
||||||
|
if (room.lessThan(amount)) throw new BadRequestException('موجودی حساب کافی نیست.');
|
||||||
|
await this.prisma.$transaction([
|
||||||
|
this.prisma.financialMovement.update({
|
||||||
|
where: { id: movement.id },
|
||||||
|
data: {
|
||||||
|
accountId: account.id,
|
||||||
|
amount,
|
||||||
|
occurredAt: parseDate(input.occurredAt) ?? movement.occurredAt,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.financialPayroll.update({
|
||||||
|
where: { id: payroll.id },
|
||||||
|
data: { status: payrollStatus(payroll.payable, otherPaid.plus(amount)) },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return this.listPayroll(actor);
|
||||||
|
}
|
||||||
|
|
||||||
async listRecurring(actor: Actor) {
|
async listRecurring(actor: Actor) {
|
||||||
const rows = await this.prisma.financialRecurringItem.findMany({
|
const rows = await this.prisma.financialRecurringItem.findMany({
|
||||||
where: { organizationId: actor.organizationId },
|
where: { organizationId: actor.organizationId },
|
||||||
@@ -327,6 +472,8 @@ export class TreasuryOpsService {
|
|||||||
sheet.addRow(['شاخص', 'این دوره', 'دوره قبل']);
|
sheet.addRow(['شاخص', 'این دوره', 'دوره قبل']);
|
||||||
const rows: Array<[string, string, string]> = [
|
const rows: Array<[string, string, string]> = [
|
||||||
['درآمد ثبتشده', data.current.bookedIncome, data.previous.bookedIncome],
|
['درآمد ثبتشده', 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.bookedExpense, data.previous.bookedExpense],
|
||||||
['سود عملیاتی', data.current.operatingProfit, data.previous.operatingProfit],
|
['سود عملیاتی', data.current.operatingProfit, data.previous.operatingProfit],
|
||||||
['ورود وجه', data.current.cashIn, data.previous.cashIn],
|
['ورود وجه', data.current.cashIn, data.previous.cashIn],
|
||||||
@@ -411,10 +558,15 @@ export class TreasuryOpsService {
|
|||||||
amount: money(amount),
|
amount: money(amount),
|
||||||
share: bookedExpense.equals(0) ? '0' : amount.div(bookedExpense).mul(100).toFixed(1),
|
share: bookedExpense.equals(0) ? '0' : amount.div(bookedExpense).mul(100).toFixed(1),
|
||||||
}));
|
}));
|
||||||
|
const invoiceSales = await invoiceSalesInPeriod(this.prisma, organizationId, from, to);
|
||||||
return {
|
return {
|
||||||
bookedIncome: money(bookedIncome),
|
bookedIncome: money(bookedIncome),
|
||||||
|
invoiceSales: invoiceSales.sales,
|
||||||
|
invoiceCredits: invoiceSales.credits,
|
||||||
bookedExpense: money(bookedExpense),
|
bookedExpense: money(bookedExpense),
|
||||||
operatingProfit: money(bookedIncome.minus(bookedExpense)),
|
operatingProfit: money(
|
||||||
|
bookedIncome.plus(invoiceSales.net).minus(bookedExpense),
|
||||||
|
),
|
||||||
cashIn: money(cashIn),
|
cashIn: money(cashIn),
|
||||||
cashOut: money(cashOut),
|
cashOut: money(cashOut),
|
||||||
cashNet: money(cashIn.minus(cashOut)),
|
cashNet: money(cashIn.minus(cashOut)),
|
||||||
@@ -475,12 +627,22 @@ export class TreasuryOpsService {
|
|||||||
period: string;
|
period: string;
|
||||||
baseAmount: Prisma.Decimal;
|
baseAmount: Prisma.Decimal;
|
||||||
benefits: Prisma.Decimal;
|
benefits: Prisma.Decimal;
|
||||||
|
benefitsReason?: string | null;
|
||||||
bonus: Prisma.Decimal;
|
bonus: Prisma.Decimal;
|
||||||
|
bonusReason?: string | null;
|
||||||
deductions: Prisma.Decimal;
|
deductions: Prisma.Decimal;
|
||||||
|
deductionsReason?: string | null;
|
||||||
payable: Prisma.Decimal;
|
payable: Prisma.Decimal;
|
||||||
dueDate: Date;
|
dueDate: Date;
|
||||||
status: string;
|
status: string;
|
||||||
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>;
|
movements: Array<{
|
||||||
|
id: string;
|
||||||
|
amount: Prisma.Decimal;
|
||||||
|
voidedAt: Date | null;
|
||||||
|
accountId: string;
|
||||||
|
occurredAt: Date;
|
||||||
|
account?: { name: string } | null;
|
||||||
|
}>;
|
||||||
},
|
},
|
||||||
fullName: string,
|
fullName: string,
|
||||||
) {
|
) {
|
||||||
@@ -493,13 +655,25 @@ export class TreasuryOpsService {
|
|||||||
period: row.period,
|
period: row.period,
|
||||||
baseAmount: money(row.baseAmount),
|
baseAmount: money(row.baseAmount),
|
||||||
benefits: money(row.benefits),
|
benefits: money(row.benefits),
|
||||||
|
benefitsReason: row.benefitsReason?.trim() || null,
|
||||||
bonus: money(row.bonus),
|
bonus: money(row.bonus),
|
||||||
|
bonusReason: row.bonusReason?.trim() || null,
|
||||||
deductions: money(row.deductions),
|
deductions: money(row.deductions),
|
||||||
|
deductionsReason: row.deductionsReason?.trim() || null,
|
||||||
payable: money(row.payable),
|
payable: money(row.payable),
|
||||||
paidAmount: money(paid),
|
paidAmount: money(paid),
|
||||||
remaining: money(left.isNegative() ? 0 : left),
|
remaining: money(left.isNegative() ? 0 : left),
|
||||||
dueDate: row.dueDate.toISOString(),
|
dueDate: row.dueDate.toISOString(),
|
||||||
status: row.status,
|
status: row.status,
|
||||||
|
payments: row.movements
|
||||||
|
.filter((item) => !item.voidedAt)
|
||||||
|
.map((item) => ({
|
||||||
|
id: item.id,
|
||||||
|
amount: money(item.amount),
|
||||||
|
occurredAt: item.occurredAt.toISOString(),
|
||||||
|
accountId: item.accountId,
|
||||||
|
accountName: item.account?.name ?? '',
|
||||||
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -129,6 +129,29 @@ export class TreasuryController {
|
|||||||
return this.treasury.partyBalances(user, kind === 'expense' ? 'expense' : 'income');
|
return this.treasury.partyBalances(user, kind === 'expense' ? 'expense' : 'income');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('party-balances/collect')
|
||||||
|
collectPartyBalance(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Body()
|
||||||
|
body: {
|
||||||
|
kind?: string;
|
||||||
|
partyKind?: 'person' | 'company' | 'user';
|
||||||
|
partyId?: string;
|
||||||
|
amount?: string | number;
|
||||||
|
accountId?: string;
|
||||||
|
occurredAt?: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return this.treasury.collectPartyBalance(user, {
|
||||||
|
kind: body.kind === 'expense' ? 'expense' : 'income',
|
||||||
|
partyKind: body.partyKind ?? 'person',
|
||||||
|
partyId: body.partyId ?? '',
|
||||||
|
amount: body.amount ?? 0,
|
||||||
|
accountId: body.accountId ?? '',
|
||||||
|
occurredAt: body.occurredAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@Get('documents')
|
@Get('documents')
|
||||||
documents(
|
documents(
|
||||||
@CurrentUser() user: Actor,
|
@CurrentUser() user: Actor,
|
||||||
@@ -158,6 +181,33 @@ export class TreasuryController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('documents/:id')
|
||||||
|
getDocument(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
|
return this.treasury.getDocument(user, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('documents/:id')
|
||||||
|
updateDocument(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body()
|
||||||
|
body: {
|
||||||
|
title?: string;
|
||||||
|
notes?: string | null;
|
||||||
|
categoryId?: string | null;
|
||||||
|
method?: string | null;
|
||||||
|
bookedAt?: string;
|
||||||
|
amount?: string | number;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return this.treasury.updateDocument(user, id, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('documents/:id')
|
||||||
|
deleteDocument(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
|
return this.treasury.deleteDocument(user, id);
|
||||||
|
}
|
||||||
|
|
||||||
@Get('attachments/:id')
|
@Get('attachments/:id')
|
||||||
async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) {
|
async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||||
const file = await this.treasury.openAttachment(user, id);
|
const file = await this.treasury.openAttachment(user, id);
|
||||||
@@ -232,6 +282,25 @@ export class TreasuryController {
|
|||||||
return this.ops.createPayroll(user, body);
|
return this.ops.createPayroll(user, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Patch('payroll/:id')
|
||||||
|
updatePayroll(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: Parameters<TreasuryOpsService['updatePayroll']>[2],
|
||||||
|
) {
|
||||||
|
return this.ops.updatePayroll(user, id, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('payroll/:id/payments/:movementId')
|
||||||
|
updatePayrollPayment(
|
||||||
|
@CurrentUser() user: Actor,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Param('movementId') movementId: string,
|
||||||
|
@Body() body: Parameters<TreasuryOpsService['updatePayrollPayment']>[3],
|
||||||
|
) {
|
||||||
|
return this.ops.updatePayrollPayment(user, id, movementId, body);
|
||||||
|
}
|
||||||
|
|
||||||
@Post('payroll/:id/pay')
|
@Post('payroll/:id/pay')
|
||||||
payPayroll(
|
payPayroll(
|
||||||
@CurrentUser() user: Actor,
|
@CurrentUser() user: Actor,
|
||||||
|
|||||||
@@ -4,7 +4,11 @@ import {
|
|||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { parseUserTreasuryAccess } from '@mento/shared';
|
import {
|
||||||
|
canManageTreasuryDocuments,
|
||||||
|
parseUserTreasuryAccess,
|
||||||
|
permissionsWithTreasuryOverride,
|
||||||
|
} from '@mento/shared';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import ExcelJS from 'exceljs';
|
import ExcelJS from 'exceljs';
|
||||||
@@ -25,6 +29,7 @@ import { PrismaService } from '../prisma/prisma.service';
|
|||||||
import { LocalFileStorage } from '../storage/local-file.storage';
|
import { LocalFileStorage } from '../storage/local-file.storage';
|
||||||
import { StorageQuotaService } from '../billing/storage-quota.service';
|
import { StorageQuotaService } from '../billing/storage-quota.service';
|
||||||
import type { Actor } from '../common/record-scope';
|
import type { Actor } from '../common/record-scope';
|
||||||
|
import { loadInvoicePartyPositions, invoiceSalesInPeriod } from './invoice-ledger';
|
||||||
import { TreasuryReceivablesService } from './treasury-receivables.service';
|
import { TreasuryReceivablesService } from './treasury-receivables.service';
|
||||||
|
|
||||||
const INCOME_CATEGORIES = ['فروش خدمات', 'فروش کالا', 'سایر درآمدها'];
|
const INCOME_CATEGORIES = ['فروش خدمات', 'فروش کالا', 'سایر درآمدها'];
|
||||||
@@ -359,6 +364,7 @@ export class TreasuryService {
|
|||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
accountId,
|
accountId,
|
||||||
voidedAt: null,
|
voidedAt: null,
|
||||||
|
kind: { not: 'allocation' },
|
||||||
...(from || to
|
...(from || to
|
||||||
? {
|
? {
|
||||||
occurredAt: {
|
occurredAt: {
|
||||||
@@ -377,6 +383,7 @@ export class TreasuryService {
|
|||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
accountId,
|
accountId,
|
||||||
voidedAt: null,
|
voidedAt: null,
|
||||||
|
kind: { not: 'allocation' },
|
||||||
occurredAt: { lt: from },
|
occurredAt: { lt: from },
|
||||||
},
|
},
|
||||||
select: { direction: true, amount: true },
|
select: { direction: true, amount: true },
|
||||||
@@ -503,13 +510,87 @@ export class TreasuryService {
|
|||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
},
|
},
|
||||||
include: { category: true, account: true, movements: true, attachments: { select: { id: true, fileName: true } } },
|
include: {
|
||||||
|
category: true,
|
||||||
|
account: true,
|
||||||
|
movements: true,
|
||||||
|
attachments: { select: { id: true, fileName: true, mimeType: true } },
|
||||||
|
},
|
||||||
orderBy: { bookedAt: 'desc' },
|
orderBy: { bookedAt: 'desc' },
|
||||||
take: 200,
|
take: 200,
|
||||||
});
|
});
|
||||||
return rows.map((row) => this.toDocumentDto(row));
|
return rows.map((row) => this.toDocumentDto(row));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getDocument(actor: Actor, id: string): Promise<FinancialDocumentDto> {
|
||||||
|
const doc = await this.requireScopedDocument(actor, id);
|
||||||
|
return this.toDocumentDto(doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateDocument(
|
||||||
|
actor: Actor,
|
||||||
|
id: string,
|
||||||
|
input: {
|
||||||
|
title?: string;
|
||||||
|
notes?: string | null;
|
||||||
|
categoryId?: string | null;
|
||||||
|
method?: string | null;
|
||||||
|
bookedAt?: string;
|
||||||
|
amount?: string | number;
|
||||||
|
},
|
||||||
|
): Promise<FinancialDocumentDto> {
|
||||||
|
await this.assertDocumentsManage(actor);
|
||||||
|
const doc = await this.requireScopedDocument(actor, id);
|
||||||
|
if (doc.status === 'void' || doc.voidedAt) {
|
||||||
|
throw new BadRequestException('سند باطلشده قابل ویرایش نیست.');
|
||||||
|
}
|
||||||
|
const data: Prisma.FinancialDocumentUncheckedUpdateInput = {};
|
||||||
|
if (input.title !== undefined) {
|
||||||
|
const title = input.title.trim();
|
||||||
|
if (title.length < 2) throw new BadRequestException('عنوان را وارد کنید.');
|
||||||
|
data.title = title;
|
||||||
|
}
|
||||||
|
if (input.notes !== undefined) data.notes = input.notes?.trim() || null;
|
||||||
|
if (input.categoryId !== undefined) data.categoryId = input.categoryId || null;
|
||||||
|
if (input.method !== undefined) data.method = input.method || null;
|
||||||
|
if (input.bookedAt !== undefined) {
|
||||||
|
const bookedAt = startOfDay(input.bookedAt);
|
||||||
|
if (!bookedAt) throw new BadRequestException('تاریخ نامعتبر است.');
|
||||||
|
data.bookedAt = bookedAt;
|
||||||
|
}
|
||||||
|
if (input.amount !== undefined) {
|
||||||
|
const active = doc.movements.filter((row) => !row.voidedAt);
|
||||||
|
if (active.length > 0 || doc.status !== 'open') {
|
||||||
|
throw new BadRequestException('مبلغ فقط برای سند باز بدون دریافت/پرداخت قابل تغییر است.');
|
||||||
|
}
|
||||||
|
const amount = dec(input.amount);
|
||||||
|
if (!amount.greaterThan(0)) throw new BadRequestException('مبلغ باید بزرگتر از صفر باشد.');
|
||||||
|
data.amount = amount;
|
||||||
|
}
|
||||||
|
await this.prisma.financialDocument.update({ where: { id: doc.id }, data });
|
||||||
|
return this.getDocument(actor, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteDocument(actor: Actor, id: string): Promise<{ ok: true }> {
|
||||||
|
await this.assertDocumentsManage(actor);
|
||||||
|
const doc = await this.requireScopedDocument(actor, id);
|
||||||
|
const active = doc.movements.filter((row) => !row.voidedAt);
|
||||||
|
if (doc.status !== 'void' && active.length > 0) {
|
||||||
|
throw new BadRequestException('ابتدا سند را ابطال کنید، سپس حذف کنید.');
|
||||||
|
}
|
||||||
|
const attachments = await this.prisma.financialAttachment.findMany({
|
||||||
|
where: { documentId: doc.id, organizationId: actor.organizationId },
|
||||||
|
select: { id: true, storageKey: true },
|
||||||
|
});
|
||||||
|
for (const file of attachments) {
|
||||||
|
const bytes = await this.files.sizeOf(file.storageKey);
|
||||||
|
await this.files.remove(file.storageKey);
|
||||||
|
if (bytes) await this.storage.addLocal(actor.organizationId, -bytes);
|
||||||
|
}
|
||||||
|
await this.prisma.financialDocument.delete({ where: { id: doc.id } });
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
async createDocument(
|
async createDocument(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
input: {
|
input: {
|
||||||
@@ -530,6 +611,8 @@ export class TreasuryService {
|
|||||||
settleAmount?: string | number | null;
|
settleAmount?: string | number | null;
|
||||||
accountId?: string | null;
|
accountId?: string | null;
|
||||||
settledAt?: string | null;
|
settledAt?: string | null;
|
||||||
|
/** دریافت یا پرداخت روی مانده؛ سند تعهدی جدید نمیسازد. */
|
||||||
|
settlement?: boolean;
|
||||||
},
|
},
|
||||||
): Promise<FinancialDocumentDto> {
|
): Promise<FinancialDocumentDto> {
|
||||||
const title = input.title.trim();
|
const title = input.title.trim();
|
||||||
@@ -552,14 +635,19 @@ export class TreasuryService {
|
|||||||
if (input.accountId) {
|
if (input.accountId) {
|
||||||
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
|
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
|
||||||
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
|
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
|
||||||
if (input.kind === 'expense' && settle.greaterThan(0)) {
|
|
||||||
const balance = await this.accountBalance(account.id);
|
|
||||||
if (balance.lessThan(settle)) {
|
|
||||||
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const bookedAt = startOfDay(input.bookedAt) ?? new Date();
|
const bookedAt = startOfDay(input.bookedAt) ?? new Date();
|
||||||
|
const settlement = input.settlement === true;
|
||||||
|
if (settlement) {
|
||||||
|
if (party.partyKind === 'other') {
|
||||||
|
throw new BadRequestException('برای دریافت یا پرداخت، طرف حساب واقعی لازم است.');
|
||||||
|
}
|
||||||
|
if (!settle.equals(amount) || !settle.greaterThan(0)) {
|
||||||
|
throw new BadRequestException('مبلغ دریافت یا پرداخت را وارد کنید.');
|
||||||
|
}
|
||||||
|
if (!input.accountId) throw new BadRequestException('حساب را انتخاب کنید.');
|
||||||
|
}
|
||||||
|
const payExisting = settlement;
|
||||||
const doc = await this.prisma.$transaction(async (tx) => {
|
const doc = await this.prisma.$transaction(async (tx) => {
|
||||||
const reference = await this.nextDocumentReference(
|
const reference = await this.nextDocumentReference(
|
||||||
tx,
|
tx,
|
||||||
@@ -606,6 +694,45 @@ export class TreasuryService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (payExisting && input.accountId) {
|
||||||
|
const leftover = await this.allocatePartyBalance(tx, actor, {
|
||||||
|
party,
|
||||||
|
sourceId: created.id,
|
||||||
|
kind: input.kind,
|
||||||
|
amount: settle,
|
||||||
|
accountId: input.accountId,
|
||||||
|
occurredAt: startOfDay(input.settledAt ?? undefined) ?? bookedAt,
|
||||||
|
memo: title,
|
||||||
|
});
|
||||||
|
if (leftover.greaterThan(0)) {
|
||||||
|
const opposite = input.kind === 'income' ? 'expense' : 'income';
|
||||||
|
const oppositeRef = await this.nextDocumentReference(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
opposite,
|
||||||
|
input.bookedAt,
|
||||||
|
bookedAt,
|
||||||
|
);
|
||||||
|
await tx.financialDocument.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
kind: opposite,
|
||||||
|
title,
|
||||||
|
amount: leftover,
|
||||||
|
bookedAt,
|
||||||
|
personId: party.personId,
|
||||||
|
companyId: party.companyId,
|
||||||
|
userId: party.userId,
|
||||||
|
partyKind: party.partyKind,
|
||||||
|
partyName: party.partyName,
|
||||||
|
status: 'open',
|
||||||
|
reference: oppositeRef,
|
||||||
|
notes: `source:${created.id}`,
|
||||||
|
createdById: actor.userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
return tx.financialDocument.findUniqueOrThrow({
|
return tx.financialDocument.findUniqueOrThrow({
|
||||||
where: { id: created.id },
|
where: { id: created.id },
|
||||||
include: { category: true, account: true, movements: true },
|
include: { category: true, account: true, movements: true },
|
||||||
@@ -727,6 +854,7 @@ export class TreasuryService {
|
|||||||
amount: Prisma.Decimal;
|
amount: Prisma.Decimal;
|
||||||
settled: Prisma.Decimal;
|
settled: Prisma.Decimal;
|
||||||
remaining: Prisma.Decimal;
|
remaining: Prisma.Decimal;
|
||||||
|
documentRemaining: Prisma.Decimal;
|
||||||
}>();
|
}>();
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
if (row.partyKind === 'other') continue;
|
if (row.partyKind === 'other') continue;
|
||||||
@@ -747,13 +875,43 @@ export class TreasuryService {
|
|||||||
amount: new Prisma.Decimal(0),
|
amount: new Prisma.Decimal(0),
|
||||||
settled: new Prisma.Decimal(0),
|
settled: new Prisma.Decimal(0),
|
||||||
remaining: new Prisma.Decimal(0),
|
remaining: new Prisma.Decimal(0),
|
||||||
|
documentRemaining: new Prisma.Decimal(0),
|
||||||
};
|
};
|
||||||
current.amount = current.amount.plus(row.amount);
|
current.amount = current.amount.plus(row.amount);
|
||||||
current.settled = current.settled.plus(settled);
|
current.settled = current.settled.plus(settled);
|
||||||
current.remaining = current.remaining.plus(rawRemaining);
|
current.remaining = current.remaining.plus(rawRemaining);
|
||||||
|
current.documentRemaining = current.documentRemaining.plus(rawRemaining);
|
||||||
buckets.set(key, current);
|
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),
|
||||||
|
documentRemaining: 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()]
|
return [...buckets.values()]
|
||||||
|
.filter((row) => row.remaining.greaterThan(0))
|
||||||
.sort((a, b) => b.remaining.comparedTo(a.remaining))
|
.sort((a, b) => b.remaining.comparedTo(a.remaining))
|
||||||
.map((row) => ({
|
.map((row) => ({
|
||||||
key: row.key,
|
key: row.key,
|
||||||
@@ -762,9 +920,116 @@ export class TreasuryService {
|
|||||||
amount: money(row.amount),
|
amount: money(row.amount),
|
||||||
settledAmount: money(row.settled),
|
settledAmount: money(row.settled),
|
||||||
remaining: money(row.remaining),
|
remaining: money(row.remaining),
|
||||||
|
documentRemaining: money(row.documentRemaining),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** دریافت یا پرداختِ بخشی از ماندهٔ سندهای باز یک طرف حساب، بدون ساخت سند جدید. */
|
||||||
|
async collectPartyBalance(
|
||||||
|
actor: Actor,
|
||||||
|
input: {
|
||||||
|
kind: 'income' | 'expense';
|
||||||
|
partyKind: 'person' | 'company' | 'user';
|
||||||
|
partyId: string;
|
||||||
|
amount: string | number;
|
||||||
|
accountId: string;
|
||||||
|
occurredAt?: string;
|
||||||
|
},
|
||||||
|
): Promise<{ applied: string; documentCount: number }> {
|
||||||
|
const amount = dec(input.amount);
|
||||||
|
if (!amount.greaterThan(0)) throw new BadRequestException('مبلغ باید بزرگتر از صفر باشد.');
|
||||||
|
const partyId = input.partyId.trim();
|
||||||
|
if (!partyId) throw new BadRequestException('طرف حساب را انتخاب کنید.');
|
||||||
|
if (input.partyKind !== 'person' && input.partyKind !== 'company' && input.partyKind !== 'user') {
|
||||||
|
throw new BadRequestException('این مانده به سند بازی وصل نیست.');
|
||||||
|
}
|
||||||
|
if (!input.accountId.trim()) throw new BadRequestException('حساب را انتخاب کنید.');
|
||||||
|
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
|
||||||
|
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
|
||||||
|
const scope = await this.accountScope(actor);
|
||||||
|
const docs = await this.prisma.financialDocument.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
kind: input.kind,
|
||||||
|
voidedAt: null,
|
||||||
|
status: { in: ['open', 'partial'] },
|
||||||
|
partyKind: input.partyKind,
|
||||||
|
...(input.partyKind === 'person' ? { personId: partyId } : {}),
|
||||||
|
...(input.partyKind === 'company' ? { companyId: partyId } : {}),
|
||||||
|
...(input.partyKind === 'user' ? { userId: partyId } : {}),
|
||||||
|
...(scope ? { OR: [{ accountId: null }, { accountId: { in: scope } }] } : {}),
|
||||||
|
},
|
||||||
|
include: { movements: { select: { amount: true, voidedAt: true } } },
|
||||||
|
orderBy: [{ bookedAt: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
});
|
||||||
|
const open = docs
|
||||||
|
.map((doc) => {
|
||||||
|
const remaining = doc.amount.minus(this.settledOf(doc.movements));
|
||||||
|
return { doc, remaining };
|
||||||
|
})
|
||||||
|
.filter((row) => row.remaining.greaterThan(0));
|
||||||
|
const available = open.reduce((sum, row) => sum.plus(row.remaining), new Prisma.Decimal(0));
|
||||||
|
if (!available.greaterThan(0)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'سند بازی برای کم کردن این مانده نیست. اگر مانده از فاکتور است، دریافت را روی خود فاکتور ثبت کنید.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (amount.greaterThan(available)) {
|
||||||
|
throw new BadRequestException('مبلغ از ماندهٔ سندهای باز این طرف حساب بیشتر است.');
|
||||||
|
}
|
||||||
|
const occurredAt = startOfDay(input.occurredAt) ?? new Date();
|
||||||
|
let left = amount;
|
||||||
|
const touched: string[] = [];
|
||||||
|
await this.prisma.$transaction(async (tx) => {
|
||||||
|
for (const row of open) {
|
||||||
|
if (!left.greaterThan(0)) break;
|
||||||
|
const slice = left.lessThan(row.remaining) ? left : row.remaining;
|
||||||
|
const status = slice.equals(row.remaining) ? 'settled' : 'partial';
|
||||||
|
await tx.financialMovement.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
accountId: account.id,
|
||||||
|
documentId: row.doc.id,
|
||||||
|
direction: input.kind === 'income' ? 'in' : 'out',
|
||||||
|
amount: slice,
|
||||||
|
kind: input.kind === 'income' ? 'receipt' : 'payment',
|
||||||
|
occurredAt,
|
||||||
|
memo: input.kind === 'income' ? 'دریافت از مانده' : 'پرداخت از مانده',
|
||||||
|
createdById: actor.userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.financialDocument.update({
|
||||||
|
where: { id: row.doc.id },
|
||||||
|
data: { status, accountId: account.id },
|
||||||
|
});
|
||||||
|
if (status === 'settled') {
|
||||||
|
await tx.financialRecurringOccurrence.updateMany({
|
||||||
|
where: { documentId: row.doc.id, status: 'pending' },
|
||||||
|
data: { status: 'confirmed' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
touched.push(row.doc.id);
|
||||||
|
left = left.minus(slice);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await this.prisma.financialAuditLog.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
entityType: 'document',
|
||||||
|
entityId: touched[0] ?? partyId,
|
||||||
|
action: 'settle',
|
||||||
|
after: {
|
||||||
|
amount: amount.toFixed(2),
|
||||||
|
accountId: account.id,
|
||||||
|
documentIds: touched,
|
||||||
|
partyId,
|
||||||
|
},
|
||||||
|
actorUserId: actor.userId,
|
||||||
|
},
|
||||||
|
}).catch(() => undefined);
|
||||||
|
return { applied: money(amount), documentCount: touched.length };
|
||||||
|
}
|
||||||
|
|
||||||
private async resolveParty(
|
private async resolveParty(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
input: {
|
input: {
|
||||||
@@ -851,12 +1116,6 @@ export class TreasuryService {
|
|||||||
}
|
}
|
||||||
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
|
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
|
||||||
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
|
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
|
||||||
if (doc.kind === 'expense') {
|
|
||||||
const balance = await this.accountBalance(account.id);
|
|
||||||
if (balance.lessThan(amount)) {
|
|
||||||
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const nextSettled = settled.plus(amount);
|
const nextSettled = settled.plus(amount);
|
||||||
const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial';
|
const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial';
|
||||||
await this.prisma.$transaction([
|
await this.prisma.$transaction([
|
||||||
@@ -908,16 +1167,51 @@ export class TreasuryService {
|
|||||||
});
|
});
|
||||||
if (!doc || doc.voidedAt) throw new NotFoundException('سند پیدا نشد.');
|
if (!doc || doc.voidedAt) throw new NotFoundException('سند پیدا نشد.');
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
await this.prisma.$transaction([
|
await this.prisma.$transaction(async (tx) => {
|
||||||
this.prisma.financialMovement.updateMany({
|
const allocations = await tx.financialMovement.findMany({
|
||||||
|
where: { organizationId: actor.organizationId, reference: `alloc:${doc.id}`, voidedAt: null },
|
||||||
|
select: { documentId: true },
|
||||||
|
});
|
||||||
|
await tx.financialMovement.updateMany({
|
||||||
where: { documentId: doc.id, voidedAt: null },
|
where: { documentId: doc.id, voidedAt: null },
|
||||||
data: { voidedAt: now },
|
data: { voidedAt: now },
|
||||||
}),
|
});
|
||||||
this.prisma.financialDocument.update({
|
await tx.financialMovement.updateMany({
|
||||||
|
where: { organizationId: actor.organizationId, reference: `alloc:${doc.id}`, voidedAt: null },
|
||||||
|
data: { voidedAt: now },
|
||||||
|
});
|
||||||
|
await tx.financialDocument.update({
|
||||||
where: { id: doc.id },
|
where: { id: doc.id },
|
||||||
data: { status: 'void', voidedAt: now, voidReason: reason?.trim() || 'ابطال' },
|
data: { status: 'void', voidedAt: now, voidReason: reason?.trim() || 'ابطال' },
|
||||||
}),
|
});
|
||||||
]);
|
const excess = await tx.financialDocument.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
notes: `source:${doc.id}`,
|
||||||
|
voidedAt: null,
|
||||||
|
status: { in: ['open', 'partial'] },
|
||||||
|
},
|
||||||
|
include: { movements: { select: { voidedAt: true } } },
|
||||||
|
});
|
||||||
|
for (const child of excess) {
|
||||||
|
if (child.movements.some((row) => !row.voidedAt)) continue;
|
||||||
|
await tx.financialDocument.update({
|
||||||
|
where: { id: child.id },
|
||||||
|
data: { status: 'void', voidedAt: now, voidReason: 'ابطال سند مبدأ' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const affected = [...new Set(allocations.map((row) => row.documentId).filter((id): id is string => Boolean(id)))];
|
||||||
|
for (const documentId of affected) {
|
||||||
|
const row = await tx.financialDocument.findUnique({
|
||||||
|
where: { id: documentId },
|
||||||
|
include: { movements: { select: { amount: true, voidedAt: true } } },
|
||||||
|
});
|
||||||
|
if (!row || row.voidedAt || row.status === 'void') continue;
|
||||||
|
const settled = this.settledOf(row.movements);
|
||||||
|
const status = settled.equals(0) ? 'open' : settled.greaterThanOrEqualTo(row.amount) ? 'settled' : 'partial';
|
||||||
|
await tx.financialDocument.update({ where: { id: row.id }, data: { status } });
|
||||||
|
}
|
||||||
|
});
|
||||||
const fresh = await this.prisma.financialDocument.findUniqueOrThrow({
|
const fresh = await this.prisma.financialDocument.findUniqueOrThrow({
|
||||||
where: { id: doc.id },
|
where: { id: doc.id },
|
||||||
include: { category: true, account: true, movements: true },
|
include: { category: true, account: true, movements: true },
|
||||||
@@ -1092,6 +1386,17 @@ export class TreasuryService {
|
|||||||
}
|
}
|
||||||
const bookedIncome = dec(income._sum.amount);
|
const bookedIncome = dec(income._sum.amount);
|
||||||
const bookedExpense = dec(expense._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(
|
const totalBalance = accounts.reduce(
|
||||||
(sum, account) => sum.plus(account.balance),
|
(sum, account) => sum.plus(account.balance),
|
||||||
new Prisma.Decimal(0),
|
new Prisma.Decimal(0),
|
||||||
@@ -1101,7 +1406,7 @@ export class TreasuryService {
|
|||||||
actualReceipts: money(dec(receipts._sum.amount)),
|
actualReceipts: money(dec(receipts._sum.amount)),
|
||||||
bookedExpense: money(bookedExpense),
|
bookedExpense: money(bookedExpense),
|
||||||
actualPayments: money(dec(payments._sum.amount)),
|
actualPayments: money(dec(payments._sum.amount)),
|
||||||
operatingProfit: money(bookedIncome.minus(bookedExpense)),
|
operatingProfit: money(bookedIncome.plus(invoiceSales.net).minus(bookedExpense)),
|
||||||
receivables: money(receivables),
|
receivables: money(receivables),
|
||||||
payables: money(payables),
|
payables: money(payables),
|
||||||
totalBalance: money(totalBalance),
|
totalBalance: money(totalBalance),
|
||||||
@@ -1111,6 +1416,76 @@ export class TreasuryService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** مبلغ قطعی را از ماندهٔ باز همان طرف کم میکند؛ اول سندهای همنوع، بعد طرف مقابل. روی موجودی حساب اثر ندارد. */
|
||||||
|
private async allocatePartyBalance(
|
||||||
|
tx: Prisma.TransactionClient,
|
||||||
|
actor: Actor,
|
||||||
|
input: {
|
||||||
|
party: { partyKind: string; personId: string | null; companyId: string | null; userId: string | null };
|
||||||
|
sourceId: string;
|
||||||
|
kind: 'income' | 'expense';
|
||||||
|
amount: Prisma.Decimal;
|
||||||
|
accountId: string;
|
||||||
|
occurredAt: Date;
|
||||||
|
memo: string;
|
||||||
|
},
|
||||||
|
): Promise<Prisma.Decimal> {
|
||||||
|
const scope = await this.accountScope(actor);
|
||||||
|
const openDocs = await tx.financialDocument.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
id: { not: input.sourceId },
|
||||||
|
voidedAt: null,
|
||||||
|
status: { in: ['open', 'partial'] },
|
||||||
|
partyKind: input.party.partyKind,
|
||||||
|
...(input.party.personId ? { personId: input.party.personId } : {}),
|
||||||
|
...(input.party.companyId ? { companyId: input.party.companyId } : {}),
|
||||||
|
...(input.party.userId ? { userId: input.party.userId } : {}),
|
||||||
|
...(scope ? { OR: [{ accountId: null }, { accountId: { in: scope } }] } : {}),
|
||||||
|
},
|
||||||
|
include: { movements: { select: { amount: true, voidedAt: true } } },
|
||||||
|
orderBy: [{ bookedAt: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
});
|
||||||
|
const ordered = [
|
||||||
|
...openDocs.filter((row) => row.kind === input.kind),
|
||||||
|
...openDocs.filter((row) => row.kind !== input.kind),
|
||||||
|
];
|
||||||
|
let left = input.amount;
|
||||||
|
for (const row of ordered) {
|
||||||
|
if (!left.greaterThan(0)) break;
|
||||||
|
const remaining = row.amount.minus(this.settledOf(row.movements));
|
||||||
|
if (!remaining.greaterThan(0)) continue;
|
||||||
|
const slice = left.lessThan(remaining) ? left : remaining;
|
||||||
|
const status = slice.equals(remaining) ? 'settled' : 'partial';
|
||||||
|
await tx.financialMovement.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
accountId: input.accountId,
|
||||||
|
documentId: row.id,
|
||||||
|
direction: row.kind === 'income' ? 'in' : 'out',
|
||||||
|
amount: slice,
|
||||||
|
kind: 'allocation',
|
||||||
|
occurredAt: input.occurredAt,
|
||||||
|
memo: input.memo,
|
||||||
|
reference: `alloc:${input.sourceId}`,
|
||||||
|
createdById: actor.userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.financialDocument.update({
|
||||||
|
where: { id: row.id },
|
||||||
|
data: { status },
|
||||||
|
});
|
||||||
|
if (status === 'settled') {
|
||||||
|
await tx.financialRecurringOccurrence.updateMany({
|
||||||
|
where: { documentId: row.id, status: 'pending' },
|
||||||
|
data: { status: 'confirmed' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
left = left.minus(slice);
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
private settledOf(movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>) {
|
private settledOf(movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>) {
|
||||||
return movements
|
return movements
|
||||||
.filter((row) => !row.voidedAt)
|
.filter((row) => !row.voidedAt)
|
||||||
@@ -1119,7 +1494,7 @@ export class TreasuryService {
|
|||||||
|
|
||||||
private async accountBalance(accountId: string) {
|
private async accountBalance(accountId: string) {
|
||||||
const rows = await this.prisma.financialMovement.findMany({
|
const rows = await this.prisma.financialMovement.findMany({
|
||||||
where: { accountId, voidedAt: null },
|
where: { accountId, voidedAt: null, kind: { not: 'allocation' } },
|
||||||
select: { direction: true, amount: true },
|
select: { direction: true, amount: true },
|
||||||
});
|
});
|
||||||
return rows.reduce(
|
return rows.reduce(
|
||||||
@@ -1128,6 +1503,47 @@ export class TreasuryService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async actorPermissions(actor: Actor): Promise<string[]> {
|
||||||
|
const membership = await this.prisma.membership.findFirst({
|
||||||
|
where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true },
|
||||||
|
select: {
|
||||||
|
orgRole: { select: { permissions: true } },
|
||||||
|
treasuryAccessOverride: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const rolePermissions = Array.isArray(membership?.orgRole?.permissions)
|
||||||
|
? membership.orgRole.permissions.map(String)
|
||||||
|
: [];
|
||||||
|
return permissionsWithTreasuryOverride(
|
||||||
|
rolePermissions,
|
||||||
|
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertDocumentsManage(actor: Actor) {
|
||||||
|
if (canManageTreasuryDocuments(actor.role, await this.actorPermissions(actor))) return;
|
||||||
|
throw new ForbiddenException('اجازه ویرایش یا حذف اسناد را ندارید.');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async requireScopedDocument(actor: Actor, id: string) {
|
||||||
|
const scope = await this.accountScope(actor);
|
||||||
|
const doc = await this.prisma.financialDocument.findFirst({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
...(scope ? { OR: [{ accountId: null }, { accountId: { in: scope } }] } : {}),
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
category: true,
|
||||||
|
account: true,
|
||||||
|
movements: true,
|
||||||
|
attachments: { select: { id: true, fileName: true, mimeType: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!doc) throw new NotFoundException('سند پیدا نشد.');
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
private async accountScope(actor: Actor): Promise<string[] | null> {
|
private async accountScope(actor: Actor): Promise<string[] | null> {
|
||||||
if (actor.role === 'owner' || actor.role === 'admin') return null;
|
if (actor.role === 'owner' || actor.role === 'admin') return null;
|
||||||
const membership = await this.prisma.membership.findFirst({
|
const membership = await this.prisma.membership.findFirst({
|
||||||
@@ -1194,7 +1610,7 @@ export class TreasuryService {
|
|||||||
const from = startOfDay(range?.from);
|
const from = startOfDay(range?.from);
|
||||||
const to = startOfDay(range?.to);
|
const to = startOfDay(range?.to);
|
||||||
const movements = await this.prisma.financialMovement.findMany({
|
const movements = await this.prisma.financialMovement.findMany({
|
||||||
where: { accountId: account.id, voidedAt: null },
|
where: { accountId: account.id, voidedAt: null, kind: { not: 'allocation' } },
|
||||||
select: { direction: true, amount: true, kind: true, occurredAt: true },
|
select: { direction: true, amount: true, kind: true, occurredAt: true },
|
||||||
});
|
});
|
||||||
let balance = new Prisma.Decimal(0);
|
let balance = new Prisma.Decimal(0);
|
||||||
@@ -1251,7 +1667,8 @@ export class TreasuryService {
|
|||||||
category?: { name: string } | null;
|
category?: { name: string } | null;
|
||||||
account?: { name: string } | null;
|
account?: { name: string } | null;
|
||||||
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>;
|
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>;
|
||||||
attachments?: Array<{ id: string; fileName: string }>;
|
attachments?: Array<{ id: string; fileName: string; mimeType?: string }>;
|
||||||
|
voidedAt?: Date | null;
|
||||||
}): FinancialDocumentDto {
|
}): FinancialDocumentDto {
|
||||||
const settled = this.settledOf(row.movements);
|
const settled = this.settledOf(row.movements);
|
||||||
const rawRemaining = row.amount.minus(settled);
|
const rawRemaining = row.amount.minus(settled);
|
||||||
|
|||||||
@@ -104,8 +104,10 @@ export class UsersService {
|
|||||||
orgRoleId: dto.orgRoleId,
|
orgRoleId: dto.orgRoleId,
|
||||||
role: dto.role,
|
role: dto.role,
|
||||||
});
|
});
|
||||||
if (resolved.role === 'owner' && actorRole !== 'owner') {
|
if (resolved.role === 'owner') {
|
||||||
throw new ForbiddenException('فقط مالک میتواند نقش مدیر سیستم را واگذار کند');
|
throw new BadRequestException(
|
||||||
|
'هر محیط فقط یک مالک دارد و مالک همان کسی است که ثبتنام کرده. برای دسترسی کامل نقش مدیر را انتخاب کنید.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingUser = await this.prisma.user.findFirst({ where: { mobile } });
|
const existingUser = await this.prisma.user.findFirst({ where: { mobile } });
|
||||||
@@ -449,6 +451,10 @@ export class UsersService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (nextRole === 'owner' && target.role !== 'owner') {
|
||||||
|
await this.memberships.assertSoleOwner(organizationId, target.userId);
|
||||||
|
}
|
||||||
|
|
||||||
if (target.role === 'owner' && nextRole !== 'owner') {
|
if (target.role === 'owner' && nextRole !== 'owner') {
|
||||||
const owners = await this.memberships.countActiveOwners(
|
const owners = await this.memberships.countActiveOwners(
|
||||||
organizationId,
|
organizationId,
|
||||||
@@ -456,7 +462,7 @@ export class UsersService {
|
|||||||
);
|
);
|
||||||
if (owners < 1) {
|
if (owners < 1) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
'حداقل یک مالک برای سازمان لازم است؛ ابتدا مالک دیگری تعیین کنید',
|
'مالک محیط همان کسی است که ثبتنام کرده و نمیتوان نقش او را عوض کرد',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -528,6 +534,9 @@ export class UsersService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isActive && !target.isActive) {
|
if (isActive && !target.isActive) {
|
||||||
|
if (target.role === 'owner') {
|
||||||
|
await this.memberships.assertSoleOwner(organizationId, targetId);
|
||||||
|
}
|
||||||
await this.billing.assertSeatAvailable(organizationId, targetId);
|
await this.billing.assertSeatAvailable(organizationId, targetId);
|
||||||
}
|
}
|
||||||
await this.prisma.membership.update({
|
await this.prisma.membership.update({
|
||||||
@@ -558,6 +567,9 @@ export class UsersService {
|
|||||||
resolved: { role: UserRole; orgRoleId: string },
|
resolved: { role: UserRole; orgRoleId: string },
|
||||||
): Promise<OrgUserDto> {
|
): Promise<OrgUserDto> {
|
||||||
await this.billing.assertSeatAvailable(organizationId, userId);
|
await this.billing.assertSeatAvailable(organizationId, userId);
|
||||||
|
if (resolved.role === 'owner') {
|
||||||
|
await this.memberships.assertSoleOwner(organizationId, userId);
|
||||||
|
}
|
||||||
const existing = await this.prisma.membership.findFirst({
|
const existing = await this.prisma.membership.findFirst({
|
||||||
where: { userId, organizationId },
|
where: { userId, organizationId },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ describe('اتوماسیون پیام', () => {
|
|||||||
'سلام علی از منتکت - {unknown}',
|
'سلام علی از منتکت - {unknown}',
|
||||||
);
|
);
|
||||||
assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x');
|
assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x');
|
||||||
|
assert.equal(
|
||||||
|
applyMessageTemplate('از طرف {از طرف}', { from: 'هنراندیشه' }),
|
||||||
|
'از طرف هنراندیشه',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('متن پیامک بریده نمیشود', () => {
|
it('متن پیامک بریده نمیشود', () => {
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { describe, it } from 'node:test';
|
import { describe, it } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { leadsDeepWhere, resolveSectionAccess } from '../src/common/data-access';
|
import {
|
||||||
|
customersCompanyWhere,
|
||||||
|
customersPersonWhere,
|
||||||
|
leadsDeepWhere,
|
||||||
|
resolveSectionAccess,
|
||||||
|
} from '../src/common/data-access';
|
||||||
import {
|
import {
|
||||||
noteAccessWhere,
|
noteAccessWhere,
|
||||||
normalizeDataVisibility,
|
normalizeDataVisibility,
|
||||||
@@ -122,3 +127,49 @@ describe('عمق داده وقتی نقش فقط بعضی بخشها را ذ
|
|||||||
assert.deepEqual(leads.section, { mode: 'rules', rules: [{ owners: ['self'] }] });
|
assert.deepEqual(leads.section, { mode: 'rules', rules: [{ owners: ['self'] }] });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('مسئول گروه مشتری روی عمق داده', () => {
|
||||||
|
const selfAccess = { mode: 'rules' as const, rules: [{ owners: ['self' as const] }] };
|
||||||
|
|
||||||
|
it('محدودیت self با OR مسئول گروه برای شخص', () => {
|
||||||
|
const where = customersPersonWhere({
|
||||||
|
userId: 'u1',
|
||||||
|
role: 'sales',
|
||||||
|
customersAccess: selfAccess,
|
||||||
|
teamPeerIds: null,
|
||||||
|
});
|
||||||
|
assert.deepEqual(where, {
|
||||||
|
OR: [
|
||||||
|
{ ownerId: 'u1' },
|
||||||
|
{ groupLinks: { some: { group: { assignees: { some: { id: 'u1' } } } } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('محدودیت self با OR مسئول گروه برای شرکت', () => {
|
||||||
|
const where = customersCompanyWhere({
|
||||||
|
userId: 'u1',
|
||||||
|
role: 'sales',
|
||||||
|
customersAccess: selfAccess,
|
||||||
|
teamPeerIds: null,
|
||||||
|
});
|
||||||
|
assert.deepEqual(where, {
|
||||||
|
OR: [
|
||||||
|
{ ownerId: 'u1' },
|
||||||
|
{ groupLinks: { some: { group: { assignees: { some: { id: 'u1' } } } } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('بدون محدودیت عمقی، فیلتر اضافه نمیشود', () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
customersPersonWhere({
|
||||||
|
userId: 'u1',
|
||||||
|
role: 'sales',
|
||||||
|
customersAccess: { mode: 'all', rules: [] },
|
||||||
|
teamPeerIds: null,
|
||||||
|
}),
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||||
import type { CustomerGroupDto, PersonImportSourceStatDto, PersonMood } from '@mento/shared';
|
import type { CustomerGroupDto, PersonImportSourceStatDto, PersonMood } from '@mento/shared';
|
||||||
|
import { ACTIVITY_EXPERIENCE_OPTIONS } from '@mento/shared';
|
||||||
import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood';
|
import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood';
|
||||||
import { groupSwatch } from '@/lib/customer-groups';
|
import { groupSwatch } from '@/lib/customer-groups';
|
||||||
import { toFaDigits } from '@/lib/jalali';
|
import { toFaDigits } from '@/lib/jalali';
|
||||||
@@ -12,6 +13,7 @@ export type ContactsFilterValue = {
|
|||||||
sources: string[];
|
sources: string[];
|
||||||
moods: PersonMood[];
|
moods: PersonMood[];
|
||||||
disc: string;
|
disc: string;
|
||||||
|
activityExperiences: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -33,7 +35,13 @@ const emit = defineEmits<{
|
|||||||
close: [];
|
close: [];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const draft = reactive<ContactsFilterValue>({ groups: [], sources: [], moods: [], disc: '' });
|
const draft = reactive<ContactsFilterValue>({
|
||||||
|
groups: [],
|
||||||
|
sources: [],
|
||||||
|
moods: [],
|
||||||
|
disc: '',
|
||||||
|
activityExperiences: [],
|
||||||
|
});
|
||||||
const draftSort = ref('');
|
const draftSort = ref('');
|
||||||
const groupQuery = ref('');
|
const groupQuery = ref('');
|
||||||
const GROUP_SEARCH_MIN = 8;
|
const GROUP_SEARCH_MIN = 8;
|
||||||
@@ -50,6 +58,7 @@ watch(
|
|||||||
draft.sources = [...props.value.sources];
|
draft.sources = [...props.value.sources];
|
||||||
draft.moods = [...props.value.moods];
|
draft.moods = [...props.value.moods];
|
||||||
draft.disc = props.value.disc;
|
draft.disc = props.value.disc;
|
||||||
|
draft.activityExperiences = [...(props.value.activityExperiences ?? [])];
|
||||||
draftSort.value = props.sort ?? defaultSort.value;
|
draftSort.value = props.sort ?? defaultSort.value;
|
||||||
groupQuery.value = '';
|
groupQuery.value = '';
|
||||||
},
|
},
|
||||||
@@ -77,7 +86,12 @@ const filteredGroups = computed(() => {
|
|||||||
const draftCount = computed(
|
const draftCount = computed(
|
||||||
() =>
|
() =>
|
||||||
draft.groups.length +
|
draft.groups.length +
|
||||||
(isPeople.value ? draft.sources.length + draft.moods.length + (draft.disc ? 1 : 0) : 0) +
|
(isPeople.value
|
||||||
|
? draft.sources.length +
|
||||||
|
draft.moods.length +
|
||||||
|
draft.activityExperiences.length +
|
||||||
|
(draft.disc ? 1 : 0)
|
||||||
|
: 0) +
|
||||||
(hasSort.value && draftSort.value !== defaultSort.value ? 1 : 0),
|
(hasSort.value && draftSort.value !== defaultSort.value ? 1 : 0),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -92,6 +106,7 @@ function clearAll() {
|
|||||||
draft.sources = [];
|
draft.sources = [];
|
||||||
draft.moods = [];
|
draft.moods = [];
|
||||||
draft.disc = '';
|
draft.disc = '';
|
||||||
|
draft.activityExperiences = [];
|
||||||
if (hasSort.value) draftSort.value = defaultSort.value;
|
if (hasSort.value) draftSort.value = defaultSort.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,6 +118,7 @@ function apply() {
|
|||||||
sources: [...draft.sources],
|
sources: [...draft.sources],
|
||||||
moods: [...draft.moods],
|
moods: [...draft.moods],
|
||||||
disc: draft.disc,
|
disc: draft.disc,
|
||||||
|
activityExperiences: [...draft.activityExperiences],
|
||||||
},
|
},
|
||||||
hasSort.value ? draftSort.value : undefined,
|
hasSort.value ? draftSort.value : undefined,
|
||||||
);
|
);
|
||||||
@@ -126,6 +142,9 @@ function apply() {
|
|||||||
<strong>{{ hasSort ? 'فیلتر و مرتبسازی' : 'فیلترها' }}</strong>
|
<strong>{{ hasSort ? 'فیلتر و مرتبسازی' : 'فیلترها' }}</strong>
|
||||||
<button type="button" class="link" :disabled="!draftCount" @click="clearAll">پاک کردن همه</button>
|
<button type="button" class="link" :disabled="!draftCount" @click="clearAll">پاک کردن همه</button>
|
||||||
</header>
|
</header>
|
||||||
|
<p v-if="isPeople" class="facet-hint">
|
||||||
|
گروه، منبع و وضعیت با هم جمع میشوند؛ هر کدام کافی است (بدون تکرار).
|
||||||
|
</p>
|
||||||
|
|
||||||
<div class="panel-body">
|
<div class="panel-body">
|
||||||
<section v-if="hasSort" class="sec">
|
<section v-if="hasSort" class="sec">
|
||||||
@@ -207,6 +226,27 @@ function apply() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="sec">
|
||||||
|
<h4>
|
||||||
|
سابقه فعالیت
|
||||||
|
<span v-if="draft.activityExperiences.length" class="sel">
|
||||||
|
{{ toFaDigits(draft.activityExperiences.length) }} انتخاب
|
||||||
|
</span>
|
||||||
|
</h4>
|
||||||
|
<div class="pills">
|
||||||
|
<button
|
||||||
|
v-for="item in ACTIVITY_EXPERIENCE_OPTIONS"
|
||||||
|
:key="item"
|
||||||
|
type="button"
|
||||||
|
class="pill"
|
||||||
|
:class="{ on: draft.activityExperiences.includes(item) }"
|
||||||
|
@click="toggle(draft.activityExperiences, item)"
|
||||||
|
>
|
||||||
|
{{ item }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section v-if="canBehavior" class="sec">
|
<section v-if="canBehavior" class="sec">
|
||||||
<h4>تیپ DISC</h4>
|
<h4>تیپ DISC</h4>
|
||||||
<div class="pills">
|
<div class="pills">
|
||||||
@@ -264,6 +304,15 @@ function apply() {
|
|||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 1px solid var(--line);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.facet-hint {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.35rem 0.9rem 0.55rem;
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
color: #64748b;
|
||||||
|
line-height: 1.45;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
.panel-foot {
|
.panel-foot {
|
||||||
border-top: 1px solid var(--line);
|
border-top: 1px solid var(--line);
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
|
|||||||
@@ -1,29 +1,54 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import type { CustomerGroupColor, CustomerGroupDto } from '@mento/shared';
|
import type { CustomerGroupColor, CustomerGroupDto, OrgUserDto } from '@mento/shared';
|
||||||
import { CUSTOMER_GROUP_COLORS } from '@mento/shared';
|
import { CUSTOMER_GROUP_COLORS } from '@mento/shared';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import { toFaDigits } from '@/lib/jalali';
|
import { toFaDigits } from '@/lib/jalali';
|
||||||
|
import { normalizeSearchText } from '@/lib/search';
|
||||||
import {
|
import {
|
||||||
CUSTOMER_GROUP_COLOR_LABELS,
|
CUSTOMER_GROUP_COLOR_LABELS,
|
||||||
groupSwatch,
|
groupSwatch,
|
||||||
useCustomerGroups,
|
useCustomerGroups,
|
||||||
} from '@/lib/customer-groups';
|
} from '@/lib/customer-groups';
|
||||||
|
import { useAuthStore } from '@/stores/auth';
|
||||||
import { UiButton, UiInput, UiModal } from '@/components/ui';
|
import { UiButton, UiInput, UiModal } from '@/components/ui';
|
||||||
import UiIcon from '@/components/UiIcon.vue';
|
import UiIcon from '@/components/UiIcon.vue';
|
||||||
|
import OrgUserPersonPick from '@/components/OrgUserPersonPick.vue';
|
||||||
|
|
||||||
const props = defineProps<{ open: boolean }>();
|
const props = defineProps<{ open: boolean }>();
|
||||||
const emit = defineEmits<{ close: []; changed: [] }>();
|
const emit = defineEmits<{ close: []; changed: [] }>();
|
||||||
|
|
||||||
|
const auth = useAuthStore();
|
||||||
|
const canManage = computed(
|
||||||
|
() => auth.user?.role === 'owner' || auth.user?.role === 'admin',
|
||||||
|
);
|
||||||
|
|
||||||
const { groups, load } = useCustomerGroups();
|
const { groups, load } = useCustomerGroups();
|
||||||
|
const users = ref<OrgUserDto[]>([]);
|
||||||
const newName = ref('');
|
const newName = ref('');
|
||||||
const newColor = ref<CustomerGroupColor>('teal');
|
const newColor = ref<CustomerGroupColor>('teal');
|
||||||
|
const newAssigneeIds = ref<string[]>([]);
|
||||||
const editingId = ref<string | null>(null);
|
const editingId = ref<string | null>(null);
|
||||||
const editName = ref('');
|
const editName = ref('');
|
||||||
|
const assigneeDraft = ref<Record<string, string[]>>({});
|
||||||
|
const listQuery = ref('');
|
||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
|
|
||||||
|
const filteredGroups = computed(() => {
|
||||||
|
const q = normalizeSearchText(listQuery.value);
|
||||||
|
if (!q) return groups.value;
|
||||||
|
return groups.value.filter((g) => {
|
||||||
|
const assigneeNames = (g.assignees ?? []).map((a) => a.fullName).join(' ');
|
||||||
|
return (
|
||||||
|
normalizeSearchText(g.name).includes(q) ||
|
||||||
|
normalizeSearchText(g.parentName ?? '').includes(q) ||
|
||||||
|
normalizeSearchText(assigneeNames).includes(q)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
function errorText(e: unknown, fallback: string) {
|
function errorText(e: unknown, fallback: string) {
|
||||||
if (axios.isAxiosError(e)) {
|
if (axios.isAxiosError(e)) {
|
||||||
const msg = (e.response?.data as { message?: string | string[] } | undefined)?.message;
|
const msg = (e.response?.data as { message?: string | string[] } | undefined)?.message;
|
||||||
@@ -33,12 +58,30 @@ function errorText(e: unknown, fallback: string) {
|
|||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadUsers() {
|
||||||
|
try {
|
||||||
|
const { data } = await api.get<OrgUserDto[]>('/users');
|
||||||
|
users.value = data.filter((u) => u.isActive !== false);
|
||||||
|
} catch {
|
||||||
|
users.value = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncAssigneeDraft() {
|
||||||
|
const next: Record<string, string[]> = {};
|
||||||
|
for (const g of groups.value) {
|
||||||
|
next[g.id] = (g.assignees ?? []).map((a) => a.id);
|
||||||
|
}
|
||||||
|
assigneeDraft.value = next;
|
||||||
|
}
|
||||||
|
|
||||||
async function run(task: () => Promise<unknown>, fallback: string) {
|
async function run(task: () => Promise<unknown>, fallback: string) {
|
||||||
busy.value = true;
|
busy.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
try {
|
try {
|
||||||
await task();
|
await task();
|
||||||
await load(true);
|
await load(true);
|
||||||
|
syncAssigneeDraft();
|
||||||
emit('changed');
|
emit('changed');
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -53,10 +96,18 @@ async function create() {
|
|||||||
const name = newName.value.trim();
|
const name = newName.value.trim();
|
||||||
if (!name) return;
|
if (!name) return;
|
||||||
const ok = await run(
|
const ok = await run(
|
||||||
() => api.post('/customer-groups', { name, color: newColor.value }),
|
() =>
|
||||||
|
api.post('/customer-groups', {
|
||||||
|
name,
|
||||||
|
color: newColor.value,
|
||||||
|
assigneeIds: newAssigneeIds.value,
|
||||||
|
}),
|
||||||
'ساخت گروه ناموفق بود.',
|
'ساخت گروه ناموفق بود.',
|
||||||
);
|
);
|
||||||
if (ok) newName.value = '';
|
if (ok) {
|
||||||
|
newName.value = '';
|
||||||
|
newAssigneeIds.value = [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startEdit(g: CustomerGroupDto) {
|
function startEdit(g: CustomerGroupDto) {
|
||||||
@@ -82,6 +133,24 @@ async function setColor(g: CustomerGroupDto, color: CustomerGroupColor) {
|
|||||||
await run(() => api.patch(`/customer-groups/${g.id}`, { color }), 'تغییر رنگ ناموفق بود.');
|
await run(() => api.patch(`/customer-groups/${g.id}`, { color }), 'تغییر رنگ ناموفق بود.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function onAssigneesChange(g: CustomerGroupDto, ids: string[]) {
|
||||||
|
assigneeDraft.value = { ...assigneeDraft.value, [g.id]: ids };
|
||||||
|
const prev = (g.assignees ?? []).map((a) => a.id).sort().join(',');
|
||||||
|
const next = [...ids].sort().join(',');
|
||||||
|
if (prev === next) return;
|
||||||
|
await run(
|
||||||
|
() => api.patch(`/customer-groups/${g.id}`, { assigneeIds: ids }),
|
||||||
|
'ذخیره مسئولان گروه ناموفق بود.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function assigneeLabel(g: CustomerGroupDto) {
|
||||||
|
const names = (g.assignees ?? []).map((a) => a.fullName).filter(Boolean);
|
||||||
|
if (!names.length) return 'بدون مسئول';
|
||||||
|
if (names.length === 1) return names[0]!;
|
||||||
|
return `${names[0]} و ${toFaDigits(names.length - 1)} نفر دیگر`;
|
||||||
|
}
|
||||||
|
|
||||||
async function remove(g: CustomerGroupDto) {
|
async function remove(g: CustomerGroupDto) {
|
||||||
const used = g.personCount + g.companyCount;
|
const used = g.personCount + g.companyCount;
|
||||||
const note = used ? ` این گروه از ${toFaDigits(used)} مخاطب برداشته میشود (خود مخاطبها حذف نمیشوند).` : '';
|
const note = used ? ` این گروه از ${toFaDigits(used)} مخاطب برداشته میشود (خود مخاطبها حذف نمیشوند).` : '';
|
||||||
@@ -95,9 +164,12 @@ watch(
|
|||||||
if (!open) return;
|
if (!open) return;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
editingId.value = null;
|
editingId.value = null;
|
||||||
void load(true).catch(() => {
|
listQuery.value = '';
|
||||||
error.value = 'بارگذاری گروهها ناموفق بود.';
|
void Promise.all([load(true), loadUsers()])
|
||||||
});
|
.then(() => syncAssigneeDraft())
|
||||||
|
.catch(() => {
|
||||||
|
error.value = 'بارگذاری گروهها ناموفق بود.';
|
||||||
|
});
|
||||||
},
|
},
|
||||||
{ immediate: true },
|
{ immediate: true },
|
||||||
);
|
);
|
||||||
@@ -107,34 +179,60 @@ watch(
|
|||||||
<UiModal :open="open" title="گروههای مشتری" @close="emit('close')">
|
<UiModal :open="open" title="گروههای مشتری" @close="emit('close')">
|
||||||
<div class="manager">
|
<div class="manager">
|
||||||
<p class="lead">
|
<p class="lead">
|
||||||
هر شخص یا شرکت میتواند چند گروه داشته باشد. گروههایی که از تهحساب میآیند با برچسب
|
هر شخص یا شرکت میتواند چند گروه داشته باشد. مسئولان گروه (اختیاری) اعضای آن گروه را مثل
|
||||||
«تهحساب» مشخص شدهاند.
|
مشتریان خود میبینند. گروههای تهحساب با برچسب «تهحساب» مشخص شدهاند.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<form class="new-row" @submit.prevent="create">
|
<form v-if="canManage" class="create-panel" @submit.prevent="create">
|
||||||
<UiInput v-model="newName" placeholder="نام گروه جدید" :maxlength="80" :disabled="busy" />
|
<header class="create-head">
|
||||||
<div class="swatches">
|
<strong>گروه جدید</strong>
|
||||||
<button
|
<span>نام، رنگ و مسئولان را مشخص کنید و افزودن بزنید.</span>
|
||||||
v-for="c in CUSTOMER_GROUP_COLORS"
|
</header>
|
||||||
:key="c"
|
<div class="new-row">
|
||||||
type="button"
|
<UiInput v-model="newName" placeholder="نام گروه جدید" :maxlength="80" :disabled="busy" />
|
||||||
class="swatch"
|
<div class="swatches">
|
||||||
:class="{ on: newColor === c }"
|
<button
|
||||||
:style="{ background: groupSwatch(c).fg }"
|
v-for="c in CUSTOMER_GROUP_COLORS"
|
||||||
:title="CUSTOMER_GROUP_COLOR_LABELS[c]"
|
:key="c"
|
||||||
@click="newColor = c"
|
type="button"
|
||||||
|
class="swatch"
|
||||||
|
:class="{ on: newColor === c }"
|
||||||
|
:style="{ background: groupSwatch(c).fg }"
|
||||||
|
:title="CUSTOMER_GROUP_COLOR_LABELS[c]"
|
||||||
|
@click="newColor = c"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<UiButton type="submit" variant="primary" size="sm" :disabled="busy || !newName.trim()">
|
||||||
|
<UiIcon name="plus" :size="15" />
|
||||||
|
افزودن
|
||||||
|
</UiButton>
|
||||||
|
</div>
|
||||||
|
<div v-if="users.length" class="assignee-field create-assignees">
|
||||||
|
<span class="assignees-label">مسئولان (اختیاری)</span>
|
||||||
|
<OrgUserPersonPick
|
||||||
|
v-model="newAssigneeIds"
|
||||||
|
:users="users"
|
||||||
|
:disabled="busy"
|
||||||
|
empty-label="انتخاب مسئول"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<UiButton type="submit" variant="primary" size="sm" :disabled="busy || !newName.trim()">
|
|
||||||
<UiIcon name="plus" :size="15" />
|
|
||||||
افزودن
|
|
||||||
</UiButton>
|
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<p v-if="error" class="error">{{ error }}</p>
|
<p v-if="error" class="error">{{ error }}</p>
|
||||||
|
|
||||||
<ul v-if="groups.length" class="list">
|
<div v-if="canManage || groups.length" class="list-head">
|
||||||
<li v-for="g in groups" :key="g.id" class="row">
|
<h3 class="list-title">گروههای موجود</h3>
|
||||||
|
<label v-if="groups.length" class="list-search">
|
||||||
|
<UiIcon name="search" :size="15" />
|
||||||
|
<input
|
||||||
|
v-model="listQuery"
|
||||||
|
type="search"
|
||||||
|
placeholder="جستجوی گروه یا مسئول…"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<ul v-if="filteredGroups.length" class="list">
|
||||||
|
<li v-for="g in filteredGroups" :key="g.id" class="row">
|
||||||
<div class="name-cell">
|
<div class="name-cell">
|
||||||
<form v-if="editingId === g.id" class="edit" @submit.prevent="saveName(g)">
|
<form v-if="editingId === g.id" class="edit" @submit.prevent="saveName(g)">
|
||||||
<UiInput v-model="editName" :maxlength="80" :disabled="busy" />
|
<UiInput v-model="editName" :maxlength="80" :disabled="busy" />
|
||||||
@@ -152,9 +250,10 @@ watch(
|
|||||||
<span class="count">
|
<span class="count">
|
||||||
{{ toFaDigits(g.personCount) }} شخص · {{ toFaDigits(g.companyCount) }} شرکت
|
{{ toFaDigits(g.personCount) }} شخص · {{ toFaDigits(g.companyCount) }} شرکت
|
||||||
</span>
|
</span>
|
||||||
|
<span v-if="!canManage" class="assignee-summary">{{ assigneeLabel(g) }}</span>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="editingId !== g.id" class="row-actions">
|
<div v-if="editingId !== g.id && canManage" class="row-actions">
|
||||||
<div class="swatches">
|
<div class="swatches">
|
||||||
<button
|
<button
|
||||||
v-for="c in CUSTOMER_GROUP_COLORS"
|
v-for="c in CUSTOMER_GROUP_COLORS"
|
||||||
@@ -173,8 +272,20 @@ watch(
|
|||||||
<UiIcon name="trash" :size="14" />
|
<UiIcon name="trash" :size="14" />
|
||||||
</UiButton>
|
</UiButton>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="canManage && users.length" class="assignee-field">
|
||||||
|
<span class="assignees-label">مسئولان</span>
|
||||||
|
<OrgUserPersonPick
|
||||||
|
:model-value="assigneeDraft[g.id] ?? []"
|
||||||
|
:users="users"
|
||||||
|
:disabled="busy"
|
||||||
|
empty-label="انتخاب مسئول"
|
||||||
|
@update:model-value="(ids) => (assigneeDraft[g.id] = ids)"
|
||||||
|
@change="(ids) => onAssigneesChange(g, ids)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
<p v-else-if="groups.length && listQuery.trim()" class="muted">گروهی با این جستجو پیدا نشد.</p>
|
||||||
<p v-else class="muted">هنوز گروهی ساخته نشده است.</p>
|
<p v-else class="muted">هنوز گروهی ساخته نشده است.</p>
|
||||||
</div>
|
</div>
|
||||||
</UiModal>
|
</UiModal>
|
||||||
@@ -200,6 +311,78 @@ watch(
|
|||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.create-panel {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.85rem 0.95rem;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent, #0d9488) 28%, #e2e8f0);
|
||||||
|
border-radius: 12px;
|
||||||
|
background:
|
||||||
|
linear-gradient(180deg, color-mix(in srgb, var(--accent, #0d9488) 8%, #fff) 0%, #fff 72%);
|
||||||
|
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.create-head {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.create-head strong {
|
||||||
|
color: var(--accent-deep, #0f766e);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.create-head span {
|
||||||
|
color: #64748b;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.list-head {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.list-title {
|
||||||
|
margin: 0;
|
||||||
|
color: #475569;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.list-search {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
min-width: min(16rem, 100%);
|
||||||
|
flex: 1 1 12rem;
|
||||||
|
max-width: 18rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
padding: 0 0.65rem;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: var(--radius, 10px);
|
||||||
|
background: #fff;
|
||||||
|
color: #94a3b8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.list-search:focus-within {
|
||||||
|
border-color: #5eead4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.list-search input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
outline: none;
|
||||||
|
background: transparent;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: #0f172a;
|
||||||
|
}
|
||||||
|
|
||||||
.new-row,
|
.new-row,
|
||||||
.edit {
|
.edit {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -240,11 +423,9 @@ watch(
|
|||||||
.list {
|
.list {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0 0 0.25rem;
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 0.4rem;
|
gap: 0.4rem;
|
||||||
max-height: 55vh;
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.row {
|
.row {
|
||||||
@@ -282,14 +463,38 @@ watch(
|
|||||||
padding: 0.05rem 0.4rem;
|
padding: 0.05rem 0.4rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.count {
|
.count,
|
||||||
|
.assignee-summary {
|
||||||
color: #94a3b8;
|
color: #94a3b8;
|
||||||
font-size: 0.78rem;
|
font-size: 0.78rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.assignee-summary {
|
||||||
|
flex: 1 1 100%;
|
||||||
|
}
|
||||||
|
|
||||||
.row-actions {
|
.row-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.assignee-field {
|
||||||
|
flex: 1 1 100%;
|
||||||
|
display: grid;
|
||||||
|
gap: 0.35rem;
|
||||||
|
padding-top: 0.35rem;
|
||||||
|
border-top: 1px dashed #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.create-assignees {
|
||||||
|
border-top: 1px dashed color-mix(in srgb, var(--accent, #0d9488) 22%, #e2e8f0);
|
||||||
|
padding-top: 0.65rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assignees-label {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: #64748b;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ const props = withDefaults(
|
|||||||
defineProps<{
|
defineProps<{
|
||||||
modelValue: SectionDataAccess;
|
modelValue: SectionDataAccess;
|
||||||
section?: DataAccessSection;
|
section?: DataAccessSection;
|
||||||
groups?: IdOption[];
|
|
||||||
stages?: IdOption[];
|
stages?: IdOption[];
|
||||||
pipelines?: IdOption[];
|
pipelines?: IdOption[];
|
||||||
boards?: IdOption[];
|
boards?: IdOption[];
|
||||||
@@ -36,7 +35,6 @@ const props = withDefaults(
|
|||||||
}>(),
|
}>(),
|
||||||
{
|
{
|
||||||
section: 'customers',
|
section: 'customers',
|
||||||
groups: () => [],
|
|
||||||
stages: () => [],
|
stages: () => [],
|
||||||
pipelines: () => [],
|
pipelines: () => [],
|
||||||
boards: () => [],
|
boards: () => [],
|
||||||
@@ -53,9 +51,9 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const sectionLabel = computed(() => DATA_ACCESS_SECTION_LABELS[props.section]);
|
const sectionLabel = computed(() => DATA_ACCESS_SECTION_LABELS[props.section]);
|
||||||
|
|
||||||
const showGroups = computed(() => props.section === 'customers');
|
|
||||||
const showMoods = computed(() => props.section === 'customers');
|
const showMoods = computed(() => props.section === 'customers');
|
||||||
const showImportSources = computed(() => props.section === 'customers');
|
const showImportSources = computed(() => props.section === 'customers');
|
||||||
|
const isCustomers = computed(() => props.section === 'customers');
|
||||||
const showLeadSources = computed(() => props.section === 'leads');
|
const showLeadSources = computed(() => props.section === 'leads');
|
||||||
const showNoteTypes = computed(() => props.section === 'notes');
|
const showNoteTypes = computed(() => props.section === 'notes');
|
||||||
const showTicketStatuses = computed(() => props.section === 'tickets');
|
const showTicketStatuses = computed(() => props.section === 'tickets');
|
||||||
@@ -119,9 +117,8 @@ const boardsLegend = computed(() =>
|
|||||||
/** چند قانون قدیمی → یک فیلتر (اتحاد گزینهها) برای ویرایش ساده */
|
/** چند قانون قدیمی → یک فیلتر (اتحاد گزینهها) برای ویرایش ساده */
|
||||||
function collapseRules(rules: DataAccessRule[]): DataAccessRule {
|
function collapseRules(rules: DataAccessRule[]): DataAccessRule {
|
||||||
if (!rules.length) return {};
|
if (!rules.length) return {};
|
||||||
if (rules.length === 1) return { ...rules[0]! };
|
if (rules.length === 1) return stripCustomerGroupIds({ ...rules[0]! });
|
||||||
const owners = new Set<DataAccessOwnerKind>();
|
const owners = new Set<DataAccessOwnerKind>();
|
||||||
const groupIds = new Set<string>();
|
|
||||||
const sources = new Set<string>();
|
const sources = new Set<string>();
|
||||||
const moods = new Set<PersonMood>();
|
const moods = new Set<PersonMood>();
|
||||||
const stageIds = new Set<string>();
|
const stageIds = new Set<string>();
|
||||||
@@ -130,7 +127,6 @@ function collapseRules(rules: DataAccessRule[]): DataAccessRule {
|
|||||||
const typeIds = new Set<string>();
|
const typeIds = new Set<string>();
|
||||||
for (const r of rules) {
|
for (const r of rules) {
|
||||||
for (const o of r.owners ?? []) owners.add(o);
|
for (const o of r.owners ?? []) owners.add(o);
|
||||||
for (const id of r.groupIds ?? []) groupIds.add(id);
|
|
||||||
for (const s of r.sources ?? []) sources.add(s);
|
for (const s of r.sources ?? []) sources.add(s);
|
||||||
for (const m of r.moods ?? []) moods.add(m);
|
for (const m of r.moods ?? []) moods.add(m);
|
||||||
for (const id of r.stageIds ?? []) stageIds.add(id);
|
for (const id of r.stageIds ?? []) stageIds.add(id);
|
||||||
@@ -140,7 +136,6 @@ function collapseRules(rules: DataAccessRule[]): DataAccessRule {
|
|||||||
}
|
}
|
||||||
const out: DataAccessRule = {};
|
const out: DataAccessRule = {};
|
||||||
if (owners.size) out.owners = [...owners];
|
if (owners.size) out.owners = [...owners];
|
||||||
if (groupIds.size) out.groupIds = [...groupIds];
|
|
||||||
if (sources.size) out.sources = [...sources];
|
if (sources.size) out.sources = [...sources];
|
||||||
if (moods.size) out.moods = [...moods];
|
if (moods.size) out.moods = [...moods];
|
||||||
if (stageIds.size) out.stageIds = [...stageIds];
|
if (stageIds.size) out.stageIds = [...stageIds];
|
||||||
@@ -150,10 +145,17 @@ function collapseRules(rules: DataAccessRule[]): DataAccessRule {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** دسترسی گروه فقط از مسئولگروه؛ groupIds دیگر در فیلتر مشتریان ذخیره/نمایش نمیشود */
|
||||||
|
function stripCustomerGroupIds(rule: DataAccessRule): DataAccessRule {
|
||||||
|
if (!isCustomers.value || !rule.groupIds?.length) return rule;
|
||||||
|
const { groupIds: _drop, ...rest } = rule;
|
||||||
|
return rest;
|
||||||
|
}
|
||||||
|
|
||||||
function ruleHasAnyFilter(rule: DataAccessRule): boolean {
|
function ruleHasAnyFilter(rule: DataAccessRule): boolean {
|
||||||
return Boolean(
|
return Boolean(
|
||||||
rule.owners?.length ||
|
rule.owners?.length ||
|
||||||
rule.groupIds?.length ||
|
(!isCustomers.value && rule.groupIds?.length) ||
|
||||||
rule.sources?.length ||
|
rule.sources?.length ||
|
||||||
rule.moods?.length ||
|
rule.moods?.length ||
|
||||||
rule.stageIds?.length ||
|
rule.stageIds?.length ||
|
||||||
@@ -184,10 +186,26 @@ const mode = computed({
|
|||||||
|
|
||||||
const filter = computed(() => collapseRules(props.modelValue?.rules ?? []));
|
const filter = computed(() => collapseRules(props.modelValue?.rules ?? []));
|
||||||
|
|
||||||
|
/** پاکسازی groupIds قدیمی مشتریان هنگام باز شدن ویرایشگر */
|
||||||
|
watch(
|
||||||
|
() => [props.section, props.modelValue] as const,
|
||||||
|
() => {
|
||||||
|
if (!isCustomers.value || props.modelValue?.mode !== 'rules') return;
|
||||||
|
const rules = props.modelValue.rules ?? [];
|
||||||
|
if (!rules.some((r) => r.groupIds?.length)) return;
|
||||||
|
const collapsed = collapseRules(rules);
|
||||||
|
emit('update:modelValue', {
|
||||||
|
mode: 'rules',
|
||||||
|
rules: [ruleHasAnyFilter(collapsed) ? collapsed : {}],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
function emitFilter(next: DataAccessRule) {
|
function emitFilter(next: DataAccessRule) {
|
||||||
const cleaned: DataAccessRule = {};
|
const cleaned: DataAccessRule = {};
|
||||||
if (next.owners?.length) cleaned.owners = [...next.owners];
|
if (next.owners?.length) cleaned.owners = [...next.owners];
|
||||||
if (next.groupIds?.length) cleaned.groupIds = [...next.groupIds];
|
if (!isCustomers.value && next.groupIds?.length) cleaned.groupIds = [...next.groupIds];
|
||||||
if (next.sources?.length) cleaned.sources = [...next.sources];
|
if (next.sources?.length) cleaned.sources = [...next.sources];
|
||||||
if (next.moods?.length) cleaned.moods = [...next.moods];
|
if (next.moods?.length) cleaned.moods = [...next.moods];
|
||||||
if (next.stageIds?.length) cleaned.stageIds = [...next.stageIds];
|
if (next.stageIds?.length) cleaned.stageIds = [...next.stageIds];
|
||||||
@@ -210,7 +228,6 @@ function toggleOwner(kind: DataAccessOwnerKind) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ListKey =
|
type ListKey =
|
||||||
| 'groupIds'
|
|
||||||
| 'sources'
|
| 'sources'
|
||||||
| 'moods'
|
| 'moods'
|
||||||
| 'stageIds'
|
| 'stageIds'
|
||||||
@@ -293,16 +310,6 @@ const moodOptions: Choice[] = PERSON_MOODS.map((mood) => ({
|
|||||||
const pickers = computed((): Picker[] => {
|
const pickers = computed((): Picker[] => {
|
||||||
const rule = filter.value;
|
const rule = filter.value;
|
||||||
const items: Picker[] = [];
|
const items: Picker[] = [];
|
||||||
if (showGroups.value) {
|
|
||||||
items.push({
|
|
||||||
key: 'groupIds',
|
|
||||||
legend: 'گروهها',
|
|
||||||
mode: 'multiple',
|
|
||||||
placeholder: props.groups.length ? 'جستجو و انتخاب گروه…' : 'گروهی تعریف نشده',
|
|
||||||
notFound: props.groups.length ? 'موردی پیدا نشد' : 'گروهی تعریف نشده',
|
|
||||||
options: withSelected(namedOptions(props.groups), rule.groupIds),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (showImportSources.value) {
|
if (showImportSources.value) {
|
||||||
const ready = props.importSourcesReady;
|
const ready = props.importSourcesReady;
|
||||||
const failed = props.importSourcesFailed;
|
const failed = props.importSourcesFailed;
|
||||||
@@ -417,7 +424,6 @@ const filterSummary = computed(() => {
|
|||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
if (rule.owners?.includes('self')) parts.push(ownerSelfLabel.value);
|
if (rule.owners?.includes('self')) parts.push(ownerSelfLabel.value);
|
||||||
if (rule.owners?.includes('team')) parts.push('تیمهای عضو');
|
if (rule.owners?.includes('team')) parts.push('تیمهای عضو');
|
||||||
if (rule.groupIds?.length) parts.push(`${rule.groupIds.length} گروه`);
|
|
||||||
if (rule.sources?.length) parts.push(`${rule.sources.length} مورد منبع/نوع`);
|
if (rule.sources?.length) parts.push(`${rule.sources.length} مورد منبع/نوع`);
|
||||||
if (rule.moods?.length) parts.push(`${rule.moods.length} حال`);
|
if (rule.moods?.length) parts.push(`${rule.moods.length} حال`);
|
||||||
if (rule.pipelineIds?.length) parts.push(`${rule.pipelineIds.length} پایپلاین`);
|
if (rule.pipelineIds?.length) parts.push(`${rule.pipelineIds.length} پایپلاین`);
|
||||||
@@ -443,9 +449,12 @@ const filterSummary = computed(() => {
|
|||||||
|
|
||||||
<template v-if="mode === 'rules'">
|
<template v-if="mode === 'rules'">
|
||||||
<p class="hint">
|
<p class="hint">
|
||||||
فقط رکوردهایی دیده میشوند که با
|
فیلترهای پرشده با هم
|
||||||
<strong>همهٔ فیلترهای پرشده</strong>
|
<strong>جمع میشوند</strong>
|
||||||
جور باشند. در هر فهرست، چند انتخاب یعنی هر کدام کافی است. خالی یعنی بدون محدودیت.
|
؛ هر بُعد کافی است (بدون تکرار). در هر فهرست هم چند انتخاب یعنی اتحاد. خالی یعنی بدون محدودیت آن بُعد.
|
||||||
|
<template v-if="isCustomers">
|
||||||
|
اعضای گروههایی که این کاربر مسئولشان است جداگانه به همین محدوده اضافه میشوند.
|
||||||
|
</template>
|
||||||
</p>
|
</p>
|
||||||
<p v-if="hadMultipleRules" class="hint warn">
|
<p v-if="hadMultipleRules" class="hint warn">
|
||||||
تنظیم قبلی چندتکه بود؛ اینجا در یک فیلتر ادغام شده. با ذخیره به همین شکل ساده ثبت میشود.
|
تنظیم قبلی چندتکه بود؛ اینجا در یک فیلتر ادغام شده. با ذخیره به همین شکل ساده ثبت میشود.
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import {
|
|||||||
emptySectionDataAccess,
|
emptySectionDataAccess,
|
||||||
} from '@mento/shared';
|
} from '@mento/shared';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import { useCustomerGroups } from '@/lib/customer-groups';
|
|
||||||
import DataAccessEditor, { type IdOption } from '@/components/DataAccessEditor.vue';
|
import DataAccessEditor, { type IdOption } from '@/components/DataAccessEditor.vue';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -85,7 +84,6 @@ function setSection(key: DataAccessSection, next: SectionDataAccess) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const { groups: customerGroups, load: loadCustomerGroups } = useCustomerGroups();
|
|
||||||
const importSources = ref<Array<{ value: string; label: string }>>([]);
|
const importSources = ref<Array<{ value: string; label: string }>>([]);
|
||||||
const importSourcesReady = ref(false);
|
const importSourcesReady = ref(false);
|
||||||
const importSourcesFailed = ref(false);
|
const importSourcesFailed = ref(false);
|
||||||
@@ -142,7 +140,6 @@ async function loadTreasuryAccounts() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadOptions() {
|
async function loadOptions() {
|
||||||
await loadCustomerGroups().catch(() => undefined);
|
|
||||||
try {
|
try {
|
||||||
const { data } = await api.get<PersonImportSourceStatDto[]>('/people/source-stats');
|
const { data } = await api.get<PersonImportSourceStatDto[]>('/people/source-stats');
|
||||||
importSources.value = data.map((row) => ({ value: row.source, label: row.label }));
|
importSources.value = data.map((row) => ({ value: row.source, label: row.label }));
|
||||||
@@ -362,7 +359,6 @@ const typesForActive = computed(() => {
|
|||||||
:key="active"
|
:key="active"
|
||||||
:section="editorSection"
|
:section="editorSection"
|
||||||
:model-value="sectionValue(editorSection)"
|
:model-value="sectionValue(editorSection)"
|
||||||
:groups="customerGroups"
|
|
||||||
:stages="stagesForActive"
|
:stages="stagesForActive"
|
||||||
:pipelines="pipelines"
|
:pipelines="pipelines"
|
||||||
:boards="boardsForActive"
|
:boards="boardsForActive"
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ const props = withDefaults(
|
|||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
clearable?: boolean;
|
clearable?: boolean;
|
||||||
icon?: 'calendar' | 'clock' | 'bell';
|
icon?: 'calendar' | 'clock' | 'bell';
|
||||||
|
/** اگر داده شود، متن باکس بهجای تاریخ خام همین مقدار است. */
|
||||||
|
displayText?: string;
|
||||||
|
/** نمایی که با باز شدن پنل دیده میشود. */
|
||||||
|
startView?: 'days' | 'months' | 'years';
|
||||||
}>(),
|
}>(),
|
||||||
{
|
{
|
||||||
mode: 'date',
|
mode: 'date',
|
||||||
@@ -37,6 +41,8 @@ const props = withDefaults(
|
|||||||
disabled: false,
|
disabled: false,
|
||||||
clearable: true,
|
clearable: true,
|
||||||
icon: undefined,
|
icon: undefined,
|
||||||
|
displayText: '',
|
||||||
|
startView: 'days',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -87,6 +93,7 @@ const triggerIcon = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const display = computed(() => {
|
const display = computed(() => {
|
||||||
|
if (props.displayText) return props.displayText;
|
||||||
if (props.mode === 'time') {
|
if (props.mode === 'time') {
|
||||||
const match = /^(\d{1,2}):(\d{2})$/.exec(model.value);
|
const match = /^(\d{1,2}):(\d{2})$/.exec(model.value);
|
||||||
if (!match) return '';
|
if (!match) return '';
|
||||||
@@ -353,7 +360,7 @@ function place() {
|
|||||||
|
|
||||||
function liftAboveOverlays() {
|
function liftAboveOverlays() {
|
||||||
let z = 120;
|
let z = 120;
|
||||||
for (const el of document.querySelectorAll('.ant-modal-wrap, .ant-drawer')) {
|
for (const el of document.querySelectorAll('.ant-modal-wrap, .ant-drawer, .ant-popover, [role="dialog"], [data-lead-filter]')) {
|
||||||
const zi = Number.parseInt(window.getComputedStyle(el).zIndex, 10);
|
const zi = Number.parseInt(window.getComputedStyle(el).zIndex, 10);
|
||||||
if (Number.isFinite(zi)) z = Math.max(z, zi + 20);
|
if (Number.isFinite(zi)) z = Math.max(z, zi + 20);
|
||||||
}
|
}
|
||||||
@@ -368,7 +375,7 @@ function onWindowChange() {
|
|||||||
async function show() {
|
async function show() {
|
||||||
if (props.disabled) return;
|
if (props.disabled) return;
|
||||||
syncDraftFrom(parsed.value);
|
syncDraftFrom(parsed.value);
|
||||||
calView.value = 'days';
|
calView.value = props.startView;
|
||||||
clockFace.value = 'hour';
|
clockFace.value = 'hour';
|
||||||
syncViewport();
|
syncViewport();
|
||||||
liftAboveOverlays();
|
liftAboveOverlays();
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ const props = withDefaults(
|
|||||||
/** اگر true باشد مقدار عددی emit میشود (نه رشته) */
|
/** اگر true باشد مقدار عددی emit میشود (نه رشته) */
|
||||||
asNumber?: boolean;
|
asNumber?: boolean;
|
||||||
dir?: 'ltr' | 'rtl';
|
dir?: 'ltr' | 'rtl';
|
||||||
|
addonAfter?: string;
|
||||||
}>(),
|
}>(),
|
||||||
{
|
{
|
||||||
required: false,
|
required: false,
|
||||||
@@ -30,6 +31,7 @@ const props = withDefaults(
|
|||||||
decimals: 2,
|
decimals: 2,
|
||||||
asNumber: false,
|
asNumber: false,
|
||||||
dir: 'ltr',
|
dir: 'ltr',
|
||||||
|
addonAfter: '',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -129,6 +131,7 @@ function normalizeSep(raw: string): string {
|
|||||||
:disabled="disabled"
|
:disabled="disabled"
|
||||||
:readonly="readonly"
|
:readonly="readonly"
|
||||||
:value="text"
|
:value="text"
|
||||||
|
:addon-after="addonAfter || undefined"
|
||||||
style="width: 100%; font-variant-numeric: tabular-nums"
|
style="width: 100%; font-variant-numeric: tabular-nums"
|
||||||
@focus="onFocus"
|
@focus="onFocus"
|
||||||
@blur="onBlur"
|
@blur="onBlur"
|
||||||
|
|||||||
@@ -0,0 +1,367 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, ref, watch } from 'vue';
|
||||||
|
import type { OrgUserDto } from '@mento/shared';
|
||||||
|
import { toFaDigits } from '@/lib/jalali';
|
||||||
|
import { normalizeSearchText } from '@/lib/search';
|
||||||
|
import UiIcon from '@/components/UiIcon.vue';
|
||||||
|
import UserAvatar from '@/components/UserAvatar.vue';
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
modelValue: string[];
|
||||||
|
users: Array<Pick<OrgUserDto, 'id' | 'fullName' | 'orgRoleName' | 'hasAvatar'>>;
|
||||||
|
disabled?: boolean;
|
||||||
|
emptyLabel?: string;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
disabled: false,
|
||||||
|
emptyLabel: 'انتخاب مسئول',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [ids: string[]];
|
||||||
|
change: [ids: string[]];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const open = ref(false);
|
||||||
|
const query = ref('');
|
||||||
|
const searchInput = ref<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
|
const selected = computed(() =>
|
||||||
|
props.modelValue
|
||||||
|
.map((id) => props.users.find((u) => u.id === id))
|
||||||
|
.filter((u): u is NonNullable<typeof u> => Boolean(u)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const label = computed(() => {
|
||||||
|
if (!selected.value.length) return props.emptyLabel;
|
||||||
|
if (selected.value.length === 1) return selected.value[0]!.fullName;
|
||||||
|
return `${selected.value[0]!.fullName} و ${toFaDigits(selected.value.length - 1)} نفر دیگر`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const filtered = computed(() => {
|
||||||
|
const q = normalizeSearchText(query.value);
|
||||||
|
if (!q) return props.users;
|
||||||
|
return props.users.filter(
|
||||||
|
(u) =>
|
||||||
|
normalizeSearchText(u.fullName).includes(q) ||
|
||||||
|
normalizeSearchText(u.orgRoleName ?? '').includes(q),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
function toggleMenu() {
|
||||||
|
if (props.disabled) return;
|
||||||
|
open.value = !open.value;
|
||||||
|
if (open.value) {
|
||||||
|
void nextTick(() => searchInput.value?.focus());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
open.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setIds(next: string[]) {
|
||||||
|
emit('update:modelValue', next);
|
||||||
|
emit('change', next);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(userId: string) {
|
||||||
|
if (props.disabled) return;
|
||||||
|
const set = new Set(props.modelValue);
|
||||||
|
if (set.has(userId)) set.delete(userId);
|
||||||
|
else set.add(userId);
|
||||||
|
setIds([...set]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(userId: string) {
|
||||||
|
if (props.disabled) return;
|
||||||
|
if (!props.modelValue.includes(userId)) return;
|
||||||
|
setIds(props.modelValue.filter((id) => id !== userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(open, (isOpen) => {
|
||||||
|
if (!isOpen) query.value = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
defineExpose({ close });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="wrap" @click.stop>
|
||||||
|
<button
|
||||||
|
class="picker person-pick"
|
||||||
|
type="button"
|
||||||
|
:disabled="disabled"
|
||||||
|
@click="toggleMenu"
|
||||||
|
>
|
||||||
|
<div class="assignee-avatars">
|
||||||
|
<UserAvatar
|
||||||
|
v-for="user in selected.slice(0, 3)"
|
||||||
|
:key="user.id"
|
||||||
|
:name="user.fullName"
|
||||||
|
:user-id="user.id"
|
||||||
|
:has-avatar="user.hasAvatar"
|
||||||
|
:size="28"
|
||||||
|
/>
|
||||||
|
<UserAvatar v-if="!selected.length" name="مسئول" :size="28" />
|
||||||
|
</div>
|
||||||
|
<span :class="{ ghost: !selected.length }">{{ label }}</span>
|
||||||
|
<UiIcon name="chevron" :size="16" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-if="selected.length" class="chips">
|
||||||
|
<span v-for="user in selected" :key="user.id" class="chip">
|
||||||
|
{{ user.fullName }}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="chip-x"
|
||||||
|
:disabled="disabled"
|
||||||
|
:aria-label="`حذف ${user.fullName}`"
|
||||||
|
@click="remove(user.id)"
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="open" class="menu person-menu multi-menu" @click.stop>
|
||||||
|
<label class="person-search">
|
||||||
|
<UiIcon name="search" :size="15" />
|
||||||
|
<input
|
||||||
|
ref="searchInput"
|
||||||
|
v-model="query"
|
||||||
|
type="search"
|
||||||
|
placeholder="جستجوی نام یا نقش…"
|
||||||
|
@keydown.esc="close"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<ul class="person-list">
|
||||||
|
<li v-for="user in filtered" :key="user.id">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="multi-option"
|
||||||
|
:class="{ on: modelValue.includes(user.id) }"
|
||||||
|
@click="toggle(user.id)"
|
||||||
|
>
|
||||||
|
<span class="check" :class="{ on: modelValue.includes(user.id) }">
|
||||||
|
<UiIcon v-if="modelValue.includes(user.id)" name="check-plain" :size="12" />
|
||||||
|
</span>
|
||||||
|
<UserAvatar
|
||||||
|
:name="user.fullName"
|
||||||
|
:user-id="user.id"
|
||||||
|
:has-avatar="user.hasAvatar"
|
||||||
|
:size="28"
|
||||||
|
/>
|
||||||
|
<span class="role-name">{{ user.fullName }}</span>
|
||||||
|
<small v-if="user.orgRoleName" class="role-count">{{ user.orgRoleName }}</small>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
<li v-if="!filtered.length" class="menu-empty">موردی پیدا نشد.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.wrap {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
min-width: 12rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker {
|
||||||
|
width: 100%;
|
||||||
|
min-height: var(--control-h, 36px);
|
||||||
|
height: var(--control-h, 36px);
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: var(--radius, 10px);
|
||||||
|
background: #fff;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
padding: 0.4rem 0.7rem;
|
||||||
|
font: inherit;
|
||||||
|
text-align: start;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker:disabled {
|
||||||
|
opacity: 0.65;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker .ghost {
|
||||||
|
color: #94a3b8;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker :deep(.ico:last-child) {
|
||||||
|
margin-inline-start: auto;
|
||||||
|
color: #94a3b8;
|
||||||
|
transform: rotate(90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.assignee-avatars {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assignee-avatars :deep(.avatar),
|
||||||
|
.assignee-avatars > * {
|
||||||
|
margin-inline-end: -0.35rem;
|
||||||
|
box-shadow: 0 0 0 2px #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chips {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.35rem;
|
||||||
|
margin-top: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 0.15rem 0.35rem 0.15rem 0.55rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #f0fdfa;
|
||||||
|
border: 1px solid #99f6e4;
|
||||||
|
color: #0f766e;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-x {
|
||||||
|
appearance: none;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
line-height: 1;
|
||||||
|
padding: 0 0.2rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-x:hover:not(:disabled) {
|
||||||
|
background: #ccfbf1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-x:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.menu {
|
||||||
|
position: absolute;
|
||||||
|
inset-inline: 0;
|
||||||
|
top: calc(100% + 0.25rem);
|
||||||
|
z-index: 40;
|
||||||
|
margin: 0;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: var(--radius, 10px);
|
||||||
|
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.14);
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-menu {
|
||||||
|
max-height: none;
|
||||||
|
overflow: visible;
|
||||||
|
display: grid;
|
||||||
|
gap: 0.35rem;
|
||||||
|
padding: 0.45rem;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-search {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45rem;
|
||||||
|
height: 2.4rem;
|
||||||
|
padding: 0 0.7rem;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: var(--radius, 10px);
|
||||||
|
color: #94a3b8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-search:focus-within {
|
||||||
|
border-color: #5eead4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-search input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
outline: none;
|
||||||
|
background: transparent;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
color: #0f172a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
max-height: 15rem;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .multi-option {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.55rem;
|
||||||
|
width: 100%;
|
||||||
|
border: 0;
|
||||||
|
background: none;
|
||||||
|
padding: 0.55rem 0.5rem;
|
||||||
|
border-radius: var(--radius, 10px);
|
||||||
|
font: inherit;
|
||||||
|
text-align: start;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .multi-option:hover {
|
||||||
|
background: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .multi-option.on {
|
||||||
|
background: #f0fdfa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .check {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border: 1.5px solid #cbd5e1;
|
||||||
|
border-radius: 5px;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .check.on {
|
||||||
|
background: #14b8a6;
|
||||||
|
border-color: #14b8a6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .role-name {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-menu .role-count {
|
||||||
|
margin-inline-start: auto;
|
||||||
|
color: #94a3b8;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.menu-empty {
|
||||||
|
padding: 0.6rem;
|
||||||
|
color: #94a3b8;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,10 +1,23 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, nextTick, ref, watch } from 'vue';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import type { OutboundSmsHistoryResponse, OutboundSmsLogDto } from '@mento/shared';
|
import type {
|
||||||
import { MESSAGE_AUTOMATION_FIELDS, countSmsParts } from '@mento/shared';
|
OutboundSmsHistoryResponse,
|
||||||
|
OutboundSmsLogDto,
|
||||||
|
PersonAssetsDto,
|
||||||
|
SmsTemplateDto,
|
||||||
|
} from '@mento/shared';
|
||||||
|
import {
|
||||||
|
MESSAGE_AUTOMATION_FIELDS,
|
||||||
|
SMS_TEMPLATE_BODY_MAX,
|
||||||
|
SMS_TEMPLATE_MAX,
|
||||||
|
SMS_TEMPLATE_NAME_MAX,
|
||||||
|
countSmsParts,
|
||||||
|
} from '@mento/shared';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
|
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
|
||||||
|
import { formatTahesabBedBes } from '@/lib/tahesab';
|
||||||
|
import { useAuthStore } from '@/stores/auth';
|
||||||
import { UiButton, UiModal } from '@/components/ui';
|
import { UiButton, UiModal } from '@/components/ui';
|
||||||
|
|
||||||
const props = withDefaults(
|
const props = withDefaults(
|
||||||
@@ -25,7 +38,7 @@ const props = withDefaults(
|
|||||||
recordTitle: '',
|
recordTitle: '',
|
||||||
company: '',
|
company: '',
|
||||||
title: 'ارسال پیامک',
|
title: 'ارسال پیامک',
|
||||||
defaultText: 'سلام {نام} عزیز',
|
defaultText: '',
|
||||||
nest: false,
|
nest: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -35,18 +48,73 @@ const emit = defineEmits<{
|
|||||||
sent: [];
|
sent: [];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
type Panel = 'none' | 'fields' | 'templates';
|
||||||
|
|
||||||
|
const auth = useAuthStore();
|
||||||
const text = ref('');
|
const text = ref('');
|
||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const done = ref('');
|
const done = ref('');
|
||||||
const fieldsOpen = ref(false);
|
const notice = ref('');
|
||||||
|
const panel = ref<Panel>('none');
|
||||||
|
const savingTemplate = ref(false);
|
||||||
|
const templateName = ref('');
|
||||||
|
const templateBody = ref('');
|
||||||
const bodyEl = ref<HTMLTextAreaElement | null>(null);
|
const bodyEl = ref<HTMLTextAreaElement | null>(null);
|
||||||
|
const templateBodyEl = ref<HTMLTextAreaElement | null>(null);
|
||||||
const history = ref<OutboundSmsLogDto[]>([]);
|
const history = ref<OutboundSmsLogDto[]>([]);
|
||||||
const historyLoading = ref(false);
|
const historyLoading = ref(false);
|
||||||
|
const templates = ref<SmsTemplateDto[]>([]);
|
||||||
|
const templatesLoading = ref(false);
|
||||||
|
const fromOrg = ref('');
|
||||||
|
const rialBalanceText = ref('');
|
||||||
|
const metalBalanceText = ref('');
|
||||||
|
|
||||||
|
const METAL_FIELD_LABELS: Record<string, string> = {
|
||||||
|
MandeyeVazni: 'طلا',
|
||||||
|
MandeyeVazniNoghre: 'نقره',
|
||||||
|
MandeyeKolBeTALA: 'کل به طلا',
|
||||||
|
MandeMenhayeSeke: 'منهای سکه',
|
||||||
|
};
|
||||||
|
|
||||||
|
function isMetalMandehKey(key: string) {
|
||||||
|
if (METAL_FIELD_LABELS[key]) return true;
|
||||||
|
if (key.startsWith('Seke_')) return true;
|
||||||
|
return /Vazni|طلا|نقره|فلز|Gold|Silver/i.test(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function metalFieldLabel(key: string) {
|
||||||
|
if (METAL_FIELD_LABELS[key]) return METAL_FIELD_LABELS[key]!;
|
||||||
|
if (key.startsWith('Seke_')) return `سکه ${key.slice(5)}`;
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyAssetsToVars(assets: PersonAssetsDto) {
|
||||||
|
const fields = assets.mandehFields ?? [];
|
||||||
|
const mali = fields.find((f) => f.key === 'MandeyeMali' || f.key === 'MandeyeKolBePool');
|
||||||
|
const rialRaw = mali?.value ?? assets.rialBalance;
|
||||||
|
rialBalanceText.value =
|
||||||
|
rialRaw == null || String(rialRaw).trim() === ''
|
||||||
|
? ''
|
||||||
|
: formatTahesabBedBes(rialRaw);
|
||||||
|
const metalParts = fields
|
||||||
|
.filter((f) => isMetalMandehKey(f.key) && f.value != null && String(f.value).trim() !== '')
|
||||||
|
.map((f) => `${metalFieldLabel(f.key)} ${formatTahesabBedBes(f.value)}`.trim());
|
||||||
|
metalBalanceText.value =
|
||||||
|
metalParts.join('، ') ||
|
||||||
|
(assets.goldBalance != null ? `طلا ${formatTahesabBedBes(assets.goldBalance)}` : '');
|
||||||
|
}
|
||||||
|
|
||||||
const preview = computed(() => fill(text.value));
|
const preview = computed(() => fill(text.value));
|
||||||
const count = computed(() => text.value.length);
|
const count = computed(() => text.value.length);
|
||||||
const parts = computed(() => countSmsParts(text.value));
|
const parts = computed(() => countSmsParts(text.value));
|
||||||
|
const canSaveTemplate = computed(
|
||||||
|
() =>
|
||||||
|
templateName.value.trim().length >= 1 &&
|
||||||
|
templateBody.value.trim().length >= 2 &&
|
||||||
|
templates.value.length < SMS_TEMPLATE_MAX &&
|
||||||
|
!savingTemplate.value,
|
||||||
|
);
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.open,
|
() => props.open,
|
||||||
@@ -55,12 +123,43 @@ watch(
|
|||||||
text.value = props.defaultText;
|
text.value = props.defaultText;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
done.value = '';
|
done.value = '';
|
||||||
fieldsOpen.value = false;
|
notice.value = '';
|
||||||
|
panel.value = 'none';
|
||||||
|
templateName.value = '';
|
||||||
|
templateBody.value = '';
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
|
fromOrg.value = auth.user?.organizationName?.trim() || '';
|
||||||
|
rialBalanceText.value = '';
|
||||||
|
metalBalanceText.value = '';
|
||||||
void loadHistory();
|
void loadHistory();
|
||||||
|
void loadTemplates();
|
||||||
|
void loadContextVars();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
async function loadContextVars() {
|
||||||
|
if (!fromOrg.value) {
|
||||||
|
try {
|
||||||
|
const { data } = await api.get<{ name?: string }>('/organizations/current');
|
||||||
|
if (data?.name?.trim()) fromOrg.value = data.name.trim();
|
||||||
|
} catch {
|
||||||
|
/* نام سازمان از auth کافی است */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const personMatch = props.endpoint.match(/\/people\/([^/]+)\/(?:sms|birthday-sms)/);
|
||||||
|
if (!personMatch?.[1]) return;
|
||||||
|
try {
|
||||||
|
const { data } = await api.get<PersonAssetsDto>(
|
||||||
|
`/integrations/tahesab/people/${personMatch[1]}/assets`,
|
||||||
|
{ params: { refresh: '0' } },
|
||||||
|
);
|
||||||
|
applyAssetsToVars(data);
|
||||||
|
} catch {
|
||||||
|
rialBalanceText.value = '';
|
||||||
|
metalBalanceText.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function loadHistory() {
|
async function loadHistory() {
|
||||||
history.value = [];
|
history.value = [];
|
||||||
if (!props.historyEndpoint) return;
|
if (!props.historyEndpoint) return;
|
||||||
@@ -77,41 +176,158 @@ async function loadHistory() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadTemplates() {
|
||||||
|
templatesLoading.value = true;
|
||||||
|
try {
|
||||||
|
const { data } = await api.get<SmsTemplateDto[]>('/sms-templates');
|
||||||
|
templates.value = Array.isArray(data) ? data : [];
|
||||||
|
} catch (e) {
|
||||||
|
templates.value = [];
|
||||||
|
error.value = apiMessage(e, 'بارگذاری پیامکهای آماده ناموفق بود.');
|
||||||
|
} finally {
|
||||||
|
templatesLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_FIELD_HINT: Record<string, string> = {
|
||||||
|
عنوان: '〔عنوان ثبت نشده〕',
|
||||||
|
title: '〔عنوان ثبت نشده〕',
|
||||||
|
شرکت: '〔شرکت مشتری ثبت نشده〕',
|
||||||
|
company: '〔شرکت مشتری ثبت نشده〕',
|
||||||
|
نام: '〔نام ثبت نشده〕',
|
||||||
|
name: '〔نام ثبت نشده〕',
|
||||||
|
شماره: '〔شماره ثبت نشده〕',
|
||||||
|
phone: '〔شماره ثبت نشده〕',
|
||||||
|
'از طرف': '〔سازمان ثبت نشده〕',
|
||||||
|
from: '〔سازمان ثبت نشده〕',
|
||||||
|
'مانده ریالی': '〔مانده ریالی نیست〕',
|
||||||
|
rialBalance: '〔مانده ریالی نیست〕',
|
||||||
|
'مانده فلزی': '〔مانده فلزی نیست〕',
|
||||||
|
metalBalance: '〔مانده فلزی نیست〕',
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeTemplateKey(key: string) {
|
||||||
|
return String(key ?? '')
|
||||||
|
.normalize('NFKC')
|
||||||
|
.replace(/[\u200c\u200d\u200e\u200f\ufeff]/g, '')
|
||||||
|
.replace(/ي/g, 'ی')
|
||||||
|
.replace(/ك/g, 'ک')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** پیشنمایش؛ اگر مقدار خالی باشد نشانه میگذارد تا با فیلد خالی قاطی نشود. */
|
||||||
function fill(source: string) {
|
function fill(source: string) {
|
||||||
const map: Record<string, string> = {
|
const from = fromOrg.value.trim();
|
||||||
نام: props.name,
|
const rial = rialBalanceText.value.trim();
|
||||||
name: props.name,
|
const metal = metalBalanceText.value.trim();
|
||||||
شماره: props.phone,
|
const entries: Array<[string, string]> = [
|
||||||
phone: props.phone,
|
['نام', props.name.trim()],
|
||||||
تاریخ: formatJalaliDay(new Date()),
|
['name', props.name.trim()],
|
||||||
date: formatJalaliDay(new Date()),
|
['شماره', props.phone.trim()],
|
||||||
عنوان: props.recordTitle || props.name,
|
['phone', props.phone.trim()],
|
||||||
title: props.recordTitle || props.name,
|
['تاریخ', formatJalaliDay(new Date())],
|
||||||
شرکت: props.company,
|
['date', formatJalaliDay(new Date())],
|
||||||
company: props.company,
|
['عنوان', props.recordTitle.trim()],
|
||||||
};
|
['title', props.recordTitle.trim()],
|
||||||
return source.replace(/\{([^}]+)\}/g, (full, key: string) => {
|
['شرکت', props.company.trim()],
|
||||||
const next = map[key.trim()];
|
['company', props.company.trim()],
|
||||||
return next === undefined ? full : next;
|
['از طرف', from],
|
||||||
|
['ازطرف', from],
|
||||||
|
['from', from],
|
||||||
|
['مانده ریالی', rial],
|
||||||
|
['ماندهریالی', rial],
|
||||||
|
['rialBalance', rial],
|
||||||
|
['مانده فلزی', metal],
|
||||||
|
['ماندهفلزی', metal],
|
||||||
|
['metalBalance', metal],
|
||||||
|
];
|
||||||
|
const map: Record<string, string> = {};
|
||||||
|
const hints: Record<string, string> = {};
|
||||||
|
for (const [key, value] of entries) {
|
||||||
|
const norm = normalizeTemplateKey(key);
|
||||||
|
map[norm] = value;
|
||||||
|
if (EMPTY_FIELD_HINT[key]) hints[norm] = EMPTY_FIELD_HINT[key]!;
|
||||||
|
}
|
||||||
|
return source.replace(/\{([^}]+)\}/g, (full, rawKey: string) => {
|
||||||
|
const key = normalizeTemplateKey(rawKey);
|
||||||
|
if (!(key in map)) return full;
|
||||||
|
const next = map[key] ?? '';
|
||||||
|
if (next) return next;
|
||||||
|
return hints[key] ?? full;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function insertField(token: string) {
|
function insertInto(
|
||||||
const el = bodyEl.value;
|
target: 'compose' | 'draft',
|
||||||
const current = text.value;
|
token: string,
|
||||||
|
) {
|
||||||
|
const el = target === 'compose' ? bodyEl.value : templateBodyEl.value;
|
||||||
|
const current = target === 'compose' ? text.value : templateBody.value;
|
||||||
|
const setValue = (next: string) => {
|
||||||
|
if (target === 'compose') text.value = next;
|
||||||
|
else templateBody.value = next;
|
||||||
|
};
|
||||||
if (!el) {
|
if (!el) {
|
||||||
text.value = `${current}${token}`;
|
setValue(`${current}${token}`);
|
||||||
} else {
|
return;
|
||||||
const start = el.selectionStart ?? current.length;
|
}
|
||||||
const end = el.selectionEnd ?? start;
|
const start = el.selectionStart ?? current.length;
|
||||||
text.value = `${current.slice(0, start)}${token}${current.slice(end)}`;
|
const end = el.selectionEnd ?? start;
|
||||||
const caret = start + token.length;
|
setValue(`${current.slice(0, start)}${token}${current.slice(end)}`);
|
||||||
requestAnimationFrame(() => {
|
const caret = start + token.length;
|
||||||
el.focus();
|
void nextTick(() => {
|
||||||
el.setSelectionRange(caret, caret);
|
el.focus();
|
||||||
});
|
el.setSelectionRange(caret, caret);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPanel(next: Panel) {
|
||||||
|
panel.value = panel.value === next ? 'none' : next;
|
||||||
|
notice.value = '';
|
||||||
|
if (panel.value === 'templates') {
|
||||||
|
error.value = '';
|
||||||
|
void loadTemplates();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyTemplate(item: SmsTemplateDto) {
|
||||||
|
text.value = item.body;
|
||||||
|
error.value = '';
|
||||||
|
notice.value = `قالب «${item.name}» در متن پیام قرار گرفت.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveTemplate() {
|
||||||
|
const name = templateName.value.trim().slice(0, SMS_TEMPLATE_NAME_MAX);
|
||||||
|
const body = templateBody.value.trim().slice(0, SMS_TEMPLATE_BODY_MAX);
|
||||||
|
if (!canSaveTemplate.value || !name || body.length < 2) return;
|
||||||
|
savingTemplate.value = true;
|
||||||
|
error.value = '';
|
||||||
|
notice.value = '';
|
||||||
|
try {
|
||||||
|
const { data } = await api.post<SmsTemplateDto[]>('/sms-templates', { name, body });
|
||||||
|
templates.value = Array.isArray(data) ? data : [];
|
||||||
|
templateName.value = '';
|
||||||
|
templateBody.value = '';
|
||||||
|
notice.value = `پیامک آماده «${name}» ذخیره شد.`;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = apiMessage(e, 'ذخیره پیامک آماده ناموفق بود.');
|
||||||
|
} finally {
|
||||||
|
savingTemplate.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeTemplate(item: SmsTemplateDto) {
|
||||||
|
if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return;
|
||||||
|
error.value = '';
|
||||||
|
notice.value = '';
|
||||||
|
try {
|
||||||
|
const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`);
|
||||||
|
templates.value = Array.isArray(data) ? data : [];
|
||||||
|
notice.value = `«${item.name}» حذف شد.`;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = apiMessage(e, 'حذف پیامک آماده ناموفق بود.');
|
||||||
}
|
}
|
||||||
fieldsOpen.value = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function apiMessage(e: unknown, fallback: string) {
|
function apiMessage(e: unknown, fallback: string) {
|
||||||
@@ -122,17 +338,28 @@ function apiMessage(e: unknown, fallback: string) {
|
|||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function send() {
|
async function send(force = false) {
|
||||||
if (!props.endpoint || busy.value || done.value) return;
|
if (!props.endpoint || busy.value || done.value) return;
|
||||||
busy.value = true;
|
busy.value = true;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
|
notice.value = '';
|
||||||
try {
|
try {
|
||||||
await api.post(props.endpoint, { text: text.value });
|
await api.post(props.endpoint, { text: text.value, ...(force ? { force: true } : {}) });
|
||||||
done.value = 'پیامک ارسال شد.';
|
done.value = 'پیامک ارسال شد.';
|
||||||
emit('sent');
|
emit('sent');
|
||||||
void loadHistory();
|
void loadHistory();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error.value = apiMessage(e, 'ارسال پیامک ناموفق بود.');
|
if (axios.isAxiosError(e) && e.response?.status === 409) {
|
||||||
|
const msg = apiMessage(e, 'قبلاً پیامک تبریک فرستاده شده است. دوباره بفرستیم؟');
|
||||||
|
if (confirm(msg)) {
|
||||||
|
busy.value = false;
|
||||||
|
await send(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
error.value = msg;
|
||||||
|
} else {
|
||||||
|
error.value = apiMessage(e, 'ارسال پیامک ناموفق بود.');
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
}
|
}
|
||||||
@@ -152,22 +379,141 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div class="tools">
|
<div class="tools">
|
||||||
<button type="button" class="pill" @click="fieldsOpen = !fieldsOpen">فیلدهای پویا</button>
|
<div class="tool-row">
|
||||||
<div v-if="fieldsOpen" class="fields">
|
|
||||||
<button
|
<button
|
||||||
v-for="item in MESSAGE_AUTOMATION_FIELDS"
|
|
||||||
:key="item.token"
|
|
||||||
type="button"
|
type="button"
|
||||||
@click="insertField(item.token)"
|
class="pill"
|
||||||
|
:class="{ on: panel === 'fields' }"
|
||||||
|
@click="openPanel('fields')"
|
||||||
>
|
>
|
||||||
<code>{{ item.token }}</code>
|
فیلدهای پویا
|
||||||
<span>{{ item.label }}</span>
|
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="pill"
|
||||||
|
:class="{ on: panel === 'templates' }"
|
||||||
|
@click="openPanel('templates')"
|
||||||
|
>
|
||||||
|
ساخت پیامک آماده
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="panel === 'fields'" class="panel">
|
||||||
|
<p class="panel-hint">روی فیلد بزنید تا داخل متن پیام درج شود.</p>
|
||||||
|
<div class="field-grid">
|
||||||
|
<button
|
||||||
|
v-for="item in MESSAGE_AUTOMATION_FIELDS"
|
||||||
|
:key="item.token"
|
||||||
|
type="button"
|
||||||
|
@click="insertInto('compose', item.token)"
|
||||||
|
>
|
||||||
|
<code>{{ item.token }}</code>
|
||||||
|
<span>{{ item.label }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="panel === 'templates'" class="panel">
|
||||||
|
<div class="draft">
|
||||||
|
<strong>ساخت پیامک آماده جدید</strong>
|
||||||
|
<p class="panel-hint">این متن جدا از پیام ارسالی است؛ بعد از ذخیره، عنوانش بالا برای استفاده سریع میآید.</p>
|
||||||
|
<input
|
||||||
|
v-model="templateName"
|
||||||
|
type="text"
|
||||||
|
:maxlength="SMS_TEMPLATE_NAME_MAX"
|
||||||
|
placeholder="نام قالب (مثلاً پیگیری جلسه)"
|
||||||
|
autocomplete="off"
|
||||||
|
/>
|
||||||
|
<textarea
|
||||||
|
ref="templateBodyEl"
|
||||||
|
v-model="templateBody"
|
||||||
|
rows="3"
|
||||||
|
:maxlength="SMS_TEMPLATE_BODY_MAX"
|
||||||
|
placeholder="متن قالب، مثلاً: سلام {نام} عزیز…"
|
||||||
|
/>
|
||||||
|
<div class="tpl-fields" role="group" aria-label="فیلدهای پویا برای قالب">
|
||||||
|
<span class="tpl-fields-label">درج فیلد در قالب:</span>
|
||||||
|
<button
|
||||||
|
v-for="item in MESSAGE_AUTOMATION_FIELDS"
|
||||||
|
:key="`tpl-${item.token}`"
|
||||||
|
type="button"
|
||||||
|
:title="item.label"
|
||||||
|
@click="insertInto('draft', item.token)"
|
||||||
|
>
|
||||||
|
<code>{{ item.token }}</code>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="save-btn"
|
||||||
|
:disabled="!canSaveTemplate"
|
||||||
|
@click="saveTemplate"
|
||||||
|
>
|
||||||
|
{{ savingTemplate ? 'در حال ذخیره…' : 'ذخیره قالب' }}
|
||||||
|
</button>
|
||||||
|
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted">
|
||||||
|
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="templates.length" class="manage-list">
|
||||||
|
<p class="panel-hint">حذف قالبهای ذخیرهشده:</p>
|
||||||
|
<ul class="template-list">
|
||||||
|
<li v-for="item in templates" :key="`del-${item.id}`">
|
||||||
|
<span class="pick-name">{{ item.name }}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="del"
|
||||||
|
:aria-label="`حذف ${item.name}`"
|
||||||
|
@click="removeTemplate(item)"
|
||||||
|
>
|
||||||
|
حذف
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<textarea ref="bodyEl" v-model="text" rows="4" maxlength="500" placeholder="سلام {نام} عزیز" />
|
<div class="compose-layout">
|
||||||
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p>
|
<div class="compose-main">
|
||||||
|
<label class="compose-label" for="sms-compose-body">متن پیام ارسالی</label>
|
||||||
|
<textarea
|
||||||
|
id="sms-compose-body"
|
||||||
|
ref="bodyEl"
|
||||||
|
v-model="text"
|
||||||
|
rows="5"
|
||||||
|
maxlength="500"
|
||||||
|
placeholder="متن پیام را بنویسید یا از ستون قالبها انتخاب کنید"
|
||||||
|
/>
|
||||||
|
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="quick-col" aria-label="انتخاب سریع پیامک آماده">
|
||||||
|
<strong class="quick-col-title">قالبها</strong>
|
||||||
|
<div v-if="templatesLoading" class="muted tiny">در حال بارگذاری…</div>
|
||||||
|
<div
|
||||||
|
v-else-if="templates.length"
|
||||||
|
class="quick-templates"
|
||||||
|
role="list"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-for="item in templates"
|
||||||
|
:key="item.id"
|
||||||
|
type="button"
|
||||||
|
class="tpl-chip"
|
||||||
|
role="listitem"
|
||||||
|
:title="item.body"
|
||||||
|
@click="applyTemplate(item)"
|
||||||
|
>
|
||||||
|
{{ item.name }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p v-else class="muted tiny quick-empty">
|
||||||
|
هنوز قالبی نیست. از «ساخت پیامک آماده» بسازید.
|
||||||
|
</p>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="preview">
|
<div class="preview">
|
||||||
<span>پیشنمایش</span>
|
<span>پیشنمایش</span>
|
||||||
@@ -195,6 +541,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p v-if="error" class="err">{{ error }}</p>
|
<p v-if="error" class="err">{{ error }}</p>
|
||||||
|
<p v-else-if="notice" class="ok">{{ notice }}</p>
|
||||||
<p v-if="done" class="ok">{{ done }}</p>
|
<p v-if="done" class="ok">{{ done }}</p>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
@@ -234,66 +581,279 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.tools {
|
.tools {
|
||||||
position: relative;
|
margin-bottom: 0.55rem;
|
||||||
margin-bottom: 0.45rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.pill,
|
.tool-row {
|
||||||
.fields button {
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill {
|
||||||
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
|
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
|
||||||
background: var(--accent-subtle);
|
background: var(--accent-subtle);
|
||||||
color: var(--accent-deep);
|
color: var(--accent-deep);
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
font: inherit;
|
font: inherit;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
|
||||||
|
|
||||||
.pill {
|
|
||||||
padding: 0.28rem 0.7rem;
|
padding: 0.28rem 0.7rem;
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.fields {
|
.pill.on {
|
||||||
position: absolute;
|
background: var(--accent-deep);
|
||||||
z-index: 2;
|
color: #fff;
|
||||||
top: calc(100% + 0.3rem);
|
border-color: var(--accent-deep);
|
||||||
inset-inline: 0;
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
margin-top: 0.45rem;
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 0.25rem;
|
gap: 0.45rem;
|
||||||
max-width: 100%;
|
padding: 0.55rem;
|
||||||
padding: 0.4rem;
|
|
||||||
background: #fff;
|
background: #fff;
|
||||||
border: 1px solid #e7eef2;
|
border: 1px solid #e7eef2;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.fields button {
|
.panel-hint {
|
||||||
|
margin: 0;
|
||||||
|
color: #64748b;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-grid button {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 0.6rem;
|
gap: 0.6rem;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
padding: 0.35rem 0.5rem;
|
padding: 0.35rem 0.5rem;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
text-align: start;
|
text-align: start;
|
||||||
}
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
.fields code {
|
|
||||||
color: var(--accent-deep);
|
color: var(--accent-deep);
|
||||||
}
|
}
|
||||||
|
|
||||||
textarea {
|
.field-grid code {
|
||||||
|
color: var(--accent-deep);
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: 0.3rem;
|
||||||
|
max-height: 9.5rem;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-list li {
|
||||||
|
display: flex;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.compose-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) 10.5rem;
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: stretch;
|
||||||
|
margin-bottom: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.compose-main {
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
align-content: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-col {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.35rem;
|
||||||
|
min-height: 0;
|
||||||
|
max-height: 11.5rem;
|
||||||
|
padding: 0.5rem;
|
||||||
|
border: 1px solid #e7eef2;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: #fafbfc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-col-title {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: #0f172a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-templates {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.3rem;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: auto;
|
||||||
|
flex: 1;
|
||||||
|
padding-inline-end: 0.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tpl-chip {
|
||||||
|
flex: none;
|
||||||
|
width: 100%;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
|
||||||
|
background: #fff;
|
||||||
|
color: var(--accent-deep);
|
||||||
|
border-radius: 8px;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.76rem;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 0.4rem 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: start;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tpl-chip:hover {
|
||||||
|
background: var(--accent-subtle);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-empty {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiny {
|
||||||
|
font-size: 0.72rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.compose-layout {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quick-col {
|
||||||
|
max-height: 8.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.manage-list {
|
||||||
|
padding-top: 0.45rem;
|
||||||
|
border-top: 1px solid #eef2f7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-list .pick-name {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0.4rem 0.5rem;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
color: #0f172a;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-list .del {
|
||||||
|
flex: none;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: transparent;
|
||||||
|
color: #b91c1c;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.35rem 0.45rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.draft {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.35rem;
|
||||||
|
padding-top: 0.45rem;
|
||||||
|
border-top: 1px solid #eef2f7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.draft strong {
|
||||||
|
font-size: 0.86rem;
|
||||||
|
color: #0f172a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.draft input,
|
||||||
|
.draft textarea,
|
||||||
|
#sms-compose-body {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
border: 1px solid #e2e8f0;
|
border: 1px solid #e2e8f0;
|
||||||
border-radius: 12px;
|
border-radius: 10px;
|
||||||
padding: 0.7rem 0.8rem;
|
padding: 0.55rem 0.7rem;
|
||||||
font: inherit;
|
font: inherit;
|
||||||
resize: vertical;
|
|
||||||
color: #0f172a;
|
color: #0f172a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.draft textarea,
|
||||||
|
#sms-compose-body {
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tpl-fields {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tpl-fields-label {
|
||||||
|
color: #64748b;
|
||||||
|
font-size: 0.74rem;
|
||||||
|
margin-inline-end: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tpl-fields button {
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
|
||||||
|
background: #fff;
|
||||||
|
color: var(--accent-deep);
|
||||||
|
border-radius: 999px;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.74rem;
|
||||||
|
padding: 0.2rem 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tpl-fields code {
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-btn {
|
||||||
|
justify-self: start;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #0f766e;
|
||||||
|
color: #fff;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
padding: 0.45rem 0.75rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-btn:disabled {
|
||||||
|
opacity: 0.45;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.compose-label {
|
||||||
|
display: block;
|
||||||
|
margin: 0.15rem 0 0.35rem;
|
||||||
|
color: #475569;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
.count {
|
.count {
|
||||||
margin: 0.35rem 0 0;
|
margin: 0.35rem 0 0;
|
||||||
color: #94a3b8;
|
color: #94a3b8;
|
||||||
@@ -316,6 +876,7 @@ textarea {
|
|||||||
margin: 0.3rem 0 0;
|
margin: 0.3rem 0 0;
|
||||||
color: #134e4a;
|
color: #134e4a;
|
||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
|
white-space: pre-wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.history {
|
.history {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user