2026-08-29 21:06:30 +03:30
|
|
|
import {
|
|
|
|
|
BadRequestException,
|
|
|
|
|
Injectable,
|
|
|
|
|
NotFoundException,
|
|
|
|
|
} from '@nestjs/common';
|
|
|
|
|
import type {
|
|
|
|
|
ActivityDto,
|
2026-10-07 12:29:23 +03:30
|
|
|
ActivityFieldValues,
|
2026-08-29 21:06:30 +03:30
|
|
|
ActivityFilter,
|
|
|
|
|
ActivitySummaryDto,
|
2026-10-07 11:18:53 +03:30
|
|
|
ActivityStageCountsDto,
|
2026-08-29 21:06:30 +03:30
|
|
|
CreateActivityRequest,
|
|
|
|
|
PaginatedResponse,
|
|
|
|
|
UpdateActivityRequest,
|
|
|
|
|
} from '@mento/shared';
|
|
|
|
|
import { Prisma } from '@prisma/client';
|
|
|
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
|
|
|
import { NotificationsService } from '../notifications/notifications.service';
|
2026-09-09 21:43:17 +03:30
|
|
|
import { AutomationsService } from '../automations/automations.service';
|
2026-09-13 19:11:47 +03:30
|
|
|
import { MessageAutomationsService } from '../message-automations/message-automations.service';
|
2026-10-07 12:29:23 +03:30
|
|
|
import {
|
|
|
|
|
type Actor,
|
|
|
|
|
activityAccessWhere,
|
|
|
|
|
dealAccessWhere,
|
|
|
|
|
ownerWhere,
|
|
|
|
|
} from '../common/record-scope';
|
2026-09-26 14:59:48 +03:30
|
|
|
import { normalizeTags } from '../common/tags';
|
2026-10-10 21:28:49 +03:30
|
|
|
import { GamificationService } from '../gamification/gamification.service';
|
|
|
|
|
import { tehranDayKey } from '../routines/routine-dates';
|
2026-10-06 15:04:46 +03:30
|
|
|
import { buildSearchWhere, ci } from '../common/search';
|
2026-10-15 10:48:30 +03:30
|
|
|
import { activityPriorWhere } from '../common/prior-archive';
|
2026-10-07 11:18:53 +03:30
|
|
|
import { ActivityStagesService, type StageDefaults } from './activity-stages.service';
|
2026-10-07 12:29:23 +03:30
|
|
|
import {
|
|
|
|
|
ActivityTypesService,
|
|
|
|
|
type SystemTypes,
|
|
|
|
|
type TypeRow,
|
|
|
|
|
} from './activity-types.service';
|
|
|
|
|
|
|
|
|
|
type DtoContext = { stages?: StageDefaults; types?: SystemTypes };
|
2026-08-29 21:06:30 +03:30
|
|
|
|
2026-10-15 10:48:30 +03:30
|
|
|
type ActivityActor = Pick<Actor, 'userId' | 'role' | 'priorLens'>;
|
2026-08-29 21:06:30 +03:30
|
|
|
|
2026-10-07 11:18:53 +03:30
|
|
|
/** stageId = شناسهٔ مرحله یا 'all'؛ وقتی ست باشد فیلتر زمانی وضعیت را تحمیل نمیکند (جز عقبافتاده) */
|
|
|
|
|
type StageScope = { stageId: string };
|
|
|
|
|
|
|
|
|
|
type ListFacets = {
|
|
|
|
|
type?: ActivityDto['type'];
|
2026-10-07 12:29:23 +03:30
|
|
|
typeDefId?: string;
|
2026-10-07 11:18:53 +03:30
|
|
|
status?: ActivityDto['status'];
|
|
|
|
|
assigneeId?: string;
|
|
|
|
|
};
|
|
|
|
|
|
2026-08-29 21:06:30 +03:30
|
|
|
type ActivityRow = {
|
|
|
|
|
id: string;
|
|
|
|
|
type: ActivityDto['type'];
|
|
|
|
|
status: ActivityDto['status'];
|
2026-09-02 21:29:00 +03:30
|
|
|
priority: ActivityDto['priority'];
|
2026-08-29 21:06:30 +03:30
|
|
|
title: string;
|
|
|
|
|
description: string | null;
|
|
|
|
|
dueAt: Date | null;
|
2026-09-02 21:29:00 +03:30
|
|
|
durationMinutes: number | null;
|
|
|
|
|
reminderAt: Date | null;
|
2026-09-05 02:04:39 +03:30
|
|
|
reminderNotifyApp: boolean;
|
|
|
|
|
reminderNotifySms: boolean;
|
2026-10-06 13:49:03 +03:30
|
|
|
reminderSentAt: Date | null;
|
2026-08-29 21:06:30 +03:30
|
|
|
completedAt: Date | null;
|
2026-10-15 10:48:30 +03:30
|
|
|
importSource?: string;
|
2026-09-26 14:59:48 +03:30
|
|
|
tags: string[];
|
2026-08-29 21:06:30 +03:30
|
|
|
createdAt: Date;
|
|
|
|
|
updatedAt: Date;
|
|
|
|
|
person: { id: string; firstName: string; lastName: string } | null;
|
|
|
|
|
company: { id: string; name: string } | null;
|
|
|
|
|
deal: { id: string; title: string } | null;
|
2026-10-11 14:12:36 +03:30
|
|
|
lead?: { id: string; title: string } | null;
|
2026-08-29 21:06:30 +03:30
|
|
|
assignee: { id: string; fullName: string } | null;
|
2026-10-03 13:16:13 +03:30
|
|
|
assignees: Array<{ id: string; fullName: string }>;
|
2026-09-02 21:29:00 +03:30
|
|
|
createdBy: { id: string; fullName: string } | null;
|
2026-10-07 11:18:53 +03:30
|
|
|
stage?: { id: string; kind: ActivityDto['status'] } | null;
|
2026-10-07 12:29:23 +03:30
|
|
|
typeDef?: { id: string; name: string; icon: string; color: string } | null;
|
|
|
|
|
fields?: Prisma.JsonValue | null;
|
|
|
|
|
participantIds?: string[];
|
2026-08-29 21:06:30 +03:30
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const include = {
|
2026-10-07 11:18:53 +03:30
|
|
|
stage: { select: { id: true, kind: true } },
|
2026-10-07 12:29:23 +03:30
|
|
|
typeDef: { select: { id: true, name: true, icon: true, color: true } },
|
2026-08-29 21:06:30 +03:30
|
|
|
person: { select: { id: true, firstName: true, lastName: true } },
|
|
|
|
|
company: { select: { id: true, name: true } },
|
|
|
|
|
deal: { select: { id: true, title: true } },
|
2026-10-11 14:12:36 +03:30
|
|
|
lead: { select: { id: true, title: true } },
|
2026-08-29 21:06:30 +03:30
|
|
|
assignee: { select: { id: true, fullName: true } },
|
2026-10-03 13:16:13 +03:30
|
|
|
assignees: { select: { id: true, fullName: true }, orderBy: { fullName: 'asc' as const } },
|
2026-09-02 21:29:00 +03:30
|
|
|
createdBy: { select: { id: true, fullName: true } },
|
2026-08-29 21:06:30 +03:30
|
|
|
} satisfies Prisma.ActivityInclude;
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class ActivitiesService {
|
|
|
|
|
constructor(
|
|
|
|
|
private readonly prisma: PrismaService,
|
|
|
|
|
private readonly notifications: NotificationsService,
|
2026-09-09 21:43:17 +03:30
|
|
|
private readonly automations: AutomationsService,
|
2026-09-13 19:11:47 +03:30
|
|
|
private readonly messageAutomations: MessageAutomationsService,
|
2026-10-07 11:18:53 +03:30
|
|
|
private readonly stages: ActivityStagesService,
|
2026-10-07 12:29:23 +03:30
|
|
|
private readonly types: ActivityTypesService,
|
2026-10-10 21:28:49 +03:30
|
|
|
private readonly game: GamificationService,
|
2026-08-29 21:06:30 +03:30
|
|
|
) {}
|
|
|
|
|
|
2026-10-07 12:29:23 +03:30
|
|
|
private async ctx(organizationId: string): Promise<DtoContext> {
|
|
|
|
|
const [stages, types] = await Promise.all([
|
|
|
|
|
this.stages.defaults(organizationId),
|
|
|
|
|
this.types.system(organizationId),
|
|
|
|
|
]);
|
|
|
|
|
return { stages, types };
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-29 21:06:30 +03:30
|
|
|
async summary(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
): Promise<ActivitySummaryDto> {
|
|
|
|
|
const { start, end } = dayBounds();
|
2026-10-07 12:29:23 +03:30
|
|
|
const scope = activityAccessWhere(actor);
|
2026-10-15 10:48:30 +03:30
|
|
|
const prior = activityPriorWhere(actor.priorLens);
|
2026-10-06 12:44:09 +03:30
|
|
|
const [todayCount, overdueCount] = await Promise.all([
|
|
|
|
|
this.prisma.activity.count({
|
|
|
|
|
where: {
|
2026-10-15 10:48:30 +03:30
|
|
|
AND: [
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
...scope,
|
|
|
|
|
status: 'open',
|
|
|
|
|
dueAt: { gte: start, lt: end },
|
|
|
|
|
},
|
|
|
|
|
prior,
|
|
|
|
|
],
|
2026-10-06 12:44:09 +03:30
|
|
|
},
|
|
|
|
|
}),
|
|
|
|
|
this.prisma.activity.count({
|
|
|
|
|
where: {
|
2026-10-15 10:48:30 +03:30
|
|
|
AND: [
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
...scope,
|
|
|
|
|
status: 'open',
|
|
|
|
|
dueAt: { lt: start },
|
|
|
|
|
},
|
|
|
|
|
prior,
|
|
|
|
|
],
|
2026-10-06 12:44:09 +03:30
|
|
|
},
|
|
|
|
|
}),
|
|
|
|
|
]);
|
2026-08-29 21:06:30 +03:30
|
|
|
const [today, overdue, upcoming] = await Promise.all([
|
|
|
|
|
this.prisma.activity.findMany({
|
|
|
|
|
where: {
|
2026-10-15 10:48:30 +03:30
|
|
|
AND: [
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
...scope,
|
|
|
|
|
status: 'open',
|
|
|
|
|
dueAt: { gte: start, lt: end },
|
|
|
|
|
},
|
|
|
|
|
prior,
|
|
|
|
|
],
|
2026-08-29 21:06:30 +03:30
|
|
|
},
|
|
|
|
|
include,
|
|
|
|
|
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
|
|
|
|
take: 20,
|
|
|
|
|
}),
|
|
|
|
|
this.prisma.activity.findMany({
|
|
|
|
|
where: {
|
2026-10-15 10:48:30 +03:30
|
|
|
AND: [
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
...scope,
|
|
|
|
|
status: 'open',
|
|
|
|
|
dueAt: { lt: start },
|
|
|
|
|
},
|
|
|
|
|
prior,
|
|
|
|
|
],
|
2026-08-29 21:06:30 +03:30
|
|
|
},
|
|
|
|
|
include,
|
|
|
|
|
orderBy: [{ dueAt: 'asc' }],
|
|
|
|
|
take: 20,
|
|
|
|
|
}),
|
|
|
|
|
this.prisma.activity.findMany({
|
|
|
|
|
where: {
|
2026-10-15 10:48:30 +03:30
|
|
|
AND: [
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
...scope,
|
|
|
|
|
status: 'open',
|
|
|
|
|
OR: [{ dueAt: { gte: end } }, { dueAt: null }],
|
|
|
|
|
},
|
|
|
|
|
prior,
|
|
|
|
|
],
|
2026-08-29 21:06:30 +03:30
|
|
|
},
|
|
|
|
|
include,
|
|
|
|
|
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
|
|
|
|
take: 10,
|
|
|
|
|
}),
|
|
|
|
|
]);
|
|
|
|
|
|
2026-10-07 12:29:23 +03:30
|
|
|
const ctx = await this.ctx(organizationId);
|
2026-08-29 21:06:30 +03:30
|
|
|
return {
|
2026-10-07 12:29:23 +03:30
|
|
|
today: today.map((row) => this.toDto(row, ctx)),
|
|
|
|
|
overdue: overdue.map((row) => this.toDto(row, ctx)),
|
|
|
|
|
upcoming: upcoming.map((row) => this.toDto(row, ctx)),
|
2026-10-06 12:44:09 +03:30
|
|
|
todayCount,
|
|
|
|
|
overdueCount,
|
2026-08-29 21:06:30 +03:30
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async list(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
filter: ActivityFilter = 'today',
|
|
|
|
|
q?: string,
|
|
|
|
|
page = 1,
|
|
|
|
|
limit = 50,
|
|
|
|
|
entity?: {
|
|
|
|
|
personId?: string;
|
|
|
|
|
companyId?: string;
|
|
|
|
|
dealId?: string;
|
2026-10-11 14:12:36 +03:30
|
|
|
leadId?: string;
|
2026-08-29 21:06:30 +03:30
|
|
|
},
|
|
|
|
|
range?: {
|
|
|
|
|
from?: string;
|
|
|
|
|
to?: string;
|
|
|
|
|
},
|
2026-09-28 12:28:14 +03:30
|
|
|
desk?: 'mine' | 'team',
|
2026-10-07 11:18:53 +03:30
|
|
|
facets?: ListFacets,
|
|
|
|
|
stageScope?: StageScope,
|
2026-08-29 21:06:30 +03:30
|
|
|
): Promise<PaginatedResponse<ActivityDto>> {
|
2026-10-07 12:29:23 +03:30
|
|
|
const typeRows = await this.types.rows(organizationId);
|
2026-08-29 21:06:30 +03:30
|
|
|
const where = this.buildWhere(
|
|
|
|
|
organizationId,
|
|
|
|
|
actor,
|
|
|
|
|
filter,
|
|
|
|
|
q,
|
|
|
|
|
entity,
|
|
|
|
|
range,
|
2026-09-28 12:28:14 +03:30
|
|
|
desk,
|
2026-10-03 12:00:46 +03:30
|
|
|
facets,
|
2026-10-07 11:18:53 +03:30
|
|
|
stageScope,
|
2026-10-07 12:29:23 +03:30
|
|
|
typeRows,
|
2026-08-29 21:06:30 +03:30
|
|
|
);
|
2026-10-07 11:18:53 +03:30
|
|
|
if (stageScope && stageScope.stageId !== 'all') {
|
|
|
|
|
(where.AND as Prisma.ActivityWhereInput[]).push(
|
|
|
|
|
await this.stages.whereForStage(organizationId, stageScope.stageId),
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-10-07 12:29:23 +03:30
|
|
|
const ctx: DtoContext = {
|
|
|
|
|
stages: await this.stages.defaults(organizationId),
|
|
|
|
|
types: this.types.systemOf(typeRows),
|
|
|
|
|
};
|
2026-08-29 21:06:30 +03:30
|
|
|
const take = Math.min(Math.max(limit, 1), 200);
|
|
|
|
|
const [rows, total] = await this.prisma.$transaction([
|
|
|
|
|
this.prisma.activity.findMany({
|
|
|
|
|
where,
|
|
|
|
|
include,
|
|
|
|
|
orderBy: [{ dueAt: 'asc' }, { createdAt: 'desc' }],
|
|
|
|
|
skip: (page - 1) * take,
|
|
|
|
|
take,
|
|
|
|
|
}),
|
|
|
|
|
this.prisma.activity.count({ where }),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
return {
|
2026-10-07 12:29:23 +03:30
|
|
|
items: rows.map((row) => this.toDto(row, ctx)),
|
2026-08-29 21:06:30 +03:30
|
|
|
total,
|
|
|
|
|
page,
|
|
|
|
|
limit: take,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-07 11:18:53 +03:30
|
|
|
/** تعداد فعالیت هر مرحله با همان فیلترهای لیست (زمان، جستجو، میز، نوع، کارشناس) */
|
|
|
|
|
async stageCounts(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
filter: ActivityFilter,
|
|
|
|
|
q?: string,
|
|
|
|
|
desk?: 'mine' | 'team',
|
|
|
|
|
facets?: ListFacets,
|
|
|
|
|
): Promise<ActivityStageCountsDto> {
|
|
|
|
|
const rows = await this.stages.rows(organizationId);
|
|
|
|
|
const defaults = this.stages.defaultsOf(rows);
|
|
|
|
|
const kindOf = new Map(rows.map((r) => [r.id, r.kind]));
|
|
|
|
|
const where = this.buildWhere(
|
|
|
|
|
organizationId,
|
|
|
|
|
actor,
|
|
|
|
|
filter,
|
|
|
|
|
q,
|
|
|
|
|
undefined,
|
|
|
|
|
undefined,
|
|
|
|
|
desk,
|
|
|
|
|
facets,
|
|
|
|
|
{ stageId: 'all' },
|
2026-10-07 12:29:23 +03:30
|
|
|
await this.types.rows(organizationId),
|
2026-10-07 11:18:53 +03:30
|
|
|
);
|
|
|
|
|
const groups = await this.prisma.activity.groupBy({
|
|
|
|
|
by: ['status', 'stageId'],
|
|
|
|
|
where,
|
|
|
|
|
_count: { _all: true },
|
|
|
|
|
});
|
|
|
|
|
const counts: Record<string, number> = Object.fromEntries(rows.map((r) => [r.id, 0]));
|
|
|
|
|
let total = 0;
|
|
|
|
|
for (const g of groups) {
|
|
|
|
|
const n = g._count._all;
|
|
|
|
|
total += n;
|
|
|
|
|
const target =
|
|
|
|
|
g.stageId && kindOf.get(g.stageId) === g.status ? g.stageId : defaults[g.status];
|
|
|
|
|
if (target) counts[target] = (counts[target] ?? 0) + n;
|
|
|
|
|
}
|
|
|
|
|
return { counts, total };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async moveToStage(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
id: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
stageId: string,
|
|
|
|
|
): Promise<ActivityDto> {
|
|
|
|
|
await this.ensureExists(organizationId, id, actor);
|
|
|
|
|
const stage = await this.stages.get(organizationId, stageId);
|
|
|
|
|
const existing = await this.prisma.activity.findFirst({
|
|
|
|
|
where: { id, organizationId },
|
|
|
|
|
select: { status: true, completedAt: true },
|
|
|
|
|
});
|
|
|
|
|
const row = await this.prisma.activity.update({
|
|
|
|
|
where: { id },
|
|
|
|
|
data: {
|
|
|
|
|
stageId: stage.id,
|
|
|
|
|
status: stage.kind,
|
|
|
|
|
completedAt:
|
|
|
|
|
stage.kind === 'done'
|
|
|
|
|
? existing?.status === 'done'
|
|
|
|
|
? existing.completedAt ?? new Date()
|
|
|
|
|
: new Date()
|
|
|
|
|
: stage.kind === 'open'
|
|
|
|
|
? null
|
|
|
|
|
: undefined,
|
|
|
|
|
},
|
|
|
|
|
include,
|
|
|
|
|
});
|
|
|
|
|
if (stage.kind === 'done' && existing?.status !== 'done') {
|
|
|
|
|
await this.fireDone(organizationId, row);
|
|
|
|
|
}
|
2026-10-07 12:29:23 +03:30
|
|
|
return this.toDto(row, await this.ctx(organizationId));
|
2026-10-07 11:18:53 +03:30
|
|
|
}
|
|
|
|
|
|
2026-08-29 21:06:30 +03:30
|
|
|
async get(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
id: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
): Promise<ActivityDto> {
|
|
|
|
|
const row = await this.prisma.activity.findFirst({
|
2026-10-07 12:29:23 +03:30
|
|
|
where: { id, organizationId, ...activityAccessWhere(actor) },
|
2026-08-29 21:06:30 +03:30
|
|
|
include,
|
|
|
|
|
});
|
|
|
|
|
if (!row) throw new NotFoundException('فعالیت پیدا نشد');
|
2026-10-07 12:29:23 +03:30
|
|
|
const dto = this.toDto(row, await this.ctx(organizationId));
|
|
|
|
|
if (row.participantIds.length) {
|
|
|
|
|
dto.participantUsers = await this.prisma.user.findMany({
|
|
|
|
|
where: { id: { in: row.participantIds } },
|
|
|
|
|
select: { id: true, fullName: true },
|
|
|
|
|
orderBy: { fullName: 'asc' },
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return dto;
|
2026-08-29 21:06:30 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async create(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
userId: string,
|
|
|
|
|
dto: CreateActivityRequest,
|
|
|
|
|
actor?: ActivityActor,
|
|
|
|
|
): Promise<ActivityDto> {
|
|
|
|
|
const linkActor = actor ?? { userId, role: 'owner' };
|
|
|
|
|
await this.assertLinks(organizationId, linkActor, dto);
|
2026-10-03 13:16:13 +03:30
|
|
|
const assigneeIds = await this.normalizeAssigneeIds(
|
|
|
|
|
organizationId,
|
|
|
|
|
dto.assigneeIds?.length
|
|
|
|
|
? dto.assigneeIds
|
|
|
|
|
: dto.assigneeId
|
|
|
|
|
? [dto.assigneeId]
|
|
|
|
|
: [userId],
|
|
|
|
|
);
|
|
|
|
|
const assigneeId = assigneeIds[0] ?? userId;
|
2026-10-07 11:18:53 +03:30
|
|
|
const initialStageId = emptyToNull(dto.stageId ?? null);
|
|
|
|
|
const initialStage = initialStageId
|
|
|
|
|
? await this.stages.get(organizationId, initialStageId)
|
|
|
|
|
: null;
|
2026-10-07 12:29:23 +03:30
|
|
|
const resolved = await this.types.resolve(organizationId, {
|
|
|
|
|
typeDefId: dto.typeDefId,
|
|
|
|
|
type: dto.type,
|
|
|
|
|
});
|
|
|
|
|
const { fields, participantIds } = await this.types.sanitizeValues(
|
|
|
|
|
organizationId,
|
|
|
|
|
resolved.fields,
|
|
|
|
|
dto.fields,
|
|
|
|
|
);
|
2026-08-29 21:06:30 +03:30
|
|
|
|
|
|
|
|
const row = await this.prisma.activity.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId,
|
2026-10-07 11:18:53 +03:30
|
|
|
...(initialStage
|
|
|
|
|
? {
|
|
|
|
|
stageId: initialStage.id,
|
|
|
|
|
status: initialStage.kind,
|
|
|
|
|
completedAt: initialStage.kind === 'done' ? new Date() : null,
|
|
|
|
|
}
|
|
|
|
|
: {}),
|
2026-08-29 21:06:30 +03:30
|
|
|
title: dto.title.trim(),
|
2026-10-07 12:29:23 +03:30
|
|
|
type: resolved.baseType,
|
|
|
|
|
typeDefId: resolved.typeDefId,
|
|
|
|
|
fields: fields as Prisma.InputJsonValue,
|
|
|
|
|
participantIds,
|
2026-09-02 21:29:00 +03:30
|
|
|
priority: dto.priority ?? 'medium',
|
2026-08-29 21:06:30 +03:30
|
|
|
description: emptyToNull(dto.description),
|
|
|
|
|
dueAt: dto.dueAt ? new Date(dto.dueAt) : null,
|
2026-09-02 21:29:00 +03:30
|
|
|
durationMinutes: dto.durationMinutes ?? null,
|
|
|
|
|
reminderAt: dto.reminderAt ? new Date(dto.reminderAt) : null,
|
2026-09-05 02:04:39 +03:30
|
|
|
reminderNotifyApp: dto.reminderNotifyApp ?? true,
|
|
|
|
|
reminderNotifySms: dto.reminderNotifySms ?? false,
|
2026-09-26 14:59:48 +03:30
|
|
|
tags: normalizeTags(dto.tags),
|
2026-08-29 21:06:30 +03:30
|
|
|
personId: emptyToNull(dto.personId ?? null),
|
|
|
|
|
companyId: emptyToNull(dto.companyId ?? null),
|
|
|
|
|
dealId: emptyToNull(dto.dealId ?? null),
|
|
|
|
|
assigneeId,
|
2026-10-03 13:16:13 +03:30
|
|
|
assignees: assigneeIds.length
|
|
|
|
|
? { connect: assigneeIds.map((id) => ({ id })) }
|
|
|
|
|
: undefined,
|
2026-09-02 21:29:00 +03:30
|
|
|
createdById: userId,
|
2026-08-29 21:06:30 +03:30
|
|
|
},
|
|
|
|
|
include,
|
|
|
|
|
});
|
|
|
|
|
|
2026-10-03 13:16:13 +03:30
|
|
|
for (const uid of assigneeIds) {
|
2026-08-29 21:06:30 +03:30
|
|
|
await this.notifications.create({
|
|
|
|
|
organizationId,
|
2026-10-03 13:16:13 +03:30
|
|
|
userId: uid,
|
2026-08-29 21:06:30 +03:30
|
|
|
type: 'activity_assigned',
|
|
|
|
|
title: 'فعالیت جدید برای شما',
|
|
|
|
|
body: row.title,
|
|
|
|
|
link: `/activities/${row.id}`,
|
|
|
|
|
entityType: 'activity',
|
|
|
|
|
entityId: row.id,
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-10-07 12:29:23 +03:30
|
|
|
await this.notifyParticipants(
|
|
|
|
|
organizationId,
|
|
|
|
|
row,
|
|
|
|
|
participantIds.filter((uid) => !assigneeIds.includes(uid) && uid !== userId),
|
|
|
|
|
);
|
2026-08-29 21:06:30 +03:30
|
|
|
|
2026-09-13 19:11:47 +03:30
|
|
|
await this.messageAutomations.onEvent('activity_created', {
|
|
|
|
|
organizationId,
|
|
|
|
|
entityType: 'activity',
|
|
|
|
|
entityId: row.id,
|
|
|
|
|
title: row.title,
|
|
|
|
|
personId: row.person?.id ?? null,
|
|
|
|
|
companyId: row.company?.id ?? null,
|
|
|
|
|
dealId: row.deal?.id ?? null,
|
|
|
|
|
assigneeId: row.assignee?.id ?? null,
|
|
|
|
|
ownerId: row.assignee?.id ?? null,
|
|
|
|
|
});
|
2026-10-10 21:28:49 +03:30
|
|
|
const gameBase = {
|
|
|
|
|
organizationId,
|
|
|
|
|
userId,
|
|
|
|
|
entityType: 'activity',
|
|
|
|
|
entityId: row.id,
|
|
|
|
|
entityTitle: row.title,
|
|
|
|
|
facts: {
|
|
|
|
|
activityType: row.type,
|
|
|
|
|
typeName: row.typeDef?.name ?? null,
|
|
|
|
|
priority: row.priority,
|
|
|
|
|
hasDescription: !!row.description?.trim(),
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
this.game.emit({ ...gameBase, event: 'ACTIVITY_CREATED' });
|
|
|
|
|
if (row.type === 'call') this.game.emit({ ...gameBase, event: 'CALL_LOGGED' });
|
|
|
|
|
if (row.type === 'meeting') this.game.emit({ ...gameBase, event: 'MEETING_CREATED' });
|
2026-10-07 11:18:53 +03:30
|
|
|
if (initialStage?.kind === 'done') {
|
|
|
|
|
await this.fireDone(organizationId, row);
|
|
|
|
|
}
|
2026-09-13 19:11:47 +03:30
|
|
|
|
2026-10-07 12:29:23 +03:30
|
|
|
return this.toDto(row, await this.ctx(organizationId));
|
2026-08-29 21:06:30 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async update(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
id: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
dto: UpdateActivityRequest,
|
|
|
|
|
): Promise<ActivityDto> {
|
|
|
|
|
await this.ensureExists(organizationId, id, actor);
|
|
|
|
|
await this.assertLinks(organizationId, actor, dto);
|
|
|
|
|
|
2026-10-07 12:29:23 +03:30
|
|
|
const existing = await this.prisma.activity.findFirst({
|
|
|
|
|
where: { id, organizationId },
|
|
|
|
|
select: { status: true, type: true, typeDefId: true, fields: true, participantIds: true },
|
|
|
|
|
});
|
2026-08-29 21:06:30 +03:30
|
|
|
const data: Prisma.ActivityUncheckedUpdateInput = {};
|
|
|
|
|
if (dto.title !== undefined) data.title = dto.title.trim();
|
2026-10-07 12:29:23 +03:30
|
|
|
let addedParticipants: string[] = [];
|
|
|
|
|
const typeChanged = 'typeDefId' in dto || dto.type !== undefined;
|
|
|
|
|
if (typeChanged || dto.fields !== undefined) {
|
|
|
|
|
const resolved = await this.types.resolve(
|
|
|
|
|
organizationId,
|
|
|
|
|
typeChanged
|
|
|
|
|
? { typeDefId: dto.typeDefId, type: dto.type }
|
|
|
|
|
: { typeDefId: existing?.typeDefId, type: existing?.type },
|
|
|
|
|
);
|
|
|
|
|
const { fields, participantIds } = await this.types.sanitizeValues(
|
|
|
|
|
organizationId,
|
|
|
|
|
resolved.fields,
|
|
|
|
|
dto.fields ?? existing?.fields,
|
|
|
|
|
);
|
|
|
|
|
data.type = resolved.baseType;
|
|
|
|
|
data.typeDefId = resolved.typeDefId;
|
|
|
|
|
data.fields = fields as Prisma.InputJsonValue;
|
|
|
|
|
data.participantIds = participantIds;
|
|
|
|
|
const before = new Set(existing?.participantIds ?? []);
|
|
|
|
|
addedParticipants = participantIds.filter((uid) => !before.has(uid) && uid !== actor.userId);
|
|
|
|
|
}
|
2026-09-02 21:29:00 +03:30
|
|
|
if (dto.priority !== undefined) data.priority = dto.priority;
|
2026-08-29 21:06:30 +03:30
|
|
|
if ('description' in dto) data.description = emptyToNull(dto.description);
|
|
|
|
|
if ('dueAt' in dto) data.dueAt = dto.dueAt ? new Date(dto.dueAt) : null;
|
2026-09-02 21:29:00 +03:30
|
|
|
if ('durationMinutes' in dto) data.durationMinutes = dto.durationMinutes ?? null;
|
2026-10-06 13:49:03 +03:30
|
|
|
if ('reminderAt' in dto) {
|
|
|
|
|
const nextReminder = dto.reminderAt ? new Date(dto.reminderAt) : null;
|
|
|
|
|
const current = await this.prisma.activity.findUnique({
|
|
|
|
|
where: { id },
|
|
|
|
|
select: { reminderAt: true },
|
|
|
|
|
});
|
|
|
|
|
const prevMs = current?.reminderAt?.getTime() ?? null;
|
|
|
|
|
const nextMs = nextReminder?.getTime() ?? null;
|
|
|
|
|
data.reminderAt = nextReminder;
|
|
|
|
|
if (prevMs !== nextMs) data.reminderSentAt = null;
|
|
|
|
|
}
|
2026-09-05 02:04:39 +03:30
|
|
|
if (dto.reminderNotifyApp !== undefined) data.reminderNotifyApp = dto.reminderNotifyApp;
|
|
|
|
|
if (dto.reminderNotifySms !== undefined) data.reminderNotifySms = dto.reminderNotifySms;
|
2026-09-26 14:59:48 +03:30
|
|
|
if ('tags' in dto) data.tags = normalizeTags(dto.tags);
|
2026-08-29 21:06:30 +03:30
|
|
|
if ('personId' in dto) data.personId = emptyToNull(dto.personId ?? null);
|
|
|
|
|
if ('companyId' in dto) data.companyId = emptyToNull(dto.companyId ?? null);
|
|
|
|
|
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
|
2026-10-03 13:16:13 +03:30
|
|
|
let assigneeConnect: Array<{ id: string }> | undefined;
|
|
|
|
|
if (dto.assigneeIds !== undefined) {
|
|
|
|
|
const assigneeIds = await this.normalizeAssigneeIds(
|
|
|
|
|
organizationId,
|
|
|
|
|
dto.assigneeIds,
|
|
|
|
|
);
|
|
|
|
|
if (!assigneeIds.length) {
|
|
|
|
|
throw new BadRequestException('حداقل یک مسئول لازم است');
|
|
|
|
|
}
|
|
|
|
|
data.assigneeId = assigneeIds[0]!;
|
|
|
|
|
assigneeConnect = assigneeIds.map((uid) => ({ id: uid }));
|
|
|
|
|
} else if ('assigneeId' in dto) {
|
2026-08-29 21:06:30 +03:30
|
|
|
const assigneeId = emptyToNull(dto.assigneeId ?? null);
|
|
|
|
|
if (assigneeId) await this.assertUserInOrg(organizationId, assigneeId);
|
|
|
|
|
data.assigneeId = assigneeId;
|
2026-10-03 13:16:13 +03:30
|
|
|
if (assigneeId) assigneeConnect = [{ id: assigneeId }];
|
|
|
|
|
else assigneeConnect = [];
|
2026-08-29 21:06:30 +03:30
|
|
|
}
|
|
|
|
|
if (dto.status !== undefined) {
|
|
|
|
|
data.status = dto.status;
|
|
|
|
|
data.completedAt =
|
|
|
|
|
dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const row = await this.prisma.activity.update({
|
|
|
|
|
where: { id },
|
2026-10-03 13:16:13 +03:30
|
|
|
data: {
|
|
|
|
|
...data,
|
|
|
|
|
...(assigneeConnect
|
|
|
|
|
? { assignees: { set: assigneeConnect } }
|
|
|
|
|
: {}),
|
|
|
|
|
},
|
2026-08-29 21:06:30 +03:30
|
|
|
include,
|
|
|
|
|
});
|
2026-10-07 12:29:23 +03:30
|
|
|
if (addedParticipants.length) {
|
|
|
|
|
const assigneeSet = new Set([
|
|
|
|
|
...(row.assignee ? [row.assignee.id] : []),
|
|
|
|
|
...row.assignees.map((a) => a.id),
|
|
|
|
|
]);
|
|
|
|
|
await this.notifyParticipants(
|
|
|
|
|
organizationId,
|
|
|
|
|
row,
|
|
|
|
|
addedParticipants.filter((uid) => !assigneeSet.has(uid)),
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-09-09 21:43:17 +03:30
|
|
|
if (dto.status === 'done' && existing?.status !== 'done') {
|
|
|
|
|
await this.fireDone(organizationId, row);
|
|
|
|
|
}
|
2026-10-07 12:29:23 +03:30
|
|
|
return this.toDto(row, await this.ctx(organizationId));
|
2026-08-29 21:06:30 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async complete(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
id: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
): Promise<ActivityDto> {
|
|
|
|
|
await this.ensureExists(organizationId, id, actor);
|
2026-09-09 21:43:17 +03:30
|
|
|
const existing = await this.prisma.activity.findFirst({
|
|
|
|
|
where: { id, organizationId },
|
|
|
|
|
select: { status: true },
|
|
|
|
|
});
|
2026-08-29 21:06:30 +03:30
|
|
|
const row = await this.prisma.activity.update({
|
|
|
|
|
where: { id },
|
|
|
|
|
data: { status: 'done', completedAt: new Date() },
|
|
|
|
|
include,
|
|
|
|
|
});
|
2026-09-09 21:43:17 +03:30
|
|
|
if (existing?.status !== 'done') {
|
|
|
|
|
await this.fireDone(organizationId, row);
|
|
|
|
|
}
|
2026-10-07 12:29:23 +03:30
|
|
|
return this.toDto(row, await this.ctx(organizationId));
|
2026-08-29 21:06:30 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async remove(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
id: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
await this.ensureExists(organizationId, id, actor);
|
|
|
|
|
await this.prisma.activity.delete({ where: { id } });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private buildWhere(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
filter: ActivityFilter,
|
|
|
|
|
q?: string,
|
|
|
|
|
entity?: {
|
|
|
|
|
personId?: string;
|
|
|
|
|
companyId?: string;
|
|
|
|
|
dealId?: string;
|
2026-10-11 14:12:36 +03:30
|
|
|
leadId?: string;
|
2026-08-29 21:06:30 +03:30
|
|
|
},
|
|
|
|
|
range?: {
|
|
|
|
|
from?: string;
|
|
|
|
|
to?: string;
|
|
|
|
|
},
|
2026-09-28 12:28:14 +03:30
|
|
|
desk?: 'mine' | 'team',
|
2026-10-07 11:18:53 +03:30
|
|
|
facets?: ListFacets,
|
|
|
|
|
stageScope?: StageScope,
|
2026-10-07 12:29:23 +03:30
|
|
|
typeRows: TypeRow[] = [],
|
2026-08-29 21:06:30 +03:30
|
|
|
): Prisma.ActivityWhereInput {
|
|
|
|
|
const { start, end } = dayBounds();
|
2026-10-03 13:16:13 +03:30
|
|
|
const scope: Prisma.ActivityWhereInput =
|
|
|
|
|
desk === 'mine'
|
2026-08-29 21:06:30 +03:30
|
|
|
? {
|
|
|
|
|
OR: [
|
2026-10-03 13:16:13 +03:30
|
|
|
{ assigneeId: actor.userId },
|
|
|
|
|
{ assignees: { some: { id: actor.userId } } },
|
2026-10-07 12:29:23 +03:30
|
|
|
{ participantIds: { has: actor.userId } },
|
2026-08-29 21:06:30 +03:30
|
|
|
],
|
|
|
|
|
}
|
2026-10-07 12:29:23 +03:30
|
|
|
: activityAccessWhere(actor);
|
2026-10-03 13:16:13 +03:30
|
|
|
const facetAssignee = facets?.assigneeId?.trim();
|
2026-10-07 12:29:23 +03:30
|
|
|
const facetTypeDef = facets?.typeDefId?.trim();
|
2026-10-03 13:16:13 +03:30
|
|
|
const andParts: Prisma.ActivityWhereInput[] = [
|
|
|
|
|
scope,
|
|
|
|
|
...(facets?.type ? [{ type: facets.type }] : []),
|
2026-10-07 12:29:23 +03:30
|
|
|
...(facetTypeDef ? [this.types.whereForType(typeRows, facetTypeDef)] : []),
|
2026-10-03 13:16:13 +03:30
|
|
|
...(facets?.status ? [{ status: facets.status }] : []),
|
|
|
|
|
...(facetAssignee
|
|
|
|
|
? [
|
|
|
|
|
{
|
|
|
|
|
OR: [
|
|
|
|
|
{ assigneeId: facetAssignee },
|
|
|
|
|
{ assignees: { some: { id: facetAssignee } } },
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
]
|
|
|
|
|
: []),
|
|
|
|
|
...(entity?.personId ? [{ personId: entity.personId }] : []),
|
|
|
|
|
...(entity?.companyId ? [{ companyId: entity.companyId }] : []),
|
|
|
|
|
...(entity?.dealId ? [{ dealId: entity.dealId }] : []),
|
2026-10-11 14:12:36 +03:30
|
|
|
...(entity?.leadId ? [{ leadId: entity.leadId }] : []),
|
2026-10-03 13:16:13 +03:30
|
|
|
];
|
2026-10-06 15:04:46 +03:30
|
|
|
const search = buildSearchWhere<Prisma.ActivityWhereInput>(q, (t) => [
|
|
|
|
|
{ title: ci(t) },
|
|
|
|
|
{ description: ci(t) },
|
2026-10-07 13:17:29 +03:30
|
|
|
{ tags: { has: t.replace(/^#/, '') } },
|
2026-10-06 15:04:46 +03:30
|
|
|
{
|
|
|
|
|
person: {
|
|
|
|
|
OR: [
|
|
|
|
|
{ firstName: ci(t) },
|
|
|
|
|
{ lastName: ci(t) },
|
|
|
|
|
{ mobile: { contains: t } },
|
|
|
|
|
{ phone: { contains: t } },
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
{ company: { name: ci(t) } },
|
|
|
|
|
{ deal: { title: ci(t) } },
|
2026-10-07 12:29:23 +03:30
|
|
|
{ assignee: { fullName: ci(t) } },
|
|
|
|
|
{ assignees: { some: { fullName: ci(t) } } },
|
|
|
|
|
...typesMatching(t).map((type) => ({ type })),
|
|
|
|
|
...this.types.searchByName(typeRows, t),
|
2026-10-06 15:04:46 +03:30
|
|
|
]);
|
|
|
|
|
if (search) andParts.push(search);
|
2026-10-15 10:48:30 +03:30
|
|
|
const onRecord = Boolean(entity?.personId || entity?.companyId || entity?.dealId);
|
|
|
|
|
if (!onRecord) andParts.push(activityPriorWhere(actor.priorLens));
|
2026-10-03 13:16:13 +03:30
|
|
|
const base: Prisma.ActivityWhereInput = {
|
|
|
|
|
organizationId,
|
|
|
|
|
AND: andParts,
|
2026-08-29 21:06:30 +03:30
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const fromDate = range?.from ? new Date(range.from) : null;
|
|
|
|
|
const toDate = range?.to ? new Date(range.to) : null;
|
|
|
|
|
if (fromDate || toDate) {
|
|
|
|
|
return {
|
|
|
|
|
...base,
|
|
|
|
|
dueAt: {
|
|
|
|
|
...(fromDate && !Number.isNaN(fromDate.getTime())
|
|
|
|
|
? { gte: fromDate }
|
|
|
|
|
: {}),
|
|
|
|
|
...(toDate && !Number.isNaN(toDate.getTime()) ? { lt: toDate } : {}),
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-03 12:00:46 +03:30
|
|
|
// Explicit status facet overrides the status implied by time tabs.
|
2026-10-07 11:18:53 +03:30
|
|
|
// With stage tabs/columns the stage decides status; time filters only narrow dueAt.
|
|
|
|
|
const impliedOpen = facets?.status
|
|
|
|
|
? { status: facets.status }
|
|
|
|
|
: stageScope
|
|
|
|
|
? {}
|
|
|
|
|
: { status: 'open' as const };
|
2026-10-03 12:00:46 +03:30
|
|
|
const impliedDone = facets?.status ? { status: facets.status } : { status: 'done' as const };
|
|
|
|
|
|
2026-08-29 21:06:30 +03:30
|
|
|
switch (filter) {
|
|
|
|
|
case 'today':
|
2026-10-03 12:00:46 +03:30
|
|
|
return { ...base, ...impliedOpen, dueAt: { gte: start, lt: end } };
|
2026-08-29 21:06:30 +03:30
|
|
|
case 'overdue':
|
2026-10-07 11:18:53 +03:30
|
|
|
// عقبافتاده ذاتاً یعنی باز و موعدگذشته
|
|
|
|
|
return {
|
|
|
|
|
...base,
|
|
|
|
|
...(facets?.status ? { status: facets.status } : { status: 'open' as const }),
|
|
|
|
|
dueAt: { lt: start },
|
|
|
|
|
};
|
2026-08-29 21:06:30 +03:30
|
|
|
case 'upcoming':
|
|
|
|
|
return {
|
|
|
|
|
...base,
|
2026-10-03 12:00:46 +03:30
|
|
|
...impliedOpen,
|
2026-08-29 21:06:30 +03:30
|
|
|
OR: [{ dueAt: { gte: end } }, { dueAt: null }],
|
|
|
|
|
};
|
|
|
|
|
case 'done':
|
2026-10-03 12:00:46 +03:30
|
|
|
return { ...base, ...impliedDone };
|
2026-08-29 21:06:30 +03:30
|
|
|
case 'all':
|
|
|
|
|
default:
|
|
|
|
|
return base;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-09 21:43:17 +03:30
|
|
|
private async fireDone(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
row: {
|
|
|
|
|
id: string;
|
|
|
|
|
title: string;
|
|
|
|
|
person: { id: string } | null;
|
|
|
|
|
company: { id: string } | null;
|
|
|
|
|
deal: { id: string } | null;
|
|
|
|
|
assignee: { id: string } | null;
|
2026-10-10 21:28:49 +03:30
|
|
|
type: string;
|
|
|
|
|
priority: string;
|
|
|
|
|
dueAt: Date | null;
|
|
|
|
|
typeDef?: { name: string } | null;
|
2026-09-09 21:43:17 +03:30
|
|
|
},
|
|
|
|
|
) {
|
2026-10-10 21:28:49 +03:30
|
|
|
this.game.emit({
|
|
|
|
|
organizationId,
|
|
|
|
|
userId: row.assignee?.id,
|
|
|
|
|
event: 'TASK_COMPLETED',
|
|
|
|
|
entityType: 'activity',
|
|
|
|
|
entityId: row.id,
|
|
|
|
|
entityTitle: row.title,
|
|
|
|
|
facts: {
|
|
|
|
|
activityType: row.type,
|
|
|
|
|
typeName: row.typeDef?.name ?? null,
|
|
|
|
|
priority: row.priority,
|
|
|
|
|
onTime: !row.dueAt || tehranDayKey() <= tehranDayKey(row.dueAt),
|
|
|
|
|
},
|
|
|
|
|
});
|
2026-09-13 19:11:47 +03:30
|
|
|
const ctx = {
|
2026-09-09 21:43:17 +03:30
|
|
|
organizationId,
|
2026-09-13 19:11:47 +03:30
|
|
|
entityType: 'activity' as const,
|
2026-09-09 21:43:17 +03:30
|
|
|
entityId: row.id,
|
|
|
|
|
title: row.title,
|
|
|
|
|
personId: row.person?.id ?? null,
|
|
|
|
|
companyId: row.company?.id ?? null,
|
|
|
|
|
dealId: row.deal?.id ?? null,
|
|
|
|
|
assigneeId: row.assignee?.id ?? null,
|
|
|
|
|
ownerId: row.assignee?.id ?? null,
|
2026-09-13 19:11:47 +03:30
|
|
|
};
|
|
|
|
|
await this.automations.runTrigger('activity_done', ctx);
|
|
|
|
|
await this.messageAutomations.onEvent('activity_done', ctx);
|
2026-09-09 21:43:17 +03:30
|
|
|
}
|
|
|
|
|
|
2026-08-29 21:06:30 +03:30
|
|
|
private async ensureExists(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
id: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
) {
|
|
|
|
|
const found = await this.prisma.activity.findFirst({
|
2026-10-07 12:29:23 +03:30
|
|
|
where: { id, organizationId, ...activityAccessWhere(actor) },
|
2026-08-29 21:06:30 +03:30
|
|
|
select: { id: true },
|
|
|
|
|
});
|
|
|
|
|
if (!found) throw new NotFoundException('فعالیت پیدا نشد');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async assertUserInOrg(organizationId: string, userId: string) {
|
|
|
|
|
const user = await this.prisma.user.findFirst({
|
2026-09-15 21:37:58 +03:30
|
|
|
where: { id: userId, memberships: { some: { organizationId } } },
|
2026-08-29 21:06:30 +03:30
|
|
|
select: { id: true },
|
|
|
|
|
});
|
|
|
|
|
if (!user) throw new BadRequestException('مسئول انتخابشده معتبر نیست');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async assertLinks(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
actor: ActivityActor,
|
|
|
|
|
dto: {
|
|
|
|
|
personId?: string | null;
|
|
|
|
|
companyId?: string | null;
|
|
|
|
|
dealId?: string | null;
|
|
|
|
|
},
|
|
|
|
|
) {
|
|
|
|
|
const personId = emptyToNull(dto.personId ?? null);
|
|
|
|
|
const companyId = emptyToNull(dto.companyId ?? null);
|
|
|
|
|
const dealId = emptyToNull(dto.dealId ?? null);
|
|
|
|
|
const scope = ownerWhere(actor);
|
|
|
|
|
|
|
|
|
|
if (personId) {
|
|
|
|
|
const person = await this.prisma.person.findFirst({
|
|
|
|
|
where: { id: personId, organizationId, ...scope },
|
|
|
|
|
select: { id: true },
|
|
|
|
|
});
|
|
|
|
|
if (!person) throw new BadRequestException('شخص انتخابشده معتبر نیست');
|
|
|
|
|
}
|
|
|
|
|
if (companyId) {
|
|
|
|
|
const company = await this.prisma.company.findFirst({
|
|
|
|
|
where: { id: companyId, organizationId, ...scope },
|
|
|
|
|
select: { id: true },
|
|
|
|
|
});
|
|
|
|
|
if (!company) throw new BadRequestException('شرکت انتخابشده معتبر نیست');
|
|
|
|
|
}
|
|
|
|
|
if (dealId) {
|
|
|
|
|
const deal = await this.prisma.deal.findFirst({
|
2026-09-27 14:25:32 +03:30
|
|
|
where: { id: dealId, organizationId, ...dealAccessWhere(actor) },
|
2026-08-29 21:06:30 +03:30
|
|
|
select: { id: true },
|
|
|
|
|
});
|
|
|
|
|
if (!deal) throw new BadRequestException('معامله انتخابشده معتبر نیست');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-07 12:29:23 +03:30
|
|
|
private async notifyParticipants(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
row: { id: string; title: string },
|
|
|
|
|
userIds: string[],
|
|
|
|
|
) {
|
|
|
|
|
for (const uid of new Set(userIds)) {
|
|
|
|
|
await this.notifications.create({
|
|
|
|
|
organizationId,
|
|
|
|
|
userId: uid,
|
|
|
|
|
type: 'activity_assigned',
|
|
|
|
|
title: 'شما بهعنوان شرکتکننده اضافه شدید',
|
|
|
|
|
body: row.title,
|
|
|
|
|
link: `/activities/${row.id}`,
|
|
|
|
|
entityType: 'activity',
|
|
|
|
|
entityId: row.id,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private toDto(row: ActivityRow, ctx?: DtoContext): ActivityDto {
|
|
|
|
|
const fields =
|
|
|
|
|
row.fields && typeof row.fields === 'object' && !Array.isArray(row.fields)
|
|
|
|
|
? (row.fields as unknown as ActivityFieldValues)
|
|
|
|
|
: {};
|
2026-08-29 21:06:30 +03:30
|
|
|
return {
|
2026-10-07 12:29:23 +03:30
|
|
|
stageId: this.stages.effectiveStageId(row, ctx?.stages),
|
|
|
|
|
typeDef: row.typeDef
|
|
|
|
|
? this.types.toSummary(row.typeDef)
|
|
|
|
|
: (ctx?.types?.[row.type] ?? null),
|
|
|
|
|
fields,
|
|
|
|
|
participantIds: row.participantIds ?? [],
|
2026-08-29 21:06:30 +03:30
|
|
|
id: row.id,
|
|
|
|
|
type: row.type,
|
|
|
|
|
status: row.status,
|
2026-09-02 21:29:00 +03:30
|
|
|
priority: row.priority,
|
2026-08-29 21:06:30 +03:30
|
|
|
title: row.title,
|
|
|
|
|
description: row.description,
|
|
|
|
|
dueAt: row.dueAt?.toISOString() ?? null,
|
2026-09-02 21:29:00 +03:30
|
|
|
durationMinutes: row.durationMinutes,
|
|
|
|
|
reminderAt: row.reminderAt?.toISOString() ?? null,
|
2026-09-05 02:04:39 +03:30
|
|
|
reminderNotifyApp: row.reminderNotifyApp,
|
|
|
|
|
reminderNotifySms: row.reminderNotifySms,
|
2026-10-06 13:49:03 +03:30
|
|
|
reminderSentAt: row.reminderSentAt?.toISOString() ?? null,
|
2026-08-29 21:06:30 +03:30
|
|
|
completedAt: row.completedAt?.toISOString() ?? null,
|
2026-10-15 10:48:30 +03:30
|
|
|
importSource: row.importSource ?? 'manual',
|
2026-09-26 14:59:48 +03:30
|
|
|
tags: row.tags ?? [],
|
2026-08-29 21:06:30 +03:30
|
|
|
person: row.person
|
|
|
|
|
? {
|
|
|
|
|
id: row.person.id,
|
|
|
|
|
fullName: `${row.person.firstName} ${row.person.lastName}`.trim(),
|
|
|
|
|
}
|
|
|
|
|
: null,
|
|
|
|
|
company: row.company,
|
|
|
|
|
deal: row.deal,
|
2026-10-11 14:12:36 +03:30
|
|
|
lead: row.lead ?? null,
|
2026-08-29 21:06:30 +03:30
|
|
|
assignee: row.assignee,
|
2026-10-03 13:16:13 +03:30
|
|
|
assignees: (() => {
|
|
|
|
|
const list = [...(row.assignees ?? [])];
|
|
|
|
|
if (row.assignee && !list.some((a) => a.id === row.assignee!.id)) {
|
|
|
|
|
list.unshift(row.assignee);
|
|
|
|
|
}
|
|
|
|
|
return list;
|
|
|
|
|
})(),
|
2026-09-02 21:29:00 +03:30
|
|
|
createdBy: row.createdBy,
|
2026-08-29 21:06:30 +03:30
|
|
|
createdAt: row.createdAt.toISOString(),
|
|
|
|
|
updatedAt: row.updatedAt.toISOString(),
|
|
|
|
|
};
|
|
|
|
|
}
|
2026-10-03 13:16:13 +03:30
|
|
|
|
|
|
|
|
private async normalizeAssigneeIds(
|
|
|
|
|
organizationId: string,
|
|
|
|
|
raw?: string[] | null,
|
|
|
|
|
): Promise<string[]> {
|
|
|
|
|
const ids = [
|
|
|
|
|
...new Set((raw ?? []).map((id) => id.trim()).filter(Boolean)),
|
|
|
|
|
];
|
|
|
|
|
if (!ids.length) return [];
|
|
|
|
|
const count = await this.prisma.user.count({
|
|
|
|
|
where: { organizationId, id: { in: ids }, isActive: true },
|
|
|
|
|
});
|
|
|
|
|
if (count !== ids.length) {
|
|
|
|
|
throw new BadRequestException('یکی از مسئولان انتخابشده معتبر نیست');
|
|
|
|
|
}
|
|
|
|
|
return ids;
|
|
|
|
|
}
|
2026-08-29 21:06:30 +03:30
|
|
|
}
|
|
|
|
|
|
2026-10-07 12:29:23 +03:30
|
|
|
const TYPE_SEARCH_TERMS: Record<ActivityDto['type'], string[]> = {
|
|
|
|
|
call: ['تماس', 'تلفن', 'call'],
|
|
|
|
|
meeting: ['جلسه', 'ملاقات', 'meeting'],
|
|
|
|
|
task: ['وظیفه', 'تسک', 'task'],
|
|
|
|
|
note: ['پیام', 'یادداشت', 'note'],
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/** جستجوی «جلسه» یا «تماس» → فیلتر نوع فعالیت */
|
|
|
|
|
function typesMatching(term: string): ActivityDto['type'][] {
|
|
|
|
|
const t = term.trim().toLowerCase();
|
|
|
|
|
if (t.length < 2) return [];
|
|
|
|
|
return (Object.keys(TYPE_SEARCH_TERMS) as ActivityDto['type'][]).filter((type) =>
|
|
|
|
|
TYPE_SEARCH_TERMS[type].some((label) => label.includes(t) || t.includes(label)),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-29 21:06:30 +03:30
|
|
|
function emptyToNull(value?: string | null): string | null {
|
|
|
|
|
if (value == null) return null;
|
|
|
|
|
const trimmed = value.trim();
|
|
|
|
|
return trimmed.length ? trimmed : null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function dayBounds(now = new Date()) {
|
|
|
|
|
const start = new Date(now);
|
|
|
|
|
start.setHours(0, 0, 0, 0);
|
|
|
|
|
const end = new Date(start);
|
|
|
|
|
end.setDate(end.getDate() + 1);
|
|
|
|
|
return { start, end };
|
|
|
|
|
}
|