Compare commits
26
Commits
dev
...
5b26b9156d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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[];
|
||||
@@ -33,6 +33,11 @@ enum ActivityStatus {
|
||||
canceled
|
||||
}
|
||||
|
||||
enum ActivityCompletionMode {
|
||||
any
|
||||
all
|
||||
}
|
||||
|
||||
enum ActivityPriority {
|
||||
low
|
||||
medium
|
||||
@@ -883,6 +888,10 @@ model Activity {
|
||||
/// زمان ارسال یادآور؛ با تغییر reminderAt پاک میشود
|
||||
reminderSentAt DateTime?
|
||||
completedAt DateTime?
|
||||
/// any = با انجام یکی بسته میشود؛ all = هر مسئول باید سهم خودش را بزند
|
||||
completionMode ActivityCompletionMode @default(any)
|
||||
/// مسئولانی که سهم خود را در حالت all ثبت کردهاند
|
||||
completedByIds String[] @default([])
|
||||
tags String[] @default([])
|
||||
personId String?
|
||||
person Person? @relation(fields: [personId], references: [id], onDelete: SetNull)
|
||||
@@ -2447,8 +2456,11 @@ model FinancialPayroll {
|
||||
period String
|
||||
baseAmount Decimal @db.Decimal(18, 2)
|
||||
benefits Decimal @default(0) @db.Decimal(18, 2)
|
||||
benefitsReason String?
|
||||
bonus Decimal @default(0) @db.Decimal(18, 2)
|
||||
bonusReason String?
|
||||
deductions Decimal @default(0) @db.Decimal(18, 2)
|
||||
deductionsReason String?
|
||||
payable Decimal @db.Decimal(18, 2)
|
||||
dueDate DateTime
|
||||
notes String?
|
||||
@@ -2953,18 +2965,28 @@ model MontifyWebhookDelivery {
|
||||
@@index([connectionId, createdAt])
|
||||
}
|
||||
|
||||
/// اتصال تلفن سازمانی / سانترال (وبهوک عمومی)
|
||||
/// اتصال تلفن سازمانی / سانترال (وبهوک عمومی یا ارائهدهنده)
|
||||
model VoipConnection {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
label String
|
||||
/// generic | daftareshoma
|
||||
provider String @default("generic")
|
||||
enabled Boolean @default(true)
|
||||
webhookSecretCiphertext String?
|
||||
webhookSecretIv String?
|
||||
webhookSecretTag String?
|
||||
/// قالب URL شروع تماس؛ جای {number} شماره مینشیند
|
||||
/// قالب URL شروع تماس؛ جای {number} شماره مینشیند (generic)
|
||||
clickToCallUrl String?
|
||||
/// توکن Bearer API دفتر شما (رمزنگاریشده)
|
||||
apiTokenCiphertext String?
|
||||
apiTokenIv String?
|
||||
apiTokenTag String?
|
||||
/// شماره مبدأ در تماس خروجی دفتر شما (from_number)
|
||||
fromNumber String?
|
||||
/// خط/داخلی سازمان در دفتر شما (caller_extension)
|
||||
callerExtension String?
|
||||
lastEventAt DateTime?
|
||||
lastError String?
|
||||
calls VoipCallLog[]
|
||||
@@ -2972,6 +2994,7 @@ model VoipConnection {
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([organizationId, enabled])
|
||||
@@index([organizationId, provider])
|
||||
}
|
||||
|
||||
model VoipCallLog {
|
||||
@@ -2986,6 +3009,8 @@ model VoipCallLog {
|
||||
status String @default("completed")
|
||||
fromNumber String?
|
||||
toNumber String?
|
||||
/// خط/داخلی سازمان که تماس روی آن بوده (مثلاً CalleeExtension دفتر شما)
|
||||
lineExtension String?
|
||||
personId String?
|
||||
activityId String?
|
||||
durationSec Int?
|
||||
@@ -3010,6 +3035,8 @@ model VoipCallLog {
|
||||
|
||||
@@unique([connectionId, externalCallId])
|
||||
@@index([organizationId, syncedAt])
|
||||
@@index([organizationId, lineExtension])
|
||||
@@index([organizationId, status])
|
||||
@@index([personId])
|
||||
@@index([activityId])
|
||||
@@index([summaryStatus, summaryNextAttemptAt])
|
||||
|
||||
@@ -438,8 +438,16 @@ export class ActivitiesController {
|
||||
}
|
||||
|
||||
@Patch(':id/complete')
|
||||
complete(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||
return this.activitiesService.complete(user.organizationId, id, user);
|
||||
complete(
|
||||
@CurrentUser() user: Actor,
|
||||
@Param('id') id: string,
|
||||
@Query('force') force?: string,
|
||||
@Query('undo') undo?: string,
|
||||
) {
|
||||
return this.activitiesService.complete(user.organizationId, id, user, {
|
||||
force: force === '1' || force === 'true',
|
||||
undo: undo === '1' || undo === 'true',
|
||||
});
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
|
||||
@@ -52,6 +52,28 @@ type ActivityActor = Pick<
|
||||
'userId' | 'role' | 'priorLens' | 'priorCutoff' | 'leadsAccess' | 'teamPeerIds'
|
||||
>;
|
||||
|
||||
function assigneeIdList(row: {
|
||||
assigneeId?: string | null;
|
||||
assignees?: Array<{ id: string }>;
|
||||
}): string[] {
|
||||
const ids = row.assignees?.map((item) => item.id) ?? [];
|
||||
if (ids.length) return [...new Set(ids)];
|
||||
return row.assigneeId ? [row.assigneeId] : [];
|
||||
}
|
||||
|
||||
function canForceClose(
|
||||
actor: { userId: string; role: string },
|
||||
createdById: string | null | undefined,
|
||||
): boolean {
|
||||
return actor.role === 'owner' || actor.role === 'admin' || actor.userId === createdById;
|
||||
}
|
||||
|
||||
function reconcileAllShares(assigneeIds: string[], completedByIds: string[]) {
|
||||
const kept = [...new Set(completedByIds.filter((id) => assigneeIds.includes(id)))];
|
||||
const done = assigneeIds.length > 0 && assigneeIds.every((id) => kept.includes(id));
|
||||
return { status: done ? ('done' as const) : ('open' as const), completedByIds: kept };
|
||||
}
|
||||
|
||||
/** stageId = شناسهٔ مرحله یا 'all'؛ وقتی ست باشد فیلتر زمانی وضعیت را تحمیل نمیکند (جز عقبافتاده) */
|
||||
type StageScope = { stageId: string };
|
||||
|
||||
@@ -82,6 +104,8 @@ type ActivityRow = {
|
||||
reminderNotifySms: boolean;
|
||||
reminderSentAt: Date | null;
|
||||
completedAt: Date | null;
|
||||
completionMode?: 'any' | 'all';
|
||||
completedByIds?: string[];
|
||||
importSource?: string;
|
||||
promotedFromPriorAt?: Date | null;
|
||||
tags: string[];
|
||||
@@ -186,22 +210,39 @@ export class ActivitiesService {
|
||||
return { stages, types };
|
||||
}
|
||||
|
||||
/** کارهای بازِ «من» که سهمشان ثبت شده، از میز کار شخص خارج میشوند. */
|
||||
private deskScope(
|
||||
actor: ActivityActor,
|
||||
desk?: 'mine' | 'team',
|
||||
): Prisma.ActivityWhereInput {
|
||||
if (desk !== 'mine') return activityAccessWhere(actor);
|
||||
return {
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ assigneeId: actor.userId },
|
||||
{ assignees: { some: { id: actor.userId } } },
|
||||
{ participantIds: { has: actor.userId } },
|
||||
],
|
||||
},
|
||||
{
|
||||
NOT: {
|
||||
completionMode: 'all',
|
||||
status: 'open',
|
||||
completedByIds: { has: actor.userId },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async summary(
|
||||
organizationId: string,
|
||||
actor: ActivityActor,
|
||||
desk?: 'mine' | 'team',
|
||||
): Promise<ActivitySummaryDto> {
|
||||
const { start, end } = dayBounds();
|
||||
const scope: Prisma.ActivityWhereInput =
|
||||
desk === 'mine'
|
||||
? {
|
||||
OR: [
|
||||
{ assigneeId: actor.userId },
|
||||
{ assignees: { some: { id: actor.userId } } },
|
||||
{ participantIds: { has: actor.userId } },
|
||||
],
|
||||
}
|
||||
: activityAccessWhere(actor);
|
||||
const scope = this.deskScope(actor, desk);
|
||||
const prior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
|
||||
const [todayCount, overdueCount] = await Promise.all([
|
||||
this.prisma.activity.count({
|
||||
@@ -534,8 +575,24 @@ export class ActivitiesService {
|
||||
const stage = await this.stages.get(organizationId, stageId);
|
||||
const existing = await this.prisma.activity.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: { status: true, completedAt: true },
|
||||
select: {
|
||||
status: true,
|
||||
completedAt: true,
|
||||
completionMode: true,
|
||||
completedByIds: true,
|
||||
createdById: true,
|
||||
assigneeId: true,
|
||||
assignees: { select: { id: true } },
|
||||
},
|
||||
});
|
||||
if (
|
||||
stage.kind === 'done' &&
|
||||
existing?.completionMode === 'all' &&
|
||||
assigneeIdList(existing).length > 1 &&
|
||||
!canForceClose(actor, existing.createdById)
|
||||
) {
|
||||
return this.complete(organizationId, id, actor);
|
||||
}
|
||||
const row = await this.prisma.activity.update({
|
||||
where: { id },
|
||||
data: {
|
||||
@@ -550,6 +607,9 @@ export class ActivitiesService {
|
||||
: stage.kind === 'open'
|
||||
? null
|
||||
: undefined,
|
||||
...(stage.kind === 'open' && existing?.status !== 'open'
|
||||
? { completedByIds: [] }
|
||||
: {}),
|
||||
},
|
||||
include,
|
||||
});
|
||||
@@ -675,6 +735,8 @@ export class ActivitiesService {
|
||||
assignees: assigneeIds.length
|
||||
? { connect: assigneeIds.map((id) => ({ id })) }
|
||||
: undefined,
|
||||
completionMode: dto.completionMode === 'all' ? 'all' : 'any',
|
||||
completedByIds: [],
|
||||
createdById: userId,
|
||||
},
|
||||
include,
|
||||
@@ -743,7 +805,17 @@ export class ActivitiesService {
|
||||
|
||||
const existing = await this.prisma.activity.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: { status: true, type: true, typeDefId: true, fields: true, participantIds: true },
|
||||
select: {
|
||||
status: true,
|
||||
type: true,
|
||||
typeDefId: true,
|
||||
fields: true,
|
||||
participantIds: true,
|
||||
completionMode: true,
|
||||
completedByIds: true,
|
||||
assigneeId: true,
|
||||
assignees: { select: { id: true } },
|
||||
},
|
||||
});
|
||||
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
||||
if (dto.title !== undefined) data.title = dto.title.trim();
|
||||
@@ -812,6 +884,7 @@ export class ActivitiesService {
|
||||
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
|
||||
if ('leadId' in dto) data.leadId = emptyToNull(dto.leadId ?? null);
|
||||
let assigneeConnect: Array<{ id: string }> | undefined;
|
||||
let nextAssigneeIds: string[] | undefined;
|
||||
if (dto.assigneeIds !== undefined || 'assigneeId' in dto) {
|
||||
const current = await this.prisma.activity.findFirst({
|
||||
where: { id, organizationId },
|
||||
@@ -839,6 +912,7 @@ export class ActivitiesService {
|
||||
);
|
||||
data.assigneeId = assigneeIds[0]!;
|
||||
assigneeConnect = assigneeIds.map((uid) => ({ id: uid }));
|
||||
nextAssigneeIds = assigneeIds;
|
||||
} else {
|
||||
const assigneeId = emptyToNull(dto.assigneeId ?? null);
|
||||
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
||||
@@ -852,12 +926,41 @@ export class ActivitiesService {
|
||||
data.assigneeId = assigneeId;
|
||||
if (assigneeId) assigneeConnect = [{ id: assigneeId }];
|
||||
else assigneeConnect = [];
|
||||
nextAssigneeIds = assigneeId ? [assigneeId] : [];
|
||||
}
|
||||
}
|
||||
if (dto.status !== undefined) {
|
||||
data.status = dto.status;
|
||||
data.completedAt =
|
||||
dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined;
|
||||
const modeChanged = dto.completionMode === 'any' || dto.completionMode === 'all';
|
||||
const nextMode = modeChanged ? dto.completionMode! : (existing?.completionMode ?? 'any');
|
||||
if (modeChanged) data.completionMode = nextMode;
|
||||
const prevAssigneeIds = assigneeIdList(existing ?? {});
|
||||
const nextIds = nextAssigneeIds ?? prevAssigneeIds;
|
||||
const explicitDone = dto.status === 'done';
|
||||
const explicitReopen = dto.status === 'open' && existing?.status !== 'open';
|
||||
const explicitCancel = dto.status === 'canceled';
|
||||
if (explicitDone) {
|
||||
data.status = 'done';
|
||||
data.completedAt = new Date();
|
||||
} else if (explicitReopen) {
|
||||
data.status = 'open';
|
||||
data.completedAt = null;
|
||||
data.completedByIds = [];
|
||||
} else if (explicitCancel) {
|
||||
data.status = 'canceled';
|
||||
} else if (nextMode === 'any' && modeChanged) {
|
||||
data.completedByIds = [];
|
||||
} else if (nextMode === 'all' && (modeChanged || nextAssigneeIds)) {
|
||||
const reconciled = reconcileAllShares(nextIds, existing?.completedByIds ?? []);
|
||||
data.completedByIds = reconciled.completedByIds;
|
||||
const finishedStaysFinished = existing?.status === 'done' && !nextAssigneeIds;
|
||||
if (existing?.status !== 'canceled' && !finishedStaysFinished) {
|
||||
if (reconciled.status === 'done' && existing?.status !== 'done') {
|
||||
data.status = 'done';
|
||||
data.completedAt = new Date();
|
||||
} else if (reconciled.status === 'open' && existing?.status === 'done') {
|
||||
data.status = 'open';
|
||||
data.completedAt = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const row = await this.prisma.activity.update({
|
||||
@@ -881,7 +984,7 @@ export class ActivitiesService {
|
||||
addedParticipants.filter((uid) => !assigneeSet.has(uid)),
|
||||
);
|
||||
}
|
||||
if (dto.status === 'done' && existing?.status !== 'done') {
|
||||
if (data.status === 'done' && existing?.status !== 'done') {
|
||||
await this.fireDone(organizationId, row);
|
||||
}
|
||||
return this.toDto(row, await this.ctx(organizationId));
|
||||
@@ -891,18 +994,74 @@ export class ActivitiesService {
|
||||
organizationId: string,
|
||||
id: string,
|
||||
actor: ActivityActor,
|
||||
options: { force?: boolean; undo?: boolean } = {},
|
||||
): Promise<ActivityDto> {
|
||||
await this.ensureExists(organizationId, id, actor);
|
||||
const existing = await this.prisma.activity.findFirst({
|
||||
where: { id, organizationId },
|
||||
select: { status: true },
|
||||
select: {
|
||||
status: true,
|
||||
completionMode: true,
|
||||
completedByIds: true,
|
||||
createdById: true,
|
||||
assigneeId: true,
|
||||
assignees: { select: { id: true } },
|
||||
},
|
||||
});
|
||||
if (!existing) throw new NotFoundException('فعالیت پیدا نشد');
|
||||
if (existing.status === 'canceled') {
|
||||
throw new BadRequestException('فعالیت لغو شده است');
|
||||
}
|
||||
|
||||
const assignees = assigneeIdList(existing);
|
||||
const allowedForce = canForceClose(actor, existing.createdById);
|
||||
if (options.force && !allowedForce) {
|
||||
throw new ForbiddenException('بستن فعالیت برای همه فقط برای سازنده یا مدیر ممکن است');
|
||||
}
|
||||
|
||||
if (options.undo) {
|
||||
if (existing.completionMode !== 'all' || existing.status !== 'open') {
|
||||
throw new BadRequestException('سهم انجامشده را فقط تا وقتی فعالیت باز است میتوان لغو کرد');
|
||||
}
|
||||
const row = await this.prisma.activity.update({
|
||||
where: { id },
|
||||
data: {
|
||||
completedByIds: existing.completedByIds.filter((uid) => uid !== actor.userId),
|
||||
},
|
||||
include,
|
||||
});
|
||||
return this.toDto(row, await this.ctx(organizationId));
|
||||
}
|
||||
|
||||
const personal =
|
||||
existing.completionMode === 'all' && assignees.length > 1 && !options.force;
|
||||
if (!personal) {
|
||||
const row = await this.prisma.activity.update({
|
||||
where: { id },
|
||||
data: { status: 'done', completedAt: new Date() },
|
||||
include,
|
||||
});
|
||||
if (existing.status !== 'done') await this.fireDone(organizationId, row);
|
||||
return this.toDto(row, await this.ctx(organizationId));
|
||||
}
|
||||
|
||||
if (!assignees.includes(actor.userId)) {
|
||||
throw new ForbiddenException('فقط مسئول این فعالیت میتواند سهم خودش را ثبت کند');
|
||||
}
|
||||
const reconciled = reconcileAllShares(assignees, [
|
||||
...existing.completedByIds,
|
||||
actor.userId,
|
||||
]);
|
||||
const row = await this.prisma.activity.update({
|
||||
where: { id },
|
||||
data: { status: 'done', completedAt: new Date() },
|
||||
data: {
|
||||
completedByIds: reconciled.completedByIds,
|
||||
status: reconciled.status,
|
||||
completedAt: reconciled.status === 'done' ? new Date() : null,
|
||||
},
|
||||
include,
|
||||
});
|
||||
if (existing?.status !== 'done') {
|
||||
if (reconciled.status === 'done' && existing.status !== 'done') {
|
||||
await this.fireDone(organizationId, row);
|
||||
}
|
||||
return this.toDto(row, await this.ctx(organizationId));
|
||||
@@ -1108,16 +1267,7 @@ export class ActivitiesService {
|
||||
typeRows: TypeRow[] = [],
|
||||
): Prisma.ActivityWhereInput {
|
||||
const { start, end } = dayBounds();
|
||||
const scope: Prisma.ActivityWhereInput =
|
||||
desk === 'mine'
|
||||
? {
|
||||
OR: [
|
||||
{ assigneeId: actor.userId },
|
||||
{ assignees: { some: { id: actor.userId } } },
|
||||
{ participantIds: { has: actor.userId } },
|
||||
],
|
||||
}
|
||||
: activityAccessWhere(actor);
|
||||
const scope = this.deskScope(actor, desk);
|
||||
const facetAssignee = facets?.assigneeId?.trim();
|
||||
const facetTypeDef = facets?.typeDefId?.trim();
|
||||
const facetTitle = facets?.title?.trim();
|
||||
@@ -1418,6 +1568,8 @@ export class ActivitiesService {
|
||||
reminderNotifySms: row.reminderNotifySms,
|
||||
reminderSentAt: row.reminderSentAt?.toISOString() ?? null,
|
||||
completedAt: row.completedAt?.toISOString() ?? null,
|
||||
completionMode: row.completionMode ?? 'any',
|
||||
completedByIds: row.completedByIds ?? [],
|
||||
importSource: row.importSource ?? 'manual',
|
||||
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
|
||||
tags: row.tags ?? [],
|
||||
|
||||
@@ -384,6 +384,10 @@ export class CreateActivityDto {
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
assigneeIds?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['any', 'all'])
|
||||
completionMode?: 'any' | 'all';
|
||||
}
|
||||
|
||||
export class UpdateActivityDto {
|
||||
@@ -484,4 +488,8 @@ export class UpdateActivityDto {
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
assigneeIds?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['any', 'all'])
|
||||
completionMode?: 'any' | 'all';
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ import type {
|
||||
StorageUsageDto,
|
||||
SubscriptionSummaryDto,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
parseUserTreasuryAccess,
|
||||
permissionsWithTreasuryOverride,
|
||||
} from '@mento/shared';
|
||||
import { Prisma } from '@prisma/client';
|
||||
/** Ensures Express.Multer.File augmentation is loaded for saveAvatar. */
|
||||
import type {} from 'multer';
|
||||
@@ -848,6 +852,9 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
const role = membership?.role ?? user.role;
|
||||
const rolePermissions = Array.isArray(membership?.orgRole?.permissions)
|
||||
? membership.orgRole.permissions.filter((item) => typeof item === 'string')
|
||||
: [];
|
||||
const orgName = membership?.organization.name;
|
||||
const sub =
|
||||
subscription ??
|
||||
@@ -879,9 +886,10 @@ export class AuthService {
|
||||
storage,
|
||||
isOrgOwner: role === 'owner',
|
||||
priorArchive: this.priorArchiveFor(membership),
|
||||
permissions: (Array.isArray(membership?.orgRole?.permissions)
|
||||
? membership.orgRole.permissions.filter((item) => typeof item === 'string')
|
||||
: []) as AuthUserDto['permissions'],
|
||||
permissions: permissionsWithTreasuryOverride(
|
||||
rolePermissions,
|
||||
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
|
||||
) as AuthUserDto['permissions'],
|
||||
...(viewAs ? { viewAs } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -195,6 +195,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
const peers = await this.prisma.teamMember.findMany({
|
||||
where: {
|
||||
teamId: { in: memberships.map((m) => m.teamId) },
|
||||
team: { organizationId },
|
||||
user: {
|
||||
memberships: { some: { organizationId, isActive: true } },
|
||||
},
|
||||
},
|
||||
select: { userId: true },
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
SectionDataAccess,
|
||||
UserRole,
|
||||
} from '@mento/shared';
|
||||
import { DATA_SCOPES, canViewAllRecords } from '@mento/shared';
|
||||
import { DATA_SCOPES, canViewAllRecords, sectionHasDataAccessLimits } from '@mento/shared';
|
||||
import type { Prisma } from '@prisma/client';
|
||||
import {
|
||||
activitiesDeepWhere,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
notesDeepWhere,
|
||||
projectsDeepWhere,
|
||||
routinesDeepWhere,
|
||||
sectionOwnerIdUnion,
|
||||
ticketsDeepWhere,
|
||||
} from './data-access';
|
||||
|
||||
@@ -60,6 +61,65 @@ export type Actor = {
|
||||
|
||||
export type ScopedActor = Pick<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 با سطح دید مخصوص یک بخش (اگر تنظیم شده باشد). */
|
||||
export function forScope<T extends ScopedActor>(actor: T, scope: DataScope): T {
|
||||
const s = actor.scopes?.[scope];
|
||||
@@ -109,9 +169,16 @@ export function scopedOwnerIds(
|
||||
|
||||
/** فیلتر مالکیت؛ پیشفرض بخش «مشتریان» (Person / Company). برای فاکتور/پیشفاکتور scope=finance. */
|
||||
export function ownerWhere(
|
||||
actor: ScopedActor,
|
||||
actor: DeepAccessActor,
|
||||
scope: DataScope = 'contacts',
|
||||
): { ownerId: string } | { ownerId: { in: string[] } } | Record<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);
|
||||
if (!ids) return {};
|
||||
if (ids.length === 1) return { ownerId: ids[0]! };
|
||||
@@ -153,11 +220,16 @@ export function projectCardAccessWhere(
|
||||
}
|
||||
|
||||
/** فعالیتها بر اساس مسئول اصلی یا مسئولان مشترک */
|
||||
export function assigneeWhere(
|
||||
actor: ScopedActor,
|
||||
): Prisma.ActivityWhereInput {
|
||||
const ids = scopedOwnerIds(actor, 'activities');
|
||||
export function assigneeWhere(actor: DeepAccessActor): Prisma.ActivityWhereInput {
|
||||
const deep = deepOwnerIds(actor, 'activities');
|
||||
const ids =
|
||||
deep.kind === 'open'
|
||||
? null
|
||||
: deep.kind === 'ids'
|
||||
? deep.ids
|
||||
: scopedOwnerIds(actor, 'activities');
|
||||
if (!ids) return {};
|
||||
if (!ids.length) return { assigneeId: '__no_access__' };
|
||||
return {
|
||||
OR: [
|
||||
{ assigneeId: { in: ids } },
|
||||
|
||||
@@ -112,9 +112,13 @@ export class CompaniesService {
|
||||
...(groupIds.length ? [{ groupLinks: { some: { groupId: { in: groupIds } } } }] : []),
|
||||
];
|
||||
const where: Prisma.CompanyWhereInput = {
|
||||
organizationId: actor.organizationId,
|
||||
...customersCompanyWhere(actor),
|
||||
...(and.length ? { AND: and } : {}),
|
||||
AND: [
|
||||
{
|
||||
organizationId: actor.organizationId,
|
||||
...customersCompanyWhere(actor),
|
||||
},
|
||||
...and,
|
||||
],
|
||||
};
|
||||
|
||||
const [rows, total] = await this.prisma.$transaction([
|
||||
|
||||
@@ -218,11 +218,15 @@ export class PeopleService implements OnModuleInit {
|
||||
if (disc) and.push(disc);
|
||||
if (groupIds.length) and.push({ groupLinks: { some: { groupId: { in: groupIds } } } });
|
||||
return {
|
||||
organizationId: actor.organizationId,
|
||||
...customersPersonWhere(actor),
|
||||
...(moods.length ? { mood: { in: moods } } : {}),
|
||||
...(sources.length ? { importSource: { in: sources } } : {}),
|
||||
...(and.length ? { AND: and } : {}),
|
||||
AND: [
|
||||
{
|
||||
organizationId: actor.organizationId,
|
||||
...customersPersonWhere(actor),
|
||||
},
|
||||
...(moods.length ? [{ mood: { in: moods } }] : []),
|
||||
...(sources.length ? [{ importSource: { in: sources } }] : []),
|
||||
...and,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -438,6 +438,77 @@ export class TahesabPersonLinkService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* کدهایی که لینک ندارند ولی شمارهشان مال مشتریِ از قبل لینکشدهٔ همین اتصال است.
|
||||
* یک شخص فقط یک کد تهحساب دارد؛ این کدها مشتری تازه نیستند.
|
||||
*/
|
||||
private async duplicateOwners(
|
||||
organizationId: string,
|
||||
connectionId: string,
|
||||
rows: Array<{ moshtariCode: number | null; tel: string }>,
|
||||
) {
|
||||
const pending = rows.filter(
|
||||
(row): row is { moshtariCode: number; tel: string } => row.moshtariCode != null,
|
||||
);
|
||||
const keys = [
|
||||
...new Set(pending.flatMap((row) => phoneIdentityKeys(storedPhoneNumber(row.tel)))),
|
||||
];
|
||||
const out = new Map<
|
||||
number,
|
||||
{ moshtariCode: number; personId: string; personName: string }
|
||||
>();
|
||||
if (!keys.length) return out;
|
||||
|
||||
const people = await this.prisma.person.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
OR: [{ mobile: { in: keys } }, { phone: { in: keys } }],
|
||||
accountingLinks: { some: { connectionId } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
phone: true,
|
||||
accountingLinks: {
|
||||
where: { connectionId },
|
||||
select: { moshtariCode: true },
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
const byKey = new Map<
|
||||
string,
|
||||
{ moshtariCode: number; personId: string; personName: string }
|
||||
>();
|
||||
for (const person of people) {
|
||||
const link = person.accountingLinks[0];
|
||||
if (!link) continue;
|
||||
const info = {
|
||||
moshtariCode: link.moshtariCode,
|
||||
personId: person.id,
|
||||
personName: `${person.firstName} ${person.lastName}`.trim(),
|
||||
};
|
||||
for (const key of [
|
||||
...phoneIdentityKeys(person.mobile),
|
||||
...phoneIdentityKeys(person.phone),
|
||||
]) {
|
||||
if (!byKey.has(key)) byKey.set(key, info);
|
||||
}
|
||||
}
|
||||
for (const row of pending) {
|
||||
for (const key of phoneIdentityKeys(storedPhoneNumber(row.tel))) {
|
||||
const hit = byKey.get(key);
|
||||
if (hit && hit.moshtariCode !== row.moshtariCode) {
|
||||
out.set(row.moshtariCode, hit);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async search(organizationId: string, dto: SearchTahesabDto) {
|
||||
const { api } = await this.connections.getApi(
|
||||
organizationId,
|
||||
@@ -516,7 +587,7 @@ export class TahesabPersonLinkService {
|
||||
});
|
||||
const byCode = new Map(existing.map((e) => [e.moshtariCode, e]));
|
||||
|
||||
const results = mapped.map((row) => {
|
||||
const linked = mapped.map((row) => {
|
||||
const link = row.moshtariCode != null ? byCode.get(row.moshtariCode) : undefined;
|
||||
return {
|
||||
...row,
|
||||
@@ -527,6 +598,22 @@ export class TahesabPersonLinkService {
|
||||
: null,
|
||||
};
|
||||
});
|
||||
const duplicates = await this.duplicateOwners(
|
||||
organizationId,
|
||||
dto.connectionId,
|
||||
linked.filter((row) => !row.alreadyLinked),
|
||||
);
|
||||
const results = linked.map((row) => {
|
||||
if (row.alreadyLinked || row.moshtariCode == null) return row;
|
||||
const dup = duplicates.get(row.moshtariCode);
|
||||
if (!dup) return row;
|
||||
return {
|
||||
...row,
|
||||
duplicateOfCode: dup.moshtariCode,
|
||||
duplicatePersonId: dup.personId,
|
||||
duplicatePersonName: dup.personName,
|
||||
};
|
||||
});
|
||||
|
||||
await this.prisma.accountingSyncJob.create({
|
||||
data: {
|
||||
@@ -601,7 +688,6 @@ export class TahesabPersonLinkService {
|
||||
const sourceRef = String(dto.moshtariCode);
|
||||
|
||||
let personId = dto.personId;
|
||||
let preserveExistingLink = false;
|
||||
if (personId) {
|
||||
const existing = await this.getPerson(organizationId, personId);
|
||||
const prevFirst = existing.firstName;
|
||||
@@ -630,8 +716,8 @@ export class TahesabPersonLinkService {
|
||||
});
|
||||
} else {
|
||||
// اگر موبایل تکراری است → همان شخص؛ نام قبلی حفظ و نام تهحساب جایگزین.
|
||||
// اگر همان شخص قبلاً به کد دیگری از این اتصال لینک شده، لینک جابهجا نمیشود
|
||||
// تا کد قبلی دوباره «واردنشده» نشود و مشتری تکراری ساخته نشود.
|
||||
// اگر همان شخص قبلاً به کد دیگری از این اتصال لینک شده، نام و لینک دست نمیخورند
|
||||
// تا کد قبلی جابهجا نشود و این کد هم مشتری تکراری نسازد.
|
||||
const mobileKeys = phoneIdentityKeys(mobile);
|
||||
const matches = mobileKeys.length
|
||||
? await this.prisma.person.findMany({
|
||||
@@ -651,7 +737,22 @@ export class TahesabPersonLinkService {
|
||||
const byMobile = matches.find((person) => person.importSource === 'tahesab') ?? matches[0] ?? null;
|
||||
if (byMobile) {
|
||||
const linkedCode = byMobile.accountingLinks[0]?.moshtariCode;
|
||||
preserveExistingLink = linkedCode != null && linkedCode !== dto.moshtariCode;
|
||||
if (linkedCode != null && linkedCode !== dto.moshtariCode) {
|
||||
const existing = await this.prisma.personAccountingLink.findFirst({
|
||||
where: { personId: byMobile.id, connectionId: dto.connectionId },
|
||||
include: {
|
||||
connection: { select: { label: true, dbName: true, isDefault: true } },
|
||||
},
|
||||
});
|
||||
if (!existing) {
|
||||
throw new NotFoundException('لینک تهحساب این مشتری یافت نشد.');
|
||||
}
|
||||
return {
|
||||
personId: byMobile.id,
|
||||
link: this.linkDto(existing),
|
||||
duplicateOf: linkedCode,
|
||||
};
|
||||
}
|
||||
const nameChanged =
|
||||
`${byMobile.firstName} ${byMobile.lastName}`.trim() !==
|
||||
`${firstName} ${lastName}`.trim();
|
||||
@@ -670,7 +771,7 @@ export class TahesabPersonLinkService {
|
||||
: {}),
|
||||
...carryPreviousSource(byMobile, 'tahesab'),
|
||||
importSource: 'tahesab',
|
||||
sourceRef: preserveExistingLink ? String(linkedCode) : sourceRef,
|
||||
sourceRef,
|
||||
...(!byMobile.birthDate && pickBirthDate(row) ? { birthDate: pickBirthDate(row) } : {}),
|
||||
...canonicalMobileUpdate(mobile, byMobile),
|
||||
},
|
||||
@@ -696,32 +797,6 @@ export class TahesabPersonLinkService {
|
||||
}
|
||||
}
|
||||
|
||||
if (preserveExistingLink) {
|
||||
await this.applyTahesabGroup(organizationId, dto.connectionId, personId, row);
|
||||
const existing = await this.prisma.personAccountingLink.findFirst({
|
||||
where: { personId, connectionId: dto.connectionId },
|
||||
include: {
|
||||
connection: { select: { label: true, dbName: true, isDefault: true } },
|
||||
},
|
||||
});
|
||||
if (!existing) {
|
||||
throw new NotFoundException('لینک تهحساب این مشتری یافت نشد.');
|
||||
}
|
||||
if (!options?.skipJob) {
|
||||
await this.prisma.accountingSyncJob.create({
|
||||
data: {
|
||||
organizationId,
|
||||
connectionId: dto.connectionId,
|
||||
kind: 'import',
|
||||
status: 'success',
|
||||
request: dto as unknown as Prisma.InputJsonValue,
|
||||
result: { personId, linkId: existing.id, keptLink: true } as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
return { personId, link: this.linkDto(existing) };
|
||||
}
|
||||
|
||||
const link = await this.prisma.personAccountingLink.upsert({
|
||||
where: {
|
||||
personId_connectionId: {
|
||||
@@ -822,6 +897,7 @@ export class TahesabPersonLinkService {
|
||||
let emptyStreak = 0;
|
||||
let imported = 0;
|
||||
let updated = 0;
|
||||
let duplicate = 0;
|
||||
let failed = 0;
|
||||
const errors: string[] = [];
|
||||
const maxPages = 300;
|
||||
@@ -869,13 +945,14 @@ export class TahesabPersonLinkService {
|
||||
);
|
||||
updated += 1;
|
||||
} else {
|
||||
await this.importFromTahesab(
|
||||
const created = await this.importFromTahesab(
|
||||
organizationId,
|
||||
{ connectionId, moshtariCode: code },
|
||||
{ api, row },
|
||||
{ skipJob: true },
|
||||
);
|
||||
imported += 1;
|
||||
if (created.duplicateOf) duplicate += 1;
|
||||
else imported += 1;
|
||||
}
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
@@ -891,20 +968,26 @@ export class TahesabPersonLinkService {
|
||||
errors.push('فهرست مشتریان از سقف خواندن خودکار بیشتر بود.');
|
||||
}
|
||||
|
||||
const summary = `${imported} وارد شد، ${updated} بهروز شد، ${failed} خطا`;
|
||||
const summary = [
|
||||
`${imported} وارد شد`,
|
||||
`${updated} بهروز شد`,
|
||||
...(duplicate ? [`${duplicate} شماره تکراری`] : []),
|
||||
`${failed} خطا`,
|
||||
].join('، ');
|
||||
await this.prisma.accountingSyncJob.create({
|
||||
data: {
|
||||
organizationId,
|
||||
connectionId,
|
||||
kind: 'customer-sync',
|
||||
status: !imported && !updated && (failed > 0 || errors.length > 0) ? 'error' : 'success',
|
||||
result: { imported, updated, failed, pages: page - 1 } as Prisma.InputJsonValue,
|
||||
result: { imported, updated, duplicate, failed, pages: page - 1 } as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
this.logger.log(`همگامسازی مشتریان تهحساب ${connectionId}: ${summary}`);
|
||||
return {
|
||||
imported,
|
||||
updated,
|
||||
duplicate,
|
||||
failed,
|
||||
summary,
|
||||
error: errors.length ? errors.join('؛ ') : null,
|
||||
@@ -1029,6 +1112,16 @@ export class TahesabPersonLinkService {
|
||||
{ connectionId: dto.connectionId, moshtariCode },
|
||||
bulkApi ? { api: bulkApi, row: rowsByCode.get(moshtariCode) } : undefined,
|
||||
);
|
||||
if (r.duplicateOf) {
|
||||
items.push({
|
||||
moshtariCode,
|
||||
ok: true,
|
||||
skipped: true,
|
||||
personId: r.personId,
|
||||
error: `شماره تکراری است و قبلاً با کد ${r.duplicateOf} لینک شده`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
items.push({ moshtariCode, ok: true, personId: r.personId });
|
||||
} catch (e) {
|
||||
const message =
|
||||
|
||||
@@ -3,6 +3,9 @@ import { Cron } from '@nestjs/schedule';
|
||||
import { AiService } from '../../ai/ai.service';
|
||||
import { NotesService } from '../../notes/notes.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';
|
||||
|
||||
const MAX_ATTEMPTS = 3;
|
||||
@@ -17,6 +20,8 @@ export class CallSummaryService {
|
||||
private readonly stt: SttClientService,
|
||||
private readonly ai: AiService,
|
||||
private readonly notes: NotesService,
|
||||
private readonly connections: VoipConnectionsService,
|
||||
private readonly daftareshoma: DaftaresomaClient,
|
||||
) {}
|
||||
|
||||
@Cron('*/1 * * * *')
|
||||
@@ -74,7 +79,31 @@ export class CallSummaryService {
|
||||
);
|
||||
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({
|
||||
where: { id },
|
||||
data: { transcript },
|
||||
|
||||
@@ -13,6 +13,11 @@ import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { NotificationsService } from '../../notifications/notifications.service';
|
||||
import { iranMobileLookupKeys, normalizePhone } from '../../contacts/normalize';
|
||||
import { VoipConnectionsService } from './connections.service';
|
||||
import { DaftaresomaClient } from './daftareshoma-client';
|
||||
import {
|
||||
daftareshomaRecordingRef,
|
||||
parseDaftaresomaRecordingRef,
|
||||
} from './daftareshoma-webhook';
|
||||
|
||||
function digitsOnly(value: string | null | undefined): string {
|
||||
return (value ?? '').replace(/\D/g, '');
|
||||
@@ -57,19 +62,32 @@ export class VoipCallsService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly connections: VoipConnectionsService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly daftareshoma: DaftaresomaClient,
|
||||
) {}
|
||||
|
||||
async listRecent(
|
||||
organizationId: string,
|
||||
connectionId?: string,
|
||||
opts?: {
|
||||
connectionId?: string;
|
||||
direction?: string;
|
||||
status?: string;
|
||||
lineExtension?: string;
|
||||
},
|
||||
): Promise<VoipCallLogDto[]> {
|
||||
const rows = await this.prisma.voipCallLog.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
...(connectionId ? { connectionId } : {}),
|
||||
...(opts?.connectionId ? { connectionId: opts.connectionId } : {}),
|
||||
...(opts?.direction === 'inbound' || opts?.direction === 'outbound'
|
||||
? { direction: opts.direction }
|
||||
: {}),
|
||||
...(opts?.status?.trim() ? { status: opts.status.trim() } : {}),
|
||||
...(opts?.lineExtension?.trim()
|
||||
? { lineExtension: opts.lineExtension.trim() }
|
||||
: {}),
|
||||
},
|
||||
orderBy: { syncedAt: 'desc' },
|
||||
take: 50,
|
||||
take: 100,
|
||||
});
|
||||
const personIds = rows
|
||||
.map((r) => r.personId)
|
||||
@@ -91,6 +109,7 @@ export class VoipCallsService {
|
||||
status: r.status,
|
||||
fromNumber: r.fromNumber,
|
||||
toNumber: r.toNumber,
|
||||
lineExtension: r.lineExtension ?? null,
|
||||
personId: r.personId,
|
||||
personName: r.personId ? (nameById.get(r.personId) ?? null) : null,
|
||||
activityId: r.activityId,
|
||||
@@ -127,6 +146,9 @@ export class VoipCallsService {
|
||||
const toDigits = digitsOnly(event.to ?? event.callee);
|
||||
const fromNumber = fromNormalized || fromDigits || null;
|
||||
const toNumber = toNormalized || toDigits || null;
|
||||
const lineRaw = String(event.lineExtension ?? '').trim();
|
||||
const lineExtension =
|
||||
normalizePhone(lineRaw) || digitsOnly(lineRaw) || lineRaw || null;
|
||||
const matchNumber = direction === 'inbound' ? fromNumber : toNumber;
|
||||
const personId = await this.findPersonId(
|
||||
conn.organizationId,
|
||||
@@ -193,6 +215,7 @@ export class VoipCallsService {
|
||||
status,
|
||||
fromNumber,
|
||||
toNumber,
|
||||
lineExtension: lineExtension ?? existing.lineExtension,
|
||||
personId: personId ?? existing.personId,
|
||||
activityId: activityId ?? existing.activityId,
|
||||
durationSec,
|
||||
@@ -213,6 +236,7 @@ export class VoipCallsService {
|
||||
status,
|
||||
fromNumber,
|
||||
toNumber,
|
||||
lineExtension,
|
||||
personId,
|
||||
activityId,
|
||||
durationSec,
|
||||
@@ -240,6 +264,17 @@ export class VoipCallsService {
|
||||
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({
|
||||
where: {
|
||||
connectionId_externalCallId: {
|
||||
@@ -261,10 +296,67 @@ export class VoipCallsService {
|
||||
userId: string,
|
||||
number: 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);
|
||||
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({
|
||||
where: {
|
||||
organizationId,
|
||||
@@ -318,6 +410,69 @@ export class VoipCallsService {
|
||||
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 {
|
||||
return ['answered', 'completed', 'missed', 'failed'].includes(status);
|
||||
}
|
||||
|
||||
@@ -7,12 +7,17 @@ import type {
|
||||
CreateVoipConnectionRequest,
|
||||
UpdateVoipConnectionRequest,
|
||||
VoipConnectionDto,
|
||||
VoipProvider,
|
||||
} from '@mento/shared';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHmac } from 'crypto';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { TahesabCryptoService } from '../tahesab/tahesab-crypto.service';
|
||||
|
||||
function asProvider(value: string | null | undefined): VoipProvider {
|
||||
return value === 'daftareshoma' ? 'daftareshoma' : 'generic';
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class VoipConnectionsService {
|
||||
constructor(
|
||||
@@ -43,19 +48,35 @@ export class VoipConnectionsService {
|
||||
): Promise<VoipConnectionDto> {
|
||||
const label = dto.label?.trim();
|
||||
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 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({
|
||||
data: {
|
||||
organizationId,
|
||||
label,
|
||||
provider,
|
||||
enabled: dto.enabled ?? true,
|
||||
clickToCallUrl,
|
||||
fromNumber: dto.fromNumber?.trim() || null,
|
||||
callerExtension: dto.callerExtension?.trim() || null,
|
||||
webhookSecretCiphertext: secretEnc?.ciphertext,
|
||||
webhookSecretIv: secretEnc?.iv,
|
||||
webhookSecretTag: secretEnc?.tag,
|
||||
apiTokenCiphertext: tokenEnc?.ciphertext,
|
||||
apiTokenIv: tokenEnc?.iv,
|
||||
apiTokenTag: tokenEnc?.tag,
|
||||
},
|
||||
});
|
||||
return this.toDto(row, 0);
|
||||
@@ -77,6 +98,12 @@ export class VoipConnectionsService {
|
||||
if (dto.clickToCallUrl !== undefined) {
|
||||
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) {
|
||||
const wh = dto.webhookSecret?.trim();
|
||||
if (!wh) {
|
||||
@@ -90,6 +117,19 @@ export class VoipConnectionsService {
|
||||
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({
|
||||
where: { id: existing.id },
|
||||
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(
|
||||
rawBody: string | Buffer,
|
||||
signature: string | undefined,
|
||||
@@ -153,9 +208,13 @@ export class VoipConnectionsService {
|
||||
row: {
|
||||
id: string;
|
||||
label: string;
|
||||
provider?: string | null;
|
||||
enabled: boolean;
|
||||
webhookSecretCiphertext: string | null;
|
||||
apiTokenCiphertext?: string | null;
|
||||
clickToCallUrl: string | null;
|
||||
fromNumber?: string | null;
|
||||
callerExtension?: string | null;
|
||||
lastEventAt: Date | null;
|
||||
lastError: string | null;
|
||||
createdAt: Date;
|
||||
@@ -166,9 +225,13 @@ export class VoipConnectionsService {
|
||||
return {
|
||||
id: row.id,
|
||||
label: row.label,
|
||||
provider: asProvider(row.provider),
|
||||
enabled: row.enabled,
|
||||
webhookSecretSet: Boolean(row.webhookSecretCiphertext),
|
||||
apiTokenSet: Boolean(row.apiTokenCiphertext),
|
||||
clickToCallUrl: row.clickToCallUrl,
|
||||
fromNumber: row.fromNumber ?? null,
|
||||
callerExtension: row.callerExtension ?? null,
|
||||
lastEventAt: row.lastEventAt?.toISOString() ?? null,
|
||||
lastError: row.lastError,
|
||||
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 {
|
||||
IsBoolean,
|
||||
IsIn,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
@@ -12,6 +13,10 @@ export class CreateVoipConnectionDto {
|
||||
@MaxLength(80)
|
||||
label!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['generic', 'daftareshoma'])
|
||||
provider?: 'generic' | 'daftareshoma';
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
@@ -22,6 +27,21 @@ export class CreateVoipConnectionDto {
|
||||
@MaxLength(500)
|
||||
clickToCallUrl?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
apiToken?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
fromNumber?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
callerExtension?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
enabled?: boolean;
|
||||
@@ -44,6 +64,21 @@ export class UpdateVoipConnectionDto {
|
||||
@MaxLength(500)
|
||||
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()
|
||||
@IsBoolean()
|
||||
enabled?: boolean;
|
||||
|
||||
@@ -18,17 +18,31 @@ export class SttClientService {
|
||||
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();
|
||||
if (!baseUrl) {
|
||||
throw new ServiceUnavailableException('آدرس سرویس STT تنظیم نشده');
|
||||
}
|
||||
|
||||
const timeoutMs = Number(
|
||||
const waitMs = timeoutMs ?? Number(
|
||||
this.config.get<string>('STT_TIMEOUT_MS') || 180000,
|
||||
);
|
||||
const token = this.config.get<string>('STT_INTERNAL_TOKEN')?.trim() || '';
|
||||
|
||||
const audio = await this.downloadAudio(recordingUrl, timeoutMs);
|
||||
const form = new FormData();
|
||||
const blob = new Blob([new Uint8Array(audio.buffer)], {
|
||||
type: audio.contentType,
|
||||
@@ -39,7 +53,7 @@ export class SttClientService {
|
||||
if (token) headers['X-STT-Token'] = token;
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const timer = setTimeout(() => controller.abort(), waitMs);
|
||||
try {
|
||||
const res = await fetch(`${baseUrl.replace(/\/$/, '')}/transcribe`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -28,6 +28,10 @@ import {
|
||||
UpdateVoipConnectionDto,
|
||||
VoipClickToCallDto,
|
||||
} from './dto';
|
||||
import {
|
||||
isDaftaresomaWebhookPayload,
|
||||
mapDaftaresomaWebhook,
|
||||
} from './daftareshoma-webhook';
|
||||
|
||||
@Controller('integrations/voip')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
|
||||
@@ -78,8 +82,16 @@ export class VoipController {
|
||||
recent(
|
||||
@CurrentUser() user: { organizationId: string },
|
||||
@Query('connectionId') connectionId?: string,
|
||||
@Query('direction') direction?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('lineExtension') lineExtension?: string,
|
||||
) {
|
||||
return this.calls.listRecent(user.organizationId, connectionId);
|
||||
return this.calls.listRecent(user.organizationId, {
|
||||
connectionId,
|
||||
direction,
|
||||
status,
|
||||
lineExtension,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('click-to-call')
|
||||
@@ -129,11 +141,21 @@ export class VoipWebhookController {
|
||||
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' };
|
||||
}
|
||||
|
||||
const result = await this.calls.ingestWebhook(connectionId, body);
|
||||
const result = await this.calls.ingestWebhook(connectionId, event);
|
||||
return { ok: true, ...result };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { TahesabCryptoService } from '../tahesab/tahesab-crypto.service';
|
||||
import { CallSummaryService } from './call-summary.service';
|
||||
import { VoipConnectionsService } from './connections.service';
|
||||
import { VoipCallsService } from './calls.service';
|
||||
import { DaftaresomaClient } from './daftareshoma-client';
|
||||
import { SttClientService } from './stt-client.service';
|
||||
import { VoipController, VoipWebhookController } from './voip.controller';
|
||||
|
||||
@@ -17,6 +18,7 @@ import { VoipController, VoipWebhookController } from './voip.controller';
|
||||
TahesabCryptoService,
|
||||
VoipConnectionsService,
|
||||
VoipCallsService,
|
||||
DaftaresomaClient,
|
||||
SttClientService,
|
||||
CallSummaryService,
|
||||
],
|
||||
|
||||
@@ -246,7 +246,11 @@ export class LeadsController {
|
||||
@Query('source') source?: string,
|
||||
@Query('unassigned') unassigned?: string,
|
||||
@Query('archived') archived?: string,
|
||||
@Query('converted') converted?: string,
|
||||
@Query('hasMobile') hasMobile?: string,
|
||||
@Query('followUp') followUp?: string,
|
||||
@Query('createdFrom') createdFrom?: string,
|
||||
@Query('createdTo') createdTo?: string,
|
||||
) {
|
||||
return this.leads.listIds(user, {
|
||||
q,
|
||||
@@ -258,7 +262,11 @@ export class LeadsController {
|
||||
source,
|
||||
unassigned: unassigned === '1' || unassigned === 'true',
|
||||
archived: archived === '1' || archived === 'true',
|
||||
converted: converted === '1' || converted === 'true',
|
||||
hasMobile: hasMobile === '1' || hasMobile === 'true',
|
||||
followUp,
|
||||
createdFrom,
|
||||
createdTo,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -276,8 +284,12 @@ export class LeadsController {
|
||||
@Query('source') source?: string,
|
||||
@Query('unassigned') unassigned?: string,
|
||||
@Query('archived') archived?: string,
|
||||
@Query('converted') converted?: string,
|
||||
@Query('sort') sort?: string,
|
||||
@Query('hasMobile') hasMobile?: string,
|
||||
@Query('followUp') followUp?: string,
|
||||
@Query('createdFrom') createdFrom?: string,
|
||||
@Query('createdTo') createdTo?: string,
|
||||
) {
|
||||
return this.leads.list(user, {
|
||||
q,
|
||||
@@ -291,8 +303,12 @@ export class LeadsController {
|
||||
source,
|
||||
unassigned: unassigned === '1' || unassigned === 'true',
|
||||
archived: archived === '1' || archived === 'true',
|
||||
converted: converted === '1' || converted === 'true',
|
||||
sort,
|
||||
hasMobile: hasMobile === '1' || hasMobile === 'true',
|
||||
followUp,
|
||||
createdFrom,
|
||||
createdTo,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,12 @@ import { StorageQuotaService } from '../billing/storage-quota.service';
|
||||
import { LeadStagesService } from './lead-stages.service';
|
||||
import { buildSearchWhere, ci } from '../common/search';
|
||||
import { GamificationService } from '../gamification/gamification.service';
|
||||
import {
|
||||
addDays,
|
||||
isDayKey,
|
||||
tehranDayKey,
|
||||
tehranDayStart,
|
||||
} from '../routines/routine-dates';
|
||||
|
||||
const LOGO_MAX_BYTES = 2 * 1024 * 1024;
|
||||
const LOGO_EXT: Record<string, string> = {
|
||||
@@ -142,7 +148,11 @@ export class LeadsService {
|
||||
source?: string;
|
||||
unassigned?: boolean;
|
||||
archived?: boolean;
|
||||
converted?: boolean;
|
||||
hasMobile?: boolean;
|
||||
followUp?: string;
|
||||
createdFrom?: string;
|
||||
createdTo?: string;
|
||||
},
|
||||
): Prisma.LeadWhereInput {
|
||||
const search = buildSearchWhere<Prisma.LeadWhereInput>(opts.q, (t) => [
|
||||
@@ -161,22 +171,77 @@ export class LeadsService {
|
||||
if (opts.hasMobile) {
|
||||
and.push({ mobile: { not: '' } });
|
||||
}
|
||||
const follow = this.followUpWhere(opts.followUp);
|
||||
if (follow) and.push(follow);
|
||||
const createdRange = this.createdAtWhere(opts.createdFrom, opts.createdTo);
|
||||
if (createdRange) and.push(createdRange);
|
||||
return {
|
||||
organizationId: actor.organizationId,
|
||||
...leadAccessWhere(actor),
|
||||
archivedAt: opts.archived ? { not: null } : null,
|
||||
...(opts.stageId ? { stageId: opts.stageId } : {}),
|
||||
...(opts.assigneeId ? { assigneeId: opts.assigneeId } : {}),
|
||||
...(opts.unassigned ? { assigneeId: null } : {}),
|
||||
...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}),
|
||||
...(opts.region
|
||||
? { region: { contains: opts.region, mode: 'insensitive' } }
|
||||
: {}),
|
||||
...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}),
|
||||
...(opts.source
|
||||
? { source: { contains: opts.source, mode: 'insensitive' } }
|
||||
: {}),
|
||||
...(and.length ? { AND: and } : {}),
|
||||
AND: [
|
||||
{
|
||||
organizationId: actor.organizationId,
|
||||
...leadAccessWhere(actor),
|
||||
archivedAt: opts.archived ? { not: null } : null,
|
||||
...(opts.converted ? { convertedPersonId: { not: null } } : {}),
|
||||
...(opts.stageId ? { stageId: opts.stageId } : {}),
|
||||
...(opts.city ? { city: { contains: opts.city, mode: 'insensitive' } } : {}),
|
||||
...(opts.region
|
||||
? { region: { contains: opts.region, mode: 'insensitive' } }
|
||||
: {}),
|
||||
...(opts.trade ? { trade: { contains: opts.trade, mode: 'insensitive' } } : {}),
|
||||
...(opts.source
|
||||
? { source: { contains: opts.source, mode: 'insensitive' } }
|
||||
: {}),
|
||||
},
|
||||
...(opts.unassigned ? [{ assigneeId: null }] : []),
|
||||
...(opts.assigneeId && !opts.unassigned ? [{ assigneeId: opts.assigneeId }] : []),
|
||||
...and,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** مرز روز به وقت تهران برای فیلترهای «امروز». */
|
||||
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 } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -194,8 +259,12 @@ export class LeadsService {
|
||||
source?: string;
|
||||
unassigned?: boolean;
|
||||
archived?: boolean;
|
||||
converted?: boolean;
|
||||
sort?: string;
|
||||
hasMobile?: boolean;
|
||||
followUp?: string;
|
||||
createdFrom?: string;
|
||||
createdTo?: string;
|
||||
},
|
||||
): Promise<PaginatedResponse<LeadDto>> {
|
||||
await this.stages.ensureDefaults(actor.organizationId);
|
||||
@@ -243,7 +312,11 @@ export class LeadsService {
|
||||
source?: string;
|
||||
unassigned?: boolean;
|
||||
archived?: boolean;
|
||||
converted?: boolean;
|
||||
hasMobile?: boolean;
|
||||
followUp?: string;
|
||||
createdFrom?: string;
|
||||
createdTo?: string;
|
||||
},
|
||||
max = FILTERED_IDS_MAX,
|
||||
): Promise<FilteredIdsResponse> {
|
||||
@@ -1116,7 +1189,7 @@ export class LeadsService {
|
||||
newStage
|
||||
? this.prisma.lead.count({ where: { ...base, stageId: newStage.id } })
|
||||
: Promise.resolve(0),
|
||||
this.prisma.lead.count({ where: { ...base, assigneeId: null } }),
|
||||
this.prisma.lead.count({ where: { AND: [base, { assigneeId: null }] } }),
|
||||
convertedIds.length
|
||||
? this.prisma.lead.count({
|
||||
where: { ...base, stageId: { in: convertedIds } },
|
||||
|
||||
@@ -31,8 +31,11 @@ export class PipelinesController {
|
||||
constructor(private readonly pipelinesService: PipelinesService) {}
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: { organizationId: string }) {
|
||||
return this.pipelinesService.list(user.organizationId);
|
||||
list(
|
||||
@CurrentUser() user: Actor,
|
||||
@Query('forLens') forLens?: string,
|
||||
) {
|
||||
return this.pipelinesService.list(user, forLens === '1');
|
||||
}
|
||||
|
||||
@Get('board')
|
||||
|
||||
@@ -102,24 +102,55 @@ export class PipelinesService {
|
||||
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);
|
||||
const rows = await this.prisma.pipeline.findMany({
|
||||
where: { organizationId },
|
||||
include: { stages: { orderBy: { position: 'asc' } } },
|
||||
orderBy: [{ isDefault: 'desc' }, { name: 'asc' }],
|
||||
});
|
||||
const counts = await this.prisma.deal.groupBy({
|
||||
by: ['pipelineId'],
|
||||
where: { organizationId },
|
||||
_count: { _all: true },
|
||||
});
|
||||
const lens = actor?.priorLens;
|
||||
const lensActive = forLens && (lens === 'current' || lens === 'archive');
|
||||
const access = actor ? dealAccessWhere(actor) : {};
|
||||
const prior = lensActive
|
||||
? dealPriorWhere(actor?.priorLens, actor?.priorCutoff)
|
||||
: {};
|
||||
const [counts, lensCounts] = await Promise.all([
|
||||
this.prisma.deal.groupBy({
|
||||
by: ['pipelineId'],
|
||||
where: lensActive ? { organizationId, AND: [access] } : { organizationId },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
lensActive
|
||||
? this.prisma.deal.groupBy({
|
||||
by: ['pipelineId'],
|
||||
where: { organizationId, AND: [access, prior] },
|
||||
_count: { _all: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
const dealCountByPipeline = new Map(
|
||||
counts.map((row) => [row.pipelineId, row._count._all]),
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
const lensCountByPipeline = new Map(
|
||||
lensCounts.map((row) => [row.pipelineId, row._count._all]),
|
||||
);
|
||||
const visible = lensActive
|
||||
? rows.filter((row) => {
|
||||
const inLens = lensCountByPipeline.get(row.id) ?? 0;
|
||||
const total = dealCountByPipeline.get(row.id) ?? 0;
|
||||
if (lens === 'archive') return inLens > 0;
|
||||
return inLens > 0 || total === 0;
|
||||
})
|
||||
: rows;
|
||||
return visible.map((row) => ({
|
||||
...this.toPipelineDto(row),
|
||||
dealCount: dealCountByPipeline.get(row.id) ?? 0,
|
||||
dealCount: lensActive
|
||||
? (lensCountByPipeline.get(row.id) ?? 0)
|
||||
: (dealCountByPipeline.get(row.id) ?? 0),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
} from '@mento/shared';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { customersPersonWhere } from '../common/data-access';
|
||||
import {
|
||||
type Actor,
|
||||
assigneeWhere,
|
||||
@@ -54,7 +55,7 @@ export class ReportsService {
|
||||
const invoiceScope = ownerWhere(actor, 'finance');
|
||||
const activityScope = assigneeWhere(actor);
|
||||
const ticketScope = ticketAccessWhere(actor);
|
||||
const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId };
|
||||
const personScope = customersPersonWhere(actor);
|
||||
|
||||
const durationMs = end.getTime() - start.getTime();
|
||||
const prevEnd = new Date(start.getTime() - 1);
|
||||
@@ -1534,7 +1535,7 @@ export class ReportsService {
|
||||
const orgId = actor.organizationId;
|
||||
const dealScope = ownerWhere(actor, 'deals');
|
||||
const activityScope = assigneeWhere(actor);
|
||||
const personScope = elevated(actor.role) ? {} : { ownerId: actor.userId };
|
||||
const personScope = customersPersonWhere(actor);
|
||||
const rates = await loadOrgRates(this.prisma, orgId);
|
||||
const now = new Date();
|
||||
const { jy, jm } = dateToJalali(now);
|
||||
|
||||
@@ -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 {
|
||||
parseUserTreasuryAccess,
|
||||
permissionsWithTreasuryOverride,
|
||||
treasurySectionAllowed,
|
||||
type TreasurySectionKey,
|
||||
} from '@mento/shared';
|
||||
@@ -16,7 +17,12 @@ export class TreasuryAccessGuard implements CanActivate {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<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;
|
||||
if (!actor) throw new ForbiddenException('دسترسی مالی مجاز نیست.');
|
||||
if (actor.role === 'owner' || actor.role === 'admin') return true;
|
||||
@@ -30,11 +36,18 @@ export class TreasuryAccessGuard implements CanActivate {
|
||||
const rolePermissions = Array.isArray(membership?.orgRole?.permissions)
|
||||
? membership.orgRole.permissions.map(String)
|
||||
: [];
|
||||
const permissions = permissionsForTreasury(
|
||||
const permissions = permissionsWithTreasuryOverride(
|
||||
rolePermissions,
|
||||
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
|
||||
);
|
||||
const method = (req.method || 'GET').toUpperCase();
|
||||
const url = req.originalUrl || req.url || '';
|
||||
if (
|
||||
isLookupForDocuments(method, url) &&
|
||||
treasurySectionAllowed(actor.role, permissions, 'treasury_documents')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!treasurySectionAllowed(actor.role, permissions, sectionForUrl(url))) {
|
||||
throw new ForbiddenException('به این بخش مدیریت مالی دسترسی ندارید.');
|
||||
}
|
||||
@@ -42,14 +55,11 @@ export class TreasuryAccessGuard implements CanActivate {
|
||||
}
|
||||
}
|
||||
|
||||
function permissionsForTreasury(
|
||||
rolePermissions: string[],
|
||||
override: ReturnType<typeof parseUserTreasuryAccess>,
|
||||
): string[] {
|
||||
if (!override) return rolePermissions;
|
||||
const rest = rolePermissions.filter((key) => key !== 'treasury' && !key.startsWith('treasury_'));
|
||||
if (!override.enabled) return rest;
|
||||
return ['treasury', ...override.sections, ...rest];
|
||||
/** فهرست حساب و دسته برای ثبت سند لازم است؛ صفحهٔ مدیریتشان جدا میماند. */
|
||||
function isLookupForDocuments(method: string, url: string): boolean {
|
||||
if (method !== 'GET' && method !== 'HEAD') return false;
|
||||
const path = (url.split('?')[0] || '').replace(/\/+$/, '');
|
||||
return path.endsWith('/treasury/accounts') || path.endsWith('/treasury/categories');
|
||||
}
|
||||
|
||||
function sectionForUrl(url: string): TreasurySectionKey | 'treasury_documents' {
|
||||
|
||||
@@ -5,6 +5,7 @@ import ExcelJS from 'exceljs';
|
||||
import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { invoiceSalesInPeriod } from './invoice-ledger';
|
||||
|
||||
function dec(value: Prisma.Decimal | number | string | null | undefined) {
|
||||
return new Prisma.Decimal(value ?? 0);
|
||||
@@ -12,11 +13,20 @@ function dec(value: Prisma.Decimal | number | string | null | undefined) {
|
||||
function money(value: Prisma.Decimal | number | string) {
|
||||
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) {
|
||||
if (!iso) return null;
|
||||
const d = new Date(iso);
|
||||
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) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
@@ -36,9 +46,15 @@ export class TreasuryOpsService {
|
||||
async listPayroll(actor: Actor) {
|
||||
const rows = await this.prisma.financialPayroll.findMany({
|
||||
where: { organizationId: actor.organizationId },
|
||||
include: { movements: true },
|
||||
include: {
|
||||
movements: {
|
||||
where: { voidedAt: null },
|
||||
include: { account: { select: { name: true } } },
|
||||
orderBy: { occurredAt: 'desc' },
|
||||
},
|
||||
},
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 100,
|
||||
take: 500,
|
||||
});
|
||||
const users = await this.prisma.user.findMany({
|
||||
where: { id: { in: rows.map((row) => row.userId) } },
|
||||
@@ -55,8 +71,11 @@ export class TreasuryOpsService {
|
||||
period: string;
|
||||
baseAmount: string | number;
|
||||
benefits?: string | number;
|
||||
benefitsReason?: string | null;
|
||||
bonus?: string | number;
|
||||
bonusReason?: string | null;
|
||||
deductions?: string | number;
|
||||
deductionsReason?: string | null;
|
||||
dueDate?: string;
|
||||
notes?: string | null;
|
||||
},
|
||||
@@ -81,14 +100,23 @@ export class TreasuryOpsService {
|
||||
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,
|
||||
dueDate: parseDate(input.dueDate) ?? new Date(),
|
||||
notes: input.notes?.trim() || null,
|
||||
createdById: actor.userId,
|
||||
},
|
||||
include: { movements: true },
|
||||
include: {
|
||||
movements: {
|
||||
where: { voidedAt: null },
|
||||
include: { account: { select: { name: true } } },
|
||||
orderBy: { occurredAt: 'desc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
const user = await this.prisma.user.findUnique({ where: { id: row.userId }, select: { fullName: true } });
|
||||
return this.payrollDto(row, user?.fullName ?? '');
|
||||
@@ -124,7 +152,7 @@ export class TreasuryOpsService {
|
||||
if (!account) throw new BadRequestException('حساب پرداخت پیدا نشد.');
|
||||
const balance = await this.balance(account.id);
|
||||
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([
|
||||
this.prisma.financialMovement.create({
|
||||
data: {
|
||||
@@ -145,6 +173,123 @@ export class TreasuryOpsService {
|
||||
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) {
|
||||
const rows = await this.prisma.financialRecurringItem.findMany({
|
||||
where: { organizationId: actor.organizationId },
|
||||
@@ -327,6 +472,8 @@ export class TreasuryOpsService {
|
||||
sheet.addRow(['شاخص', 'این دوره', 'دوره قبل']);
|
||||
const rows: Array<[string, string, string]> = [
|
||||
['درآمد ثبتشده', data.current.bookedIncome, data.previous.bookedIncome],
|
||||
['فروش فاکتور', data.current.invoiceSales, data.previous.invoiceSales],
|
||||
['فاکتور برگشتی', data.current.invoiceCredits, data.previous.invoiceCredits],
|
||||
['هزینه ثبتشده', data.current.bookedExpense, data.previous.bookedExpense],
|
||||
['سود عملیاتی', data.current.operatingProfit, data.previous.operatingProfit],
|
||||
['ورود وجه', data.current.cashIn, data.previous.cashIn],
|
||||
@@ -411,10 +558,15 @@ export class TreasuryOpsService {
|
||||
amount: money(amount),
|
||||
share: bookedExpense.equals(0) ? '0' : amount.div(bookedExpense).mul(100).toFixed(1),
|
||||
}));
|
||||
const invoiceSales = await invoiceSalesInPeriod(this.prisma, organizationId, from, to);
|
||||
return {
|
||||
bookedIncome: money(bookedIncome),
|
||||
invoiceSales: invoiceSales.sales,
|
||||
invoiceCredits: invoiceSales.credits,
|
||||
bookedExpense: money(bookedExpense),
|
||||
operatingProfit: money(bookedIncome.minus(bookedExpense)),
|
||||
operatingProfit: money(
|
||||
bookedIncome.plus(invoiceSales.net).minus(bookedExpense),
|
||||
),
|
||||
cashIn: money(cashIn),
|
||||
cashOut: money(cashOut),
|
||||
cashNet: money(cashIn.minus(cashOut)),
|
||||
@@ -475,12 +627,22 @@ export class TreasuryOpsService {
|
||||
period: string;
|
||||
baseAmount: Prisma.Decimal;
|
||||
benefits: Prisma.Decimal;
|
||||
benefitsReason?: string | null;
|
||||
bonus: Prisma.Decimal;
|
||||
bonusReason?: string | null;
|
||||
deductions: Prisma.Decimal;
|
||||
deductionsReason?: string | null;
|
||||
payable: Prisma.Decimal;
|
||||
dueDate: Date;
|
||||
status: string;
|
||||
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>;
|
||||
movements: Array<{
|
||||
id: string;
|
||||
amount: Prisma.Decimal;
|
||||
voidedAt: Date | null;
|
||||
accountId: string;
|
||||
occurredAt: Date;
|
||||
account?: { name: string } | null;
|
||||
}>;
|
||||
},
|
||||
fullName: string,
|
||||
) {
|
||||
@@ -493,13 +655,25 @@ export class TreasuryOpsService {
|
||||
period: row.period,
|
||||
baseAmount: money(row.baseAmount),
|
||||
benefits: money(row.benefits),
|
||||
benefitsReason: row.benefitsReason?.trim() || null,
|
||||
bonus: money(row.bonus),
|
||||
bonusReason: row.bonusReason?.trim() || null,
|
||||
deductions: money(row.deductions),
|
||||
deductionsReason: row.deductionsReason?.trim() || null,
|
||||
payable: money(row.payable),
|
||||
paidAmount: money(paid),
|
||||
remaining: money(left.isNegative() ? 0 : left),
|
||||
dueDate: row.dueDate.toISOString(),
|
||||
status: row.status,
|
||||
payments: row.movements
|
||||
.filter((item) => !item.voidedAt)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
amount: money(item.amount),
|
||||
occurredAt: item.occurredAt.toISOString(),
|
||||
accountId: item.accountId,
|
||||
accountName: item.account?.name ?? '',
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -129,6 +129,29 @@ export class TreasuryController {
|
||||
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')
|
||||
documents(
|
||||
@CurrentUser() user: Actor,
|
||||
@@ -232,6 +255,25 @@ export class TreasuryController {
|
||||
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')
|
||||
payPayroll(
|
||||
@CurrentUser() user: Actor,
|
||||
|
||||
@@ -25,6 +25,7 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { LocalFileStorage } from '../storage/local-file.storage';
|
||||
import { StorageQuotaService } from '../billing/storage-quota.service';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { loadInvoicePartyPositions, invoiceSalesInPeriod } from './invoice-ledger';
|
||||
import { TreasuryReceivablesService } from './treasury-receivables.service';
|
||||
|
||||
const INCOME_CATEGORIES = ['فروش خدمات', 'فروش کالا', 'سایر درآمدها'];
|
||||
@@ -359,6 +360,7 @@ export class TreasuryService {
|
||||
organizationId: actor.organizationId,
|
||||
accountId,
|
||||
voidedAt: null,
|
||||
kind: { not: 'allocation' },
|
||||
...(from || to
|
||||
? {
|
||||
occurredAt: {
|
||||
@@ -377,6 +379,7 @@ export class TreasuryService {
|
||||
organizationId: actor.organizationId,
|
||||
accountId,
|
||||
voidedAt: null,
|
||||
kind: { not: 'allocation' },
|
||||
occurredAt: { lt: from },
|
||||
},
|
||||
select: { direction: true, amount: true },
|
||||
@@ -530,6 +533,8 @@ export class TreasuryService {
|
||||
settleAmount?: string | number | null;
|
||||
accountId?: string | null;
|
||||
settledAt?: string | null;
|
||||
/** دریافت یا پرداخت روی مانده؛ سند تعهدی جدید نمیسازد. */
|
||||
settlement?: boolean;
|
||||
},
|
||||
): Promise<FinancialDocumentDto> {
|
||||
const title = input.title.trim();
|
||||
@@ -560,6 +565,17 @@ export class TreasuryService {
|
||||
}
|
||||
}
|
||||
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 reference = await this.nextDocumentReference(
|
||||
tx,
|
||||
@@ -606,6 +622,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({
|
||||
where: { id: created.id },
|
||||
include: { category: true, account: true, movements: true },
|
||||
@@ -727,6 +782,7 @@ export class TreasuryService {
|
||||
amount: Prisma.Decimal;
|
||||
settled: Prisma.Decimal;
|
||||
remaining: Prisma.Decimal;
|
||||
documentRemaining: Prisma.Decimal;
|
||||
}>();
|
||||
for (const row of rows) {
|
||||
if (row.partyKind === 'other') continue;
|
||||
@@ -747,13 +803,43 @@ export class TreasuryService {
|
||||
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(row.amount);
|
||||
current.settled = current.settled.plus(settled);
|
||||
current.remaining = current.remaining.plus(rawRemaining);
|
||||
current.documentRemaining = current.documentRemaining.plus(rawRemaining);
|
||||
buckets.set(key, current);
|
||||
}
|
||||
|
||||
const invoiceParties = await loadInvoicePartyPositions(this.prisma, actor.organizationId);
|
||||
for (const party of invoiceParties) {
|
||||
const onDebtorSide = party.net.greaterThan(0);
|
||||
if (kind === 'income' && !onDebtorSide) continue;
|
||||
if (kind === 'expense' && onDebtorSide) continue;
|
||||
const remaining = party.net.abs();
|
||||
const amount = onDebtorSide ? party.billed : Prisma.Decimal.max(party.billed, remaining);
|
||||
const settled = Prisma.Decimal.max(amount.minus(remaining), 0);
|
||||
const current = buckets.get(party.key) ?? {
|
||||
key: party.key,
|
||||
partyKind: party.partyKind,
|
||||
partyName: party.partyName,
|
||||
amount: new Prisma.Decimal(0),
|
||||
settled: new Prisma.Decimal(0),
|
||||
remaining: new Prisma.Decimal(0),
|
||||
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()]
|
||||
.filter((row) => row.remaining.greaterThan(0))
|
||||
.sort((a, b) => b.remaining.comparedTo(a.remaining))
|
||||
.map((row) => ({
|
||||
key: row.key,
|
||||
@@ -762,9 +848,122 @@ export class TreasuryService {
|
||||
amount: money(row.amount),
|
||||
settledAmount: money(row.settled),
|
||||
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('مبلغ از ماندهٔ سندهای باز این طرف حساب بیشتر است.');
|
||||
}
|
||||
if (input.kind === 'expense') {
|
||||
const balance = await this.accountBalance(account.id);
|
||||
if (balance.lessThan(amount)) {
|
||||
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(
|
||||
actor: Actor,
|
||||
input: {
|
||||
@@ -908,16 +1107,51 @@ export class TreasuryService {
|
||||
});
|
||||
if (!doc || doc.voidedAt) throw new NotFoundException('سند پیدا نشد.');
|
||||
const now = new Date();
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.financialMovement.updateMany({
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
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 },
|
||||
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 },
|
||||
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({
|
||||
where: { id: doc.id },
|
||||
include: { category: true, account: true, movements: true },
|
||||
@@ -1092,6 +1326,17 @@ export class TreasuryService {
|
||||
}
|
||||
const bookedIncome = dec(income._sum.amount);
|
||||
const bookedExpense = dec(expense._sum.amount);
|
||||
const invoiceSales = await invoiceSalesInPeriod(
|
||||
this.prisma,
|
||||
actor.organizationId,
|
||||
from,
|
||||
to,
|
||||
);
|
||||
const invoiceParties = await loadInvoicePartyPositions(this.prisma, actor.organizationId);
|
||||
for (const party of invoiceParties) {
|
||||
if (party.net.greaterThan(0)) receivables = receivables.plus(party.net);
|
||||
else payables = payables.plus(party.net.abs());
|
||||
}
|
||||
const totalBalance = accounts.reduce(
|
||||
(sum, account) => sum.plus(account.balance),
|
||||
new Prisma.Decimal(0),
|
||||
@@ -1101,7 +1346,7 @@ export class TreasuryService {
|
||||
actualReceipts: money(dec(receipts._sum.amount)),
|
||||
bookedExpense: money(bookedExpense),
|
||||
actualPayments: money(dec(payments._sum.amount)),
|
||||
operatingProfit: money(bookedIncome.minus(bookedExpense)),
|
||||
operatingProfit: money(bookedIncome.plus(invoiceSales.net).minus(bookedExpense)),
|
||||
receivables: money(receivables),
|
||||
payables: money(payables),
|
||||
totalBalance: money(totalBalance),
|
||||
@@ -1111,6 +1356,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 }>) {
|
||||
return movements
|
||||
.filter((row) => !row.voidedAt)
|
||||
@@ -1119,7 +1434,7 @@ export class TreasuryService {
|
||||
|
||||
private async accountBalance(accountId: string) {
|
||||
const rows = await this.prisma.financialMovement.findMany({
|
||||
where: { accountId, voidedAt: null },
|
||||
where: { accountId, voidedAt: null, kind: { not: 'allocation' } },
|
||||
select: { direction: true, amount: true },
|
||||
});
|
||||
return rows.reduce(
|
||||
@@ -1194,7 +1509,7 @@ export class TreasuryService {
|
||||
const from = startOfDay(range?.from);
|
||||
const to = startOfDay(range?.to);
|
||||
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 },
|
||||
});
|
||||
let balance = new Prisma.Decimal(0);
|
||||
|
||||
@@ -30,6 +30,10 @@ const props = withDefaults(
|
||||
placeholder?: string;
|
||||
clearable?: boolean;
|
||||
icon?: 'calendar' | 'clock' | 'bell';
|
||||
/** اگر داده شود، متن باکس بهجای تاریخ خام همین مقدار است. */
|
||||
displayText?: string;
|
||||
/** نمایی که با باز شدن پنل دیده میشود. */
|
||||
startView?: 'days' | 'months' | 'years';
|
||||
}>(),
|
||||
{
|
||||
mode: 'date',
|
||||
@@ -37,6 +41,8 @@ const props = withDefaults(
|
||||
disabled: false,
|
||||
clearable: true,
|
||||
icon: undefined,
|
||||
displayText: '',
|
||||
startView: 'days',
|
||||
},
|
||||
);
|
||||
|
||||
@@ -87,6 +93,7 @@ const triggerIcon = computed(() => {
|
||||
});
|
||||
|
||||
const display = computed(() => {
|
||||
if (props.displayText) return props.displayText;
|
||||
if (props.mode === 'time') {
|
||||
const match = /^(\d{1,2}):(\d{2})$/.exec(model.value);
|
||||
if (!match) return '';
|
||||
@@ -353,7 +360,7 @@ function place() {
|
||||
|
||||
function liftAboveOverlays() {
|
||||
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, [data-lead-filter]')) {
|
||||
const zi = Number.parseInt(window.getComputedStyle(el).zIndex, 10);
|
||||
if (Number.isFinite(zi)) z = Math.max(z, zi + 20);
|
||||
}
|
||||
@@ -368,7 +375,7 @@ function onWindowChange() {
|
||||
async function show() {
|
||||
if (props.disabled) return;
|
||||
syncDraftFrom(parsed.value);
|
||||
calView.value = 'days';
|
||||
calView.value = props.startView;
|
||||
clockFace.value = 'hour';
|
||||
syncViewport();
|
||||
liftAboveOverlays();
|
||||
|
||||
@@ -22,6 +22,7 @@ const props = withDefaults(
|
||||
/** اگر true باشد مقدار عددی emit میشود (نه رشته) */
|
||||
asNumber?: boolean;
|
||||
dir?: 'ltr' | 'rtl';
|
||||
addonAfter?: string;
|
||||
}>(),
|
||||
{
|
||||
required: false,
|
||||
@@ -30,6 +31,7 @@ const props = withDefaults(
|
||||
decimals: 2,
|
||||
asNumber: false,
|
||||
dir: 'ltr',
|
||||
addonAfter: '',
|
||||
},
|
||||
);
|
||||
|
||||
@@ -129,6 +131,7 @@ function normalizeSep(raw: string): string {
|
||||
:disabled="disabled"
|
||||
:readonly="readonly"
|
||||
:value="text"
|
||||
:addon-after="addonAfter || undefined"
|
||||
style="width: 100%; font-variant-numeric: tabular-nums"
|
||||
@focus="onFocus"
|
||||
@blur="onBlur"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Select as ASelect } from 'ant-design-vue';
|
||||
import { Button as AButton, Select as ASelect } from 'ant-design-vue';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
|
||||
type PickUser = { id: string; fullName: string };
|
||||
|
||||
@@ -13,8 +14,10 @@ const props = withDefaults(
|
||||
min?: number;
|
||||
addLabel?: string;
|
||||
emptyLabel?: string;
|
||||
/** دکمهٔ انتخاب یکجای همهٔ اعضا و جمعکردن برچسبها وقتی تعداد زیاد است */
|
||||
selectAll?: boolean;
|
||||
}>(),
|
||||
{ disabled: false, min: 0, addLabel: 'افزودن', emptyLabel: 'کسی انتخاب نشده' },
|
||||
{ disabled: false, min: 0, addLabel: 'افزودن', emptyLabel: 'کسی انتخاب نشده', selectAll: false },
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -26,8 +29,25 @@ const options = computed(() =>
|
||||
props.users.map((u) => ({ value: u.id, label: u.fullName })),
|
||||
);
|
||||
|
||||
function onUpdate(value: unknown) {
|
||||
const ids = Array.isArray(value) ? value.map(String) : [];
|
||||
const allPicked = computed(
|
||||
() =>
|
||||
props.users.length > 0 &&
|
||||
props.users.every((user) => props.modelValue.includes(user.id)),
|
||||
);
|
||||
|
||||
const tagLimit = computed(() => {
|
||||
if (!props.selectAll) return undefined;
|
||||
if (allPicked.value && props.users.length > 2) return 0;
|
||||
return 'responsive' as const;
|
||||
});
|
||||
|
||||
function tagPlaceholder(omitted: unknown[]) {
|
||||
if (allPicked.value) return `همهٔ اعضا (${toFaDigits(props.users.length)})`;
|
||||
const extra = Array.isArray(omitted) ? omitted.length : 0;
|
||||
return extra ? `${toFaDigits(extra)} نفر دیگر` : '';
|
||||
}
|
||||
|
||||
function commit(ids: string[]) {
|
||||
if (ids.length < props.min && props.modelValue.length >= props.min) {
|
||||
emit('update:modelValue', [...props.modelValue]);
|
||||
return;
|
||||
@@ -35,19 +55,54 @@ function onUpdate(value: unknown) {
|
||||
emit('update:modelValue', ids);
|
||||
emit('change', ids);
|
||||
}
|
||||
|
||||
function onUpdate(value: unknown) {
|
||||
const ids = Array.isArray(value) ? value.map(String) : [];
|
||||
commit(ids);
|
||||
}
|
||||
|
||||
function pickAll() {
|
||||
if (props.disabled || allPicked.value) return;
|
||||
commit(props.users.map((user) => user.id));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-select
|
||||
mode="multiple"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:value="modelValue"
|
||||
:options="options"
|
||||
:disabled="disabled"
|
||||
:placeholder="emptyLabel"
|
||||
style="width: 100%"
|
||||
@update:value="onUpdate"
|
||||
/>
|
||||
<div class="user-multi" :class="{ 'with-all': selectAll }">
|
||||
<a-select
|
||||
mode="multiple"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:value="modelValue"
|
||||
:options="options"
|
||||
:disabled="disabled"
|
||||
:placeholder="emptyLabel"
|
||||
:max-tag-count="tagLimit"
|
||||
:max-tag-placeholder="selectAll ? tagPlaceholder : undefined"
|
||||
style="width: 100%"
|
||||
@update:value="onUpdate"
|
||||
/>
|
||||
<a-button v-if="selectAll" :disabled="disabled || allPicked || !users.length" @click="pickAll">
|
||||
همه
|
||||
</a-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.user-multi.with-all {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.user-multi.with-all :deep(.ant-select) {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.user-multi.with-all :deep(.ant-btn) {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -41,6 +41,7 @@ const emit = defineEmits<{
|
||||
stagesChanged: [];
|
||||
add: [stageId: string];
|
||||
error: [message: string];
|
||||
notice: [message: string];
|
||||
menuDeal: [activity: ActivityDto, stageId?: string];
|
||||
toggleSelect: [activityId: string];
|
||||
bulkDelete: [];
|
||||
@@ -292,6 +293,21 @@ async function moveCard(activityId: string, toStageId: string, index?: number) {
|
||||
stageId: toStageId,
|
||||
position: insertAt,
|
||||
});
|
||||
if (!same && data.status !== toStage.kind) {
|
||||
const hideFromMine = props.params.desk === 'mine';
|
||||
from.items = hideFromMine
|
||||
? prevFrom.filter((row) => row.id !== activityId)
|
||||
: prevFrom.map((row) => (row.id === activityId ? data : row));
|
||||
from.total = hideFromMine ? Math.max(0, prevFromTotal - 1) : prevFromTotal;
|
||||
to.items = prevTo;
|
||||
to.total = prevToTotal;
|
||||
emit(
|
||||
'notice',
|
||||
'سهم شما ثبت شد. فعالیت وقتی انجامشده میشود که همهٔ مسئولها سهم خود را بزنند.',
|
||||
);
|
||||
emit('changed');
|
||||
return;
|
||||
}
|
||||
const column = same ? from : to;
|
||||
column.items = column.items.map((i) => (i.id === activityId ? data : i));
|
||||
emit('changed');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { Segmented as ASegmented } from 'ant-design-vue';
|
||||
import { treasurySectionAllowed, type TreasurySectionKey } from '@mento/shared';
|
||||
@@ -8,6 +8,7 @@ import { useAuthStore } from '@/stores/auth';
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const scroller = ref<HTMLElement | null>(null);
|
||||
|
||||
const links = computed(() => {
|
||||
const role = auth.user?.role;
|
||||
@@ -41,6 +42,17 @@ const active = computed(() => {
|
||||
return '/finance';
|
||||
});
|
||||
|
||||
watch(
|
||||
active,
|
||||
async () => {
|
||||
await nextTick();
|
||||
scroller.value
|
||||
?.querySelector('.ant-segmented-item-selected')
|
||||
?.scrollIntoView({ inline: 'center', block: 'nearest' });
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
function onChange(value: string | number) {
|
||||
const next = String(value);
|
||||
if (next && next !== route.path) void router.push(next);
|
||||
@@ -49,6 +61,7 @@ function onChange(value: string | number) {
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="scroller"
|
||||
:style="{
|
||||
width: '100%',
|
||||
overflowX: 'auto',
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Table as ATable } from 'ant-design-vue';
|
||||
import {
|
||||
Flex as AFlex,
|
||||
List as AList,
|
||||
Table as ATable,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
||||
import { toman } from '@/views/treasury/treasury-format';
|
||||
import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
|
||||
|
||||
const props = defineProps<{
|
||||
rows: TreasuryPartyBalanceDto[];
|
||||
settledLabel: string;
|
||||
}>();
|
||||
|
||||
const isMobile = useTreasuryMobile();
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const AListItem = AList.Item;
|
||||
|
||||
const kindLabel: Record<string, string> = {
|
||||
person: 'مشتری',
|
||||
company: 'شرکت',
|
||||
@@ -39,10 +49,43 @@ const columns = computed(() => [
|
||||
customRender: ({ record }: { record: TreasuryPartyBalanceDto }) => toman(record.remaining),
|
||||
},
|
||||
]);
|
||||
|
||||
function kindOf(record: TreasuryPartyBalanceDto) {
|
||||
return (record.partyKind && kindLabel[record.partyKind]) || 'ثبت قبلی';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-list
|
||||
v-if="isMobile"
|
||||
:data-source="rows"
|
||||
:locale="{ emptyText: 'ماندهای نیست.' }"
|
||||
>
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<a-flex vertical :gap="4" style="width: 100%">
|
||||
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
|
||||
<a-typography-text strong>{{ item.partyName }}</a-typography-text>
|
||||
<a-typography-text type="secondary">{{ kindOf(item) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-flex justify="space-between" align="center" :gap="8">
|
||||
<a-typography-text type="secondary">مبلغ کل</a-typography-text>
|
||||
<a-typography-text>{{ toman(item.amount) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-flex justify="space-between" align="center" :gap="8">
|
||||
<a-typography-text type="secondary">{{ settledLabel }}</a-typography-text>
|
||||
<a-typography-text>{{ toman(item.settledAmount) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-flex justify="space-between" align="center" :gap="8">
|
||||
<a-typography-text type="secondary">مانده</a-typography-text>
|
||||
<a-typography-text strong>{{ toman(item.remaining) }}</a-typography-text>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
<a-table
|
||||
v-else
|
||||
:columns="columns"
|
||||
:data-source="rows"
|
||||
:pagination="false"
|
||||
|
||||
@@ -25,6 +25,11 @@ const ASelectOption = ASelect.Option;
|
||||
const ASelectOptGroup = ASelect.OptGroup;
|
||||
const { Text: ATypographyText } = Typography;
|
||||
|
||||
withDefaults(
|
||||
defineProps<{ allowOther?: boolean; placeholder?: string }>(),
|
||||
{ allowOther: true, placeholder: 'مشتری، شرکت، کاربر یا سایر' },
|
||||
);
|
||||
|
||||
const kind = defineModel<FinancialPartyKind | undefined>('kind');
|
||||
const partyId = defineModel<string | undefined>('partyId');
|
||||
|
||||
@@ -156,12 +161,12 @@ onMounted(() => {
|
||||
:filter-option="false"
|
||||
:loading="loading"
|
||||
:value="selectValue"
|
||||
placeholder="مشتری، شرکت، کاربر یا سایر"
|
||||
:placeholder="placeholder"
|
||||
style="width: 100%"
|
||||
@search="onSearch"
|
||||
@change="onChange"
|
||||
>
|
||||
<a-select-option value="other" label="سایر">سایر</a-select-option>
|
||||
<a-select-option v-if="allowOther" value="other" label="سایر">سایر</a-select-option>
|
||||
<a-select-opt-group v-if="peopleOptions.length" label="مشتریان">
|
||||
<a-select-option
|
||||
v-for="row in peopleOptions"
|
||||
|
||||
@@ -21,6 +21,7 @@ import type {
|
||||
import { canManageSettings, canViewAllRecords } from '@/lib/roles';
|
||||
import {
|
||||
canOpenPath,
|
||||
firstAllowedFinancePath,
|
||||
hasSectionPermission,
|
||||
sectionPermissionForPath,
|
||||
} from '@/lib/section-permissions';
|
||||
@@ -204,12 +205,11 @@ function cardAllowedForNav(card: {
|
||||
}) {
|
||||
if (card.ownerOnly && auth.user?.role !== 'owner') return false;
|
||||
const perms = auth.user?.permissions ?? [];
|
||||
const canTreasury = auth.user?.role === 'owner'
|
||||
|| auth.user?.role === 'admin'
|
||||
|| perms.includes('treasury')
|
||||
|| perms.some((key) => key.startsWith('treasury_'));
|
||||
if (card.to?.startsWith('/finance')) {
|
||||
return moduleAllowed(card.module ?? 'treasury') && canTreasury;
|
||||
return (
|
||||
moduleAllowed(card.module ?? 'treasury')
|
||||
&& Boolean(firstAllowedFinancePath(auth.user?.role, perms))
|
||||
);
|
||||
}
|
||||
const section = card.to ? sectionPermissionForPath(card.to) : null;
|
||||
const hasSection = section
|
||||
@@ -246,7 +246,13 @@ const openHub = computed<NavHubDef | null>(() => {
|
||||
if (!openHubKey.value) return null;
|
||||
const hub = NAV_HUBS.find((item) => item.key === openHubKey.value);
|
||||
if (!hub) return null;
|
||||
const cards = hub.cards.filter((card) => cardAllowedForNav(card));
|
||||
const financeTo = firstAllowedFinancePath(auth.user?.role, auth.user?.permissions);
|
||||
const cards = hub.cards
|
||||
.filter((card) => cardAllowedForNav(card))
|
||||
.map((card) => {
|
||||
if (!financeTo || !card.to.startsWith('/finance') || card.to === financeTo) return card;
|
||||
return { ...card, to: financeTo };
|
||||
});
|
||||
if (
|
||||
hub.key === 'customers' &&
|
||||
isMobileNav.value &&
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { jalaliToDate } from '@/lib/jalali';
|
||||
|
||||
export type ActivityThreadEntry = {
|
||||
at: Date | null;
|
||||
dateLabel: string;
|
||||
timeLabel: string;
|
||||
author: string;
|
||||
body: string;
|
||||
};
|
||||
|
||||
const STAMP = /^\[(.+?) ساعت (\S+?)(?: — (.+))?\]$/;
|
||||
|
||||
/** یادداشت فعالیت را به نظرهای جدا با مهر تاریخ/ساعت/نویسنده تبدیل میکند. */
|
||||
export function parseActivityThread(raw: string | null | undefined): ActivityThreadEntry[] | null {
|
||||
const text = (raw ?? '').replace(/\r\n/g, '\n').trim();
|
||||
if (!text) return null;
|
||||
|
||||
const entries: ActivityThreadEntry[] = [];
|
||||
const preamble: string[] = [];
|
||||
let current: ActivityThreadEntry | null = null;
|
||||
let sawStamp = false;
|
||||
|
||||
for (const line of text.split('\n')) {
|
||||
const match = line.trim().match(STAMP);
|
||||
if (match) {
|
||||
sawStamp = true;
|
||||
if (current) entries.push(trimEntry(current));
|
||||
current = {
|
||||
at: stampToDate(match[1] ?? '', match[2] ?? ''),
|
||||
dateLabel: (match[1] ?? '').trim(),
|
||||
timeLabel: (match[2] ?? '').trim(),
|
||||
author: (match[3] ?? '').trim(),
|
||||
body: '',
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if (current) current.body += `${current.body ? '\n' : ''}${line}`;
|
||||
else preamble.push(line);
|
||||
}
|
||||
if (current) entries.push(trimEntry(current));
|
||||
if (!sawStamp) return null;
|
||||
|
||||
const head = preamble.join('\n').trim();
|
||||
if (head) {
|
||||
entries.unshift({ at: null, dateLabel: '', timeLabel: '', author: '', body: head });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function trimEntry(entry: ActivityThreadEntry): ActivityThreadEntry {
|
||||
return { ...entry, body: entry.body.trim() };
|
||||
}
|
||||
|
||||
function latinDigits(value: string): string {
|
||||
const fa = '۰۱۲۳۴۵۶۷۸۹';
|
||||
const ar = '٠١٢٣٤٥٦٧٨٩';
|
||||
return value.replace(/[۰-۹٠-٩]/g, (ch) => {
|
||||
const faIndex = fa.indexOf(ch);
|
||||
return String(faIndex >= 0 ? faIndex : ar.indexOf(ch));
|
||||
});
|
||||
}
|
||||
|
||||
function stampToDate(dateLabel: string, timeLabel: string): Date | null {
|
||||
const date = latinDigits(dateLabel).match(/(\d{4})\/(\d{1,2})\/(\d{1,2})/);
|
||||
if (!date) return null;
|
||||
const at = jalaliToDate(Number(date[1]), Number(date[2]), Number(date[3]));
|
||||
if (Number.isNaN(at.getTime())) return null;
|
||||
const time = latinDigits(timeLabel).match(/(\d{1,2}):(\d{2})/);
|
||||
if (time) at.setHours(Number(time[1]), Number(time[2]), 0, 0);
|
||||
return at;
|
||||
}
|
||||
@@ -69,6 +69,30 @@ export function canOpenFinancePath(
|
||||
return treasurySectionAllowed(role, permissions, section);
|
||||
}
|
||||
|
||||
const FINANCE_ENTRIES: Array<{ path: string; section: TreasurySectionKey }> = [
|
||||
{ path: '/finance', section: 'treasury_dashboard' },
|
||||
{ path: '/finance/incomes', section: 'treasury_incomes' },
|
||||
{ path: '/finance/expenses', section: 'treasury_expenses' },
|
||||
{ path: '/finance/receivables', section: 'treasury_receivables' },
|
||||
{ path: '/finance/accounts', section: 'treasury_accounts' },
|
||||
{ path: '/finance/payroll', section: 'treasury_payroll' },
|
||||
{ path: '/finance/recurring', section: 'treasury_recurring' },
|
||||
{ path: '/finance/reports', section: 'treasury_reports' },
|
||||
{ path: '/finance/audit', section: 'treasury_audit' },
|
||||
{ path: '/finance/categories', section: 'treasury_categories' },
|
||||
];
|
||||
|
||||
/** اولین صفحهٔ مالی که این نقش واقعاً میتواند باز کند. */
|
||||
export function firstAllowedFinancePath(
|
||||
role: UserRole | string | null | undefined,
|
||||
permissions: readonly string[] | null | undefined,
|
||||
): string | null {
|
||||
for (const entry of FINANCE_ENTRIES) {
|
||||
if (treasurySectionAllowed(role, permissions, entry.section)) return entry.path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function canOpenPath(
|
||||
role: UserRole | string | null | undefined,
|
||||
permissions: readonly string[] | null | undefined,
|
||||
|
||||
@@ -2,7 +2,12 @@ import { createRouter, createWebHistory } from 'vue-router';
|
||||
import type { UserRole } from '@mento/shared';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { usePlatformAuthStore } from '@/stores/platform-auth';
|
||||
import { canOpenFinancePath, canOpenPath, sectionPermissionForPath } from '@/lib/section-permissions';
|
||||
import {
|
||||
canOpenFinancePath,
|
||||
canOpenPath,
|
||||
firstAllowedFinancePath,
|
||||
sectionPermissionForPath,
|
||||
} from '@/lib/section-permissions';
|
||||
|
||||
export const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
@@ -330,7 +335,8 @@ export const router = createRouter({
|
||||
meta: {
|
||||
roles: ['owner', 'admin'] as UserRole[],
|
||||
treasuryTitle: 'حقوق و دستمزد',
|
||||
treasuryDescription: 'پرداخت حقوق فقط با دسترسی جداگانه حقوق و دستمزد باز است.',
|
||||
treasuryDescription:
|
||||
'تعیین حقوق، پرداخت یکجا یا چندمرحلهای، و گزارش دورهها. پرداخت فقط با دسترسی حقوق و دستمزد باز است.',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -350,7 +356,8 @@ export const router = createRouter({
|
||||
meta: {
|
||||
roles: ['owner', 'admin'] as UserRole[],
|
||||
treasuryTitle: 'گزارش مالی',
|
||||
treasuryDescription: 'سود عملیاتی از درآمد و هزینه ثبتشده است، نه از خالص وجه.',
|
||||
treasuryDescription:
|
||||
'سود از درآمد، فروش فاکتور و هزینه است. بدهکاران و بستانکاران مانده فاکتور و اسناد باز را یکجا نشان میدهند.',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -681,13 +688,8 @@ router.beforeEach((to) => {
|
||||
if (canOpenFinancePath(auth.user?.role, auth.user?.permissions, String(to.path))) {
|
||||
return true;
|
||||
}
|
||||
const exactHome = to.path === '/finance' || to.path === '/finance/';
|
||||
if (
|
||||
exactHome &&
|
||||
canOpenFinancePath(auth.user?.role, auth.user?.permissions, '/finance/payroll')
|
||||
) {
|
||||
return { path: '/finance/payroll' };
|
||||
}
|
||||
const next = firstAllowedFinancePath(auth.user?.role, auth.user?.permissions);
|
||||
if (next && next !== to.path) return { path: next };
|
||||
}
|
||||
return { name: 'home' };
|
||||
}
|
||||
|
||||
@@ -214,6 +214,12 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
if (token.value) void hydrate();
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') void hydrate();
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
user,
|
||||
|
||||
@@ -201,6 +201,7 @@ const page = computed(() => {
|
||||
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const notice = ref('');
|
||||
const data = ref<PaginatedResponse<ActivityDto> | null>(null);
|
||||
const q = ref(typeof route.query.q === 'string' ? route.query.q : '');
|
||||
const users = ref<OrgUserDto[]>([]);
|
||||
@@ -837,6 +838,30 @@ function onFacetDone() {
|
||||
openCol.value = null;
|
||||
}
|
||||
|
||||
function assigneePeopleOf(item: ActivityDto) {
|
||||
if (item.assignees?.length) return item.assignees;
|
||||
return item.assignee ? [item.assignee] : [];
|
||||
}
|
||||
|
||||
function needsEveryone(item: ActivityDto) {
|
||||
return item.completionMode === 'all' && assigneePeopleOf(item).length > 1;
|
||||
}
|
||||
|
||||
function canMarkShare(item: ActivityDto) {
|
||||
if (item.status !== 'open') return false;
|
||||
if (!needsEveryone(item)) return true;
|
||||
const mine = auth.user?.id;
|
||||
if (!mine) return false;
|
||||
return (
|
||||
assigneePeopleOf(item).some((person) => person.id === mine) &&
|
||||
!item.completedByIds?.includes(mine)
|
||||
);
|
||||
}
|
||||
|
||||
function completeLabel(item: ActivityDto) {
|
||||
return needsEveryone(item) ? 'انجام سهم من' : 'انجام شد';
|
||||
}
|
||||
|
||||
async function complete(id: string) {
|
||||
menuId.value = null;
|
||||
boardMenuId.value = null;
|
||||
@@ -1503,6 +1528,7 @@ onUnmounted(() => {
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<p v-if="notice" class="ok">{{ notice }}</p>
|
||||
<p v-if="importMsg" class="ok">{{ importMsg }}</p>
|
||||
|
||||
<div v-if="selectMode" class="select-bar">
|
||||
@@ -1532,6 +1558,7 @@ onUnmounted(() => {
|
||||
@stages-changed="onStagesChanged"
|
||||
@add="openAddInStage"
|
||||
@error="(msg: string) => (error = msg)"
|
||||
@notice="(msg: string) => (notice = msg)"
|
||||
@menu-deal="onBoardMenu"
|
||||
@toggle-select="toggleSelect"
|
||||
@bulk-delete="askBulkDelete"
|
||||
@@ -1755,8 +1782,8 @@ onUnmounted(() => {
|
||||
<button v-if="canPromotePrior(item)" type="button" @click="promotePriorActivity(item.id)">
|
||||
انتقال به کار جاری
|
||||
</button>
|
||||
<button v-if="item.status === 'open'" type="button" @click="complete(item.id)">
|
||||
انجام شد
|
||||
<button v-if="canMarkShare(item)" type="button" @click="complete(item.id)">
|
||||
{{ completeLabel(item) }}
|
||||
</button>
|
||||
<button type="button" class="danger" @click="askDeleteActivity(item.id, item.title)">
|
||||
حذف
|
||||
@@ -1845,8 +1872,8 @@ onUnmounted(() => {
|
||||
<button v-if="canPromotePrior(item)" type="button" @click="promotePriorActivity(item.id)">
|
||||
انتقال به کار جاری
|
||||
</button>
|
||||
<button v-if="item.status === 'open'" type="button" @click="complete(item.id)">
|
||||
انجام شد
|
||||
<button v-if="canMarkShare(item)" type="button" @click="complete(item.id)">
|
||||
{{ completeLabel(item) }}
|
||||
</button>
|
||||
<button type="button" class="danger" @click="askDeleteActivity(item.id, item.title)">
|
||||
حذف
|
||||
|
||||
@@ -20,11 +20,13 @@ import type {
|
||||
ActivityDto,
|
||||
ActivityPriority,
|
||||
OrgUserDto,
|
||||
TeamDto,
|
||||
} from '@mento/shared';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { canAssignToOthers } from '@/lib/assign-access';
|
||||
import { activityTypeView, typeColorStyle, useActivityTypes } from '@/lib/activity-types';
|
||||
import { brand } from '@mento/shared';
|
||||
import { parseActivityThread, type ActivityThreadEntry } from '@/lib/activity-thread';
|
||||
import {
|
||||
leadNoteFileIsImage,
|
||||
noteChips,
|
||||
@@ -64,12 +66,22 @@ const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
const error = ref('');
|
||||
const activity = ref<ActivityDto | null>(null);
|
||||
const imageUrls = ref<Array<{ id: string; name: string; url: string; kind: 'image' | 'audio' | 'file' }>>([]);
|
||||
type NoteMedia = {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
kind: 'image' | 'audio' | 'file';
|
||||
createdAt: string;
|
||||
};
|
||||
const imageUrls = ref<NoteMedia[]>([]);
|
||||
const moreOpen = ref(false);
|
||||
const commentOpen = ref(false);
|
||||
const postponeOpen = ref(false);
|
||||
const noteOpen = ref(true);
|
||||
const noteModel = computed(() => parseLeadFormNotes(activity.value?.description));
|
||||
const thread = computed(() => parseActivityThread(activity.value?.description));
|
||||
const noteModel = computed(() =>
|
||||
thread.value ? { mode: 'prose' as const, prose: '', rows: [] as LeadNoteRow[] } : parseLeadFormNotes(activity.value?.description),
|
||||
);
|
||||
const noteRows = computed(() =>
|
||||
noteModel.value.mode === 'answers' ? noteModel.value.rows : ([] as LeadNoteRow[]),
|
||||
);
|
||||
@@ -80,8 +92,53 @@ const noteExtra = computed(() =>
|
||||
(chip) => !(chip.kind === 'text' && chip.text.replace(/\s+/g, '').trim() === 'پاسخهایفرم:'),
|
||||
),
|
||||
);
|
||||
const COMMENT_MEDIA_WINDOW_MS = 3 * 60 * 1000;
|
||||
|
||||
const threadBlocks = computed(() => {
|
||||
const entries = thread.value;
|
||||
if (!entries) return null;
|
||||
const blocks = entries.map((entry) => ({ ...entry, media: [] as NoteMedia[] }));
|
||||
const used = new Set<string>();
|
||||
for (const image of imageUrls.value) {
|
||||
const at = new Date(image.createdAt).getTime();
|
||||
if (Number.isNaN(at)) continue;
|
||||
let best = -1;
|
||||
let bestDelta = Number.POSITIVE_INFINITY;
|
||||
blocks.forEach((block, index) => {
|
||||
if (!block.at) return;
|
||||
const delta = block.at.getTime() - at;
|
||||
if (delta >= -60_000 && delta < bestDelta) {
|
||||
best = index;
|
||||
bestDelta = delta;
|
||||
}
|
||||
});
|
||||
if (best >= 0 && bestDelta <= COMMENT_MEDIA_WINDOW_MS) {
|
||||
blocks[best]!.media.push(image);
|
||||
used.add(image.id);
|
||||
}
|
||||
}
|
||||
const firstStamp = blocks.find((block) => block.at)?.at?.getTime() ?? Number.POSITIVE_INFINITY;
|
||||
const preamble = blocks.find((block) => !block.at);
|
||||
const loose: NoteMedia[] = [];
|
||||
for (const image of imageUrls.value) {
|
||||
if (used.has(image.id)) continue;
|
||||
const at = new Date(image.createdAt).getTime();
|
||||
if (preamble && !Number.isNaN(at) && at < firstStamp) preamble.media.push(image);
|
||||
else loose.push(image);
|
||||
}
|
||||
return { blocks, loose };
|
||||
});
|
||||
|
||||
const looseMedia = computed(() => threadBlocks.value?.loose ?? imageUrls.value);
|
||||
|
||||
const recoveredImages = ref<Record<string, string>>({});
|
||||
|
||||
function entryRows(entry: ActivityThreadEntry): LeadNoteRow[] {
|
||||
if (entry.at) return [];
|
||||
const parsed = parseLeadFormNotes(entry.body);
|
||||
return parsed.mode === 'answers' ? parsed.rows : [];
|
||||
}
|
||||
|
||||
function noteImageSrc(file: LeadNoteFile): string | null {
|
||||
if (!leadNoteFileIsImage(file)) return null;
|
||||
return file.dataUrl || recoveredImages.value[file.name] || null;
|
||||
@@ -115,18 +172,140 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
const users = ref<OrgUserDto[]>([]);
|
||||
const teams = ref<TeamDto[]>([]);
|
||||
const assignUserIds = ref<string[]>([]);
|
||||
const shareOpen = ref<Record<string, boolean>>({});
|
||||
|
||||
const assigneeNames = computed(() => {
|
||||
const assigneePeople = computed(() => {
|
||||
const a = activity.value;
|
||||
if (!a) return '—';
|
||||
const list = a.assignees?.length
|
||||
? a.assignees.map((u) => u.fullName)
|
||||
: a.assignee
|
||||
? [a.assignee.fullName]
|
||||
: [];
|
||||
if (!a) return [];
|
||||
if (a.assignees?.length) return a.assignees;
|
||||
return a.assignee ? [a.assignee] : [];
|
||||
});
|
||||
const assigneeNames = computed(() => {
|
||||
const list = assigneePeople.value.map((u) => u.fullName);
|
||||
return list.length ? list.join('، ') : '—';
|
||||
});
|
||||
const needsEveryone = computed(
|
||||
() =>
|
||||
activity.value?.completionMode === 'all' && assigneePeople.value.length > 1,
|
||||
);
|
||||
|
||||
type SharePerson = { id: string; fullName: string };
|
||||
type ShareGroup = {
|
||||
key: string;
|
||||
kind: 'team' | 'role' | 'rest';
|
||||
name: string;
|
||||
members: SharePerson[];
|
||||
};
|
||||
|
||||
const shareGroups = computed<ShareGroup[]>(() => {
|
||||
const people = assigneePeople.value;
|
||||
if (people.length < 2) return [];
|
||||
const byId = new Map(people.map((person) => [person.id, person]));
|
||||
const claimed = new Set<string>();
|
||||
const groups: ShareGroup[] = [];
|
||||
|
||||
const teamCandidates = teams.value
|
||||
.map((team) => {
|
||||
const members = [
|
||||
...new Map(
|
||||
team.members
|
||||
.map((member) => byId.get(member.userId))
|
||||
.filter((person): person is SharePerson => Boolean(person))
|
||||
.map((person) => [person.id, person]),
|
||||
).values(),
|
||||
].sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa'));
|
||||
return { id: team.id, name: team.name, members };
|
||||
})
|
||||
.filter((team) => team.members.length >= 2)
|
||||
.sort(
|
||||
(a, b) => b.members.length - a.members.length || a.name.localeCompare(b.name, 'fa'),
|
||||
);
|
||||
|
||||
for (const team of teamCandidates) {
|
||||
const free = team.members.filter((member) => !claimed.has(member.id));
|
||||
if (free.length < 2) continue;
|
||||
for (const member of free) claimed.add(member.id);
|
||||
groups.push({ key: `team:${team.id}`, kind: 'team', name: team.name, members: free });
|
||||
}
|
||||
|
||||
const roleMap = new Map<string, { name: string; members: SharePerson[] }>();
|
||||
for (const user of users.value) {
|
||||
const person = byId.get(user.id);
|
||||
if (!person || claimed.has(person.id) || !user.orgRoleId || !user.orgRoleName) continue;
|
||||
const row = roleMap.get(user.orgRoleId) ?? { name: user.orgRoleName, members: [] };
|
||||
row.members.push(person);
|
||||
roleMap.set(user.orgRoleId, row);
|
||||
}
|
||||
const roles = [...roleMap.entries()]
|
||||
.map(([id, role]) => ({
|
||||
id,
|
||||
name: role.name,
|
||||
members: [...role.members].sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa')),
|
||||
}))
|
||||
.filter((role) => role.members.length >= 2)
|
||||
.sort((a, b) => b.members.length - a.members.length || a.name.localeCompare(b.name, 'fa'));
|
||||
for (const role of roles) {
|
||||
for (const member of role.members) claimed.add(member.id);
|
||||
groups.push({ key: `role:${role.id}`, kind: 'role', name: role.name, members: role.members });
|
||||
}
|
||||
|
||||
const rest = people
|
||||
.filter((person) => !claimed.has(person.id))
|
||||
.sort((a, b) => a.fullName.localeCompare(b.fullName, 'fa'));
|
||||
if (rest.length) {
|
||||
groups.push({
|
||||
key: 'rest',
|
||||
kind: 'rest',
|
||||
name: groups.length ? 'سایر مسئولها' : 'مسئولها',
|
||||
members: rest,
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
|
||||
const completedIds = computed(() => new Set(activity.value?.completedByIds ?? []));
|
||||
|
||||
const shareUsesGroups = computed(
|
||||
() =>
|
||||
shareGroups.value.some((group) => group.kind !== 'rest' || group.members.length > 6),
|
||||
);
|
||||
|
||||
const shareDoneTotal = computed(
|
||||
() => assigneePeople.value.filter((person) => completedIds.value.has(person.id)).length,
|
||||
);
|
||||
|
||||
function shareDoneCount(members: SharePerson[]) {
|
||||
return members.filter((person) => completedIds.value.has(person.id)).length;
|
||||
}
|
||||
|
||||
function shareKindLabel(group: ShareGroup) {
|
||||
if (group.kind === 'team' && !group.name.startsWith('تیم')) return 'تیم';
|
||||
if (group.kind === 'role' && !group.name.startsWith('نقش')) return 'نقش';
|
||||
return '';
|
||||
}
|
||||
|
||||
function shareExpanded(group: ShareGroup) {
|
||||
if (group.key in shareOpen.value) return shareOpen.value[group.key];
|
||||
return group.kind === 'rest' && group.members.length <= 6;
|
||||
}
|
||||
|
||||
function toggleShare(group: ShareGroup) {
|
||||
shareOpen.value = { ...shareOpen.value, [group.key]: !shareExpanded(group) };
|
||||
}
|
||||
const myShareDone = computed(() => {
|
||||
const mine = auth.user?.id;
|
||||
return Boolean(mine && completedIds.value.has(mine));
|
||||
});
|
||||
const canForceClose = computed(() => {
|
||||
const role = auth.user?.role;
|
||||
return (
|
||||
role === 'owner' ||
|
||||
role === 'admin' ||
|
||||
activity.value?.createdBy?.id === auth.user?.id
|
||||
);
|
||||
});
|
||||
|
||||
const activityTypes = useActivityTypes();
|
||||
const typeView = computed(() => (activity.value ? activityTypeView(activity.value) : null));
|
||||
@@ -205,6 +384,7 @@ async function load() {
|
||||
try {
|
||||
const { data } = await api.get<ActivityDto>(`/activities/${id.value}`);
|
||||
activity.value = data;
|
||||
shareOpen.value = {};
|
||||
await loadActivityImages(data);
|
||||
assignUserIds.value = data.assignees?.length
|
||||
? data.assignees.map((u) => u.id)
|
||||
@@ -226,7 +406,7 @@ function clearImageUrls() {
|
||||
|
||||
async function loadActivityImages(row: ActivityDto) {
|
||||
clearImageUrls();
|
||||
const next: Array<{ id: string; name: string; url: string; kind: 'image' | 'audio' | 'file' }> = [];
|
||||
const next: NoteMedia[] = [];
|
||||
for (const image of row.images ?? []) {
|
||||
const mime = image.mimeType.toLowerCase();
|
||||
const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file';
|
||||
@@ -239,6 +419,7 @@ async function loadActivityImages(row: ActivityDto) {
|
||||
name: image.fileName,
|
||||
url: URL.createObjectURL(data),
|
||||
kind,
|
||||
createdAt: image.createdAt,
|
||||
});
|
||||
} catch {
|
||||
/* فایل در دسترس نیست */
|
||||
@@ -250,24 +431,56 @@ async function loadActivityImages(row: ActivityDto) {
|
||||
onUnmounted(clearImageUrls);
|
||||
|
||||
async function loadUsers() {
|
||||
if (!canReassign.value) return;
|
||||
try {
|
||||
const { data } = await api.get<OrgUserDto[]>('/users');
|
||||
users.value = data;
|
||||
const [usersRes, teamsRes] = await Promise.all([
|
||||
api.get<OrgUserDto[]>('/users').catch(() => ({ data: [] as OrgUserDto[] })),
|
||||
api.get<TeamDto[]>('/teams').catch(() => ({ data: [] as TeamDto[] })),
|
||||
]);
|
||||
users.value = usersRes.data;
|
||||
teams.value = teamsRes.data;
|
||||
} catch {
|
||||
users.value = [];
|
||||
teams.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function complete() {
|
||||
if (!id.value || isDone.value) return;
|
||||
async function complete(kind: 'share' | 'force' | 'undo' = 'share') {
|
||||
if (!id.value) return;
|
||||
if (kind !== 'undo' && isDone.value) return;
|
||||
saving.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
await api.patch(`/activities/${id.value}/complete`);
|
||||
await router.push({ name: 'activities' });
|
||||
const params =
|
||||
kind === 'force' ? { force: '1' } : kind === 'undo' ? { undo: '1' } : undefined;
|
||||
const { data } = await api.patch<ActivityDto>(
|
||||
`/activities/${id.value}/complete`,
|
||||
undefined,
|
||||
{ params },
|
||||
);
|
||||
if (data.status === 'done') {
|
||||
await router.push({ name: 'activities' });
|
||||
return;
|
||||
}
|
||||
activity.value = data;
|
||||
} catch {
|
||||
error.value = 'ثبت انجامشدن ناموفق بود.';
|
||||
error.value =
|
||||
kind === 'undo' ? 'لغو سهم ناموفق بود.' : 'ثبت انجامشدن ناموفق بود.';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function setCompletionMode(mode: 'any' | 'all') {
|
||||
if (!id.value || activity.value?.completionMode === mode) return;
|
||||
saving.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const { data } = await api.patch<ActivityDto>(`/activities/${id.value}`, {
|
||||
completionMode: mode,
|
||||
});
|
||||
activity.value = data;
|
||||
} catch {
|
||||
error.value = 'تغییر نحوهٔ انجام ناموفق بود.';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
@@ -535,11 +748,81 @@ onMounted(() => {
|
||||
:users="users"
|
||||
:disabled="saving"
|
||||
:min="1"
|
||||
select-all
|
||||
@change="reassign"
|
||||
/>
|
||||
<template v-else>
|
||||
{{ assigneeNames }}
|
||||
</template>
|
||||
<div v-if="canReassign && assigneePeople.length > 1" class="share-mode">
|
||||
<button
|
||||
type="button"
|
||||
:class="{ on: activity.completionMode !== 'all' }"
|
||||
:disabled="saving"
|
||||
@click="setCompletionMode('any')"
|
||||
>
|
||||
با انجام یکی کافی است
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ on: activity.completionMode === 'all' }"
|
||||
:disabled="saving"
|
||||
@click="setCompletionMode('all')"
|
||||
>
|
||||
همه باید انجام دهند
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="needsEveryone && !isDone && shareUsesGroups" class="share-board">
|
||||
<p class="share-progress">
|
||||
{{ toFaDigits(shareDoneTotal) }} از {{ toFaDigits(assigneePeople.length) }} انجام شده
|
||||
</p>
|
||||
<div v-for="group in shareGroups" :key="group.key" class="share-group">
|
||||
<button type="button" class="share-group-head" @click="toggleShare(group)">
|
||||
<UiIcon
|
||||
name="chevron"
|
||||
:size="14"
|
||||
class="share-caret"
|
||||
:class="{ open: shareExpanded(group) }"
|
||||
/>
|
||||
<span class="share-group-name">
|
||||
<small v-if="shareKindLabel(group)">{{ shareKindLabel(group) }}</small>
|
||||
{{ group.name }}
|
||||
</span>
|
||||
<em :class="{ done: shareDoneCount(group.members) === group.members.length }">
|
||||
{{ toFaDigits(shareDoneCount(group.members)) }} از {{ toFaDigits(group.members.length) }}
|
||||
</em>
|
||||
</button>
|
||||
<ul v-if="shareExpanded(group)" class="share-members">
|
||||
<li
|
||||
v-for="person in group.members"
|
||||
:key="person.id"
|
||||
:class="{ done: completedIds.has(person.id) }"
|
||||
>
|
||||
<span>{{ person.fullName }}</span>
|
||||
<em>{{ completedIds.has(person.id) ? 'انجام شد' : 'مانده' }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<ul v-else-if="needsEveryone && !isDone" class="share-list">
|
||||
<li
|
||||
v-for="person in assigneePeople"
|
||||
:key="person.id"
|
||||
:class="{ done: completedIds.has(person.id) }"
|
||||
>
|
||||
<span>{{ person.fullName }}</span>
|
||||
<em>{{ completedIds.has(person.id) ? 'انجام شد' : 'مانده' }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<button
|
||||
v-if="needsEveryone && canForceClose && !isDone"
|
||||
type="button"
|
||||
class="share-force"
|
||||
:disabled="saving"
|
||||
@click="complete('force')"
|
||||
>
|
||||
بستن برای همه
|
||||
</button>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
@@ -617,7 +900,76 @@ onMounted(() => {
|
||||
<UiIcon name="chevron" :size="16" :class="{ open: noteOpen }" />
|
||||
</button>
|
||||
<div v-show="noteOpen">
|
||||
<dl v-if="noteRows.length" class="note-rows">
|
||||
<div v-if="threadBlocks" class="note-thread">
|
||||
<article
|
||||
v-for="(entry, index) in threadBlocks.blocks"
|
||||
:key="`${entry.dateLabel}-${entry.timeLabel}-${index}`"
|
||||
class="note-bubble"
|
||||
>
|
||||
<header v-if="entry.dateLabel">
|
||||
<time>{{ entry.dateLabel }} ساعت {{ entry.timeLabel }}</time>
|
||||
<span v-if="entry.author">{{ entry.author }}</span>
|
||||
</header>
|
||||
<dl v-if="entryRows(entry).length" class="note-rows">
|
||||
<div v-for="(row, rowIndex) in entryRows(entry)" :key="`${row.label}-${rowIndex}`">
|
||||
<dt>{{ row.label }}</dt>
|
||||
<dd>
|
||||
<template v-if="row.file && noteImageSrc(row.file)">
|
||||
<a class="note-shot" :href="noteImageSrc(row.file)!" target="_blank" rel="noopener">
|
||||
<img :src="noteImageSrc(row.file)!" :alt="row.file.name" />
|
||||
</a>
|
||||
<span>{{ row.file.name }}</span>
|
||||
</template>
|
||||
<span v-else-if="row.file">{{ row.file.name }}</span>
|
||||
<template v-else>
|
||||
<template v-for="(chip, chipIndex) in noteChips(row.text)" :key="chipIndex">
|
||||
<a v-if="chip.kind === 'link'" :href="chip.href" target="_blank" rel="noopener">{{ chip.label }}</a>
|
||||
<a v-else-if="chip.kind === 'image'" class="note-shot" :href="chip.src" target="_blank" rel="noopener">
|
||||
<img :src="chip.src" :alt="chip.name" />
|
||||
</a>
|
||||
<span v-else>{{ chip.text }}</span>
|
||||
</template>
|
||||
</template>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else-if="entry.body" class="note-bubble-body">
|
||||
<template v-for="(chip, chipIndex) in noteChips(entry.body)" :key="chipIndex">
|
||||
<a v-if="chip.kind === 'link'" :href="chip.href" target="_blank" rel="noopener">{{ chip.label }}</a>
|
||||
<a v-else-if="chip.kind === 'image'" class="note-shot" :href="chip.src" target="_blank" rel="noopener">
|
||||
<img :src="chip.src" :alt="chip.name" />
|
||||
</a>
|
||||
<span v-else>{{ chip.text }}</span>
|
||||
</template>
|
||||
</p>
|
||||
<div v-if="entry.media.some((image) => image.kind === 'image')" class="note-photos">
|
||||
<a
|
||||
v-for="image in entry.media.filter((item) => item.kind === 'image')"
|
||||
:key="image.id"
|
||||
:href="image.url"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
>
|
||||
<img :src="image.url" :alt="image.name" />
|
||||
</a>
|
||||
</div>
|
||||
<div v-if="entry.media.some((image) => image.kind === 'audio')" class="note-voices">
|
||||
<audio
|
||||
v-for="image in entry.media.filter((item) => item.kind === 'audio')"
|
||||
:key="image.id"
|
||||
:src="image.url"
|
||||
controls
|
||||
preload="metadata"
|
||||
/>
|
||||
</div>
|
||||
<ul v-if="entry.media.some((image) => image.kind === 'file')" class="note-files">
|
||||
<li v-for="image in entry.media.filter((item) => item.kind === 'file')" :key="image.id">
|
||||
<a :href="image.url" :download="image.name">{{ image.name }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
</article>
|
||||
</div>
|
||||
<dl v-else-if="noteRows.length" class="note-rows">
|
||||
<div v-for="(row, index) in noteRows" :key="`${row.label}-${index}`">
|
||||
<dt>{{ row.label }}</dt>
|
||||
<dd>
|
||||
@@ -652,7 +1004,7 @@ onMounted(() => {
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else-if="!noteExtra.length && !imageUrls.length" class="empty">یادداشتی ثبت نشده.</p>
|
||||
<p v-if="noteExtra.length" class="note-extra">
|
||||
<p v-if="!threadBlocks && noteExtra.length" class="note-extra">
|
||||
<template v-for="(chip, index) in noteExtra" :key="index">
|
||||
<a
|
||||
v-if="chip.kind === 'link'"
|
||||
@@ -672,9 +1024,9 @@ onMounted(() => {
|
||||
<span v-else>{{ chip.text }}</span>
|
||||
</template>
|
||||
</p>
|
||||
<div v-if="imageUrls.some((image) => image.kind === 'image')" class="note-photos">
|
||||
<div v-if="looseMedia.some((image) => image.kind === 'image')" class="note-photos">
|
||||
<a
|
||||
v-for="image in imageUrls.filter((item) => item.kind === 'image')"
|
||||
v-for="image in looseMedia.filter((item) => item.kind === 'image')"
|
||||
:key="image.id"
|
||||
:href="image.url"
|
||||
target="_blank"
|
||||
@@ -683,17 +1035,17 @@ onMounted(() => {
|
||||
<img :src="image.url" :alt="image.name" />
|
||||
</a>
|
||||
</div>
|
||||
<div v-if="imageUrls.some((image) => image.kind === 'audio')" class="note-voices">
|
||||
<div v-if="looseMedia.some((image) => image.kind === 'audio')" class="note-voices">
|
||||
<audio
|
||||
v-for="image in imageUrls.filter((item) => item.kind === 'audio')"
|
||||
v-for="image in looseMedia.filter((item) => item.kind === 'audio')"
|
||||
:key="image.id"
|
||||
:src="image.url"
|
||||
controls
|
||||
preload="metadata"
|
||||
/>
|
||||
</div>
|
||||
<ul v-if="imageUrls.some((image) => image.kind === 'file')" class="note-files">
|
||||
<li v-for="image in imageUrls.filter((item) => item.kind === 'file')" :key="image.id">
|
||||
<ul v-if="looseMedia.some((image) => image.kind === 'file')" class="note-files">
|
||||
<li v-for="image in looseMedia.filter((item) => item.kind === 'file')" :key="image.id">
|
||||
<a :href="image.url" :download="image.name">{{ image.name }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -729,15 +1081,25 @@ onMounted(() => {
|
||||
<UiIcon name="clock" :size="16" />
|
||||
بازگشایی
|
||||
</button>
|
||||
<button
|
||||
v-else-if="needsEveryone && myShareDone"
|
||||
class="act primary"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
@click="complete('undo')"
|
||||
>
|
||||
<UiIcon name="refresh" :size="16" />
|
||||
لغو سهم من
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
class="act primary"
|
||||
type="button"
|
||||
:disabled="saving || isDone"
|
||||
@click="complete"
|
||||
@click="complete('share')"
|
||||
>
|
||||
<UiIcon name="check" :size="16" />
|
||||
انجام شد
|
||||
{{ needsEveryone ? 'انجام سهم من' : 'انجام شد' }}
|
||||
</button>
|
||||
<button class="act ghost" type="button" :disabled="saving || isDone" @click="postponeOpen = true">
|
||||
<UiIcon name="refresh" :size="16" />
|
||||
@@ -1034,6 +1396,190 @@ dd {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.share-mode {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
width: 100%;
|
||||
margin-top: 0.55rem;
|
||||
}
|
||||
|
||||
.share-mode button {
|
||||
border: 1px solid #e2e8f0;
|
||||
background: #fff;
|
||||
color: #334155;
|
||||
border-radius: 999px;
|
||||
padding: 0.25rem 0.7rem;
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.share-mode button.on {
|
||||
border-color: #14b8a6;
|
||||
background: #f0fdfa;
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.share-list {
|
||||
list-style: none;
|
||||
margin: 0.55rem 0 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.share-list li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
font-size: 0.86rem;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.share-list em {
|
||||
font-style: normal;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.share-list li.done em {
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.share-board {
|
||||
width: 100%;
|
||||
margin-top: 0.55rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.share-progress {
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.share-group {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.7rem;
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.share-group-head {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0.4rem 0.65rem;
|
||||
font: inherit;
|
||||
font-size: 0.84rem;
|
||||
font-weight: 600;
|
||||
color: #334155;
|
||||
text-align: start;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.share-group-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.share-group-name small {
|
||||
margin-inline-end: 0.3rem;
|
||||
color: #94a3b8;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.share-group-head em {
|
||||
font-style: normal;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.share-group-head em.done {
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.share-group-head :deep(.share-caret) {
|
||||
color: #94a3b8;
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.share-group-head :deep(.share-caret.open) {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.share-members {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0.15rem 0.55rem 0.55rem;
|
||||
max-height: 14rem;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.share-members li {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
padding: 0.12rem 0.45rem 0.12rem 0.15rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.share-members li span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.share-members em {
|
||||
flex: 0 0 auto;
|
||||
font-style: normal;
|
||||
font-size: 0.68rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
background: #f1f5f9;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.share-members li.done em {
|
||||
background: #f0fdfa;
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.share-force {
|
||||
margin-top: 0.45rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #0f766e;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.flag.low,
|
||||
.priority.low {
|
||||
color: #16a34a;
|
||||
@@ -1098,6 +1644,46 @@ dd {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.note-thread {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.note-bubble {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.85rem;
|
||||
background: #f8fafc;
|
||||
padding: 0.7rem 0.85rem;
|
||||
}
|
||||
|
||||
.note-bubble header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.35rem;
|
||||
color: #64748b;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.note-bubble header span {
|
||||
color: #0f766e;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.note .note-bubble-body {
|
||||
margin: 0;
|
||||
color: #334155;
|
||||
line-height: 1.9;
|
||||
white-space: pre-line;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.note-bubble .note-rows {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.note-rows {
|
||||
margin: 0.75rem 0 0;
|
||||
display: grid;
|
||||
|
||||
@@ -129,6 +129,7 @@ const personId = ref('');
|
||||
const leadId = ref('');
|
||||
const dealId = ref('');
|
||||
const assigneeIds = ref<string[]>([]);
|
||||
const completionMode = ref<'any' | 'all'>('any');
|
||||
const isDone = ref(false);
|
||||
const needsNote = ref(false);
|
||||
const reminderAt = ref('');
|
||||
@@ -440,6 +441,7 @@ function resetForm() {
|
||||
personId.value = '';
|
||||
dealId.value = '';
|
||||
assigneeIds.value = auth.user?.id ? [auth.user.id] : [];
|
||||
completionMode.value = 'any';
|
||||
pickedRoleIds.value = [];
|
||||
pickedTeamIds.value = [];
|
||||
isDone.value = false;
|
||||
@@ -528,6 +530,7 @@ async function load() {
|
||||
: auth.user?.id
|
||||
? [auth.user.id]
|
||||
: [];
|
||||
completionMode.value = data.completionMode === 'all' ? 'all' : 'any';
|
||||
refreshPickedGroups();
|
||||
isDone.value = data.status === 'done';
|
||||
await loadSavedPhotos(data);
|
||||
@@ -605,6 +608,7 @@ function payload(): CreateActivityRequest {
|
||||
leadId: leadId.value || null,
|
||||
assigneeIds: [...assigneeIds.value],
|
||||
assigneeId: assigneeIds.value[0] || null,
|
||||
completionMode: assigneeIds.value.length > 1 ? completionMode.value : 'any',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -978,7 +982,9 @@ async function submit(next: 'detail' | 'new' = 'detail') {
|
||||
savedId = data.id;
|
||||
createdActivityId.value = data.id;
|
||||
if (isDone.value) {
|
||||
await api.patch(`/activities/${savedId}/complete`);
|
||||
await api.patch(`/activities/${savedId}/complete`, undefined, {
|
||||
params: { force: '1' },
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await api.patch(`/activities/${savedId}`, {
|
||||
@@ -1269,6 +1275,20 @@ watch([id, isNew], () => void load(), { immediate: true });
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div v-if="assigneeIds.length > 1" class="completion-mode">
|
||||
<span>نحوهٔ انجام</span>
|
||||
<label>
|
||||
<input v-model="completionMode" type="radio" value="any" />
|
||||
با انجام یکی کافی است
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="completionMode" type="radio" value="all" />
|
||||
همهٔ مسئولها باید انجام دهند
|
||||
</label>
|
||||
<p v-if="completionMode === 'all'" class="completion-hint">
|
||||
هر کدام از همین افراد باید جداگانه سهم خودش را انجام دهد.
|
||||
</p>
|
||||
</div>
|
||||
<small class="hint">
|
||||
{{
|
||||
canAssignOthers
|
||||
@@ -1799,6 +1819,66 @@ watch([id, isNew], () => void load(), { immediate: true });
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.completion-mode {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.completion-mode > span {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.completion-mode label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
margin: 0;
|
||||
padding: 0.2rem 0.65rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #334155;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.completion-mode label:has(input:checked) {
|
||||
border-color: #14b8a6;
|
||||
background: #f0fdfa;
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.completion-mode input {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
flex: 0 0 14px;
|
||||
accent-color: #0d9488;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.completion-hint {
|
||||
width: 100%;
|
||||
margin: 0.15rem 0 0;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.assignee-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
+741
-142
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@ import NoteCategoriesManager from '@/components/notes/NoteCategoriesManager.vue'
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import VoiceToTextButton from '@/components/VoiceToTextButton.vue';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { UiDropdownMenu } from '@/components/ui';
|
||||
import { appendSpokenText } from '@/lib/spoken-text';
|
||||
import { canManageSettings } from '@/lib/roles';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
@@ -721,7 +722,7 @@ function syncMobileFlag() {
|
||||
|
||||
function onDocClick(ev: MouseEvent) {
|
||||
const t = ev.target as HTMLElement | null;
|
||||
if (!t?.closest?.('.card-menu')) menuOpenId.value = null;
|
||||
if (!t?.closest?.('.card-menu, .ui-dd-panel')) menuOpenId.value = null;
|
||||
}
|
||||
|
||||
watch(typeFilter, () => {
|
||||
@@ -962,27 +963,34 @@ onBeforeUnmount(() => {
|
||||
</svg>
|
||||
</span>
|
||||
<div class="card-menu" @click.stop>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn menu-btn"
|
||||
@click="menuOpenId = menuOpenId === note.id ? null : note.id"
|
||||
<UiDropdownMenu
|
||||
:open="menuOpenId === note.id"
|
||||
align="end"
|
||||
@update:open="(v) => (menuOpenId = v ? note.id : null)"
|
||||
>
|
||||
<UiIcon name="dots-v" :size="18" />
|
||||
</button>
|
||||
<div v-if="menuOpenId === note.id" class="menu-pop">
|
||||
<button type="button" @click="openEditor('default', note)">ویرایش</button>
|
||||
<button type="button" @click="togglePin(note.id)">
|
||||
<template #trigger="{ toggle }">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn menu-btn"
|
||||
aria-label="عملیات"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<UiIcon name="dots-v" :size="18" />
|
||||
</button>
|
||||
</template>
|
||||
<button type="button" @click.stop="openEditor('default', note)">ویرایش</button>
|
||||
<button type="button" @click.stop="togglePin(note.id)">
|
||||
{{ note.pinned ? 'برداشتن سنجاق' : 'سنجاق کردن' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="(note.revisionCount ?? 0) > 0"
|
||||
type="button"
|
||||
@click="openHistory(note)"
|
||||
@click.stop="openHistory(note)"
|
||||
>
|
||||
تاریخچه ویرایش
|
||||
</button>
|
||||
<button type="button" class="danger" @click="removeNote(note.id)">حذف</button>
|
||||
</div>
|
||||
<button type="button" class="danger" @click.stop="removeNote(note.id)">حذف</button>
|
||||
</UiDropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1893,42 +1901,16 @@ onBeforeUnmount(() => {
|
||||
position: relative;
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
.menu-pop {
|
||||
position: absolute;
|
||||
inset-inline-end: 0;
|
||||
top: 100%;
|
||||
z-index: 5;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
min-width: 140px;
|
||||
padding: 0.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.menu-pop button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: start;
|
||||
padding: 0.45rem 0.65rem;
|
||||
border-radius: var(--radius);
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
color: #334155;
|
||||
}
|
||||
.menu-pop button:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
.menu-pop .danger {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
margin: 0 0 0.35rem;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
color: #0f172a;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
@@ -1940,7 +1922,7 @@ onBeforeUnmount(() => {
|
||||
color: #334155;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.45;
|
||||
flex: 1;
|
||||
flex: 1 1 2.9em;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
display: -webkit-box;
|
||||
@@ -1975,13 +1957,15 @@ onBeforeUnmount(() => {
|
||||
margin-top: 0.45rem;
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
flex: 0 1 72px;
|
||||
min-height: 0;
|
||||
max-height: 72px;
|
||||
}
|
||||
.card-thumb img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 72px;
|
||||
max-height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
@@ -2198,11 +2182,16 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
|
||||
.title-input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
padding: 0.35rem 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
color: #0f172a;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
@@ -177,7 +177,9 @@ function findAccent(dealId: string): PipelineStage['color'] {
|
||||
}
|
||||
|
||||
async function loadPipelines() {
|
||||
const { data } = await api.get<PipelineDto[]>('/pipelines');
|
||||
const { data } = await api.get<PipelineDto[]>('/pipelines', {
|
||||
params: { forLens: '1' },
|
||||
});
|
||||
pipelines.value = data;
|
||||
}
|
||||
|
||||
@@ -186,16 +188,23 @@ async function load() {
|
||||
error.value = '';
|
||||
try {
|
||||
await loadPipelines();
|
||||
const pipelineId =
|
||||
typeof route.query.pipelineId === 'string'
|
||||
? route.query.pipelineId
|
||||
: undefined;
|
||||
const requested =
|
||||
typeof route.query.pipelineId === 'string' ? route.query.pipelineId : '';
|
||||
const pipelineId = pipelines.value.some((item) => item.id === requested)
|
||||
? requested
|
||||
: pipelines.value[0]?.id;
|
||||
if (!pipelineId) {
|
||||
boardPipelineId.value = '';
|
||||
stages.value = [];
|
||||
if (requested) await router.replace({ name: 'pipeline', query: {} });
|
||||
return;
|
||||
}
|
||||
const { data } = await api.get<PipelineBoardDto>('/pipelines/board', {
|
||||
params: pipelineId ? { pipelineId } : undefined,
|
||||
params: { pipelineId },
|
||||
});
|
||||
boardPipelineId.value = data.pipeline.id;
|
||||
stages.value = mapBoardToStages(data, formatDealDate);
|
||||
if (!pipelineId || pipelineId !== data.pipeline.id) {
|
||||
if (requested !== data.pipeline.id) {
|
||||
await router.replace({
|
||||
name: 'pipeline',
|
||||
query: { pipelineId: data.pipeline.id },
|
||||
|
||||
@@ -411,25 +411,25 @@ onMounted(load);
|
||||
</td>
|
||||
<td class="ops" @click.stop>
|
||||
<UiDropdownMenu
|
||||
:open="menuId === p.id"
|
||||
:open="menuId === `d:${p.id}`"
|
||||
align="end"
|
||||
@update:open="(v) => (menuId = v ? p.id : null)"
|
||||
@update:open="(v) => (menuId = v ? `d:${p.id}` : null)"
|
||||
>
|
||||
<template #trigger="{ toggle }">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
class="more"
|
||||
aria-label="عملیات"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<UiIcon name="dots" :size="16" />
|
||||
<UiIcon name="dots-v" :size="16" />
|
||||
</button>
|
||||
</template>
|
||||
<button type="button" @click="goEdit(p.id)">ویرایش</button>
|
||||
<button type="button" @click="toggleActive(p)">
|
||||
<button type="button" @click.stop="goEdit(p.id)">ویرایش</button>
|
||||
<button type="button" @click.stop="toggleActive(p)">
|
||||
{{ p.isActive ? 'غیرفعال کردن' : 'فعال کردن' }}
|
||||
</button>
|
||||
<button type="button" class="danger" @click="removeProduct(p)">حذف</button>
|
||||
<button type="button" class="danger" @click.stop="removeProduct(p)">حذف</button>
|
||||
</UiDropdownMenu>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -460,25 +460,25 @@ onMounted(load);
|
||||
</div>
|
||||
<div class="mob-side">
|
||||
<UiDropdownMenu
|
||||
:open="menuId === p.id"
|
||||
:open="menuId === `m:${p.id}`"
|
||||
align="end"
|
||||
@update:open="(v) => (menuId = v ? p.id : null)"
|
||||
@update:open="(v) => (menuId = v ? `m:${p.id}` : null)"
|
||||
>
|
||||
<template #trigger="{ toggle }">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
class="more"
|
||||
aria-label="عملیات"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<UiIcon name="dots-v" :size="16" />
|
||||
</button>
|
||||
</template>
|
||||
<button type="button" @click="goEdit(p.id)">ویرایش</button>
|
||||
<button type="button" @click="toggleActive(p)">
|
||||
<button type="button" @click.stop="goEdit(p.id)">ویرایش</button>
|
||||
<button type="button" @click.stop="toggleActive(p)">
|
||||
{{ p.isActive ? 'غیرفعال کردن' : 'فعال کردن' }}
|
||||
</button>
|
||||
<button type="button" class="danger" @click="removeProduct(p)">حذف</button>
|
||||
<button type="button" class="danger" @click.stop="removeProduct(p)">حذف</button>
|
||||
</UiDropdownMenu>
|
||||
<UiBadge :variant="p.isActive ? 'success' : 'neutral'" size="sm" dot>
|
||||
{{ p.isActive ? 'فعال' : 'غیرفعال' }}
|
||||
@@ -680,6 +680,22 @@ tr:last-child td {
|
||||
.ops {
|
||||
width: 64px;
|
||||
}
|
||||
.more {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: #94a3b8;
|
||||
border-radius: var(--radius);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
.more:hover {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
.mob-list {
|
||||
display: none;
|
||||
gap: 0.65rem;
|
||||
|
||||
@@ -64,6 +64,9 @@ type SyncResult = {
|
||||
alreadyLinked?: boolean;
|
||||
personId?: string | null;
|
||||
personName?: string | null;
|
||||
duplicateOfCode?: number | null;
|
||||
duplicatePersonId?: string | null;
|
||||
duplicatePersonName?: string | null;
|
||||
};
|
||||
const syncResults = ref<SyncResult[]>([]);
|
||||
/** هر درخواست listAll یک بازهٔ ۲۰۰۰ کدی است؛ بعد از دو بازهٔ خالی پشتسرهم، خواندن تمام میشود */
|
||||
@@ -145,9 +148,61 @@ async function saveAutoSync() {
|
||||
autoSyncSaving.value = false;
|
||||
}
|
||||
}
|
||||
/** همان قاعدهٔ سرور: موبایل ایران 09… است، بقیهٔ شمارهها فقط رقماند. */
|
||||
function customerPhoneKey(value?: string | null): string {
|
||||
const fa = '۰۱۲۳۴۵۶۷۸۹';
|
||||
const ar = '٠١٢٣٤٥٦٧٨٩';
|
||||
let digits = String(value ?? '')
|
||||
.replace(/[۰-۹٠-٩]/g, (ch) => {
|
||||
const faIndex = fa.indexOf(ch);
|
||||
return String(faIndex >= 0 ? faIndex : ar.indexOf(ch));
|
||||
})
|
||||
.replace(/\D/g, '');
|
||||
if (!digits) return '';
|
||||
if (digits.startsWith('0098') && digits.length >= 14) digits = digits.slice(4);
|
||||
else if (digits.startsWith('98') && digits.length >= 12) digits = digits.slice(2);
|
||||
if (digits.length === 10 && digits.startsWith('9')) digits = `0${digits}`;
|
||||
return digits;
|
||||
}
|
||||
|
||||
const linkedPhoneOwners = computed(() => {
|
||||
const owners = new Map<string, { code: number; personId: string | null; personName: string | null }>();
|
||||
for (const row of syncResults.value) {
|
||||
if (!row.alreadyLinked || row.moshtariCode == null) continue;
|
||||
const key = customerPhoneKey(row.tel);
|
||||
if (key && !owners.has(key)) {
|
||||
owners.set(key, {
|
||||
code: row.moshtariCode,
|
||||
personId: row.personId ?? null,
|
||||
personName: row.personName ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
return owners;
|
||||
});
|
||||
|
||||
function duplicateOwner(row: SyncResult) {
|
||||
if (row.alreadyLinked || row.moshtariCode == null) return null;
|
||||
if (row.duplicateOfCode != null) {
|
||||
return {
|
||||
code: row.duplicateOfCode,
|
||||
personId: row.duplicatePersonId ?? null,
|
||||
personName: row.duplicatePersonName ?? null,
|
||||
};
|
||||
}
|
||||
const key = customerPhoneKey(row.tel);
|
||||
if (!key) return null;
|
||||
const owner = linkedPhoneOwners.value.get(key);
|
||||
if (!owner || owner.code === row.moshtariCode) return null;
|
||||
return owner;
|
||||
}
|
||||
|
||||
const duplicateCustomerCount = computed(
|
||||
() => syncResults.value.filter((row) => duplicateOwner(row)).length,
|
||||
);
|
||||
const syncVisibleResults = computed(() =>
|
||||
syncOnlyNew.value
|
||||
? syncResults.value.filter((r) => !r.alreadyLinked)
|
||||
? syncResults.value.filter((row) => !row.alreadyLinked && !duplicateOwner(row))
|
||||
: syncResults.value,
|
||||
);
|
||||
const syncTableTotalPages = computed(() =>
|
||||
@@ -184,7 +239,7 @@ const productCategoryLabel = ref('کارساخته');
|
||||
|
||||
function pendingImportCodes() {
|
||||
return syncResults.value
|
||||
.filter((r) => r.moshtariCode != null && !r.alreadyLinked)
|
||||
.filter((r) => r.moshtariCode != null && !r.alreadyLinked && !duplicateOwner(r))
|
||||
.map((r) => r.moshtariCode as number);
|
||||
}
|
||||
|
||||
@@ -458,10 +513,12 @@ async function searchTahesab(mode: 'range' | 'filter') {
|
||||
ok.value = 'نتیجهای یافت نشد.';
|
||||
} else {
|
||||
const linked = syncResults.value.filter((r) => r.alreadyLinked).length;
|
||||
const pending = syncResults.value.length - linked;
|
||||
const duplicate = syncResults.value.filter((r) => duplicateOwner(r)).length;
|
||||
const pending = syncResults.value.length - linked - duplicate;
|
||||
ok.value =
|
||||
`${toFaDigits(syncResults.value.length)} مشتری پیدا شد` +
|
||||
` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده`;
|
||||
` · ${toFaDigits(linked)} قبلاً وارد شده · ${toFaDigits(pending)} واردنشده` +
|
||||
(duplicate ? ` · ${toFaDigits(duplicate)} شماره تکراری` : '');
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = apiErr(e, 'جستجو ناموفق');
|
||||
@@ -953,7 +1010,8 @@ onMounted(load);
|
||||
<p class="sync-sub-desc">
|
||||
تعداد دفعات در روز و ساعت هر بار را برای همین اتصال مشخص کنید. سرور در آن ساعتها، به وقت تهران،
|
||||
مشتریان تازه را وارد میکند و نام مشتریهای قبلی را هم با تهحساب تازه میکند. اگر شماره یکی باشد
|
||||
همان مشتری میماند، نام قبلی حفظ میشود و شماره به شکل ۰۹۱۲ ذخیره میشود. خاموش یعنی فقط ورود دستی.
|
||||
همان مشتری میماند و کد دیگر بهعنوان مشتری تازه وارد نمیشود. شماره به شکل ۰۹۱۲ ذخیره میشود.
|
||||
خاموش یعنی فقط ورود دستی.
|
||||
</p>
|
||||
<UiField label="تعداد در روز">
|
||||
<UiSelect
|
||||
@@ -1100,6 +1158,9 @@ onMounted(load);
|
||||
<h4 class="sync-results-title">
|
||||
نتایج جستجو ({{ syncVisibleResults.length }}<template v-if="syncOnlyNew"> از {{ syncResults.length }}</template>)
|
||||
</h4>
|
||||
<p v-if="duplicateCustomerCount" class="sync-sub-desc">
|
||||
{{ toFaDigits(duplicateCustomerCount) }} مشتری شمارهٔ تکراری دارند و جداگانه وارد نمیشوند؛ همان شخص با کد دیگری از قبل لینک است.
|
||||
</p>
|
||||
<div class="tc-row">
|
||||
<TableColumnsMenu table-key="tahesab.customers" align="end" />
|
||||
</div>
|
||||
@@ -1120,7 +1181,9 @@ onMounted(load);
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="!syncPagedResults.length">
|
||||
<td colspan="5" class="sync-empty-row">همهٔ مشتریان این نتایج قبلاً وارد شدهاند.</td>
|
||||
<td colspan="5" class="sync-empty-row">
|
||||
مشتری تازهای برای ورود نیست. شمارههای تکراری از قبل با کد دیگری لینک شدهاند.
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="r in syncPagedResults" :key="String(r.moshtariCode)">
|
||||
<td class="font-mono">{{ r.moshtariCode }}</td>
|
||||
@@ -1130,11 +1193,14 @@ onMounted(load);
|
||||
<UiBadge v-if="r.alreadyLinked" variant="success">
|
||||
لینک شده{{ r.personName ? ` (${r.personName})` : '' }}
|
||||
</UiBadge>
|
||||
<UiBadge v-else-if="duplicateOwner(r)" variant="warning">
|
||||
شماره تکراری، کد {{ toFaDigits(duplicateOwner(r)!.code) }}
|
||||
</UiBadge>
|
||||
<UiBadge v-else variant="neutral">آماده ورود</UiBadge>
|
||||
</td>
|
||||
<td>
|
||||
<UiButton
|
||||
v-if="!r.alreadyLinked"
|
||||
v-if="!r.alreadyLinked && !duplicateOwner(r)"
|
||||
size="sm"
|
||||
:disabled="!r.moshtariCode || syncBusy"
|
||||
@click="importOne(r.moshtariCode!)"
|
||||
@@ -1142,8 +1208,8 @@ onMounted(load);
|
||||
وارد کردن
|
||||
</UiButton>
|
||||
<RouterLink
|
||||
v-else-if="r.personId"
|
||||
:to="{ name: 'person-detail', params: { id: r.personId } }"
|
||||
v-else-if="r.personId || duplicateOwner(r)?.personId"
|
||||
:to="{ name: 'person-detail', params: { id: (r.personId || duplicateOwner(r)?.personId)! } }"
|
||||
>
|
||||
<UiButton variant="ghost" size="sm">
|
||||
مشاهده شخص
|
||||
|
||||
@@ -20,12 +20,20 @@ import {
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import { formatJalaliNumeric, rewriteGregorianDates, toFaDigits } from '@/lib/jalali';
|
||||
|
||||
type TabKey = 'generic' | 'daftareshoma';
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const error = ref('');
|
||||
const ok = ref('');
|
||||
const items = ref<VoipConnectionDto[]>([]);
|
||||
const calls = ref<VoipCallLogDto[]>([]);
|
||||
const tab = ref<TabKey>('daftareshoma');
|
||||
const callFilters = reactive({
|
||||
direction: '',
|
||||
status: '',
|
||||
lineExtension: '',
|
||||
});
|
||||
|
||||
const form = reactive({
|
||||
label: 'سانترال اصلی',
|
||||
@@ -34,12 +42,44 @@ const form = reactive({
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const webhookUrl = computed(() => {
|
||||
if (!items.value[0]) return '';
|
||||
const origin = typeof window !== 'undefined' ? window.location.origin : '';
|
||||
return `${origin}/api/public/integrations/voip/${items.value[0].id}/webhook`;
|
||||
const daftaForm = reactive({
|
||||
label: 'دفتر شما',
|
||||
apiToken: '',
|
||||
fromNumber: '',
|
||||
callerExtension: '',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const genericItems = computed(() =>
|
||||
items.value.filter((c) => c.provider !== 'daftareshoma'),
|
||||
);
|
||||
const daftaItems = computed(() =>
|
||||
items.value.filter((c) => c.provider === 'daftareshoma'),
|
||||
);
|
||||
|
||||
const activeDafta = computed(() => daftaItems.value[0] ?? null);
|
||||
|
||||
const knownLines = ref<string[]>([]);
|
||||
const lineOptions = computed(() => {
|
||||
const set = new Set(knownLines.value);
|
||||
for (const c of calls.value) {
|
||||
if (c.lineExtension) set.add(c.lineExtension);
|
||||
}
|
||||
if (callFilters.lineExtension) set.add(callFilters.lineExtension);
|
||||
return [...set].sort();
|
||||
});
|
||||
|
||||
const webhookUrlFor = (id: string | undefined) => {
|
||||
if (!id) return '';
|
||||
const origin = typeof window !== 'undefined' ? window.location.origin : '';
|
||||
return `${origin}/api/public/integrations/voip/${id}/webhook`;
|
||||
};
|
||||
|
||||
const genericWebhookUrl = computed(() =>
|
||||
webhookUrlFor(genericItems.value[0]?.id),
|
||||
);
|
||||
const daftaWebhookUrl = computed(() => webhookUrlFor(activeDafta.value?.id));
|
||||
|
||||
const statusLabel: Record<string, string> = {
|
||||
ringing: 'زنگ',
|
||||
answered: 'پاسخ',
|
||||
@@ -63,16 +103,32 @@ function noteLink(c: VoipCallLogDto): string | null {
|
||||
return '/notes';
|
||||
}
|
||||
|
||||
async function loadCalls() {
|
||||
const params: Record<string, string> = {};
|
||||
if (callFilters.direction) params.direction = callFilters.direction;
|
||||
if (callFilters.status) params.status = callFilters.status;
|
||||
if (callFilters.lineExtension) params.lineExtension = callFilters.lineExtension;
|
||||
const callRes = await api.get<VoipCallLogDto[]>('/integrations/voip/calls', {
|
||||
params,
|
||||
});
|
||||
calls.value = callRes.data;
|
||||
const merged = new Set(knownLines.value);
|
||||
for (const c of callRes.data) {
|
||||
if (c.lineExtension) merged.add(c.lineExtension);
|
||||
}
|
||||
knownLines.value = [...merged].sort();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const [connRes, callRes] = await Promise.all([
|
||||
const [connRes] = await Promise.all([
|
||||
api.get<VoipConnectionDto[]>('/integrations/voip/connections'),
|
||||
api.get<VoipCallLogDto[]>('/integrations/voip/calls'),
|
||||
loadCalls(),
|
||||
]);
|
||||
items.value = connRes.data;
|
||||
calls.value = callRes.data;
|
||||
fillDaftaFromActive();
|
||||
} catch (e) {
|
||||
if (axios.isAxiosError(e) && e.response?.status === 403) {
|
||||
error.value = 'ماژول تلفن سازمانی برای این محیط فعال نیست.';
|
||||
@@ -84,16 +140,30 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
async function create() {
|
||||
async function applyCallFilters() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
await loadCalls();
|
||||
} catch {
|
||||
error.value = 'فیلتر تماسها ناموفق بود.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function createGeneric() {
|
||||
if (!form.label.trim()) {
|
||||
error.value = 'نام اتصال را وارد کنید.';
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
const payload: CreateVoipConnectionRequest = {
|
||||
label: form.label.trim(),
|
||||
provider: 'generic',
|
||||
webhookSecret: form.webhookSecret.trim() || undefined,
|
||||
clickToCallUrl: form.clickToCallUrl.trim() || null,
|
||||
enabled: form.enabled,
|
||||
@@ -111,6 +181,65 @@ async function create() {
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDafta() {
|
||||
if (!daftaForm.label.trim()) {
|
||||
error.value = 'نام اتصال را وارد کنید.';
|
||||
return;
|
||||
}
|
||||
if (!activeDafta.value && !daftaForm.apiToken.trim()) {
|
||||
error.value = 'توکن API دفتر شما را وارد کنید.';
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
if (activeDafta.value) {
|
||||
await api.patch(`/integrations/voip/connections/${activeDafta.value.id}`, {
|
||||
label: daftaForm.label.trim(),
|
||||
fromNumber: daftaForm.fromNumber.trim() || null,
|
||||
callerExtension: daftaForm.callerExtension.trim() || null,
|
||||
enabled: daftaForm.enabled,
|
||||
...(daftaForm.apiToken.trim()
|
||||
? { apiToken: daftaForm.apiToken.trim() }
|
||||
: {}),
|
||||
});
|
||||
daftaForm.apiToken = '';
|
||||
ok.value = 'اتصال دفتر شما بروزرسانی شد.';
|
||||
} else {
|
||||
const payload: CreateVoipConnectionRequest = {
|
||||
label: daftaForm.label.trim(),
|
||||
provider: 'daftareshoma',
|
||||
apiToken: daftaForm.apiToken.trim(),
|
||||
fromNumber: daftaForm.fromNumber.trim() || null,
|
||||
callerExtension: daftaForm.callerExtension.trim() || null,
|
||||
enabled: daftaForm.enabled,
|
||||
};
|
||||
await api.post('/integrations/voip/connections', payload);
|
||||
daftaForm.apiToken = '';
|
||||
ok.value =
|
||||
'اتصال دفتر شما ذخیره شد. آدرس وبهوک را در پرتال دفتر شما ثبت کنید.';
|
||||
}
|
||||
await load();
|
||||
} catch (e) {
|
||||
error.value = axios.isAxiosError(e)
|
||||
? String((e.response?.data as { message?: string })?.message ?? 'ذخیره ناموفق بود.')
|
||||
: 'ذخیره ناموفق بود.';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fillDaftaFromActive() {
|
||||
const c = activeDafta.value;
|
||||
if (!c) return;
|
||||
daftaForm.label = c.label;
|
||||
daftaForm.fromNumber = c.fromNumber ?? '';
|
||||
daftaForm.callerExtension = c.callerExtension ?? '';
|
||||
daftaForm.enabled = c.enabled;
|
||||
daftaForm.apiToken = '';
|
||||
}
|
||||
|
||||
async function remove(id: string) {
|
||||
if (!confirm('این اتصال حذف شود؟')) return;
|
||||
try {
|
||||
@@ -121,18 +250,19 @@ async function remove(id: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function copyWebhook() {
|
||||
if (!webhookUrl.value) return;
|
||||
async function copyText(text: string, msg: string) {
|
||||
if (!text) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(webhookUrl.value);
|
||||
ok.value = 'آدرس وبهوک کپی شد.';
|
||||
await navigator.clipboard.writeText(text);
|
||||
ok.value = msg;
|
||||
} catch {
|
||||
error.value = 'کپی ممکن نشد.';
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
onMounted(async () => {
|
||||
await load();
|
||||
fillDaftaFromActive();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -150,81 +280,222 @@ onMounted(() => {
|
||||
</template>
|
||||
</UiPageHeader>
|
||||
|
||||
<nav class="tabs" aria-label="نوع اتصال تلفن">
|
||||
<button
|
||||
type="button"
|
||||
:class="{ on: tab === 'daftareshoma' }"
|
||||
@click="tab = 'daftareshoma'"
|
||||
>
|
||||
دفتر شما
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ on: tab === 'generic' }"
|
||||
@click="tab = 'generic'"
|
||||
>
|
||||
وبهوک عمومی
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<p v-if="ok" class="ok">{{ ok }}</p>
|
||||
|
||||
<UiCard title="اتصال جدید">
|
||||
<p class="hint">
|
||||
سانترال یا سرویس VoIP شما باید رویداد تماس را با JSON به آدرس وبهوک بفرستد.
|
||||
فیلدهای اصلی:
|
||||
<code>callId</code>،
|
||||
<code>direction</code> (inbound/outbound)،
|
||||
<code>status</code>،
|
||||
<code>from</code>،
|
||||
<code>to</code>.
|
||||
برای خلاصه خودکار یکی از
|
||||
<code>recordingUrl</code>
|
||||
(لینک فایل ضبط) یا
|
||||
<code>transcript</code>
|
||||
(متن آماده) را بفرستید؛ پس از
|
||||
<code>completed</code>
|
||||
/
|
||||
<code>answered</code>
|
||||
صف خلاصه ساخته میشود.
|
||||
امضا اختیاری با هدر
|
||||
<code>X-Voip-Signature</code>
|
||||
(HMAC-SHA256 هگز).
|
||||
</p>
|
||||
<div class="form-grid">
|
||||
<UiField label="نام">
|
||||
<UiInput v-model="form.label" placeholder="سانترال اصلی" />
|
||||
</UiField>
|
||||
<UiField label="رمز وبهوک (اختیاری)">
|
||||
<UiInput v-model="form.webhookSecret" placeholder="برای تأیید امضا" />
|
||||
</UiField>
|
||||
<UiField label="آدرس Click-to-Call (اختیاری)">
|
||||
<UiInput
|
||||
v-model="form.clickToCallUrl"
|
||||
placeholder="https://pbx.example/originate?num={number}"
|
||||
/>
|
||||
</UiField>
|
||||
</div>
|
||||
<UiButton :loading="saving" @click="create">ذخیره اتصال</UiButton>
|
||||
</UiCard>
|
||||
<template v-if="tab === 'daftareshoma'">
|
||||
<UiCard title="اتصال دفتر شما">
|
||||
<p class="hint">
|
||||
برای ثبت همه تماسهای ورودی و خروجی فقط توکن و وبهوک لازم است.
|
||||
توکن را از پرتال (توسعهدهندگان → API) بگیرید؛ بعد آدرس وبهوک را در
|
||||
<strong>تنظیمات → هوک</strong>
|
||||
با رویدادهای شروع/پایان ورودی و پایان خروجی ثبت کنید.
|
||||
فیلدهای شماره مبدأ و خط فقط برای «تماس از داخل CRM» اختیاریاند و بعداً قابل تکمیلاند.
|
||||
</p>
|
||||
<div class="form-grid">
|
||||
<UiField label="نام">
|
||||
<UiInput v-model="daftaForm.label" placeholder="دفتر شما" />
|
||||
</UiField>
|
||||
<UiField
|
||||
:label="activeDafta?.apiTokenSet ? 'توکن API (خالی = بدون تغییر)' : 'توکن API'"
|
||||
>
|
||||
<UiInput
|
||||
v-model="daftaForm.apiToken"
|
||||
type="password"
|
||||
placeholder="توکن از پرتال دفتر شما"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</UiField>
|
||||
<UiField label="شماره مبدأ — اختیاری (فقط تماس خروجی از CRM)">
|
||||
<UiInput
|
||||
v-model="daftaForm.fromNumber"
|
||||
placeholder="موبایل همکار برای click-to-call"
|
||||
dir="ltr"
|
||||
/>
|
||||
</UiField>
|
||||
<UiField label="خط پیشفرض — اختیاری (فقط تماس خروجی از CRM)">
|
||||
<UiInput
|
||||
v-model="daftaForm.callerExtension"
|
||||
placeholder="مثلاً 02128425990"
|
||||
dir="ltr"
|
||||
/>
|
||||
</UiField>
|
||||
</div>
|
||||
<UiButton :loading="saving" @click="saveDafta">
|
||||
{{ activeDafta ? 'بروزرسانی اتصال' : 'ذخیره اتصال دفتر شما' }}
|
||||
</UiButton>
|
||||
</UiCard>
|
||||
|
||||
<UiCard title="اتصالها">
|
||||
<UiEmptyState
|
||||
v-if="!loading && !items.length"
|
||||
title="اتصالی نیست"
|
||||
description="یک اتصال برای دریافت رویداد تماس بسازید."
|
||||
/>
|
||||
<div v-else class="list">
|
||||
<article v-for="c in items" :key="c.id" class="item">
|
||||
<div>
|
||||
<strong>{{ c.label }}</strong>
|
||||
<p class="muted">
|
||||
تماسهای ثبتشده {{ toFaDigits(c.callCount) }}
|
||||
·
|
||||
{{
|
||||
c.lastEventAt
|
||||
? `آخرین رویداد ${formatJalaliNumeric(new Date(c.lastEventAt))}`
|
||||
: 'هنوز رویدادی نیامده'
|
||||
}}
|
||||
</p>
|
||||
<p v-if="c.clickToCallUrl" class="muted">Click-to-Call فعال</p>
|
||||
<p v-if="c.lastError" class="warn">{{ c.lastError }}</p>
|
||||
</div>
|
||||
<UiButton variant="secondary" @click="remove(c.id)">حذف</UiButton>
|
||||
</article>
|
||||
</div>
|
||||
<div v-if="webhookUrl" class="webhook">
|
||||
<p class="hint">آدرس وبهوک:</p>
|
||||
<code>{{ webhookUrl }}</code>
|
||||
<UiButton variant="secondary" @click="copyWebhook">کپی</UiButton>
|
||||
</div>
|
||||
</UiCard>
|
||||
<UiCard title="اتصالهای دفتر شما">
|
||||
<UiEmptyState
|
||||
v-if="!loading && !daftaItems.length"
|
||||
title="اتصالی نیست"
|
||||
description="توکن و مشخصات خط را ذخیره کنید."
|
||||
/>
|
||||
<div v-else class="list">
|
||||
<article v-for="c in daftaItems" :key="c.id" class="item">
|
||||
<div>
|
||||
<strong>{{ c.label }}</strong>
|
||||
<p class="muted">
|
||||
تماسهای ثبتشده {{ toFaDigits(c.callCount) }}
|
||||
·
|
||||
{{
|
||||
c.lastEventAt
|
||||
? `آخرین رویداد ${formatJalaliNumeric(new Date(c.lastEventAt))}`
|
||||
: 'هنوز رویدادی نیامده'
|
||||
}}
|
||||
</p>
|
||||
<p class="muted">
|
||||
مبدأ {{ c.fromNumber || '—' }} · خط {{ c.callerExtension || '—' }}
|
||||
· توکن {{ c.apiTokenSet ? 'ثبت شده' : 'ندارد' }}
|
||||
</p>
|
||||
<p v-if="c.lastError" class="warn">{{ c.lastError }}</p>
|
||||
</div>
|
||||
<UiButton variant="secondary" @click="remove(c.id)">حذف</UiButton>
|
||||
</article>
|
||||
</div>
|
||||
<div v-if="daftaWebhookUrl" class="webhook">
|
||||
<p class="hint">
|
||||
آدرس وبهوک برای پرتال دفتر شما (رویدادها را با JSON به این آدرس POST کنید):
|
||||
</p>
|
||||
<code>{{ daftaWebhookUrl }}</code>
|
||||
<UiButton
|
||||
variant="secondary"
|
||||
@click="copyText(daftaWebhookUrl, 'آدرس وبهوک دفتر شما کپی شد.')"
|
||||
>
|
||||
کپی
|
||||
</UiButton>
|
||||
</div>
|
||||
</UiCard>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<UiCard title="اتصال جدید">
|
||||
<p class="hint">
|
||||
سانترال یا سرویس VoIP شما باید رویداد تماس را با JSON به آدرس وبهوک بفرستد.
|
||||
فیلدهای اصلی:
|
||||
<code>callId</code>،
|
||||
<code>direction</code> (inbound/outbound)،
|
||||
<code>status</code>،
|
||||
<code>from</code>،
|
||||
<code>to</code>.
|
||||
برای خلاصه خودکار یکی از
|
||||
<code>recordingUrl</code>
|
||||
(لینک فایل ضبط) یا
|
||||
<code>transcript</code>
|
||||
(متن آماده) را بفرستید؛ پس از
|
||||
<code>completed</code>
|
||||
/
|
||||
<code>answered</code>
|
||||
صف خلاصه ساخته میشود.
|
||||
امضا اختیاری با هدر
|
||||
<code>X-Voip-Signature</code>
|
||||
(HMAC-SHA256 هگز).
|
||||
</p>
|
||||
<div class="form-grid">
|
||||
<UiField label="نام">
|
||||
<UiInput v-model="form.label" placeholder="سانترال اصلی" />
|
||||
</UiField>
|
||||
<UiField label="رمز وبهوک (اختیاری)">
|
||||
<UiInput v-model="form.webhookSecret" placeholder="برای تأیید امضا" />
|
||||
</UiField>
|
||||
<UiField label="آدرس Click-to-Call (اختیاری)">
|
||||
<UiInput
|
||||
v-model="form.clickToCallUrl"
|
||||
placeholder="https://pbx.example/originate?num={number}"
|
||||
/>
|
||||
</UiField>
|
||||
</div>
|
||||
<UiButton :loading="saving" @click="createGeneric">ذخیره اتصال</UiButton>
|
||||
</UiCard>
|
||||
|
||||
<UiCard title="اتصالها">
|
||||
<UiEmptyState
|
||||
v-if="!loading && !genericItems.length"
|
||||
title="اتصالی نیست"
|
||||
description="یک اتصال برای دریافت رویداد تماس بسازید."
|
||||
/>
|
||||
<div v-else class="list">
|
||||
<article v-for="c in genericItems" :key="c.id" class="item">
|
||||
<div>
|
||||
<strong>{{ c.label }}</strong>
|
||||
<p class="muted">
|
||||
تماسهای ثبتشده {{ toFaDigits(c.callCount) }}
|
||||
·
|
||||
{{
|
||||
c.lastEventAt
|
||||
? `آخرین رویداد ${formatJalaliNumeric(new Date(c.lastEventAt))}`
|
||||
: 'هنوز رویدادی نیامده'
|
||||
}}
|
||||
</p>
|
||||
<p v-if="c.clickToCallUrl" class="muted">Click-to-Call فعال</p>
|
||||
<p v-if="c.lastError" class="warn">{{ c.lastError }}</p>
|
||||
</div>
|
||||
<UiButton variant="secondary" @click="remove(c.id)">حذف</UiButton>
|
||||
</article>
|
||||
</div>
|
||||
<div v-if="genericWebhookUrl" class="webhook">
|
||||
<p class="hint">آدرس وبهوک:</p>
|
||||
<code>{{ genericWebhookUrl }}</code>
|
||||
<UiButton
|
||||
variant="secondary"
|
||||
@click="copyText(genericWebhookUrl, 'آدرس وبهوک کپی شد.')"
|
||||
>
|
||||
کپی
|
||||
</UiButton>
|
||||
</div>
|
||||
</UiCard>
|
||||
</template>
|
||||
|
||||
<UiCard title="آخرین تماسها">
|
||||
<div class="call-filters">
|
||||
<UiField label="جهت">
|
||||
<select v-model="callFilters.direction" class="filter-select" @change="applyCallFilters">
|
||||
<option value="">همه</option>
|
||||
<option value="inbound">ورودی</option>
|
||||
<option value="outbound">خروجی</option>
|
||||
</select>
|
||||
</UiField>
|
||||
<UiField label="وضعیت">
|
||||
<select v-model="callFilters.status" class="filter-select" @change="applyCallFilters">
|
||||
<option value="">همه</option>
|
||||
<option value="ringing">زنگ</option>
|
||||
<option value="answered">پاسخ</option>
|
||||
<option value="missed">از دسترفته</option>
|
||||
<option value="completed">تمامشده</option>
|
||||
<option value="failed">ناموفق</option>
|
||||
</select>
|
||||
</UiField>
|
||||
<UiField label="خط">
|
||||
<select
|
||||
v-model="callFilters.lineExtension"
|
||||
class="filter-select"
|
||||
@change="applyCallFilters"
|
||||
>
|
||||
<option value="">همه خطوط</option>
|
||||
<option v-for="line in lineOptions" :key="line" :value="line">
|
||||
{{ line }}
|
||||
</option>
|
||||
</select>
|
||||
</UiField>
|
||||
</div>
|
||||
<UiEmptyState
|
||||
v-if="!calls.length"
|
||||
title="تماسی نیست"
|
||||
@@ -239,6 +510,7 @@ onMounted(() => {
|
||||
<tr>
|
||||
<th>جهت</th>
|
||||
<th>وضعیت</th>
|
||||
<th>خط</th>
|
||||
<th>از / به</th>
|
||||
<th>مشتری</th>
|
||||
<th>مدت</th>
|
||||
@@ -250,6 +522,7 @@ onMounted(() => {
|
||||
<tr v-for="c in calls" :key="c.id">
|
||||
<td>{{ c.direction === 'outbound' ? 'خروجی' : 'ورودی' }}</td>
|
||||
<td>{{ statusLabel[c.status] ?? c.status }}</td>
|
||||
<td dir="ltr">{{ c.lineExtension || '—' }}</td>
|
||||
<td>{{ c.fromNumber || '—' }} → {{ c.toNumber || '—' }}</td>
|
||||
<td>{{ c.personName || '—' }}</td>
|
||||
<td>
|
||||
@@ -294,6 +567,28 @@ onMounted(() => {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
.tabs {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
gap: 1.75rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
}
|
||||
.tabs button {
|
||||
appearance: none;
|
||||
background: none;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -1px;
|
||||
padding: 0.55rem 0.15rem;
|
||||
color: #94a3b8;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tabs button.on {
|
||||
color: #0d9488;
|
||||
border-bottom-color: #14b8a6;
|
||||
}
|
||||
.hint,
|
||||
.muted {
|
||||
color: #64748b;
|
||||
@@ -312,6 +607,21 @@ onMounted(() => {
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0 1rem;
|
||||
}
|
||||
.call-filters {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.filter-select {
|
||||
width: 100%;
|
||||
min-height: 36px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
padding: 0.35rem 0.6rem;
|
||||
background: #fff;
|
||||
font: inherit;
|
||||
}
|
||||
.list {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
@@ -404,7 +714,8 @@ th {
|
||||
color: #0f766e;
|
||||
}
|
||||
@media (max-width: 800px) {
|
||||
.form-grid {
|
||||
.form-grid,
|
||||
.call-filters {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,12 +16,16 @@ import {
|
||||
Space as ASpace,
|
||||
Statistic as AStatistic,
|
||||
Table as ATable,
|
||||
Descriptions as ADescriptions,
|
||||
DescriptionsItem as ADescriptionsItem,
|
||||
List as AList,
|
||||
} from 'ant-design-vue';
|
||||
import type { TableColumnsType } from 'ant-design-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import type { FinancialAccountDto, FinancialMovementDto } from '@mento/shared';
|
||||
import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
import { formatJalaliNumeric } from '@/lib/jalali';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
import { useTreasuryPageChrome } from './treasuryPageChrome';
|
||||
@@ -37,6 +41,8 @@ const reason = ref('');
|
||||
const note = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const columns: TableColumnsType<FinancialMovementDto> = [
|
||||
{
|
||||
title: 'تاریخ',
|
||||
@@ -168,7 +174,7 @@ onUnmounted(() => {
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="موجودی واقعی">
|
||||
<MoneyInput v-model="stated" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="stated" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
@@ -190,8 +196,29 @@ onUnmounted(() => {
|
||||
|
||||
<a-divider orientation="right">گردش حساب</a-divider>
|
||||
<a-empty v-if="!items.length" description="گردشی ثبت نشده است." />
|
||||
<a-list v-else-if="isMobile" :data-source="items">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<a-card :title="formatJalaliNumeric(new Date(item.occurredAt))" style="width: 100%">
|
||||
<a-descriptions :column="1" bordered>
|
||||
<a-descriptions-item label="شرح">{{ item.memo || '—' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="نوع">{{ item.kindLabel }}</a-descriptions-item>
|
||||
<a-descriptions-item label="ورودی">
|
||||
{{ item.direction === 'in' ? toman(item.amount) : '—' }}
|
||||
</a-descriptions-item>
|
||||
<a-descriptions-item label="خروجی">
|
||||
{{ item.direction === 'out' ? toman(item.amount) : '—' }}
|
||||
</a-descriptions-item>
|
||||
<a-descriptions-item label="مانده">
|
||||
{{ item.balanceAfter ? toman(item.balanceAfter) : '—' }}
|
||||
</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
</a-card>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
<a-table
|
||||
v-else
|
||||
v-else-if="items.length"
|
||||
:columns="columns"
|
||||
:data-source="items"
|
||||
:pagination="false"
|
||||
|
||||
@@ -27,9 +27,11 @@ import type { FinancialAccountDto, FinancialAccountType, OrgUserDto } from '@men
|
||||
import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ASelectOption = ASelect.Option;
|
||||
@@ -315,7 +317,7 @@ onMounted(() => {
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="موجودی اولیه" name="openingBalance">
|
||||
<MoneyInput v-model="form.openingBalance" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="form.openingBalance" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
@@ -400,7 +402,7 @@ onMounted(() => {
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
|
||||
>
|
||||
<MoneyInput v-model="transfer.amount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="transfer.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
@@ -420,7 +422,7 @@ onMounted(() => {
|
||||
|
||||
<a-divider orientation="right">فهرست حسابها</a-divider>
|
||||
<a-empty v-if="!accounts.length" description="حسابی ثبت نشده است." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="accounts">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="accounts">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
|
||||
@@ -23,8 +23,10 @@ import {
|
||||
} from 'ant-design-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import type { FinancialCategoryDto } from '@mento/shared';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ASelectOption = ASelect.Option;
|
||||
@@ -151,7 +153,7 @@ onMounted(() => {
|
||||
|
||||
<a-divider orientation="right">درآمد</a-divider>
|
||||
<a-empty v-if="!incomeRows.length" description="دسته درآمدی نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="incomeRows">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="incomeRows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
@@ -176,7 +178,7 @@ onMounted(() => {
|
||||
|
||||
<a-divider orientation="right">هزینه</a-divider>
|
||||
<a-empty v-if="!expenseRows.length" description="دسته هزینهای نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="expenseRows">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="expenseRows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
|
||||
@@ -158,7 +158,7 @@ onMounted(() => {
|
||||
<UiCard title="سند جدید">
|
||||
<div class="grid">
|
||||
<UiField label="عنوان"><UiInput v-model="form.title" /></UiField>
|
||||
<UiField label="مبلغ کل"><MoneyInput v-model="form.amount" :decimals="0" /></UiField>
|
||||
<UiField label="مبلغ کل"><MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" /></UiField>
|
||||
<UiField label="دستهبندی">
|
||||
<select v-model="form.categoryId" class="select">
|
||||
<option value="">بدون دسته</option>
|
||||
@@ -166,7 +166,7 @@ onMounted(() => {
|
||||
</select>
|
||||
</UiField>
|
||||
<UiField label="طرف حساب"><UiInput v-model="form.partyName" /></UiField>
|
||||
<UiField :label="settleLabel"><MoneyInput v-model="form.settleAmount" :decimals="0" /></UiField>
|
||||
<UiField :label="settleLabel"><MoneyInput addon-after="تومان" v-model="form.settleAmount" :decimals="0" /></UiField>
|
||||
<UiField label="حساب">
|
||||
<select v-model="form.accountId" class="select">
|
||||
<option value="">انتخاب حساب</option>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
@@ -14,11 +14,13 @@ import {
|
||||
Input as AInput,
|
||||
List as AList,
|
||||
Row as ARow,
|
||||
Segmented as ASegmented,
|
||||
Select as ASelect,
|
||||
Typography,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatLocalDateInput } from '@/lib/jalali';
|
||||
import type {
|
||||
FinancialAccountDto,
|
||||
FinancialCategoryDto,
|
||||
@@ -26,11 +28,13 @@ import type {
|
||||
FinancialPartyKind,
|
||||
TreasuryPartyBalanceDto,
|
||||
} from '@mento/shared';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
|
||||
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
|
||||
import { useSettleDefault } from '@/components/treasury/useSettleDefault';
|
||||
import { toman } from './treasury-format';
|
||||
import { partyNetPosition, toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
@@ -38,9 +42,11 @@ const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ASelectOption = ASelect.Option;
|
||||
|
||||
const isMobile = useTreasuryMobile();
|
||||
const kind = 'expense' as const;
|
||||
const rows = ref<FinancialDocumentDto[]>([]);
|
||||
const balances = ref<TreasuryPartyBalanceDto[]>([]);
|
||||
const receivableBalances = ref<TreasuryPartyBalanceDto[]>([]);
|
||||
const categories = ref<FinancialCategoryDto[]>([]);
|
||||
const accounts = ref<FinancialAccountDto[]>([]);
|
||||
const error = ref('');
|
||||
@@ -57,10 +63,17 @@ const form = ref({
|
||||
settleAmount: '',
|
||||
method: 'transfer',
|
||||
notes: '',
|
||||
bookedAt: formatLocalDateInput(new Date()),
|
||||
});
|
||||
const settleMirror = useSettleDefault(form);
|
||||
|
||||
const settleLabel = 'مبلغ پرداختشده';
|
||||
const entryMode = ref<'settlement' | 'accrual'>('settlement');
|
||||
const isSettlement = computed(() => entryMode.value === 'settlement');
|
||||
const entryOptions = [
|
||||
{ label: 'پرداخت', value: 'settlement' },
|
||||
{ label: 'هزینه', value: 'accrual' },
|
||||
];
|
||||
const statusLabel: Record<string, string> = {
|
||||
open: 'پرداختنشده',
|
||||
partial: 'جزئی',
|
||||
@@ -94,17 +107,32 @@ function docLine(item: FinancialDocumentDto) {
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const [docs, cats, acc, bals] = await Promise.all([
|
||||
const [docs, cats, acc, bals, receivables] = await Promise.all([
|
||||
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
|
||||
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }),
|
||||
api.get<FinancialAccountDto[]>('/treasury/accounts'),
|
||||
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }).catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
|
||||
return { data: [] as FinancialCategoryDto[] };
|
||||
}
|
||||
throw e;
|
||||
}),
|
||||
api.get<FinancialAccountDto[]>('/treasury/accounts').catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
|
||||
return { data: [] as FinancialAccountDto[] };
|
||||
}
|
||||
throw e;
|
||||
}),
|
||||
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind } }).catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
|
||||
throw e;
|
||||
}),
|
||||
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind: 'income' } }).catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
|
||||
throw e;
|
||||
}),
|
||||
]);
|
||||
rows.value = docs.data;
|
||||
balances.value = bals.data;
|
||||
receivableBalances.value = receivables.data;
|
||||
categories.value = cats.data.filter((row) => row.isActive);
|
||||
accounts.value = acc.data.filter((row) => row.isActive);
|
||||
}
|
||||
@@ -118,33 +146,61 @@ async function createDoc() {
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
const amount = parseMoneyNumber(String(form.value.amount ?? ''), 0);
|
||||
const settlement = isSettlement.value;
|
||||
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
const amount = settlement
|
||||
? settleAmount
|
||||
: parseMoneyNumber(String(form.value.amount ?? ''), 0);
|
||||
if (amount == null || amount <= 0) {
|
||||
error.value = 'مبلغ کل معتبر نیست.';
|
||||
error.value = settlement ? 'مبلغ پرداختشده معتبر نیست.' : 'مبلغ کل معتبر نیست.';
|
||||
return;
|
||||
}
|
||||
if (!form.value.partyKind || (form.value.partyKind !== 'other' && !form.value.partyId)) {
|
||||
error.value = 'طرف حساب را انتخاب کنید.';
|
||||
return;
|
||||
}
|
||||
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
if (form.value.partyKind === 'other' && settleAmount !== amount) {
|
||||
if (settlement && form.value.partyKind === 'other') {
|
||||
error.value = 'برای پرداخت، طرف حساب واقعی لازم است.';
|
||||
return;
|
||||
}
|
||||
if (!settlement && form.value.partyKind === 'other' && settleAmount !== amount) {
|
||||
error.value = 'برای سایر، مبلغ پرداختشده باید با مبلغ کل یکی باشد.';
|
||||
return;
|
||||
}
|
||||
if (!settlement && settleAmount > amount) {
|
||||
error.value = 'مبلغ پرداختشده از مبلغ کل بیشتر است.';
|
||||
return;
|
||||
}
|
||||
if ((settlement || settleAmount > 0) && !form.value.accountId) {
|
||||
error.value = 'حساب را انتخاب کنید.';
|
||||
return;
|
||||
}
|
||||
const partyKey =
|
||||
form.value.partyKind && form.value.partyKind !== 'other' && form.value.partyId
|
||||
? `${form.value.partyKind}:${form.value.partyId}`
|
||||
: '';
|
||||
const payable = partyKey
|
||||
? Number(balances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
|
||||
: 0;
|
||||
const receivable = partyKey
|
||||
? Number(receivableBalances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
|
||||
: 0;
|
||||
const collectsBalance = settlement && (payable > 0 || receivable > 0);
|
||||
const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
|
||||
kind,
|
||||
settlement,
|
||||
title: form.value.title,
|
||||
amount,
|
||||
categoryId: form.value.categoryId || null,
|
||||
categoryId: settlement ? null : form.value.categoryId || null,
|
||||
partyKind: form.value.partyKind,
|
||||
personId: form.value.partyKind === 'person' ? form.value.partyId : null,
|
||||
companyId: form.value.partyKind === 'company' ? form.value.partyId : null,
|
||||
userId: form.value.partyKind === 'user' ? form.value.partyId : null,
|
||||
accountId: form.value.accountId || null,
|
||||
settleAmount,
|
||||
settleAmount: settlement ? amount : settleAmount,
|
||||
method: form.value.method,
|
||||
notes: form.value.notes || null,
|
||||
bookedAt: form.value.bookedAt || undefined,
|
||||
});
|
||||
settleMirror.reset();
|
||||
form.value = {
|
||||
@@ -157,10 +213,13 @@ async function createDoc() {
|
||||
settleAmount: '',
|
||||
method: 'transfer',
|
||||
notes: '',
|
||||
bookedAt: formatLocalDateInput(new Date()),
|
||||
};
|
||||
ok.value = data.reference
|
||||
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
|
||||
: 'سند ثبت شد.';
|
||||
ok.value = collectsBalance
|
||||
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
|
||||
: data.reference
|
||||
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
|
||||
: 'سند ثبت شد.';
|
||||
await load();
|
||||
} catch (e) {
|
||||
error.value = apiMessage(e);
|
||||
@@ -169,6 +228,57 @@ async function createDoc() {
|
||||
}
|
||||
}
|
||||
|
||||
const partyRules = [
|
||||
{
|
||||
validator: async () => {
|
||||
if (!form.value.partyKind) throw new Error('طرف حساب الزامی است');
|
||||
if (isSettlement.value && form.value.partyKind === 'other') {
|
||||
throw new Error('برای پرداخت، طرف حساب واقعی لازم است');
|
||||
}
|
||||
if (form.value.partyKind !== 'other' && !form.value.partyId) {
|
||||
throw new Error('طرف حساب را انتخاب کنید');
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const accountRules = [
|
||||
{
|
||||
validator: async () => {
|
||||
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
if ((isSettlement.value || settled > 0) && !form.value.accountId) {
|
||||
throw new Error('حساب را انتخاب کنید');
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const remainingAmount = computed(() => {
|
||||
const total = parseMoneyNumber(String(form.value.amount ?? ''), 0) ?? 0;
|
||||
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
return Math.max(0, total - settled);
|
||||
});
|
||||
|
||||
watch(entryMode, () => {
|
||||
settleMirror.reset();
|
||||
form.value.amount = '';
|
||||
form.value.settleAmount = '';
|
||||
if (isSettlement.value && form.value.partyKind === 'other') {
|
||||
form.value.partyKind = undefined;
|
||||
form.value.partyId = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const partyPosition = computed(() => {
|
||||
const partyKind = form.value.partyKind;
|
||||
const id = form.value.partyId;
|
||||
if (!partyKind || partyKind === 'other' || !id) return null;
|
||||
const key = `${partyKind}:${id}`;
|
||||
const receivable = Number(receivableBalances.value.find((item) => item.key === key)?.remaining || 0);
|
||||
const payable = Number(balances.value.find((item) => item.key === key)?.remaining || 0);
|
||||
return partyNetPosition(receivable, payable);
|
||||
});
|
||||
|
||||
async function voidDoc(id: string) {
|
||||
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return;
|
||||
try {
|
||||
@@ -192,7 +302,10 @@ onMounted(() => {
|
||||
<a-alert v-if="ok" type="success" show-icon :message="ok" />
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-divider orientation="right">سند جدید</a-divider>
|
||||
<a-flex align="center" justify="space-between" wrap="wrap" gap="small">
|
||||
<a-typography-text strong>سند جدید</a-typography-text>
|
||||
<a-segmented v-model:value="entryMode" :options="entryOptions" />
|
||||
</a-flex>
|
||||
<a-form
|
||||
layout="vertical"
|
||||
:model="form"
|
||||
@@ -200,6 +313,23 @@ onMounted(() => {
|
||||
@finishFailed="onFinishFailed"
|
||||
>
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
|
||||
<a-row :gutter="8" align="middle">
|
||||
<a-col :span="partyPosition ? 16 : 24">
|
||||
<TreasuryPartySelect
|
||||
v-model:kind="form.partyKind"
|
||||
v-model:party-id="form.partyId"
|
||||
:allow-other="!isSettlement"
|
||||
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
|
||||
/>
|
||||
</a-col>
|
||||
<a-col v-if="partyPosition" :span="8">
|
||||
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item
|
||||
label="عنوان"
|
||||
@@ -209,21 +339,35 @@ onMounted(() => {
|
||||
<a-input v-model:value="form.title" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="8">
|
||||
<a-form-item
|
||||
label="مبلغ کل"
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
|
||||
>
|
||||
<MoneyInput v-model="form.amount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item :label="settleLabel" name="settleAmount">
|
||||
<MoneyInput v-model="form.settleAmount" :decimals="0" :disabled="form.partyKind === 'other'" />
|
||||
<a-form-item
|
||||
:label="settleLabel"
|
||||
name="settleAmount"
|
||||
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
|
||||
>
|
||||
<MoneyInput
|
||||
addon-after="تومان"
|
||||
v-model="form.settleAmount"
|
||||
:decimals="0"
|
||||
:disabled="!isSettlement && form.partyKind === 'other'"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="8">
|
||||
<a-form-item label="مانده این سند">
|
||||
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="8">
|
||||
<a-form-item label="دستهبندی" name="categoryId">
|
||||
<a-select show-search option-filter-prop="label"
|
||||
v-model:value="form.categoryId"
|
||||
@@ -238,12 +382,7 @@ onMounted(() => {
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="طرف حساب" name="partyKind">
|
||||
<TreasuryPartySelect v-model:kind="form.partyKind" v-model:party-id="form.partyId" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="حساب" name="accountId">
|
||||
<a-form-item label="حساب" name="accountId" :rules="accountRules">
|
||||
<a-select show-search option-filter-prop="label"
|
||||
v-model:value="form.accountId"
|
||||
allow-clear
|
||||
@@ -265,8 +404,18 @@ onMounted(() => {
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="تاریخ" name="bookedAt">
|
||||
<JalaliDateInput v-model="form.bookedAt" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="!isSettlement" :span="24">
|
||||
<a-form-item label="توضیحات" name="notes">
|
||||
<a-input v-model:value="form.notes" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
<a-button type="primary" html-type="submit" :loading="saving">ثبت</a-button>
|
||||
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
|
||||
</a-form>
|
||||
|
||||
<a-divider orientation="right">مانده پرداختنی</a-divider>
|
||||
@@ -290,10 +439,10 @@ onMounted(() => {
|
||||
</a-form>
|
||||
|
||||
<a-empty v-if="!rows.length" description="سندی نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="rows">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
<template v-if="!isMobile" #actions>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
<a-button
|
||||
v-if="item.status !== 'void'"
|
||||
@@ -304,7 +453,29 @@ onMounted(() => {
|
||||
ابطال
|
||||
</a-button>
|
||||
</template>
|
||||
<a-list-item-meta>
|
||||
<a-flex v-if="isMobile" vertical :gap="4" style="width: 100%">
|
||||
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
|
||||
<a-typography-text strong>{{ item.title }}</a-typography-text>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-typography-text type="secondary">
|
||||
{{ item.partyName || 'بدون طرف حساب' }} · {{ statusLabel[item.status] ?? item.status }}
|
||||
</a-typography-text>
|
||||
<a-typography-text v-if="item.reference" type="secondary">پیگیری {{ item.reference }}</a-typography-text>
|
||||
<a-typography-text v-if="item.categoryName" type="secondary">{{ item.categoryName }}</a-typography-text>
|
||||
<a-flex justify="space-between" align="center">
|
||||
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
|
||||
<a-button
|
||||
v-if="item.status !== 'void'"
|
||||
type="link"
|
||||
danger
|
||||
@click="voidDoc(item.id)"
|
||||
>
|
||||
ابطال
|
||||
</a-button>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
<a-list-item-meta v-else>
|
||||
<template #title>{{ item.title }}</template>
|
||||
<template #description>{{ docLine(item) }}</template>
|
||||
</a-list-item-meta>
|
||||
|
||||
@@ -15,8 +15,10 @@ import {
|
||||
import { api } from '@/lib/api';
|
||||
import type { TreasuryDashboardDto } from '@mento/shared';
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
|
||||
@@ -28,9 +30,9 @@ const cards = [
|
||||
{ key: 'actualReceipts', label: 'دریافت واقعی', hint: 'ورود به حساب' },
|
||||
{ key: 'bookedExpense', label: 'هزینه ثبتشده', hint: 'تعهدی' },
|
||||
{ key: 'actualPayments', label: 'پرداخت واقعی', hint: 'خروج از حساب' },
|
||||
{ key: 'operatingProfit', label: 'سود یا زیان عملیاتی', hint: 'درآمد ثبتشده − هزینه ثبتشده' },
|
||||
{ key: 'receivables', label: 'مطالبات وصولنشده', hint: 'درآمد بدون دریافت کامل' },
|
||||
{ key: 'payables', label: 'تعهدات پرداخت', hint: 'هزینه بدون پرداخت کامل' },
|
||||
{ key: 'operatingProfit', label: 'سود یا زیان عملیاتی', hint: 'درآمد و فروش فاکتور − هزینه' },
|
||||
{ key: 'receivables', label: 'مطالبات وصولنشده', hint: 'اسناد باز و مانده فاکتور' },
|
||||
{ key: 'payables', label: 'تعهدات پرداخت', hint: 'هزینه باز، حقوق و برگشتی' },
|
||||
{ key: 'totalBalance', label: 'موجودی حسابها', hint: 'صندوق و بانک' },
|
||||
] as const;
|
||||
|
||||
@@ -75,7 +77,7 @@ onMounted(async () => {
|
||||
/>
|
||||
<a-list
|
||||
v-else
|
||||
item-layout="horizontal"
|
||||
:item-layout="isMobile ? 'vertical' : 'horizontal'"
|
||||
:data-source="data.upcomingInstallments"
|
||||
>
|
||||
<template #renderItem="{ item }">
|
||||
@@ -102,7 +104,7 @@ onMounted(async () => {
|
||||
/>
|
||||
<a-list
|
||||
v-else
|
||||
item-layout="horizontal"
|
||||
:item-layout="isMobile ? 'vertical' : 'horizontal'"
|
||||
:data-source="data.upcomingPayables"
|
||||
>
|
||||
<template #renderItem="{ item }">
|
||||
@@ -127,7 +129,7 @@ onMounted(async () => {
|
||||
/>
|
||||
<a-list
|
||||
v-else
|
||||
item-layout="horizontal"
|
||||
:item-layout="isMobile ? 'vertical' : 'horizontal'"
|
||||
:data-source="data.recent"
|
||||
>
|
||||
<template #renderItem="{ item }">
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, h, onMounted, ref } from 'vue';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
Alert as AAlert,
|
||||
Avatar as AAvatar,
|
||||
Button as AButton,
|
||||
Card as ACard,
|
||||
Col as ACol,
|
||||
@@ -18,23 +17,9 @@ import {
|
||||
Row as ARow,
|
||||
Segmented as ASegmented,
|
||||
Select as ASelect,
|
||||
Space as ASpace,
|
||||
Textarea as ATextarea,
|
||||
Typography,
|
||||
message,
|
||||
theme,
|
||||
} from 'ant-design-vue';
|
||||
import type { FormInstance } from 'ant-design-vue';
|
||||
import {
|
||||
ArrowDownOutlined,
|
||||
BankOutlined,
|
||||
CheckOutlined,
|
||||
ClockCircleOutlined,
|
||||
CreditCardOutlined,
|
||||
FileTextOutlined,
|
||||
InfoCircleOutlined,
|
||||
TagOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatLocalDateInput } from '@/lib/jalali';
|
||||
import type {
|
||||
@@ -42,7 +27,6 @@ import type {
|
||||
FinancialCategoryDto,
|
||||
FinancialDocumentDto,
|
||||
FinancialPartyKind,
|
||||
TreasuryDashboardDto,
|
||||
TreasuryPartyBalanceDto,
|
||||
} from '@mento/shared';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
@@ -50,29 +34,26 @@ import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
|
||||
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
|
||||
import { useSettleDefault } from '@/components/treasury/useSettleDefault';
|
||||
import { toman } from './treasury-format';
|
||||
import { partyNetPosition, toman } from './treasury-format';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ASelectOption = ASelect.Option;
|
||||
const { token } = theme.useToken();
|
||||
const screens = Grid.useBreakpoint();
|
||||
const isMobile = computed(() => !screens.value.md);
|
||||
|
||||
const kind = 'income' as const;
|
||||
const rows = ref<FinancialDocumentDto[]>([]);
|
||||
const balances = ref<TreasuryPartyBalanceDto[]>([]);
|
||||
const payableBalances = ref<TreasuryPartyBalanceDto[]>([]);
|
||||
const categories = ref<FinancialCategoryDto[]>([]);
|
||||
const accounts = ref<FinancialAccountDto[]>([]);
|
||||
const dashboard = ref<TreasuryDashboardDto | null>(null);
|
||||
const error = ref('');
|
||||
const ok = ref('');
|
||||
const saving = ref(false);
|
||||
const q = ref('');
|
||||
const formTab = ref<'main' | 'extra'>('main');
|
||||
const mobileFormRef = ref<FormInstance>();
|
||||
|
||||
function emptyForm() {
|
||||
return {
|
||||
@@ -93,6 +74,12 @@ const form = ref(emptyForm());
|
||||
const settleMirror = useSettleDefault(form);
|
||||
|
||||
const settleLabel = 'مبلغ دریافتشده';
|
||||
const entryMode = ref<'settlement' | 'accrual'>('settlement');
|
||||
const isSettlement = computed(() => entryMode.value === 'settlement');
|
||||
const entryOptions = [
|
||||
{ label: 'دریافت', value: 'settlement' },
|
||||
{ label: 'درآمد', value: 'accrual' },
|
||||
];
|
||||
const statusLabel: Record<string, string> = {
|
||||
open: 'دریافتنشده',
|
||||
partial: 'جزئی',
|
||||
@@ -108,19 +95,51 @@ const methodOptions = [
|
||||
{ value: 'other', label: 'سایر' },
|
||||
];
|
||||
|
||||
const formTabOptions = [
|
||||
const partyRules = [
|
||||
{
|
||||
value: 'main',
|
||||
payload: 'main',
|
||||
label: h('span', {}, [h(InfoCircleOutlined), ' اطلاعات اصلی']),
|
||||
},
|
||||
{
|
||||
value: 'extra',
|
||||
payload: 'extra',
|
||||
label: h('span', {}, [h(FileTextOutlined), ' جزئیات تکمیلی']),
|
||||
validator: async () => {
|
||||
if (!form.value.partyKind) throw new Error('طرف حساب الزامی است');
|
||||
if (isSettlement.value && form.value.partyKind === 'other') {
|
||||
throw new Error('برای دریافت، طرف حساب واقعی لازم است');
|
||||
}
|
||||
if (form.value.partyKind !== 'other' && !form.value.partyId) {
|
||||
throw new Error('طرف حساب را انتخاب کنید');
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const accountRules = [
|
||||
{
|
||||
validator: async () => {
|
||||
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
if ((isSettlement.value || settled > 0) && !form.value.accountId) {
|
||||
throw new Error('حساب را انتخاب کنید');
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const partyPosition = computed(() => {
|
||||
const partyKind = form.value.partyKind;
|
||||
const id = form.value.partyId;
|
||||
if (!partyKind || partyKind === 'other' || !id) return null;
|
||||
const key = `${partyKind}:${id}`;
|
||||
const receivable = Number(balances.value.find((item) => item.key === key)?.remaining || 0);
|
||||
const payable = Number(payableBalances.value.find((item) => item.key === key)?.remaining || 0);
|
||||
return partyNetPosition(receivable, payable);
|
||||
});
|
||||
|
||||
watch(entryMode, () => {
|
||||
settleMirror.reset();
|
||||
form.value.amount = '';
|
||||
form.value.settleAmount = '';
|
||||
if (isSettlement.value && form.value.partyKind === 'other') {
|
||||
form.value.partyKind = undefined;
|
||||
form.value.partyId = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const remainingAmount = computed(() => {
|
||||
const total = parseMoneyNumber(String(form.value.amount ?? ''), 0) ?? 0;
|
||||
const settled = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
@@ -149,27 +168,39 @@ function docLine(item: FinancialDocumentDto) {
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const [docs, cats, acc, dash, bals] = await Promise.all([
|
||||
const [docs, cats, acc, bals, payables] = await Promise.all([
|
||||
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
|
||||
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }),
|
||||
api.get<FinancialAccountDto[]>('/treasury/accounts'),
|
||||
api.get<TreasuryDashboardDto>('/treasury/dashboard').catch(() => null),
|
||||
api.get<FinancialCategoryDto[]>('/treasury/categories', { params: { kind } }).catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
|
||||
return { data: [] as FinancialCategoryDto[] };
|
||||
}
|
||||
throw e;
|
||||
}),
|
||||
api.get<FinancialAccountDto[]>('/treasury/accounts').catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && (e.response?.status === 403 || e.response?.status === 404)) {
|
||||
return { data: [] as FinancialAccountDto[] };
|
||||
}
|
||||
throw e;
|
||||
}),
|
||||
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind } }).catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
|
||||
throw e;
|
||||
}),
|
||||
api.get<TreasuryPartyBalanceDto[]>('/treasury/party-balances', { params: { kind: 'expense' } }).catch((e: unknown) => {
|
||||
if (axios.isAxiosError(e) && e.response?.status === 404) return { data: [] as TreasuryPartyBalanceDto[] };
|
||||
throw e;
|
||||
}),
|
||||
]);
|
||||
rows.value = docs.data;
|
||||
balances.value = bals.data;
|
||||
payableBalances.value = payables.data;
|
||||
categories.value = cats.data.filter((row) => row.isActive);
|
||||
accounts.value = acc.data.filter((row) => row.isActive);
|
||||
if (dash) dashboard.value = dash.data;
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
settleMirror.reset();
|
||||
form.value = emptyForm();
|
||||
formTab.value = 'main';
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
}
|
||||
@@ -179,39 +210,68 @@ async function createDoc() {
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
const amount = parseMoneyNumber(String(form.value.amount ?? ''), 0);
|
||||
const settlement = isSettlement.value;
|
||||
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
const amount = settlement
|
||||
? settleAmount
|
||||
: parseMoneyNumber(String(form.value.amount ?? ''), 0);
|
||||
if (amount == null || amount <= 0) {
|
||||
error.value = 'مبلغ کل معتبر نیست.';
|
||||
error.value = settlement ? 'مبلغ دریافتشده معتبر نیست.' : 'مبلغ کل معتبر نیست.';
|
||||
return;
|
||||
}
|
||||
if (!form.value.partyKind || (form.value.partyKind !== 'other' && !form.value.partyId)) {
|
||||
error.value = 'طرف حساب را انتخاب کنید.';
|
||||
return;
|
||||
}
|
||||
const settleAmount = parseMoneyNumber(String(form.value.settleAmount ?? ''), 0) ?? 0;
|
||||
if (form.value.partyKind === 'other' && settleAmount !== amount) {
|
||||
if (settlement && form.value.partyKind === 'other') {
|
||||
error.value = 'برای دریافت، طرف حساب واقعی لازم است.';
|
||||
return;
|
||||
}
|
||||
if (!settlement && form.value.partyKind === 'other' && settleAmount !== amount) {
|
||||
error.value = 'برای سایر، مبلغ دریافتشده باید با مبلغ کل یکی باشد.';
|
||||
return;
|
||||
}
|
||||
if (!settlement && settleAmount > amount) {
|
||||
error.value = 'مبلغ دریافتشده از مبلغ کل بیشتر است.';
|
||||
return;
|
||||
}
|
||||
if ((settlement || settleAmount > 0) && !form.value.accountId) {
|
||||
error.value = 'حساب را انتخاب کنید.';
|
||||
return;
|
||||
}
|
||||
const partyKey =
|
||||
form.value.partyKind && form.value.partyKind !== 'other' && form.value.partyId
|
||||
? `${form.value.partyKind}:${form.value.partyId}`
|
||||
: '';
|
||||
const receivable = partyKey
|
||||
? Number(balances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
|
||||
: 0;
|
||||
const payable = partyKey
|
||||
? Number(payableBalances.value.find((row) => row.key === partyKey)?.documentRemaining || 0)
|
||||
: 0;
|
||||
const collectsBalance = settlement && (receivable > 0 || payable > 0);
|
||||
const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
|
||||
kind,
|
||||
settlement,
|
||||
title: form.value.title,
|
||||
amount,
|
||||
categoryId: form.value.categoryId || null,
|
||||
categoryId: settlement ? null : form.value.categoryId || null,
|
||||
partyKind: form.value.partyKind,
|
||||
personId: form.value.partyKind === 'person' ? form.value.partyId : null,
|
||||
companyId: form.value.partyKind === 'company' ? form.value.partyId : null,
|
||||
userId: form.value.partyKind === 'user' ? form.value.partyId : null,
|
||||
accountId: form.value.accountId || null,
|
||||
settleAmount,
|
||||
settleAmount: settlement ? amount : settleAmount,
|
||||
method: form.value.method,
|
||||
notes: form.value.notes || null,
|
||||
bookedAt: form.value.bookedAt || undefined,
|
||||
});
|
||||
resetForm();
|
||||
ok.value = data.reference
|
||||
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
|
||||
: 'سند ثبت شد.';
|
||||
ok.value = collectsBalance
|
||||
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
|
||||
: data.reference
|
||||
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
|
||||
: 'سند ثبت شد.';
|
||||
await load();
|
||||
} catch (e) {
|
||||
error.value = apiMessage(e);
|
||||
@@ -220,16 +280,6 @@ async function createDoc() {
|
||||
}
|
||||
}
|
||||
|
||||
async function submitMobileForm() {
|
||||
try {
|
||||
await mobileFormRef.value?.validate();
|
||||
} catch {
|
||||
formTab.value = 'main';
|
||||
return;
|
||||
}
|
||||
await createDoc();
|
||||
}
|
||||
|
||||
async function voidDoc(id: string) {
|
||||
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return;
|
||||
try {
|
||||
@@ -248,340 +298,15 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:style="
|
||||
isMobile
|
||||
? { paddingBottom: 'calc(96px + var(--mobile-tabbar-h, 3.65rem))' }
|
||||
: undefined
|
||||
"
|
||||
>
|
||||
<!-- ─── Mobile app experience ─── -->
|
||||
<template v-if="isMobile">
|
||||
<a-flex vertical :gap="token.margin">
|
||||
<a-row :gutter="[12, 12]">
|
||||
<a-col :span="12">
|
||||
<a-card
|
||||
:bordered="false"
|
||||
:body-style="{ padding: `${token.paddingSM}px` }"
|
||||
:style="{
|
||||
background: token.colorPrimaryBg,
|
||||
borderRadius: `${token.borderRadiusLG}px`,
|
||||
boxShadow: token.boxShadow,
|
||||
}"
|
||||
>
|
||||
<a-flex align="center" justify="space-between" :gap="8">
|
||||
<div :style="{ minWidth: 0, flex: 1 }">
|
||||
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
|
||||
دریافتهای این ماه
|
||||
</a-typography-text>
|
||||
<div>
|
||||
<a-typography-text
|
||||
strong
|
||||
:style="{ fontSize: '15px', color: token.colorPrimary }"
|
||||
>
|
||||
{{ toman(dashboard?.actualReceipts) }}
|
||||
</a-typography-text>
|
||||
</div>
|
||||
</div>
|
||||
<a-avatar
|
||||
:size="36"
|
||||
:style="{
|
||||
background: token.colorPrimary,
|
||||
color: token.colorTextLightSolid,
|
||||
flexShrink: 0,
|
||||
}"
|
||||
>
|
||||
<template #icon><ArrowDownOutlined /></template>
|
||||
</a-avatar>
|
||||
</a-flex>
|
||||
</a-card>
|
||||
</a-col>
|
||||
<a-col :span="12">
|
||||
<a-card
|
||||
:bordered="false"
|
||||
:body-style="{ padding: `${token.paddingSM}px` }"
|
||||
:style="{
|
||||
background: token.colorPrimaryBg,
|
||||
borderRadius: `${token.borderRadiusLG}px`,
|
||||
boxShadow: token.boxShadow,
|
||||
}"
|
||||
>
|
||||
<a-flex align="center" justify="space-between" :gap="8">
|
||||
<div :style="{ minWidth: 0, flex: 1 }">
|
||||
<a-typography-text type="secondary" :style="{ fontSize: '12px' }">
|
||||
در انتظار دریافت
|
||||
</a-typography-text>
|
||||
<div>
|
||||
<a-typography-text
|
||||
strong
|
||||
:style="{ fontSize: '15px', color: token.colorPrimary }"
|
||||
>
|
||||
{{ toman(dashboard?.receivables) }}
|
||||
</a-typography-text>
|
||||
</div>
|
||||
</div>
|
||||
<a-avatar
|
||||
:size="36"
|
||||
:style="{
|
||||
background: token.colorPrimary,
|
||||
color: token.colorTextLightSolid,
|
||||
flexShrink: 0,
|
||||
}"
|
||||
>
|
||||
<template #icon><ClockCircleOutlined /></template>
|
||||
</a-avatar>
|
||||
</a-flex>
|
||||
</a-card>
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<a-alert v-if="error" type="error" show-icon :message="error" closable @close="error = ''" />
|
||||
<a-alert v-if="ok" type="success" show-icon :message="ok" closable @close="ok = ''" />
|
||||
|
||||
<a-segmented
|
||||
v-model:value="formTab"
|
||||
block
|
||||
:options="formTabOptions"
|
||||
:style="{ background: token.colorFillTertiary }"
|
||||
/>
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-form ref="mobileFormRef" layout="vertical" :model="form" @finish="createDoc">
|
||||
<div v-show="formTab === 'main'">
|
||||
<a-form-item
|
||||
label="عنوان درآمد"
|
||||
name="title"
|
||||
:rules="[{ required: true, message: 'عنوان را وارد کنید' }]"
|
||||
>
|
||||
<a-input
|
||||
v-model:value="form.title"
|
||||
placeholder="مثلاً: دریافت قسط پروژه الف"
|
||||
>
|
||||
<template #prefix><FileTextOutlined /></template>
|
||||
</a-input>
|
||||
</a-form-item>
|
||||
|
||||
<a-row :gutter="[12, 0]">
|
||||
<a-col :span="12">
|
||||
<a-form-item label="طرف حساب" name="partyKind">
|
||||
<TreasuryPartySelect v-model:kind="form.partyKind" v-model:party-id="form.partyId" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :span="12">
|
||||
<a-form-item name="method">
|
||||
<template #label>
|
||||
<a-space :size="6">
|
||||
<CreditCardOutlined />
|
||||
<span>روش دریافت</span>
|
||||
</a-space>
|
||||
</template>
|
||||
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
|
||||
<a-select-option
|
||||
v-for="opt in methodOptions"
|
||||
:key="opt.value"
|
||||
:value="opt.value"
|
||||
:label="opt.label"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<a-form-item name="categoryId">
|
||||
<template #label>
|
||||
<a-space :size="6">
|
||||
<TagOutlined />
|
||||
<span>دستهبندی درآمد</span>
|
||||
</a-space>
|
||||
</template>
|
||||
<a-select show-search option-filter-prop="label"
|
||||
v-model:value="form.categoryId"
|
||||
allow-clear
|
||||
placeholder="انتخاب دسته"
|
||||
style="width: 100%"
|
||||
>
|
||||
<a-select-option v-for="cat in categories" :key="cat.id" :value="cat.id" :label="cat.name">
|
||||
{{ cat.name }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
|
||||
<a-row :gutter="[12, 0]">
|
||||
<a-col :span="12">
|
||||
<a-form-item
|
||||
label="مبلغ کل (تومان)"
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ کل را وارد کنید' }]"
|
||||
>
|
||||
<MoneyInput v-model="form.amount" :decimals="0" placeholder="۰" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :span="12">
|
||||
<a-form-item
|
||||
:label="`${settleLabel} (تومان)`"
|
||||
name="settleAmount"
|
||||
:rules="[{ required: true, message: 'مبلغ دریافتشده را وارد کنید' }]"
|
||||
>
|
||||
<MoneyInput
|
||||
v-model="form.settleAmount"
|
||||
:decimals="0"
|
||||
:disabled="form.partyKind === 'other'"
|
||||
placeholder="۰"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
|
||||
<a-flex
|
||||
align="center"
|
||||
justify="space-between"
|
||||
:style="{
|
||||
background: token.colorSuccessBg,
|
||||
borderRadius: `${token.borderRadiusLG * 2}px`,
|
||||
padding: `${token.paddingSM}px ${token.padding}px`,
|
||||
marginBottom: `${token.margin}px`,
|
||||
}"
|
||||
>
|
||||
<a-space :size="8">
|
||||
<span
|
||||
:style="{
|
||||
width: '8px',
|
||||
height: '8px',
|
||||
borderRadius: '50%',
|
||||
background: token.colorSuccess,
|
||||
display: 'inline-block',
|
||||
}"
|
||||
/>
|
||||
<a-typography-text type="secondary">مانده قابل دریافت</a-typography-text>
|
||||
</a-space>
|
||||
<a-typography-text strong :style="{ color: token.colorSuccess }">
|
||||
{{ toman(remainingAmount) }}
|
||||
</a-typography-text>
|
||||
</a-flex>
|
||||
|
||||
<a-row :gutter="[12, 0]">
|
||||
<a-col :span="12">
|
||||
<a-form-item label="تاریخ دریافت" name="bookedAt">
|
||||
<JalaliDateInput v-model="form.bookedAt" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :span="12">
|
||||
<a-form-item name="accountId">
|
||||
<template #label>
|
||||
<a-space :size="6">
|
||||
<BankOutlined />
|
||||
<span>حساب مقصد</span>
|
||||
</a-space>
|
||||
</template>
|
||||
<a-select show-search option-filter-prop="label"
|
||||
v-model:value="form.accountId"
|
||||
allow-clear
|
||||
placeholder="انتخاب حساب"
|
||||
style="width: 100%"
|
||||
>
|
||||
<a-select-option
|
||||
v-for="account in accounts"
|
||||
:key="account.id"
|
||||
:value="account.id"
|
||||
:label="account.name"
|
||||
>
|
||||
{{ account.name }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
|
||||
<div v-show="formTab === 'extra'">
|
||||
<a-form-item label="توضیحات" name="notes">
|
||||
<a-textarea
|
||||
v-model:value="form.notes"
|
||||
:rows="4"
|
||||
placeholder="توضیحات اختیاری…"
|
||||
/>
|
||||
</a-form-item>
|
||||
</div>
|
||||
</a-form>
|
||||
</a-card>
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-divider orientation="right">مانده دریافتنی</a-divider>
|
||||
<TreasuryPartyBalanceTable :rows="balances" settled-label="دریافتشده" />
|
||||
<a-divider orientation="right">فهرست اسناد</a-divider>
|
||||
<a-form layout="vertical">
|
||||
<a-form-item label="جستجو">
|
||||
<a-input
|
||||
v-model:value="q"
|
||||
allow-clear
|
||||
placeholder="عنوان یا شماره پیگیری"
|
||||
@press-enter="load"
|
||||
@change="load"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
<a-empty v-if="!rows.length" description="سندی نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="rows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
<a-button
|
||||
v-if="item.status !== 'void'"
|
||||
type="link"
|
||||
danger
|
||||
@click="voidDoc(item.id)"
|
||||
>
|
||||
ابطال
|
||||
</a-button>
|
||||
</template>
|
||||
<a-list-item-meta>
|
||||
<template #title>{{ item.title }}</template>
|
||||
<template #description>{{ docLine(item) }}</template>
|
||||
</a-list-item-meta>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
</a-card>
|
||||
</a-flex>
|
||||
|
||||
<div
|
||||
:style="{
|
||||
position: 'fixed',
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 'var(--mobile-tabbar-h, 3.65rem)',
|
||||
zIndex: 90,
|
||||
background: token.colorBgElevated,
|
||||
borderTop: `1px solid ${token.colorBorderSecondary}`,
|
||||
padding: `${token.paddingSM}px ${token.padding}px`,
|
||||
boxShadow: token.boxShadowSecondary,
|
||||
}"
|
||||
>
|
||||
<a-row :gutter="12">
|
||||
<a-col :span="8">
|
||||
<a-button block @click="resetForm">انصراف</a-button>
|
||||
</a-col>
|
||||
<a-col :span="16">
|
||||
<a-button type="primary" block :loading="saving" @click="submitMobileForm">
|
||||
<template #icon><CheckOutlined /></template>
|
||||
ثبت دریافت
|
||||
</a-button>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ─── Desktop (unchanged interaction model) ─── -->
|
||||
<template v-else>
|
||||
<a-flex vertical :gap="16">
|
||||
<a-flex vertical :gap="16">
|
||||
<a-alert v-if="error" type="error" show-icon :message="error" />
|
||||
<a-alert v-if="ok" type="success" show-icon :message="ok" />
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-divider orientation="right">سند جدید</a-divider>
|
||||
<a-flex align="center" justify="space-between" wrap="wrap" gap="small">
|
||||
<a-typography-text strong>سند جدید</a-typography-text>
|
||||
<a-segmented v-model:value="entryMode" :options="entryOptions" />
|
||||
</a-flex>
|
||||
<a-form
|
||||
layout="vertical"
|
||||
:model="form"
|
||||
@@ -589,6 +314,23 @@ onMounted(() => {
|
||||
@finishFailed="onFinishFailed"
|
||||
>
|
||||
<a-row :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
|
||||
<a-row :gutter="8" align="middle">
|
||||
<a-col :span="partyPosition ? 16 : 24">
|
||||
<TreasuryPartySelect
|
||||
v-model:kind="form.partyKind"
|
||||
v-model:party-id="form.partyId"
|
||||
:allow-other="!isSettlement"
|
||||
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
|
||||
/>
|
||||
</a-col>
|
||||
<a-col v-if="partyPosition" :span="8">
|
||||
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item
|
||||
label="عنوان"
|
||||
@@ -598,21 +340,35 @@ onMounted(() => {
|
||||
<a-input v-model:value="form.title" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="8">
|
||||
<a-form-item
|
||||
label="مبلغ کل"
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
|
||||
>
|
||||
<MoneyInput v-model="form.amount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item :label="settleLabel" name="settleAmount">
|
||||
<MoneyInput v-model="form.settleAmount" :decimals="0" :disabled="form.partyKind === 'other'" />
|
||||
<a-form-item
|
||||
:label="settleLabel"
|
||||
name="settleAmount"
|
||||
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
|
||||
>
|
||||
<MoneyInput
|
||||
addon-after="تومان"
|
||||
v-model="form.settleAmount"
|
||||
:decimals="0"
|
||||
:disabled="!isSettlement && form.partyKind === 'other'"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="8">
|
||||
<a-form-item label="مانده این سند">
|
||||
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text>
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="8">
|
||||
<a-form-item label="دستهبندی" name="categoryId">
|
||||
<a-select show-search option-filter-prop="label"
|
||||
v-model:value="form.categoryId"
|
||||
@@ -627,12 +383,7 @@ onMounted(() => {
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="طرف حساب" name="partyKind">
|
||||
<TreasuryPartySelect v-model:kind="form.partyKind" v-model:party-id="form.partyId" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="حساب" name="accountId">
|
||||
<a-form-item label="حساب" name="accountId" :rules="accountRules">
|
||||
<a-select show-search option-filter-prop="label"
|
||||
v-model:value="form.accountId"
|
||||
allow-clear
|
||||
@@ -669,13 +420,13 @@ onMounted(() => {
|
||||
<JalaliDateInput v-model="form.bookedAt" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="16">
|
||||
<a-col v-if="!isSettlement" :xs="24" :md="16">
|
||||
<a-form-item label="توضیحات" name="notes">
|
||||
<a-input v-model:value="form.notes" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
</a-row>
|
||||
<a-button type="primary" html-type="submit" :loading="saving">ثبت</a-button>
|
||||
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
|
||||
</a-form>
|
||||
|
||||
<a-divider orientation="right">مانده دریافتنی</a-divider>
|
||||
@@ -698,10 +449,10 @@ onMounted(() => {
|
||||
</a-form>
|
||||
|
||||
<a-empty v-if="!rows.length" description="سندی نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="rows">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
<template v-if="!isMobile" #actions>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
<a-button
|
||||
v-if="item.status !== 'void'"
|
||||
@@ -712,7 +463,29 @@ onMounted(() => {
|
||||
ابطال
|
||||
</a-button>
|
||||
</template>
|
||||
<a-list-item-meta>
|
||||
<a-flex v-if="isMobile" vertical :gap="4" style="width: 100%">
|
||||
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
|
||||
<a-typography-text strong>{{ item.title }}</a-typography-text>
|
||||
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-typography-text type="secondary">
|
||||
{{ item.partyName || 'بدون طرف حساب' }} · {{ statusLabel[item.status] ?? item.status }}
|
||||
</a-typography-text>
|
||||
<a-typography-text v-if="item.reference" type="secondary">پیگیری {{ item.reference }}</a-typography-text>
|
||||
<a-typography-text v-if="item.categoryName" type="secondary">{{ item.categoryName }}</a-typography-text>
|
||||
<a-flex justify="space-between" align="center">
|
||||
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
|
||||
<a-button
|
||||
v-if="item.status !== 'void'"
|
||||
type="link"
|
||||
danger
|
||||
@click="voidDoc(item.id)"
|
||||
>
|
||||
ابطال
|
||||
</a-button>
|
||||
</a-flex>
|
||||
</a-flex>
|
||||
<a-list-item-meta v-else>
|
||||
<template #title>{{ item.title }}</template>
|
||||
<template #description>{{ docLine(item) }}</template>
|
||||
</a-list-item-meta>
|
||||
@@ -720,8 +493,5 @@ onMounted(() => {
|
||||
</template>
|
||||
</a-list>
|
||||
</a-card>
|
||||
</a-flex>
|
||||
</template>
|
||||
|
||||
</div>
|
||||
</a-flex>
|
||||
</template>
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
import { RouterView, useRoute } from 'vue-router';
|
||||
import { Flex as AFlex, Typography, theme } from 'ant-design-vue';
|
||||
import { Flex as AFlex, Grid, Typography, theme } from 'ant-design-vue';
|
||||
import TreasuryNav from '@/components/treasury/TreasuryNav.vue';
|
||||
import { provideTreasuryPageChrome } from './treasuryPageChrome';
|
||||
|
||||
const { Title: ATypographyTitle, Text: ATypographyText } = Typography;
|
||||
const { token } = theme.useToken();
|
||||
const screens = Grid.useBreakpoint();
|
||||
const isMobile = computed(() => !screens.value.md);
|
||||
const route = useRoute();
|
||||
const chrome = provideTreasuryPageChrome();
|
||||
|
||||
@@ -31,16 +33,19 @@ const description = computed(
|
||||
(typeof route.meta.treasuryDescription === 'string' ? route.meta.treasuryDescription : ''),
|
||||
);
|
||||
|
||||
/** Keep title+subtitle block height stable across tabs (one-line subtitle). */
|
||||
const headerStyle = computed(() => ({
|
||||
minHeight: `${token.value.controlHeightLG + token.value.fontSizeLG + token.value.marginXXS}px`,
|
||||
}));
|
||||
const headerStyle = computed(() =>
|
||||
isMobile.value
|
||||
? undefined
|
||||
: {
|
||||
minHeight: `${token.value.controlHeightLG + token.value.fontSizeLG + token.value.marginXXS}px`,
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-flex vertical :gap="token.margin" :style="{ width: '100%' }">
|
||||
<a-flex vertical :gap="isMobile ? token.marginSM : token.margin" :style="{ width: '100%' }">
|
||||
<div :style="headerStyle">
|
||||
<a-typography-title :level="3" :style="{ margin: 0 }">{{ title }}</a-typography-title>
|
||||
<a-typography-title :level="isMobile ? 4 : 3" :style="{ margin: 0 }">{{ title }}</a-typography-title>
|
||||
<a-typography-text
|
||||
type="secondary"
|
||||
:ellipsis="description ? { tooltip: description } : false"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,12 +7,15 @@ import {
|
||||
Card as ACard,
|
||||
Checkbox as ACheckbox,
|
||||
Col as ACol,
|
||||
Descriptions as ADescriptions,
|
||||
DescriptionsItem as ADescriptionsItem,
|
||||
Divider as ADivider,
|
||||
Empty as AEmpty,
|
||||
Flex as AFlex,
|
||||
Form as AForm,
|
||||
FormItem as AFormItem,
|
||||
Input as AInput,
|
||||
List as AList,
|
||||
Row as ARow,
|
||||
Select as ASelect,
|
||||
Space as ASpace,
|
||||
@@ -27,6 +30,7 @@ import type { FinancialAccountDto, FinancialReceivableDto } from '@mento/shared'
|
||||
import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
import { formatJalaliNumeric } from '@/lib/jalali';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
|
||||
@@ -87,6 +91,9 @@ const installmentColumns: TableColumnsType<InstallmentRow> = [
|
||||
{ title: '', key: 'actions' },
|
||||
];
|
||||
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
|
||||
function apiMessage(e: unknown) {
|
||||
if (!axios.isAxiosError(e)) return 'عملیات ناموفق بود.';
|
||||
const msg = (e.response?.data as { message?: string | string[] })?.message;
|
||||
@@ -234,12 +241,12 @@ onMounted(() => {
|
||||
name="totalAmount"
|
||||
:rules="[{ required: true, message: 'مبلغ کل الزامی است' }]"
|
||||
>
|
||||
<MoneyInput v-model="form.totalAmount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="form.totalAmount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
<a-form-item label="پیشپرداخت" name="prepaidAmount">
|
||||
<MoneyInput v-model="form.prepaidAmount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="form.prepaidAmount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
@@ -285,7 +292,7 @@ onMounted(() => {
|
||||
<a-row v-for="(line, index) in customLines" :key="index" :gutter="[16, 0]">
|
||||
<a-col :xs="24" :md="12">
|
||||
<a-form-item :label="`مبلغ قسط ${index + 1}`">
|
||||
<MoneyInput v-model="line.amount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="line.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="12">
|
||||
@@ -320,7 +327,7 @@ onMounted(() => {
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
|
||||
>
|
||||
<MoneyInput v-model="collect.amount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="collect.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
@@ -365,7 +372,33 @@ onMounted(() => {
|
||||
</div>
|
||||
<a-typography-text strong>{{ toman(row.totalAmount) }}</a-typography-text>
|
||||
</a-flex>
|
||||
<a-list v-if="isMobile" :data-source="row.installments">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<a-card :title="`قسط ${item.position}`" style="width: 100%">
|
||||
<a-descriptions :column="1" bordered>
|
||||
<a-descriptions-item label="سررسید">
|
||||
{{ formatJalaliNumeric(new Date(item.dueDate)) }}
|
||||
</a-descriptions-item>
|
||||
<a-descriptions-item label="مبلغ">{{ toman(item.amount) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="مانده">{{ toman(item.remaining) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="وضعیت">
|
||||
{{ statusLabel[item.status] ?? item.status }}
|
||||
</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
<a-button
|
||||
v-if="item.status !== 'settled'"
|
||||
type="link"
|
||||
@click="startCollect(row, item)"
|
||||
>
|
||||
دریافت
|
||||
</a-button>
|
||||
</a-card>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
<a-table
|
||||
v-else
|
||||
:columns="installmentColumns"
|
||||
:data-source="row.installments"
|
||||
:pagination="false"
|
||||
|
||||
@@ -22,10 +22,12 @@ import { api } from '@/lib/api';
|
||||
import MoneyInput from '@/components/MoneyInput.vue';
|
||||
import JalaliDateInput from '@/components/JalaliDateInput.vue';
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
import { formatJalaliNumeric } from '@/lib/jalali';
|
||||
import { parseMoneyNumber } from '@/lib/money';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ASelectOption = ASelect.Option;
|
||||
@@ -123,7 +125,7 @@ onMounted(() => {
|
||||
name="amount"
|
||||
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
|
||||
>
|
||||
<MoneyInput v-model="form.amount" :decimals="0" />
|
||||
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
|
||||
</a-form-item>
|
||||
</a-col>
|
||||
<a-col :xs="24" :md="8">
|
||||
@@ -146,7 +148,7 @@ onMounted(() => {
|
||||
|
||||
<a-divider orientation="right">فهرست الگوها</a-divider>
|
||||
<a-empty v-if="!rows.length" description="الگویی ثبت نشده است." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="rows">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
Empty as AEmpty,
|
||||
Flex as AFlex,
|
||||
List as AList,
|
||||
Descriptions as ADescriptions,
|
||||
DescriptionsItem as ADescriptionsItem,
|
||||
Table as ATable,
|
||||
Tabs as ATabs,
|
||||
Typography,
|
||||
@@ -20,14 +22,18 @@ import type { TreasuryPartyBalanceDto } from '@mento/shared';
|
||||
import { api } from '@/lib/api';
|
||||
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
|
||||
import { toman } from './treasury-format';
|
||||
import { useTreasuryMobile } from './useTreasuryMobile';
|
||||
|
||||
const { Text: ATypographyText } = Typography;
|
||||
const isMobile = useTreasuryMobile();
|
||||
const AListItem = AList.Item;
|
||||
const AListItemMeta = AList.Item.Meta;
|
||||
const ATabPane = ATabs.TabPane;
|
||||
|
||||
type Period = {
|
||||
bookedIncome: string;
|
||||
invoiceSales: string;
|
||||
invoiceCredits: string;
|
||||
bookedExpense: string;
|
||||
operatingProfit: string;
|
||||
cashIn: string;
|
||||
@@ -61,6 +67,8 @@ const kindLabel: Record<string, string> = {
|
||||
|
||||
const lines = [
|
||||
['درآمد ثبتشده', 'bookedIncome'],
|
||||
['فروش فاکتور', 'invoiceSales'],
|
||||
['فاکتور برگشتی', 'invoiceCredits'],
|
||||
['هزینه ثبتشده', 'bookedExpense'],
|
||||
['سود عملیاتی', 'operatingProfit'],
|
||||
['ورود وجه', 'cashIn'],
|
||||
@@ -79,8 +87,8 @@ const metricRows = computed<MetricRow[]>(() => {
|
||||
return lines.map(([label, key]) => ({
|
||||
key,
|
||||
label,
|
||||
current: toman(current.value![key]),
|
||||
previous: toman(previous.value![key]),
|
||||
current: toman(current.value![key] || '0'),
|
||||
previous: toman(previous.value![key] || '0'),
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -182,8 +190,20 @@ onMounted(() => {
|
||||
<a-tabs v-model:activeKey="reportTab">
|
||||
<a-tab-pane key="periods" tab="مقایسه دورهها">
|
||||
<a-flex vertical :gap="16">
|
||||
<a-list v-if="isMobile && metricRows.length" :data-source="metricRows">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<a-card :title="item.label" style="width: 100%">
|
||||
<a-descriptions :column="1" bordered>
|
||||
<a-descriptions-item label="این دوره">{{ item.current }}</a-descriptions-item>
|
||||
<a-descriptions-item label="دوره قبل">{{ item.previous }}</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
</a-card>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
<a-table
|
||||
v-if="metricRows.length"
|
||||
v-else-if="metricRows.length"
|
||||
:columns="metricColumns"
|
||||
:data-source="metricRows"
|
||||
:pagination="false"
|
||||
@@ -193,7 +213,7 @@ onMounted(() => {
|
||||
|
||||
<a-divider orientation="right">مطالبات به تفکیک طرف حساب</a-divider>
|
||||
<a-empty v-if="!receivablesByParty.length" description="مورد بازی نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="receivablesByParty">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="receivablesByParty">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
@@ -208,7 +228,7 @@ onMounted(() => {
|
||||
|
||||
<a-divider orientation="right">تعهدات به تفکیک ماه</a-divider>
|
||||
<a-empty v-if="!payablesByMonth.length" description="تعهد بازی نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="payablesByMonth">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="payablesByMonth">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
@@ -224,7 +244,7 @@ onMounted(() => {
|
||||
<template v-if="current">
|
||||
<a-divider orientation="right">سهم هزینهها</a-divider>
|
||||
<a-empty v-if="!current.expenseCategories.length" description="دستهای نیست." />
|
||||
<a-list v-else item-layout="horizontal" :data-source="current.expenseCategories">
|
||||
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="current.expenseCategories">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item>
|
||||
<template #actions>
|
||||
@@ -244,6 +264,9 @@ onMounted(() => {
|
||||
|
||||
<a-tab-pane key="debtors" tab="بدهکاران">
|
||||
<a-flex vertical :gap="16">
|
||||
<a-typography-text type="secondary">
|
||||
ماندهٔ فاکتور صادرشده و اسناد دریافتِ باز. صدور فاکتور سند درآمد جدا نمیسازد.
|
||||
</a-typography-text>
|
||||
<a-flex justify="space-between" align="center">
|
||||
<a-typography-text type="secondary">
|
||||
{{ debtors.length }} طرف حساب · جمع مانده {{ toman(sumRemaining(debtors)) }}
|
||||
@@ -259,6 +282,9 @@ onMounted(() => {
|
||||
|
||||
<a-tab-pane key="creditors" tab="بستانکاران">
|
||||
<a-flex vertical :gap="16">
|
||||
<a-typography-text type="secondary">
|
||||
ماندهٔ فاکتور برگشتی و اسناد هزینهٔ باز. برگشتی سند هزینهٔ جدا نمیسازد.
|
||||
</a-typography-text>
|
||||
<a-flex justify="space-between" align="center">
|
||||
<a-typography-text type="secondary">
|
||||
{{ creditors.length }} طرف حساب · جمع مانده {{ toman(sumRemaining(creditors)) }}
|
||||
|
||||
@@ -3,3 +3,11 @@ export function toman(value: string | number | null | undefined) {
|
||||
if (!Number.isFinite(n)) return '۰';
|
||||
return `${new Intl.NumberFormat('fa-IR').format(Math.round(n))} تومان`;
|
||||
}
|
||||
|
||||
/** ماندهٔ دریافتنی منهای ماندهٔ پرداختنی: بد قرمز، بس سبز، صفر خاکستری. */
|
||||
export function partyNetPosition(receivable: number, payable: number) {
|
||||
const net = receivable - payable;
|
||||
if (net > 0) return { text: `بد ${toman(net)}`, type: 'danger' as const };
|
||||
if (net < 0) return { text: `بس ${toman(-net)}`, type: 'success' as const };
|
||||
return { text: `مانده ${toman(0)}`, type: 'secondary' as const };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { computed } from 'vue';
|
||||
import { Grid } from 'ant-design-vue';
|
||||
|
||||
export function useTreasuryMobile() {
|
||||
const screens = Grid.useBreakpoint();
|
||||
return computed(() => !screens.value.md);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
client_max_body_size 50m;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -636,6 +636,22 @@ export function parseUserTreasuryAccess(raw: unknown): UserTreasuryAccess | null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* دسترسی مالی کاربر، اگر تنظیم شده باشد، کلیدهای مالی نقش را جایگزین میکند.
|
||||
* null یعنی همان مجوزهای نقش.
|
||||
*/
|
||||
export function permissionsWithTreasuryOverride(
|
||||
rolePermissions: readonly string[],
|
||||
override: UserTreasuryAccess | null,
|
||||
): string[] {
|
||||
if (!override) return [...rolePermissions];
|
||||
const rest = rolePermissions.filter(
|
||||
(key) => key !== "treasury" && !key.startsWith("treasury_"),
|
||||
);
|
||||
if (!override.enabled) return rest;
|
||||
return ["treasury", ...override.sections, ...rest];
|
||||
}
|
||||
|
||||
export function emptySectionDataAccess(): SectionDataAccess {
|
||||
return { mode: "all", rules: [] };
|
||||
}
|
||||
@@ -2022,6 +2038,8 @@ export interface ActivityImageDto {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type ActivityCompletionMode = "any" | "all";
|
||||
|
||||
export interface ActivityDto {
|
||||
id: string;
|
||||
type: ActivityType;
|
||||
@@ -2039,6 +2057,10 @@ export interface ActivityDto {
|
||||
/** زمان ارسال یادآور (اگر ارسال شده باشد) */
|
||||
reminderSentAt: string | null;
|
||||
completedAt: string | null;
|
||||
/** any = با انجام یکی کافی است؛ all = هر مسئول باید سهم خودش را بزند */
|
||||
completionMode?: ActivityCompletionMode;
|
||||
/** شناسهٔ مسئولانی که سهم خود را در حالت all ثبت کردهاند */
|
||||
completedByIds?: string[];
|
||||
/** manual یا didar؛ برای جدا کردن سابقهٔ قبلی */
|
||||
importSource?: string;
|
||||
promotedFromPriorAt?: string | null;
|
||||
@@ -2096,6 +2118,8 @@ export interface CreateActivityRequest {
|
||||
assigneeId?: string | null;
|
||||
/** چند مسئول؛ اولی بهعنوان assigneeId ذخیره میشود */
|
||||
assigneeIds?: string[];
|
||||
/** پیشفرض any. فقط وقتی چند مسئول دارد معنی دارد */
|
||||
completionMode?: ActivityCompletionMode;
|
||||
}
|
||||
|
||||
export interface UpdateActivityRequest {
|
||||
@@ -2120,6 +2144,7 @@ export interface UpdateActivityRequest {
|
||||
leadId?: string | null;
|
||||
assigneeId?: string | null;
|
||||
assigneeIds?: string[];
|
||||
completionMode?: ActivityCompletionMode;
|
||||
}
|
||||
|
||||
export interface ActivitySummaryDto {
|
||||
@@ -5511,13 +5536,21 @@ export type VoipCallStatus =
|
||||
| "completed"
|
||||
| "failed";
|
||||
|
||||
export type VoipProvider = "generic" | "daftareshoma";
|
||||
|
||||
export interface VoipConnectionDto {
|
||||
id: string;
|
||||
label: string;
|
||||
provider: VoipProvider;
|
||||
enabled: boolean;
|
||||
webhookSecretSet: boolean;
|
||||
apiTokenSet: boolean;
|
||||
/** قالب URL برای شروع تماس؛ {number} جایگزین میشود */
|
||||
clickToCallUrl: string | null;
|
||||
/** شماره مبدأ تماس خروجی (دفتر شما) */
|
||||
fromNumber: string | null;
|
||||
/** خط/داخلی سازمان (دفتر شما) */
|
||||
callerExtension: string | null;
|
||||
lastEventAt: string | null;
|
||||
lastError: string | null;
|
||||
callCount: number;
|
||||
@@ -5527,8 +5560,13 @@ export interface VoipConnectionDto {
|
||||
|
||||
export interface CreateVoipConnectionRequest {
|
||||
label: string;
|
||||
provider?: VoipProvider;
|
||||
webhookSecret?: string;
|
||||
clickToCallUrl?: string | null;
|
||||
/** توکن Bearer API دفتر شما */
|
||||
apiToken?: string;
|
||||
fromNumber?: string | null;
|
||||
callerExtension?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -5536,6 +5574,9 @@ export interface UpdateVoipConnectionRequest {
|
||||
label?: string;
|
||||
webhookSecret?: string | null;
|
||||
clickToCallUrl?: string | null;
|
||||
apiToken?: string | null;
|
||||
fromNumber?: string | null;
|
||||
callerExtension?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -5553,6 +5594,8 @@ export interface VoipCallLogDto {
|
||||
status: VoipCallStatus | string;
|
||||
fromNumber: string | null;
|
||||
toNumber: string | null;
|
||||
/** خط/داخلی سازمانی که تماس روی آن بوده */
|
||||
lineExtension: string | null;
|
||||
personId: string | null;
|
||||
personName: string | null;
|
||||
activityId: string | null;
|
||||
@@ -5579,6 +5622,8 @@ export interface VoipWebhookEvent {
|
||||
status: VoipCallStatus | string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** خط/داخلی سازمان */
|
||||
lineExtension?: string;
|
||||
startedAt?: string;
|
||||
endedAt?: string;
|
||||
durationSec?: number;
|
||||
@@ -6585,6 +6630,8 @@ export interface TreasuryPartyBalanceDto {
|
||||
amount: string;
|
||||
settledAmount: string;
|
||||
remaining: string;
|
||||
/** بخشی از مانده که با دریافت/پرداخت روی سندهای باز کم میشود */
|
||||
documentRemaining: string;
|
||||
}
|
||||
|
||||
export interface TreasuryDashboardDto {
|
||||
|
||||
Reference in New Issue
Block a user