12 Commits
Author SHA1 Message Date
MahdiandCursor 0ce2533066 fix(api): load multer types for avatar upload typecheck
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 18:08:31 +03:30
MahdiandCursor bc68582fe2 Fix prior archive filter collisions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:49:51 +03:30
MahdiandCursor e86841fc60 feat(web): add prior archive promote actions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:28:57 +03:30
MahdiandCursor 5069647f79 Add prior archive team settings UI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:20:28 +03:30
MahdiandCursor 008733d338 Add prior promotion endpoints
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:13:01 +03:30
Mahdi c5708ed59b chore: stop tracking local SDD scratch files 2026-10-17 17:03:23 +03:30
MahdiandCursor 65d66bb331 Implement prior archive cutoff API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:01:52 +03:30
MahdiandCursor 79ba146118 Wire prior archive cutoff through API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 16:52:20 +03:30
MahdiandCursor 02841a5b8c refactor(api): cutoff-based prior-archive where helpers
Replace didar/live-deal filters with createdAt cutoff and promotedFromPriorAt; add unit tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 16:33:32 +03:30
Mahdi a04743c6df feat: add prior-archive promote fields and shared cutoff DTOs 2026-10-17 16:27:29 +03:30
MahdiandCursor 27635c0752 docs: add prior-archive cutoff plan and ignore worktrees
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 16:07:59 +03:30
MahdiandCursor 03e1c01023 docs: specify date-cutoff prior archive and one-way promote
Replace Didar-source classification with org cutoff date, deals/activities-only filter, and a promote tag that does not mutate record fields.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 15:29:37 +03:30
35 changed files with 1598 additions and 278 deletions
+4
View File
@@ -32,3 +32,7 @@ playwright-report/
graphify-out/
**/graphify-out/
.cursor/rules/graphify.mdc
# Local git worktrees + SDD scratch
.worktrees/
.superpowers/
-17
View File
@@ -1,17 +0,0 @@
# Task 5 report
Status: DONE
- shared build: OK
- pipeline-merge.test.ts: 5/5 pass
- api typecheck: OK
- vue-tsc: see VUE_EXIT in controller log
- graphify: attempted (may crash)
No commit required for verification-only task.
## Follow-up fix: final review important findings
Status: DONE
- I-1: Added in-transaction unmoved-deal count guard before deleting the source pipeline.
- I-3: Added 30000ms timeout to the interactive merge transaction.
- M-1: Added `@IsIn(['retarget_all'])` validation to `MergePipelineDto.leadFormMode`.
- graphify update: OK
- `cd apps/api; npx tsx --test test/pipeline-merge.test.ts`: OK, 5/5 pass
- `npm run typecheck -w @mento/api`: OK
+1 -1
View File
@@ -12,7 +12,7 @@
"prisma:seed": "tsx prisma/seed.ts",
"lint": "echo \"api lint placeholder\"",
"typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p test/tsconfig.json",
"test": "tsx --test test/tahesab-methods.test.ts test/dates.test.ts test/birthdays.test.ts test/message-automation.test.ts test/record-scope.test.ts test/gamification-engine.test.ts test/automation-branches.test.ts test/pipeline-merge.test.ts test/ask-count.test.ts test/prior-archive.test.ts"
"test": "tsx --test test/tahesab-methods.test.ts test/dates.test.ts test/birthdays.test.ts test/message-automation.test.ts test/record-scope.test.ts test/gamification-engine.test.ts test/automation-branches.test.ts test/pipeline-merge.test.ts test/ask-count.test.ts test/prior-archive.test.ts test/organizations.test.ts test/promote-from-prior.test.ts"
},
"dependencies": {
"@mento/shared": "*",
@@ -0,0 +1,8 @@
-- Prior archive: promote tag + cutoff query indexes
ALTER TABLE "Deal" ADD COLUMN "promotedFromPriorAt" TIMESTAMP(3);
ALTER TABLE "Activity" ADD COLUMN "promotedFromPriorAt" TIMESTAMP(3);
CREATE INDEX "Deal_organizationId_createdAt_idx" ON "Deal"("organizationId", "createdAt");
CREATE INDEX "Activity_organizationId_createdAt_idx" ON "Activity"("organizationId", "createdAt");
+7 -1
View File
@@ -150,7 +150,7 @@ model Organization {
enabledCurrencies String[] @default(["IRR", "USD", "EUR"])
/// ماژول‌های فعال منو برای این محیط
enabledModules String[] @default([])
/// اولین لحظهٔ روشن شدن «بایگانی اطلاعات قبل»؛ مرز فعالیت‌های قبلی
/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر
priorArchiveEnabledAt DateTime?
isActive Boolean @default(true)
createdAt DateTime @default(now())
@@ -600,6 +600,8 @@ model Deal {
code String?
/// منبع ورود: manual | didar | excel
importSource String @default("manual")
/// اگر پر باشد، رکورد از بایگانی به کار جاری منتقل شده (فقط برچسب؛ بقیه فیلدها دست‌نخورده)
promotedFromPriorAt DateTime?
/// شناسه در مبدأ (کد دیدار معامله)
sourceRef String?
amount Decimal? @db.Decimal(18, 2)
@@ -650,6 +652,7 @@ model Deal {
@@index([companyId])
@@index([ownerId])
@@index([organizationId, sourceRef])
@@index([organizationId, createdAt])
}
/// مراحل/ستون‌های فعالیت (تب و کانبان) — kind وضعیت فعالیت داخل این مرحله را تعیین می‌کند
@@ -703,6 +706,8 @@ model Activity {
title String
/// manual | didar — سابقهٔ منتقل‌شده از اطلاعات قبل
importSource String @default("manual")
/// اگر پر باشد، رکورد از بایگانی به کار جاری منتقل شده (فقط برچسب؛ بقیه فیلدها دست‌نخورده)
promotedFromPriorAt DateTime?
description String?
dueAt DateTime?
durationMinutes Int?
@@ -750,6 +755,7 @@ model Activity {
@@index([leadId])
@@index([organizationId, status, dueAt])
@@index([organizationId, importSource])
@@index([organizationId, createdAt])
@@index([organizationId, assigneeId])
@@index([organizationId, createdById])
@@index([reminderAt, reminderSentAt])
@@ -267,6 +267,11 @@ export class ActivitiesController {
return this.activitiesService.get(user.organizationId, id, user);
}
@Post(':id/promote-from-prior')
promoteFromPrior(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.activitiesService.promoteFromPrior(user, id);
}
@Post()
create(@CurrentUser() user: Actor, @Body() dto: CreateActivityDto) {
return this.activitiesService.create(
+37 -2
View File
@@ -1,5 +1,6 @@
import {
BadRequestException,
ForbiddenException,
Injectable,
NotFoundException,
} from '@nestjs/common';
@@ -65,6 +66,7 @@ type ActivityRow = {
reminderSentAt: Date | null;
completedAt: Date | null;
importSource?: string;
promotedFromPriorAt?: Date | null;
tags: string[];
createdAt: Date;
updatedAt: Date;
@@ -119,7 +121,7 @@ export class ActivitiesService {
): Promise<ActivitySummaryDto> {
const { start, end } = dayBounds();
const scope = activityAccessWhere(actor);
const prior = activityPriorWhere(actor.priorLens, new Date(), actor.priorCutoff);
const prior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
const [todayCount, overdueCount] = await Promise.all([
this.prisma.activity.count({
where: {
@@ -615,6 +617,38 @@ export class ActivitiesService {
return this.toDto(row, await this.ctx(organizationId));
}
async promoteFromPrior(actor: Actor, id: string): Promise<ActivityDto> {
if (
(actor.priorLens !== 'current' && actor.priorLens !== 'archive') ||
!actor.priorCutoff
) {
throw new ForbiddenException('بایگانی اطلاعات قبل برای شما فعال نیست.');
}
const row = await this.prisma.activity.findFirst({
where: {
id,
organizationId: actor.organizationId,
...activityAccessWhere(actor),
},
select: { id: true, createdAt: true, promotedFromPriorAt: true },
});
if (!row) throw new NotFoundException('فعالیت پیدا نشد');
if (row.promotedFromPriorAt) {
throw new BadRequestException('این فعالیت قبلاً منتقل شده است.');
}
if (row.createdAt >= actor.priorCutoff) {
throw new BadRequestException('این فعالیت در بایگانی نیست.');
}
const updated = await this.prisma.activity.update({
where: { id },
data: { promotedFromPriorAt: new Date() },
include,
});
return this.toDto(updated, await this.ctx(actor.organizationId));
}
async remove(
organizationId: string,
id: string,
@@ -701,7 +735,7 @@ export class ActivitiesService {
if (search) andParts.push(search);
const onRecord = Boolean(entity?.personId || entity?.companyId || entity?.dealId);
if (!onRecord) {
andParts.push(activityPriorWhere(actor.priorLens, new Date(), actor.priorCutoff));
andParts.push(activityPriorWhere(actor.priorLens, actor.priorCutoff));
}
const base: Prisma.ActivityWhereInput = {
organizationId,
@@ -901,6 +935,7 @@ export class ActivitiesService {
reminderSentAt: row.reminderSentAt?.toISOString() ?? null,
completedAt: row.completedAt?.toISOString() ?? null,
importSource: row.importSource ?? 'manual',
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
tags: row.tags ?? [],
person: row.person
? {
+9 -9
View File
@@ -48,9 +48,7 @@ import {
} from './ask-count';
import {
activityPriorWhere,
companyPriorWhere,
dealPriorWhere,
personPriorWhere,
} from '../common/prior-archive';
type CatalogItem = AskMentoSourceDto;
@@ -325,13 +323,11 @@ Rules:
where: {
...shared,
...(intent.mood ? { mood: intent.mood } : {}),
...(intent.personSource ? {} : personPriorWhere(actor.priorLens)),
},
})
: await this.prisma.company.count({
where: {
...shared,
...(intent.personSource ? {} : companyPriorWhere(actor.priorLens)),
},
});
const who = intent.entity === 'person' ? 'مشتری' : 'شرکت';
@@ -372,7 +368,7 @@ Rules:
? { status: 'open' as const, OR: [{ isStale: true }, { isRotten: true }] }
: {}),
},
dealPriorWhere(actor.priorLens),
dealPriorWhere(actor.priorLens, actor.priorCutoff),
],
};
const n = await this.prisma.deal.count({ where });
@@ -403,10 +399,14 @@ Rules:
activity: () =>
this.prisma.activity.count({
where: {
organizationId: orgId,
...assigneeWhere(actor),
...created,
...activityPriorWhere(actor.priorLens, new Date(), actor.priorCutoff),
AND: [
{
organizationId: orgId,
...created,
},
assigneeWhere(actor),
activityPriorWhere(actor.priorLens, actor.priorCutoff),
],
},
}),
ticket: () =>
+11 -3
View File
@@ -19,6 +19,8 @@ import type {
SubscriptionSummaryDto,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
/** Ensures Express.Multer.File augmentation is loaded for saveAvatar. */
import type {} from 'multer';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/sms.service';
import { LocalFileStorage } from '../storage/local-file.storage';
@@ -658,7 +660,9 @@ export class AuthService {
const membership = await this.prisma.membership.findFirst({
where: { userId: user.id, organizationId, isActive: true },
include: {
organization: { select: { name: true, enabledModules: true } },
organization: {
select: { name: true, enabledModules: true, priorArchiveEnabledAt: true },
},
},
});
const role = membership?.role ?? user.role;
@@ -685,13 +689,17 @@ export class AuthService {
membership: {
priorArchiveEnabled?: boolean;
priorArchiveLens?: string;
organization?: { enabledModules?: string[] };
organization?: { enabledModules?: string[]; priorArchiveEnabledAt?: Date | null };
} | null,
): AuthUserDto['priorArchive'] {
if (!membership?.priorArchiveEnabled) return undefined;
const modules = this.billing.normalizeModules(membership.organization?.enabledModules);
if (!modules.includes('prior_data_archive')) return undefined;
return { lens: membership.priorArchiveLens === 'archive' ? 'archive' : 'current' };
const orgCutoff = membership.organization?.priorArchiveEnabledAt ?? null;
return {
lens: membership.priorArchiveLens === 'archive' ? 'archive' : 'current',
cutoffAt: orgCutoff ? orgCutoff.toISOString() : null,
};
}
private async throttleChallenges(
+4 -1
View File
@@ -107,7 +107,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
visibleUserIds,
scopes,
priorLens: priorGranted ? priorLens : 'off',
priorCutoff: priorGranted ? membership.organization.priorArchiveEnabledAt : null,
priorCutoff:
priorGranted && membership.organization.priorArchiveEnabledAt
? membership.organization.priorArchiveEnabledAt
: null,
};
}
+3 -5
View File
@@ -257,17 +257,15 @@ export class BillingService {
select: { priorArchiveEnabledAt: true },
});
const enablePrior = cleaned.includes('prior_data_archive');
const cutoff = prev?.priorArchiveEnabledAt ?? new Date();
await this.prisma.organization.update({
where: { id: organizationId },
data: {
enabledModules: cleaned,
...(enablePrior && !prev?.priorArchiveEnabledAt
? { priorArchiveEnabledAt: cutoff }
: {}),
},
});
if (enablePrior) await this.backfillPriorActivities(organizationId, cutoff);
if (enablePrior && prev?.priorArchiveEnabledAt) {
await this.backfillPriorActivities(organizationId, prev.priorArchiveEnabledAt);
}
return cleaned;
}
+32 -85
View File
@@ -1,117 +1,64 @@
import type { Prisma } from '@prisma/client';
import type { Actor } from './record-scope';
export const PRIOR_IMPORT_SOURCE = 'didar';
export type PriorLens = 'off' | 'current' | 'archive';
export function actorPriorLens(actor: Pick<Actor, 'priorLens'> | undefined): PriorLens {
return actor?.priorLens ?? 'off';
}
function liveDeal(now: Date): Prisma.DealWhereInput {
return {
importSource: PRIOR_IMPORT_SOURCE,
status: 'open',
expectedCloseAt: { gt: now },
};
function hasCutoff(cutoff?: Date | null): cutoff is Date {
return cutoff instanceof Date && !Number.isNaN(cutoff.getTime());
}
function liveActivity(now: Date): Prisma.ActivityWhereInput {
return {
importSource: PRIOR_IMPORT_SOURCE,
status: 'open',
dueAt: { gt: now },
};
}
/** فعالیت باز با موعد آینده، حتی اگر قبلی باشد، در کار جاری می‌ماند. */
function stillOpenAhead(now: Date): Prisma.ActivityWhereInput {
return { status: 'open', dueAt: { gt: now } };
}
/**
* فعالیت قبلی است اگر منبعش didar باشد،
* یا قبل از روشن شدن ماژول ساخته شده و به شخص/شرکت/معاملهٔ قبلی وصل باشد.
* معاملهٔ غیرقبلی مانع نمی‌شود؛ شخص قبلی (حتی اگر بعداً منبعش عوض شده) کافی است.
* فعالیت بدون شخص و شرکت و معامله هم اگر موعدش قبل از همان لحظه باشد قبلی است.
*/
function historicalActivity(cutoff: Date): Prisma.ActivityWhereInput {
return {
OR: [
{ importSource: PRIOR_IMPORT_SOURCE },
{
createdAt: { lt: cutoff },
OR: [
{
person: {
OR: [
{ importSource: PRIOR_IMPORT_SOURCE },
{ previousImportSource: PRIOR_IMPORT_SOURCE },
],
},
},
{ company: { importSource: PRIOR_IMPORT_SOURCE } },
{ deal: { importSource: PRIOR_IMPORT_SOURCE } },
{
personId: null,
companyId: null,
dealId: null,
dueAt: { lt: cutoff },
},
],
},
],
};
}
export function personPriorWhere(lens: PriorLens | undefined): Prisma.PersonWhereInput {
if (lens === 'archive') return { importSource: PRIOR_IMPORT_SOURCE };
if (lens === 'current') return { importSource: { not: PRIOR_IMPORT_SOURCE } };
/** شخص/شرکت دیگر با این لنز فیلتر نمی‌شوند. */
export function personPriorWhere(_lens?: PriorLens): Prisma.PersonWhereInput {
return {};
}
export function companyPriorWhere(lens: PriorLens | undefined): Prisma.CompanyWhereInput {
if (lens === 'archive') return { importSource: PRIOR_IMPORT_SOURCE };
if (lens === 'current') return { importSource: { not: PRIOR_IMPORT_SOURCE } };
export function companyPriorWhere(_lens?: PriorLens): Prisma.CompanyWhereInput {
return {};
}
export function dealPriorWhere(lens: PriorLens | undefined, now = new Date()): Prisma.DealWhereInput {
export function dealPriorWhere(
lens: PriorLens | undefined,
cutoff?: Date | null,
): Prisma.DealWhereInput {
if (lens !== 'current' && lens !== 'archive') return {};
if (!hasCutoff(cutoff)) return {};
if (lens === 'current') {
return { OR: [{ importSource: { not: PRIOR_IMPORT_SOURCE } }, liveDeal(now)] };
return {
OR: [
{ createdAt: { gte: cutoff } },
{ promotedFromPriorAt: { not: null } },
],
};
}
if (lens === 'archive') {
return { importSource: PRIOR_IMPORT_SOURCE, NOT: liveDeal(now) };
}
return {};
return { createdAt: { lt: cutoff }, promotedFromPriorAt: null };
}
export function activityPriorWhere(
lens: PriorLens | undefined,
now = new Date(),
cutoff?: Date | null,
): Prisma.ActivityWhereInput {
if (lens !== 'current' && lens !== 'archive') return {};
if (!cutoff) {
if (lens === 'current') {
return { OR: [{ importSource: { not: PRIOR_IMPORT_SOURCE } }, liveActivity(now)] };
}
return { importSource: PRIOR_IMPORT_SOURCE, NOT: liveActivity(now) };
if (!hasCutoff(cutoff)) return {};
if (lens === 'current') {
return {
OR: [
{ createdAt: { gte: cutoff } },
{ promotedFromPriorAt: { not: null } },
],
};
}
const prior = historicalActivity(cutoff);
const live = stillOpenAhead(now);
if (lens === 'current') return { OR: [{ NOT: prior }, live] };
return { AND: [prior, { NOT: live }] };
return { createdAt: { lt: cutoff }, promotedFromPriorAt: null };
}
/** فهرست شخص/شرکت: در کار جاری، جستجو و فیلتر صریح منبع، قبلی‌ها را هم پیدا می‌کند. */
/** فهرست شخص/شرکت: همیشه بدون فیلتر لنز (سازگاری با call-siteهای قدیمی). */
export function listPriorLens(
lens: PriorLens | undefined,
q: string | undefined,
explicitSource: boolean,
_lens: PriorLens | undefined,
_q: string | undefined,
_explicitSource: boolean,
): PriorLens {
if (explicitSource) return 'off';
if (lens === 'current' && q?.trim()) return 'off';
return lens ?? 'off';
return 'off';
}
@@ -26,7 +26,6 @@ import {
import { normalizeTags } from '../common/tags';
import { normalizePersonImportSource } from './person-source';
import { buildSearchWhere, ci } from '../common/search';
import { companyPriorWhere, listPriorLens } from '../common/prior-archive';
import { GamificationService } from '../gamification/gamification.service';
function parseDateOrNull(raw?: string | null): Date | null {
@@ -98,7 +97,6 @@ export class CompaniesService {
const where: Prisma.CompanyWhereInput = {
organizationId: actor.organizationId,
...ownerWhere(actor),
...companyPriorWhere(listPriorLens(actor.priorLens, q, false)),
...(search ? { AND: [search] } : {}),
};
-2
View File
@@ -43,7 +43,6 @@ import { selectMonthBirthdays } from './birthday-month';
import { renderSmsText } from '../common/sms-text';
import { normalizeTags } from '../common/tags';
import { buildSearchWhere, ci } from '../common/search';
import { listPriorLens, personPriorWhere } from '../common/prior-archive';
import {
normalizePersonImportSource,
personImportSourceLabel,
@@ -138,7 +137,6 @@ export class PeopleService implements OnModuleInit {
...ownerWhere(actor),
...(opts?.mood ? { mood: opts.mood } : {}),
...(sourceFilter ? { importSource: sourceFilter } : {}),
...personPriorWhere(listPriorLens(actor.priorLens, q, Boolean(sourceFilter))),
...(search ? { AND: [search] } : {}),
};
+7
View File
@@ -12,6 +12,7 @@ import {
} from 'class-validator';
import { Type } from 'class-transformer';
import { BUSINESS_FIELDS } from '@mento/shared';
import type { UpdatePriorArchiveCutoffRequest } from '@mento/shared';
export class ExchangeRateInputDto {
@IsString()
@@ -67,3 +68,9 @@ export class UpdateOrganizationDto {
@IsIn([...BUSINESS_FIELDS])
businessField?: (typeof BUSINESS_FIELDS)[number];
}
export class UpdatePriorArchiveCutoffDto
implements UpdatePriorArchiveCutoffRequest
{
cutoffAt!: string | null;
}
@@ -1,4 +1,12 @@
import { Body, Controller, Get, Patch, Post, UseGuards } from '@nestjs/common';
import {
BadRequestException,
Body,
Controller,
Get,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/roles.decorator';
@@ -6,6 +14,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import { AuthService } from '../auth/auth.service';
import {
CreateOrganizationDto,
UpdatePriorArchiveCutoffDto,
UpdateOrgCurrenciesDto,
UpdateOrganizationDto,
} from './dto';
@@ -58,4 +67,19 @@ export class OrganizationsController {
dto,
);
}
@Patch('current/prior-archive-cutoff')
@Roles('owner')
updatePriorArchiveCutoff(
@CurrentUser() user: { organizationId: string },
@Body() dto: UpdatePriorArchiveCutoffDto,
) {
if (!Object.prototype.hasOwnProperty.call(dto ?? {}, 'cutoffAt')) {
throw new BadRequestException('تاریخ قطع باید مشخص شود.');
}
return this.organizationsService.updatePriorArchiveCutoff(
user.organizationId,
dto.cutoffAt,
);
}
}
@@ -7,6 +7,7 @@ import {
import type {
OrganizationDto,
UpdateOrgCurrenciesRequest,
UpdatePriorArchiveCutoffRequest,
} from '@mento/shared';
import { CURRENCY_CATALOG, isBusinessField } from '@mento/shared';
import { Prisma } from '@prisma/client';
@@ -214,6 +215,39 @@ export class OrganizationsService {
return this.getCurrent(organizationId);
}
async updatePriorArchiveCutoff(
organizationId: string,
cutoffAt: UpdatePriorArchiveCutoffRequest['cutoffAt'],
): Promise<OrganizationDto> {
const org = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { enabledModules: true },
});
if (!org) throw new NotFoundException('سازمان پیدا نشد');
const modules = this.billing.normalizeModules(org.enabledModules);
if (!modules.includes('prior_data_archive')) {
throw new BadRequestException(
'ماژول بایگانی اطلاعات قبل برای این محیط فعال نیست.',
);
}
let value: Date | null = null;
if (cutoffAt !== null && cutoffAt !== '') {
const parsed = new Date(cutoffAt);
if (Number.isNaN(parsed.getTime())) {
throw new BadRequestException('تاریخ قطع معتبر نیست.');
}
value = parsed;
}
await this.prisma.organization.update({
where: { id: organizationId },
data: { priorArchiveEnabledAt: value },
});
return this.getCurrent(organizationId);
}
catalog() {
return CURRENCY_CATALOG;
}
@@ -226,6 +260,7 @@ export class OrganizationsService {
baseCurrency: string;
enabledCurrencies: string[];
enabledModules?: string[];
priorArchiveEnabledAt?: Date | null;
exchangeRates: Array<{
currency: string;
rateToBase: Prisma.Decimal;
@@ -243,6 +278,7 @@ export class OrganizationsService {
baseCurrency: org.baseCurrency,
enabledCurrencies: org.enabledCurrencies,
enabledModules: this.billing.normalizeModules(org.enabledModules),
priorArchiveCutoffAt: org.priorArchiveEnabledAt?.toISOString() ?? null,
exchangeRates: org.exchangeRates.map((r) => ({
currency: r.currency,
rateToBase: Number(r.rateToBase),
@@ -113,8 +113,10 @@ export class DealsExcelService {
this.prisma.deal.findMany({
where: {
organizationId: actor.organizationId,
...dealAccessWhere(actor),
...dealPriorWhere(actor.priorLens),
AND: [
dealAccessWhere(actor),
dealPriorWhere(actor.priorLens, actor.priorCutoff),
],
},
include: {
person: {
@@ -93,6 +93,11 @@ export class DealsController {
return this.dealsService.get(user.organizationId, id, user);
}
@Post(':id/promote-from-prior')
promoteFromPrior(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.dealsService.promoteFromPrior(user, id);
}
@Post()
create(@CurrentUser() user: Actor, @Body() dto: CreateDealDto) {
return this.dealsService.create(user.organizationId, user, dto);
+34 -1
View File
@@ -1,5 +1,6 @@
import {
BadRequestException,
ForbiddenException,
Injectable,
NotFoundException,
} from '@nestjs/common';
@@ -38,7 +39,7 @@ const dealInclude = {
type DealActor = Pick<
Actor,
'userId' | 'role' | 'dataVisibility' | 'visibleUserIds'
'userId' | 'role' | 'dataVisibility' | 'visibleUserIds' | 'priorLens' | 'priorCutoff'
>;
@Injectable()
@@ -443,6 +444,38 @@ export class DealsService {
return this.pipelines.toDealDto(row);
}
async promoteFromPrior(actor: Actor, id: string): Promise<DealDto> {
if (
(actor.priorLens !== 'current' && actor.priorLens !== 'archive') ||
!actor.priorCutoff
) {
throw new ForbiddenException('بایگانی اطلاعات قبل برای شما فعال نیست.');
}
const row = await this.prisma.deal.findFirst({
where: {
id,
organizationId: actor.organizationId,
...dealAccessWhere(actor),
},
select: { id: true, createdAt: true, promotedFromPriorAt: true },
});
if (!row) throw new NotFoundException('معامله پیدا نشد');
if (row.promotedFromPriorAt) {
throw new BadRequestException('این معامله قبلاً منتقل شده است.');
}
if (row.createdAt >= actor.priorCutoff) {
throw new BadRequestException('این معامله در بایگانی نیست.');
}
const updated = await this.prisma.deal.update({
where: { id },
data: { promotedFromPriorAt: new Date() },
include: dealInclude,
});
return this.pipelines.toDealDto(updated);
}
async remove(
organizationId: string,
id: string,
+12 -3
View File
@@ -44,6 +44,7 @@ type DealRow = {
expectedCloseAt: Date | null;
code: string | null;
importSource: string;
promotedFromPriorAt: Date | null;
sourceRef: string | null;
probability: number | null;
sourceDetail: string | null;
@@ -295,7 +296,12 @@ export class PipelinesService {
pipelineId?: string,
actor?: Pick<
Actor,
'userId' | 'role' | 'dataVisibility' | 'visibleUserIds' | 'priorLens'
| 'userId'
| 'role'
| 'dataVisibility'
| 'visibleUserIds'
| 'priorLens'
| 'priorCutoff'
>,
includePrior = false,
): Promise<PipelineBoardDto> {
@@ -322,8 +328,10 @@ export class PipelinesService {
where: {
organizationId,
pipelineId: resolved.id,
...(actor ? dealAccessWhere(actor) : {}),
...(includePrior ? {} : dealPriorWhere(actor?.priorLens)),
AND: [
...(actor ? [dealAccessWhere(actor)] : []),
...(includePrior ? [] : [dealPriorWhere(actor?.priorLens, actor?.priorCutoff)]),
],
},
include: {
person: { select: { id: true, firstName: true, lastName: true } },
@@ -575,6 +583,7 @@ export class PipelinesService {
expectedCloseAt: row.expectedCloseAt?.toISOString() ?? null,
code: row.code,
importSource: row.importSource,
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
sourceRef: row.sourceRef,
probability: row.probability,
sourceDetail: row.sourceDetail,
+63 -39
View File
@@ -29,7 +29,6 @@ import { decimalToBase, loadOrgRates, toBaseAmount } from '../common/currency';
import {
activityPriorWhere,
dealPriorWhere,
personPriorWhere,
} from '../common/prior-archive';
import {
addJalaliMonths,
@@ -62,9 +61,8 @@ export class ReportsService {
const prevStart = new Date(prevEnd.getTime() - durationMs);
const now = new Date();
const peoplePrior = personPriorWhere(actor.priorLens);
const dealsPrior = dealPriorWhere(actor.priorLens, now);
const activitiesPrior = activityPriorWhere(actor.priorLens, now, actor.priorCutoff);
const dealsPrior = dealPriorWhere(actor.priorLens, actor.priorCutoff);
const activitiesPrior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
const { jy, jm } = dateToJalali(now);
const sixAgo = addJalaliMonths(jy, jm, -5);
const sixMonthStart = startOfJalaliMonth(sixAgo.jy, sixAgo.jm);
@@ -129,10 +127,14 @@ export class ReportsService {
}),
this.prisma.activity.findMany({
where: {
organizationId: orgId,
...activityScope,
...activitiesPrior,
createdAt: { gte: prevStart, lte: end },
AND: [
{
organizationId: orgId,
createdAt: { gte: prevStart, lte: end },
},
activityScope,
activitiesPrior,
],
},
select: {
id: true,
@@ -160,7 +162,6 @@ export class ReportsService {
where: {
organizationId: orgId,
...personScope,
...peoplePrior,
},
select: { mood: true, createdAt: true },
}),
@@ -1551,9 +1552,8 @@ export class ReportsService {
const yesterdayEnd = endOfDay(yesterday);
const weekAgo = new Date(now);
weekAgo.setDate(weekAgo.getDate() - 7);
const peoplePrior = personPriorWhere(actor.priorLens);
const dealsPrior = dealPriorWhere(actor.priorLens, now);
const activitiesPrior = activityPriorWhere(actor.priorLens, now, actor.priorCutoff);
const dealsPrior = dealPriorWhere(actor.priorLens, actor.priorCutoff);
const activitiesPrior = activityPriorWhere(actor.priorLens, actor.priorCutoff);
const [
wonDeals,
@@ -1569,11 +1569,15 @@ export class ReportsService {
] = await Promise.all([
this.prisma.deal.findMany({
where: {
organizationId: orgId,
status: 'won',
...dealScope,
...dealsPrior,
updatedAt: { gte: addMonthsStart(now, -5) },
AND: [
{
organizationId: orgId,
status: 'won',
updatedAt: { gte: addMonthsStart(now, -5) },
},
dealScope,
dealsPrior,
],
},
select: {
amount: true,
@@ -1587,7 +1591,13 @@ export class ReportsService {
},
}),
this.prisma.deal.count({
where: { organizationId: orgId, status: 'open', ...dealScope, ...dealsPrior },
where: {
AND: [
{ organizationId: orgId, status: 'open' },
dealScope,
dealsPrior,
],
},
}),
this.prisma.deal.findMany({
where: {
@@ -1618,7 +1628,6 @@ export class ReportsService {
where: {
organizationId: orgId,
...personScope,
...peoplePrior,
createdAt: { gte: curMonthStart, lte: curMonthEnd },
},
}),
@@ -1626,34 +1635,45 @@ export class ReportsService {
where: {
organizationId: orgId,
...personScope,
...peoplePrior,
createdAt: { gte: prevMonthStart, lte: prevMonthEnd },
},
}),
this.prisma.activity.count({
where: {
organizationId: orgId,
...activityScope,
...activitiesPrior,
status: 'open',
dueAt: { gte: todayStart, lte: todayEnd },
AND: [
{
organizationId: orgId,
status: 'open',
dueAt: { gte: todayStart, lte: todayEnd },
},
activityScope,
activitiesPrior,
],
},
}),
this.prisma.activity.count({
where: {
organizationId: orgId,
...activityScope,
...activitiesPrior,
dueAt: { gte: yesterdayStart, lte: yesterdayEnd },
AND: [
{
organizationId: orgId,
dueAt: { gte: yesterdayStart, lte: yesterdayEnd },
},
activityScope,
activitiesPrior,
],
},
}),
this.prisma.deal.count({
where: {
organizationId: orgId,
status: 'open',
...dealScope,
...dealsPrior,
updatedAt: { lte: weekAgo },
AND: [
{
organizationId: orgId,
status: 'open',
updatedAt: { lte: weekAgo },
},
dealScope,
dealsPrior,
],
},
}),
this.prisma.salesGoal.findMany({
@@ -1666,11 +1686,15 @@ export class ReportsService {
}),
this.prisma.activity.count({
where: {
organizationId: orgId,
...activityScope,
...activitiesPrior,
status: 'open',
dueAt: { lt: now },
AND: [
{
organizationId: orgId,
status: 'open',
dueAt: { lt: now },
},
activityScope,
activitiesPrior,
],
},
}),
]);
+130
View File
@@ -0,0 +1,130 @@
import 'reflect-metadata';
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { BadRequestException } from '@nestjs/common';
import type { UpdatePriorArchiveCutoffRequest } from '@mento/shared';
import { ROLES_KEY } from '../src/auth/roles.decorator';
import { OrganizationsController } from '../src/organizations/organizations.controller';
import { OrganizationsService } from '../src/organizations/organizations.service';
const cutoff = new Date('2026-10-01T00:00:00.000Z');
function makeOrg(overrides: Record<string, unknown> = {}) {
return {
id: 'org-1',
name: 'Org',
slug: 'org',
businessField: 'personal',
baseCurrency: 'IRR',
enabledCurrencies: ['IRR'],
enabledModules: ['prior_data_archive'],
priorArchiveEnabledAt: cutoff,
exchangeRates: [],
...overrides,
};
}
function makeService(org = makeOrg()) {
const calls: Array<{ where: unknown; data: unknown }> = [];
const prisma = {
organization: {
findUnique: async () => org,
update: async (args: { where: unknown; data: unknown }) => {
calls.push(args);
return org;
},
},
};
const billing = {
normalizeModules: (modules?: string[]) => modules ?? [],
};
const service = new OrganizationsService(
prisma as never,
{} as never,
{} as never,
{} as never,
billing as never,
);
return { service, calls };
}
describe('OrganizationsService prior archive cutoff', () => {
it('returns the current cutoff in the organization dto', async () => {
const { service } = makeService();
const dto = await service.getCurrent('org-1');
assert.equal(dto.priorArchiveCutoffAt, cutoff.toISOString());
});
it('updates and clears the cutoff when prior archive is enabled', async () => {
const { service, calls } = makeService();
await service.updatePriorArchiveCutoff('org-1', '2026-11-02T00:00:00.000Z');
await service.updatePriorArchiveCutoff('org-1', null);
assert.deepEqual(calls.map((call) => call.data), [
{ priorArchiveEnabledAt: new Date('2026-11-02T00:00:00.000Z') },
{ priorArchiveEnabledAt: null },
]);
});
it('rejects invalid cutoffs and disabled modules', async () => {
const enabled = makeService();
await assert.rejects(
() => enabled.service.updatePriorArchiveCutoff('org-1', 'not-a-date'),
BadRequestException,
);
const disabled = makeService(makeOrg({ enabledModules: [] }));
await assert.rejects(
() =>
disabled.service.updatePriorArchiveCutoff(
'org-1',
'2026-11-02T00:00:00.000Z',
),
BadRequestException,
);
});
});
describe('OrganizationsController prior archive cutoff', () => {
it('exposes an owner-only explicit cutoff patch', async () => {
const calls: Array<UpdatePriorArchiveCutoffRequest['cutoffAt']> = [];
const controller = new OrganizationsController(
{
updatePriorArchiveCutoff: async (
_organizationId: string,
cutoffAt: UpdatePriorArchiveCutoffRequest['cutoffAt'],
) => {
calls.push(cutoffAt);
return makeOrg();
},
} as never,
{} as never,
);
assert.deepEqual(
Reflect.getMetadata(
ROLES_KEY,
controller.updatePriorArchiveCutoff,
),
['owner'],
);
assert.throws(
() =>
controller.updatePriorArchiveCutoff(
{ organizationId: 'org-1' },
{} as UpdatePriorArchiveCutoffRequest,
),
BadRequestException,
);
await controller.updatePriorArchiveCutoff(
{ organizationId: 'org-1' },
{ cutoffAt: null },
);
assert.deepEqual(calls, [null]);
});
});
+23 -70
View File
@@ -3,85 +3,38 @@ import assert from 'node:assert/strict';
import {
activityPriorWhere,
dealPriorWhere,
listPriorLens,
personPriorWhere,
} from '../src/common/prior-archive';
const now = new Date('2026-10-15T08:00:00.000Z');
const cutoff = new Date('2026-10-01T00:00:00.000Z');
describe('بایگانی اطلاعات قبل', () => {
it('بدون مجوز فیلتر نمی‌گذارد', () => {
assert.deepEqual(personPriorWhere('off'), {});
assert.deepEqual(dealPriorWhere(undefined, now), {});
describe('بایگانی اطلاعات قبل — تاریخ قطع', () => {
it('بدون لنز یا بدون تاریخ فیلتر نمی‌گذارد', () => {
assert.deepEqual(dealPriorWhere('off', cutoff), {});
assert.deepEqual(dealPriorWhere('current', null), {});
assert.deepEqual(activityPriorWhere('archive', undefined), {});
assert.deepEqual(personPriorWhere('current'), {});
});
it('کار جاری شخص قبلی را کنار می‌گذارد و معاملهٔ بازِ موعددار را نگه می‌دارد', () => {
assert.deepEqual(personPriorWhere('current'), { importSource: { not: 'didar' } });
const where = dealPriorWhere('current', now);
assert.equal(where.OR?.length, 2);
assert.deepEqual(where.OR?.[1], {
importSource: 'didar',
status: 'open',
expectedCloseAt: { gt: now },
});
});
it('بایگانی فقط قبلی‌ها را می‌آورد و استثنای باز را برمی‌دارد', () => {
const where = activityPriorWhere('archive', now);
assert.equal(where.importSource, 'didar');
assert.deepEqual(where.NOT, {
importSource: 'didar',
status: 'open',
dueAt: { gt: now },
});
});
it('فعالیت قدیمی روی شخص قبلی از کار جاری کنار می‌رود', () => {
const cutoff = new Date('2026-10-01T00:00:00.000Z');
const current = JSON.parse(JSON.stringify(activityPriorWhere('current', now, cutoff))) as {
it('کار جاری: بعد از قطع یا منتقل‌شده', () => {
assert.deepEqual(dealPriorWhere('current', cutoff), {
OR: [
{
NOT: {
OR: [
{ importSource: string },
{
createdAt: { lt: string };
OR: Array<{ person?: { OR: Array<Record<string, string>> } }>;
},
];
};
},
{ status: string; dueAt: { gt: string } },
];
};
const linked = current.OR[0].NOT.OR[1];
assert.equal(linked.createdAt.lt, cutoff.toISOString());
assert.deepEqual(linked.OR[0], {
person: {
OR: [{ importSource: 'didar' }, { previousImportSource: 'didar' }],
},
});
assert.deepEqual(linked.OR[3], {
personId: null,
companyId: null,
dealId: null,
dueAt: { lt: cutoff.toISOString() },
});
assert.deepEqual(current.OR[1], { status: 'open', dueAt: { gt: now.toISOString() } });
const archive = JSON.parse(JSON.stringify(activityPriorWhere('archive', now, cutoff))) as {
AND: [unknown, { NOT: { status: string; dueAt: { gt: string } } }];
};
assert.deepEqual(archive.AND[0], current.OR[0].NOT);
assert.deepEqual(archive.AND[1], {
NOT: { status: 'open', dueAt: { gt: now.toISOString() } },
{ createdAt: { gte: cutoff } },
{ promotedFromPriorAt: { not: null } },
],
});
});
it('جستجوی کار جاری شخص قبلی را پیدا می‌کند', () => {
assert.equal(listPriorLens('current', 'علی', false), 'off');
assert.equal(listPriorLens('current', ' ', false), 'current');
assert.equal(listPriorLens('archive', 'علی', false), 'archive');
assert.equal(listPriorLens('current', '', true), 'off');
it('بایگانی: قبل از قطع و بدون برچسب انتقال', () => {
assert.deepEqual(activityPriorWhere('archive', cutoff), {
createdAt: { lt: cutoff },
promotedFromPriorAt: null,
});
});
it('استثنای موعد آینده دیگر نیست', () => {
const w = JSON.stringify(dealPriorWhere('current', cutoff));
assert.equal(w.includes('expectedCloseAt'), false);
assert.equal(w.includes('didar'), false);
});
});
+194
View File
@@ -0,0 +1,194 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { BadRequestException, ForbiddenException, NotFoundException } from '@nestjs/common';
import { DealsService } from '../src/pipelines/deals.service';
import { ActivitiesService } from '../src/activities/activities.service';
import type { Actor } from '../src/common/record-scope';
const cutoff = new Date('2026-10-01T00:00:00.000Z');
const priorCreatedAt = new Date('2026-09-01T00:00:00.000Z');
const currentCreatedAt = new Date('2026-10-02T00:00:00.000Z');
const promotedAt = new Date('2026-10-03T00:00:00.000Z');
const actor: Actor = {
userId: 'u1',
role: 'sales',
organizationId: 'org1',
priorLens: 'archive',
priorCutoff: cutoff,
};
function dealRow(overrides: Record<string, unknown> = {}) {
return {
id: 'deal1',
organizationId: 'org1',
title: 'Prior deal',
createdAt: priorCreatedAt,
promotedFromPriorAt: null,
...overrides,
};
}
type DealPromotionProbe = ReturnType<typeof dealRow> | null;
function activityRow(overrides: Record<string, unknown> = {}) {
return {
id: 'act1',
organizationId: 'org1',
type: 'task',
status: 'open',
priority: 'medium',
title: 'Prior activity',
description: null,
dueAt: null,
durationMinutes: null,
reminderAt: null,
reminderNotifyApp: true,
reminderNotifySms: false,
reminderSentAt: null,
completedAt: null,
tags: [],
createdAt: priorCreatedAt,
updatedAt: priorCreatedAt,
promotedFromPriorAt: null,
person: null,
company: null,
deal: null,
lead: null,
assignee: null,
assignees: [],
createdBy: null,
participantIds: [],
...overrides,
};
}
type ActivityPromotionProbe = ReturnType<typeof activityRow> | null;
describe('promote from prior', () => {
it('promotes an accessible prior deal by setting only promotedFromPriorAt', async () => {
const calls: unknown[] = [];
const prisma = {
deal: {
findFirst: async (args: unknown) => {
calls.push(['findFirst', args]);
return dealRow();
},
update: async (args: unknown) => {
calls.push(['update', args]);
return dealRow({ promotedFromPriorAt: promotedAt });
},
},
};
const pipelines = {
toDealDto: (row: { id: string; createdAt: Date; promotedFromPriorAt: Date | null }) => ({
id: row.id,
createdAt: row.createdAt.toISOString(),
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
}),
};
const service = new DealsService(
prisma as never,
pipelines as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const dto = await service.promoteFromPrior(actor, 'deal1');
const updateArgs = (calls[1] as [string, { data: Record<string, unknown> }])[1];
assert.deepEqual(Object.keys(updateArgs.data), ['promotedFromPriorAt']);
assert.equal(dto.createdAt, priorCreatedAt.toISOString());
assert.equal(dto.promotedFromPriorAt, promotedAt.toISOString());
});
it('rejects deal promote when prior lens is off or cutoff missing', async () => {
const service = new DealsService({} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never);
await assert.rejects(
service.promoteFromPrior({ ...actor, priorLens: 'off' }, 'deal1'),
ForbiddenException,
);
await assert.rejects(
service.promoteFromPrior({ ...actor, priorCutoff: null }, 'deal1'),
ForbiddenException,
);
});
it('rejects deal promote unless the record is unpromoted prior data', async () => {
const prisma = {
deal: {
findFirst: async (): Promise<DealPromotionProbe> =>
dealRow({ promotedFromPriorAt: promotedAt }),
},
};
const service = new DealsService(prisma as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never);
await assert.rejects(service.promoteFromPrior(actor, 'deal1'), BadRequestException);
prisma.deal.findFirst = async () => dealRow({ createdAt: currentCreatedAt });
await assert.rejects(service.promoteFromPrior(actor, 'deal1'), BadRequestException);
prisma.deal.findFirst = async () => null;
await assert.rejects(service.promoteFromPrior(actor, 'deal1'), NotFoundException);
});
it('promotes an accessible prior activity by setting only promotedFromPriorAt', async () => {
const calls: unknown[] = [];
const prisma = {
activity: {
findFirst: async (args: unknown) => {
calls.push(['findFirst', args]);
return activityRow();
},
update: async (args: unknown) => {
calls.push(['update', args]);
return activityRow({ promotedFromPriorAt: promotedAt });
},
},
};
const service = new ActivitiesService(
prisma as never,
{} as never,
{} as never,
{} as never,
{ defaults: async () => ({}), effectiveStageId: () => null } as never,
{ system: async () => ({}), toSummary: (row: unknown) => row } as never,
{} as never,
);
const dto = await service.promoteFromPrior(actor, 'act1');
const updateArgs = (calls[1] as [string, { data: Record<string, unknown> }])[1];
assert.deepEqual(Object.keys(updateArgs.data), ['promotedFromPriorAt']);
assert.equal(dto.createdAt, priorCreatedAt.toISOString());
assert.equal(dto.promotedFromPriorAt, promotedAt.toISOString());
});
it('rejects activity promote unless the actor and record are eligible', async () => {
const prisma = {
activity: {
findFirst: async (): Promise<ActivityPromotionProbe> =>
activityRow({ createdAt: currentCreatedAt }),
},
};
const service = new ActivitiesService(
prisma as never,
{} as never,
{} as never,
{} as never,
{ defaults: async () => ({}), effectiveStageId: () => null } as never,
{ system: async () => ({}), toSummary: (row: unknown) => row } as never,
{} as never,
);
await assert.rejects(service.promoteFromPrior({ ...actor, priorLens: 'off' }, 'act1'), ForbiddenException);
await assert.rejects(service.promoteFromPrior(actor, 'act1'), BadRequestException);
prisma.activity.findFirst = async () => null;
await assert.rejects(service.promoteFromPrior(actor, 'act1'), NotFoundException);
});
});
+158 -12
View File
@@ -3,10 +3,13 @@ import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import type {
OrganizationDto,
OrgUserDto,
TeamDto,
TeamMemberRole,
UpdatePriorArchiveCutoffRequest,
UpdateUserVisibilityRequest,
} from '@mento/shared';
import {
@@ -17,7 +20,7 @@ import {
type DataVisibility,
} from '@mento/shared';
import { UiButton, UiEmptyState, UiField, UiInput } from '@/components/ui';
import { toFaDigits } from '@/lib/jalali';
import { formatLocalDateInput, parseLocalInput, toFaDigits } from '@/lib/jalali';
const props = defineProps<{
users: OrgUserDto[];
@@ -31,7 +34,22 @@ const showPriorArchive = computed(
Boolean(auth.user.enabledModules?.includes('prior_data_archive')),
);
const priorUsers = computed(() => props.users.filter((u) => u.isActive !== false));
const selectedPriorUsers = computed(() => priorUsers.value.filter((u) => u.priorArchiveEnabled));
const priorSearch = ref('');
const priorPick = ref('');
const priorSavingId = ref('');
const cutoffLocal = ref('');
const cutoffSaving = ref(false);
const cutoffLoading = ref(false);
const availablePriorUsers = computed(() => {
const q = priorSearch.value.trim().toLowerCase();
return priorUsers.value.filter((u) => {
if (u.priorArchiveEnabled) return false;
if (!q) return true;
return [u.fullName, u.email, u.mobile].filter(Boolean).some((v) => String(v).toLowerCase().includes(q));
});
});
const emit = defineEmits<{
refreshUsers: [];
@@ -57,6 +75,7 @@ const editableUsers = computed(() =>
async function setPriorArchive(userId: string, enabled: boolean) {
priorSavingId.value = userId;
priorPick.value = '';
error.value = '';
ok.value = '';
try {
@@ -74,6 +93,51 @@ async function setPriorArchive(userId: string, enabled: boolean) {
}
}
function cutoffPayload(value: string): UpdatePriorArchiveCutoffRequest {
const parsed = parseLocalInput(value);
return { cutoffAt: parsed ? parsed.toISOString() : null };
}
async function loadPriorArchiveCutoff() {
cutoffLoading.value = true;
try {
const { data } = await api.get<OrganizationDto>('/organizations/current');
cutoffLocal.value = data.priorArchiveCutoffAt
? formatLocalDateInput(new Date(data.priorArchiveCutoffAt))
: '';
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'بارگذاری تاریخ بایگانی ناموفق بود.')
: 'بارگذاری تاریخ بایگانی ناموفق بود.';
} finally {
cutoffLoading.value = false;
}
}
async function onCutoffChange(value: string) {
cutoffLocal.value = value;
cutoffSaving.value = true;
error.value = '';
ok.value = '';
try {
await api.patch('/organizations/current/prior-archive-cutoff', cutoffPayload(value));
ok.value = value ? 'تاریخ بایگانی اطلاعات قبل ذخیره شد.' : 'تاریخ بایگانی اطلاعات قبل پاک شد.';
await auth.hydrate();
} catch (e) {
error.value = axios.isAxiosError(e)
? String((e.response?.data as { message?: string })?.message ?? 'ذخیره تاریخ بایگانی ناموفق بود.')
: 'ذخیره تاریخ بایگانی ناموفق بود.';
await loadPriorArchiveCutoff();
} finally {
cutoffSaving.value = false;
}
}
function pickPriorUser(userId: string) {
if (!userId) return;
void setPriorArchive(userId, true);
}
async function load() {
loading.value = true;
error.value = '';
@@ -229,6 +293,7 @@ async function setVisibility(userId: string, payload: UpdateUserVisibilityReques
onMounted(() => {
void load();
if (showPriorArchive.value) void loadPriorArchiveCutoff();
});
</script>
@@ -326,20 +391,49 @@ onMounted(() => {
</section>
<section v-if="showPriorArchive" class="card">
<h3>بایگانی اطلاعات قبل</h3>
<header class="prior-head">
<h3>بایگانی اطلاعات قبل</h3>
<JalaliDateInput
:model-value="cutoffLocal"
mode="date"
placeholder="تاریخ برش"
:disabled="cutoffSaving || cutoffLoading"
@update:model-value="onCutoffChange"
/>
</header>
<p class="hint">
فقط کاربرانی که تیک می‌خورند سوئیچ کار جاری و بایگانی را می‌بینند. بقیهٔ محیط مثل قبل همهٔ
رکوردها را مطابق سطح دسترسی خودشان می‌بینند.
</p>
<label v-for="u in priorUsers" :key="u.id" class="vis-row">
<input
type="checkbox"
:checked="Boolean(u.priorArchiveEnabled)"
:disabled="priorSavingId === u.id"
@change="setPriorArchive(u.id, ($event.target as HTMLInputElement).checked)"
/>
<span>{{ u.fullName }}</span>
</label>
<div class="prior-picker">
<UiInput v-model="priorSearch" placeholder="جستجوی کاربر…" />
<select
v-model="priorPick"
:disabled="!availablePriorUsers.length || Boolean(priorSavingId)"
@change="pickPriorUser(($event.target as HTMLSelectElement).value)"
>
<option value="">
{{ availablePriorUsers.length ? 'انتخاب کاربر برای فعال‌سازی' : 'کاربر دیگری پیدا نشد' }}
</option>
<option v-for="u in availablePriorUsers" :key="u.id" :value="u.id">
{{ u.fullName }}
</option>
</select>
</div>
<div v-if="selectedPriorUsers.length" class="prior-chips">
<span v-for="u in selectedPriorUsers" :key="u.id" class="prior-chip">
{{ u.fullName }}
<button
type="button"
:disabled="priorSavingId === u.id"
:aria-label="`حذف ${u.fullName}`"
@click="setPriorArchive(u.id, false)"
>
×
</button>
</span>
</div>
<p v-else class="hint">هنوز کاربری برای دیدن سوئیچ بایگانی انتخاب نشده است.</p>
</section>
<section class="card">
@@ -429,6 +523,57 @@ onMounted(() => {
margin: 0 0 0.75rem;
font-size: 1rem;
}
.prior-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
margin-bottom: 0.75rem;
}
.prior-head h3 {
margin: 0;
}
.prior-head :deep(.trigger) {
min-width: 12rem;
}
.prior-picker {
display: grid;
grid-template-columns: minmax(10rem, 1fr) minmax(13rem, 1fr);
gap: 0.6rem;
margin-top: 0.75rem;
}
.prior-chips {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
margin-top: 0.75rem;
}
.prior-chip {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border: 1px solid #ccfbf1;
border-radius: 999px;
background: #f0fdfa;
color: #0f766e;
padding: 0.25rem 0.6rem;
font-size: 0.85rem;
font-weight: 600;
}
.prior-chip button {
border: 0;
background: transparent;
color: inherit;
cursor: pointer;
font: inherit;
line-height: 1;
padding: 0;
}
.prior-chip button:disabled {
opacity: 0.45;
cursor: wait;
}
.row {
display: grid;
grid-template-columns: 1fr 1fr auto;
@@ -534,7 +679,8 @@ select {
}
@media (max-width: 800px) {
.row,
.vis-row {
.vis-row,
.prior-picker {
grid-template-columns: 1fr;
}
}
@@ -41,7 +41,7 @@ const emit = defineEmits<{
stagesChanged: [];
add: [stageId: string];
error: [message: string];
menuDeal: [activityId: string];
menuDeal: [activity: ActivityDto];
toggleSelect: [activityId: string];
bulkDelete: [];
}>();
@@ -115,6 +115,8 @@ function toCard(item: ActivityDto, stageId: string): PipelineDeal {
date: dateText(item),
initials: initialsFromTitle(party || item.title),
stageId,
createdAt: item.createdAt,
promotedFromPriorAt: item.promotedFromPriorAt ?? null,
assigneeNames,
ownerId: item.assignee?.id ?? null,
assigneeIds: (item.assignees ?? []).map((a) => a.id),
@@ -205,6 +207,19 @@ function findStageOf(id: string) {
return Object.entries(columns.value).find(([, col]) => col.items.some((i) => i.id === id))?.[0];
}
function findActivity(id: string) {
for (const col of Object.values(columns.value)) {
const item = col.items.find((i) => i.id === id);
if (item) return item;
}
return null;
}
function onMenuActivity(id: string) {
const item = findActivity(id);
if (item) emit('menuDeal', item);
}
function onDragStart(deal: PipelineDeal, event: DragEvent) {
draggingId.value = deal.id;
overlayDeal.value = deal;
@@ -397,7 +412,7 @@ function openActivity(id: string) {
@drop="onDrop"
@add-deal="emit('add', $event)"
@open-deal="openActivity"
@menu-deal="emit('menuDeal', $event)"
@menu-deal="onMenuActivity"
@toggle-select="emit('toggleSelect', $event)"
@bulk-delete="emit('bulkDelete')"
@rename-stage="onRenameStage"
+5
View File
@@ -13,6 +13,8 @@ export type PipelineDeal = {
/** شناسه مرحله فعلی — هنگام جابه‌جایی به‌روز می‌شود */
stageId?: string;
currencyUnit?: string;
createdAt?: string;
promotedFromPriorAt?: string | null;
/** نام مسئولان برای نمایش روی کارت */
assigneeNames?: string[];
ownerId?: string | null;
@@ -176,6 +178,7 @@ export function mapBoardToStages(
stageId: string;
expectedCloseAt: string | null;
createdAt: string;
promotedFromPriorAt: string | null;
person: { fullName: string } | null;
company: { name: string } | null;
owner?: { id: string; fullName: string } | null;
@@ -225,6 +228,8 @@ export function mapBoardToStages(
),
stageId: deal.stageId,
currencyUnit: currencyUnitLabel(deal.currency),
createdAt: deal.createdAt,
promotedFromPriorAt: deal.promotedFromPriorAt,
assigneeNames,
ownerId: deal.owner?.id ?? null,
assigneeIds: (deal.assignees ?? []).map((a) => a.id),
+52 -6
View File
@@ -231,6 +231,7 @@ const activityModal = ref<{
} | null>(null);
const menuId = ref<string | null>(null);
const boardMenuId = ref<string | null>(null);
const boardMenuActivity = ref<ActivityDto | null>(null);
const boardMenuStyle = ref<Record<string, string> | null>(null);
const deleteActivityIds = ref<string[]>([]);
const deleteSingleTitle = ref('');
@@ -572,6 +573,7 @@ function clearFacets() {
async function complete(id: string) {
menuId.value = null;
boardMenuId.value = null;
boardMenuActivity.value = null;
try {
await api.patch(`/activities/${id}/complete`);
await refreshAll();
@@ -585,6 +587,27 @@ function closePopovers() {
menuId.value = null;
}
function canPromotePrior(item: ActivityDto) {
const pa = auth.user?.priorArchive;
if (!pa || pa.lens !== 'archive' || !pa.cutoffAt) return false;
if (item.promotedFromPriorAt) return false;
return new Date(item.createdAt).getTime() < new Date(pa.cutoffAt).getTime();
}
async function promotePriorActivity(id: string) {
menuId.value = null;
boardMenuId.value = null;
boardMenuActivity.value = null;
error.value = '';
try {
await api.post(`/activities/${id}/promote-from-prior`);
kanbanReload.value += 1;
await refreshAll();
} catch {
error.value = 'انتقال فعالیت به کار جاری ناموفق بود.';
}
}
const deleteConfirmCopy = computed(() => {
const n = deleteActivityIds.value.length;
if (n <= 0) return '';
@@ -604,6 +627,7 @@ function activityTitle(id: string) {
function startSelect(id: string) {
menuId.value = null;
boardMenuId.value = null;
boardMenuActivity.value = null;
selectMode.value = true;
selectedIds.value = new Set([id]);
}
@@ -624,6 +648,7 @@ function clearSelect() {
function askDeleteActivity(id: string, title?: string) {
menuId.value = null;
boardMenuId.value = null;
boardMenuActivity.value = null;
deleteSingleTitle.value = title?.trim() || activityTitle(id);
deleteActivityIds.value = [id];
}
@@ -632,6 +657,7 @@ function askBulkDelete() {
if (!selectedIds.value.size) return;
menuId.value = null;
boardMenuId.value = null;
boardMenuActivity.value = null;
deleteSingleTitle.value = '';
deleteActivityIds.value = [...selectedIds.value];
}
@@ -659,12 +685,13 @@ async function confirmDeleteActivities() {
}
}
function onBoardMenu(activityId: string) {
boardMenuId.value = boardMenuId.value === activityId ? null : activityId;
function onBoardMenu(activity: ActivityDto) {
boardMenuId.value = boardMenuId.value === activity.id ? null : activity.id;
boardMenuActivity.value = boardMenuId.value ? activity : null;
boardMenuStyle.value = null;
if (!boardMenuId.value) return;
void nextTick(() => {
boardMenuStyle.value = cardMenuStyle(activityId);
boardMenuStyle.value = cardMenuStyle(activity.id);
});
}
@@ -672,6 +699,7 @@ const unbindBoardMenuDismiss = bindMenuDismiss(
() => boardMenuId.value != null,
() => {
boardMenuId.value = null;
boardMenuActivity.value = null;
},
);
@@ -783,6 +811,7 @@ onMounted(() => {
watch(viewMode, () => {
clearSelect();
boardMenuId.value = null;
boardMenuActivity.value = null;
menuId.value = null;
});
@@ -1213,6 +1242,9 @@ onUnmounted(() => {
<RouterLink :to="{ name: 'activity-edit', params: { id: item.id } }">
ویرایش
</RouterLink>
<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>
@@ -1297,6 +1329,12 @@ onUnmounted(() => {
<RouterLink :to="{ name: 'activity-detail', params: { id: item.id } }">
مشاهده
</RouterLink>
<RouterLink :to="{ name: 'activity-edit', params: { id: item.id } }">
ویرایش
</RouterLink>
<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>
@@ -1348,17 +1386,25 @@ onUnmounted(() => {
<RouterLink
role="menuitem"
:to="{ name: 'activity-detail', params: { id: boardMenuId } }"
@click="boardMenuId = null"
@click="boardMenuId = null; boardMenuActivity = null"
>
مشاهده
</RouterLink>
<RouterLink
role="menuitem"
:to="{ name: 'activity-edit', params: { id: boardMenuId } }"
@click="boardMenuId = null"
@click="boardMenuId = null; boardMenuActivity = null"
>
ویرایش
</RouterLink>
<button
v-if="boardMenuActivity && canPromotePrior(boardMenuActivity)"
type="button"
role="menuitem"
@click="promotePriorActivity(boardMenuActivity.id)"
>
انتقال به کار جاری
</button>
<button
type="button"
role="menuitem"
@@ -1367,7 +1413,7 @@ onUnmounted(() => {
>
حذف
</button>
<button type="button" role="menuitem" @click="boardMenuId = null">بستن</button>
<button type="button" role="menuitem" @click="boardMenuId = null; boardMenuActivity = null">بستن</button>
</div>
</Teleport>
+8 -12
View File
@@ -186,21 +186,17 @@ const auth = useAuthStore();
const priorArchiveOn = computed(() => Boolean(auth.user?.priorArchive));
function isPriorActivity(row: ActivityDto) {
if (row.importSource !== 'didar') return false;
if (row.status === 'open' && row.dueAt && new Date(row.dueAt).getTime() > Date.now()) return false;
return true;
const cutoff = auth.user?.priorArchive?.cutoffAt;
if (!auth.user?.priorArchive || !cutoff) return false;
if (row.promotedFromPriorAt) return false;
return new Date(row.createdAt).getTime() < new Date(cutoff).getTime();
}
function isPriorDeal(row: DealDto) {
if (row.importSource !== 'didar') return false;
if (
row.status === 'open' &&
row.expectedCloseAt &&
new Date(row.expectedCloseAt).getTime() > Date.now()
) {
return false;
}
return true;
const cutoff = auth.user?.priorArchive?.cutoffAt;
if (!auth.user?.priorArchive || !cutoff) return false;
if (row.promotedFromPriorAt) return false;
return new Date(row.createdAt).getTime() < new Date(cutoff).getTime();
}
const lastCallAt = computed(() => {
+35
View File
@@ -497,6 +497,33 @@ function onOpenDeal(dealId: string) {
void router.push({ name: 'deal-detail', params: { id: dealId } });
}
function findDeal(dealId: string | null) {
if (!dealId) return null;
for (const stage of stages.value) {
const deal = stage.deals.find((d) => d.id === dealId);
if (deal) return deal;
}
return null;
}
function canPromotePrior(deal: PipelineDeal | null) {
const pa = auth.user?.priorArchive;
if (!deal || !pa || pa.lens !== 'archive' || !pa.cutoffAt || !deal.createdAt) return false;
if (deal.promotedFromPriorAt) return false;
return new Date(deal.createdAt).getTime() < new Date(pa.cutoffAt).getTime();
}
async function promotePriorDeal(dealId: string) {
menuOpenId.value = null;
error.value = '';
try {
await api.post(`/deals/${dealId}/promote-from-prior`);
await load();
} catch (e) {
error.value = apiMessage(e, 'انتقال معامله به کار جاری ناموفق بود.');
}
}
const pageBusy = ref(false);
const busyMessage = ref('لطفاً صبر کنید…');
@@ -721,6 +748,14 @@ defineExpose({ updateDealStage: applyUpdateDealStage });
>
ویرایش
</button>
<button
v-if="canPromotePrior(findDeal(menuOpenId))"
type="button"
role="menuitem"
@click="promotePriorDeal(menuOpenId)"
>
انتقال به کار جاری
</button>
<button type="button" role="menuitem" class="danger" @click="askDeleteDeal(menuOpenId)">
حذف
</button>
@@ -0,0 +1,586 @@
# Prior Archive Cutoff Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Split deals/activities into current vs archive by an org-wide Jalali cutoff date, with a one-way promote tag that never mutates other fields.
**Architecture:** Reuse `Organization.priorArchiveEnabledAt` as the cutoff (nullable = no filter). Add `promotedFromPriorAt` on `Deal` and `Activity`. Rewrite `prior-archive.ts` to filter only by `createdAt` + promote tag (drop Didar/`importSource` and the open-future exception). Expose cutoff on auth + org APIs; owner sets date and multi-selects users in Teams settings; promote action lives in the existing three-dot menus when lens is archive.
**Tech Stack:** NestJS, Prisma, node:test, `@mento/shared`, Vue 3, existing `JalaliDateInput`, `UiDropdownMenu`.
**Spec:** `docs/superpowers/specs/2026-10-17-prior-data-archive-cutoff-design.md`
## Global Constraints
- npm workspaces only (`npm run … -w @mento/…`); never pnpm/yarn
- Prisma only from `apps/api` (needs `apps/api/.env`)
- Shell is PowerShell: use `;` not `&&`
- Transfer never changes `createdAt` or any field except `promotedFromPriorAt`
- Filter applies only to deals and activities; people/leads/rules/etc. stay unfiltered
- Without user prior-archive grant: no switch, no filter (full environment)
- Without cutoff date: no filter even if user is granted
- After code edits: `graphify update .` (may crash; non-blocking)
- Do not start implementation commits unless the user asked to implement / commit
## File Map
| File | Responsibility |
|---|---|
| `apps/api/prisma/schema.prisma` | `promotedFromPriorAt` on Deal/Activity; comment on org cutoff |
| `apps/api/prisma/migrations/*` | Migration |
| `apps/api/src/common/prior-archive.ts` | Pure where builders for deal/activity |
| `apps/api/test/prior-archive.test.ts` | Unit tests for new rules |
| `packages/shared/src/index.ts` | DTO fields: cutoff, promote flag, auth priorArchive shape |
| `apps/api/src/auth/jwt.strategy.ts` | `priorCutoff` only when grant + cutoff present |
| `apps/api/src/auth/auth.service.ts` | Expose `priorArchive.cutoffAt` |
| `apps/api/src/billing/billing.service.ts` | Stop auto-stamping cutoff on module enable |
| `apps/api/src/organizations/*` | Owner PATCH cutoff date |
| `apps/api/src/pipelines/*` + `activities/*` | Use new where; promote endpoints; DTO mapping |
| `apps/api/src/contacts/people.service.ts` | Remove person prior filter |
| `apps/api/src/contacts/companies.service.ts` | Remove company prior filter |
| `apps/api/src/reports/reports.service.ts` | Drop person prior; pass cutoff to deal/activity |
| `apps/api/src/ai/ai-ask.service.ts` | Same |
| `apps/web/src/components/TeamsSettingsPanel.vue` | Date next to h3 + multi-select users |
| `apps/web/src/views/ActivitiesView.vue` | Promote in three-dot menu |
| `apps/web/src/views/PipelineBoardView.vue` | Promote in deal menu-pop |
| `apps/web/src/views/PersonProfileView.vue` | Client split by cutoff + promote, not Didar |
---
### Task 1: Schema + shared DTO fields
**Files:**
- Modify: `apps/api/prisma/schema.prisma`
- Create: migration under `apps/api/prisma/migrations/`
- Modify: `packages/shared/src/index.ts`
**Interfaces:**
- Produces:
- `Deal.promotedFromPriorAt DateTime?`
- `Activity.promotedFromPriorAt DateTime?`
- `Organization.priorArchiveEnabledAt` comment = cutoff date (start of selected day)
- `AuthUserDto.priorArchive?: { lens: 'current' \| 'archive'; cutoffAt: string | null } | null`
- `OrganizationDto.priorArchiveCutoffAt?: string | null`
- `DealDto.promotedFromPriorAt: string | null`
- `ActivityDto.promotedFromPriorAt?: string | null`
- `UpdatePriorArchiveCutoffRequest { cutoffAt: string | null }` (ISO date or null)
- [ ] **Step 1: Update Prisma models**
On `Organization`, change comment of `priorArchiveEnabledAt` to:
`/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر`
On `Deal` and `Activity`, after `importSource` (or near `createdAt`), add:
```prisma
/// اگر پر باشد، رکورد از بایگانی به کار جاری منتقل شده (فقط برچسب؛ بقیه فیلدها دست‌نخورده)
promotedFromPriorAt DateTime?
```
Add indexes optional: `@@index([organizationId, createdAt])` only if missing; do not over-index.
- [ ] **Step 2: Create migration**
```powershell
cd apps/api; npx prisma migrate dev --name prior_archive_promote_cutoff
```
Expected: migration applies; client generates.
- [ ] **Step 3: Shared types** in `packages/shared/src/index.ts`
```ts
// AuthUserDto
priorArchive?: { lens: "current" | "archive"; cutoffAt: string | null } | null;
// OrganizationDto
priorArchiveCutoffAt?: string | null;
export interface UpdatePriorArchiveCutoffRequest {
/** ISO datetime (start of selected Jalali day) or null to clear */
cutoffAt: string | null;
}
// DealDto
promotedFromPriorAt: string | null;
// ActivityDto
promotedFromPriorAt?: string | null;
```
- [ ] **Step 4: Build shared**
```powershell
npm run build -w @mento/shared
```
Expected: success.
---
### Task 2: Rewrite `prior-archive.ts` (TDD)
**Files:**
- Modify: `apps/api/test/prior-archive.test.ts` (replace entirely)
- Modify: `apps/api/src/common/prior-archive.ts` (replace filter logic)
**Interfaces:**
- Consumes: cutoff `Date | null | undefined`, lens
- Produces:
- `dealPriorWhere(lens, cutoff): Prisma.DealWhereInput`
- `activityPriorWhere(lens, cutoff): Prisma.ActivityWhereInput`
- Keep `actorPriorLens`, `PriorLens`, `listPriorLens` if still used; `personPriorWhere` / `companyPriorWhere` become always `{}` (or delete and fix imports in Task 3)
- [ ] **Step 1: Write failing tests** — replace `apps/api/test/prior-archive.test.ts` with:
```ts
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import {
activityPriorWhere,
dealPriorWhere,
personPriorWhere,
} from '../src/common/prior-archive';
const cutoff = new Date('2026-10-01T00:00:00.000Z');
describe('بایگانی اطلاعات قبل — تاریخ قطع', () => {
it('بدون لنز یا بدون تاریخ فیلتر نمی‌گذارد', () => {
assert.deepEqual(dealPriorWhere('off', cutoff), {});
assert.deepEqual(dealPriorWhere('current', null), {});
assert.deepEqual(activityPriorWhere('archive', undefined), {});
assert.deepEqual(personPriorWhere('current'), {});
});
it('کار جاری: بعد از قطع یا منتقل‌شده', () => {
assert.deepEqual(dealPriorWhere('current', cutoff), {
OR: [
{ createdAt: { gte: cutoff } },
{ promotedFromPriorAt: { not: null } },
],
});
});
it('بایگانی: قبل از قطع و بدون برچسب انتقال', () => {
assert.deepEqual(activityPriorWhere('archive', cutoff), {
createdAt: { lt: cutoff },
promotedFromPriorAt: null,
});
});
it('استثنای موعد آینده دیگر نیست', () => {
const w = JSON.stringify(dealPriorWhere('current', cutoff));
assert.equal(w.includes('expectedCloseAt'), false);
assert.equal(w.includes('didar'), false);
});
});
```
- [ ] **Step 2: Run tests — expect FAIL**
```powershell
cd apps/api; npx tsx --test test/prior-archive.test.ts
```
- [ ] **Step 3: Implement** `apps/api/src/common/prior-archive.ts`:
```ts
import type { Prisma } from '@prisma/client';
import type { Actor } from './record-scope';
export type PriorLens = 'off' | 'current' | 'archive';
export function actorPriorLens(actor: Pick<Actor, 'priorLens'> | undefined): PriorLens {
return actor?.priorLens ?? 'off';
}
function hasCutoff(cutoff?: Date | null): cutoff is Date {
return cutoff instanceof Date && !Number.isNaN(cutoff.getTime());
}
/** شخص/شرکت دیگر با این لنز فیلتر نمی‌شوند. */
export function personPriorWhere(_lens?: PriorLens): Prisma.PersonWhereInput {
return {};
}
export function companyPriorWhere(_lens?: PriorLens): Prisma.CompanyWhereInput {
return {};
}
export function dealPriorWhere(
lens: PriorLens | undefined,
cutoff?: Date | null,
): Prisma.DealWhereInput {
if (lens !== 'current' && lens !== 'archive') return {};
if (!hasCutoff(cutoff)) return {};
if (lens === 'current') {
return {
OR: [
{ createdAt: { gte: cutoff } },
{ promotedFromPriorAt: { not: null } },
],
};
}
return { createdAt: { lt: cutoff }, promotedFromPriorAt: null };
}
export function activityPriorWhere(
lens: PriorLens | undefined,
cutoff?: Date | null,
): Prisma.ActivityWhereInput {
if (lens !== 'current' && lens !== 'archive') return {};
if (!hasCutoff(cutoff)) return {};
if (lens === 'current') {
return {
OR: [
{ createdAt: { gte: cutoff } },
{ promotedFromPriorAt: { not: null } },
],
};
}
return { createdAt: { lt: cutoff }, promotedFromPriorAt: null };
}
/** فهرست شخص/شرکت: همیشه بدون فیلتر لنز (سازگاری با call-siteهای قدیمی). */
export function listPriorLens(
_lens: PriorLens | undefined,
_q: string | undefined,
_explicitSource: boolean,
): PriorLens {
return 'off';
}
```
Remove `PRIOR_IMPORT_SOURCE`, `liveDeal`, `liveActivity`, `historicalActivity`, `stillOpenAhead`.
- [ ] **Step 4: Run tests — expect PASS**
```powershell
cd apps/api; npx tsx --test test/prior-archive.test.ts
```
---
### Task 3: Wire API call-sites + auth cutoff + stop auto-stamp
**Files:**
- Modify: `apps/api/src/auth/jwt.strategy.ts`
- Modify: `apps/api/src/auth/auth.service.ts` (`priorArchiveFor`)
- Modify: `apps/api/src/billing/billing.service.ts` (do not set `priorArchiveEnabledAt` on module enable)
- Modify call sites of `dealPriorWhere` / `activityPriorWhere` / person+company filters:
- `apps/api/src/pipelines/pipelines.service.ts`
- `apps/api/src/pipelines/deals-excel.service.ts`
- `apps/api/src/activities/activities.service.ts`
- `apps/api/src/reports/reports.service.ts`
- `apps/api/src/ai/ai-ask.service.ts`
- `apps/api/src/contacts/people.service.ts`
- `apps/api/src/contacts/companies.service.ts`
- Modify DTO mappers: `pipelines.service.ts` `toDealDto`, `activities.service.ts` `toDto`
**Interfaces:**
- Consumes: `actor.priorCutoff`, new `dealPriorWhere(lens, cutoff)` signature (no `now`)
- Produces: auth payload includes `cutoffAt`; DTOs include `promotedFromPriorAt`
- [ ] **Step 1: jwt.strategy** — set cutoff only when granted:
```ts
priorLens: priorGranted ? priorLens : 'off',
priorCutoff:
priorGranted && membership.organization.priorArchiveEnabledAt
? membership.organization.priorArchiveEnabledAt
: null,
```
- [ ] **Step 2: auth.service `priorArchiveFor`** — return:
```ts
return {
lens: membership.priorArchiveLens === 'archive' ? 'archive' : 'current',
cutoffAt: orgCutoff ? orgCutoff.toISOString() : null,
};
```
Load org cutoff in the membership select used by `me` / login (same field already on org via jwt; ensure `me` path also has it).
- [ ] **Step 3: Fix every `dealPriorWhere(actor.priorLens, now)` → `dealPriorWhere(actor.priorLens, actor.priorCutoff)`** and `activityPriorWhere(lens, now, cutoff)` → `activityPriorWhere(lens, cutoff)`.
- [ ] **Step 4: Remove person/company prior filtering** from people/companies list and reports/ai-ask (either delete spreads of `personPriorWhere` / `companyPriorWhere` or leave no-ops from Task 2).
- [ ] **Step 5: Map `promotedFromPriorAt`** in `toDealDto` / activity `toDto`:
```ts
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
```
- [ ] **Step 6: billing.service** — when enabling `prior_data_archive`, do **not** write `priorArchiveEnabledAt`. Leave existing values untouched. Owner sets cutoff via Task 4.
- [ ] **Step 7: Typecheck**
```powershell
npm run typecheck -w @mento/api
```
Expected: pass (fix any remaining old signatures).
---
### Task 4: Owner API — set org cutoff date
**Files:**
- Modify: `apps/api/src/organizations/dto.ts`
- Modify: `apps/api/src/organizations/organizations.service.ts` (`toDto`, new method)
- Modify: `apps/api/src/organizations/organizations.controller.ts`
- Modify: `packages/shared` if `UpdatePriorArchiveCutoffRequest` not already added in Task 1
**Interfaces:**
- Produces: `PATCH /organizations/current/prior-archive-cutoff` body `{ cutoffAt: string | null }`
- Roles: `@Roles('owner')` only (same as user prior-archive toggle)
- `getCurrent` includes `priorArchiveCutoffAt`
- [ ] **Step 1: Service method**
```ts
async updatePriorArchiveCutoff(
organizationId: string,
cutoffAt: string | null,
): Promise<OrganizationDto> {
const modules = /* load enabledModules */;
if (!modules.includes('prior_data_archive')) {
throw new BadRequestException('ماژول بایگانی اطلاعات قبل برای این محیط فعال نیست.');
}
let value: Date | null = null;
if (cutoffAt != null && cutoffAt !== '') {
const d = new Date(cutoffAt);
if (Number.isNaN(d.getTime())) {
throw new BadRequestException('تاریخ قطع معتبر نیست.');
}
value = d;
}
await this.prisma.organization.update({
where: { id: organizationId },
data: { priorArchiveEnabledAt: value },
});
return this.getCurrent(organizationId);
}
```
Include `priorArchiveCutoffAt: org.priorArchiveEnabledAt?.toISOString() ?? null` in `toDto`.
- [ ] **Step 2: Controller**
```ts
@Patch('current/prior-archive-cutoff')
@Roles('owner')
updatePriorArchiveCutoff(
@CurrentUser() user: { organizationId: string },
@Body() body: { cutoffAt?: string | null },
) {
return this.organizationsService.updatePriorArchiveCutoff(
user.organizationId,
body.cutoffAt === undefined ? null : body.cutoffAt,
);
}
```
Treat missing vs null carefully: prefer explicit `{ cutoffAt: null }` to clear; require property present.
- [ ] **Step 3: Manual smoke** — owner PATCH with ISO start-of-day; GET current shows field.
---
### Task 5: Promote endpoints (deal + activity)
**Files:**
- Modify: `apps/api/src/pipelines/deals.service.ts`
- Modify: `apps/api/src/pipelines/deals.controller.ts`
- Modify: `apps/api/src/activities/activities.service.ts`
- Modify: `apps/api/src/activities/activities.controller.ts`
**Interfaces:**
- Produces:
- `POST /deals/:id/promote-from-prior` → `DealDto`
- `POST /activities/:id/promote-from-prior` → `ActivityDto`
- Rules: actor `priorLens` is `current` or `archive` (grant on); cutoff set; record `createdAt < cutoff`; `promotedFromPriorAt` is null; access where passes; set **only** `promotedFromPriorAt: new Date()`.
- [ ] **Step 1: deals.service.promoteFromPrior**
```ts
async promoteFromPrior(actor: Actor, id: string): Promise<DealDto> {
if (actor.priorLens === 'off' || !actor.priorCutoff) {
throw new ForbiddenException('بایگانی اطلاعات قبل برای شما فعال نیست.');
}
const row = await this.prisma.deal.findFirst({
where: { id, organizationId: actor.organizationId, ...dealAccessWhere(actor) },
});
if (!row) throw new NotFoundException('معامله پیدا نشد');
if (row.promotedFromPriorAt) {
throw new BadRequestException('این معامله قبلاً منتقل شده است.');
}
if (row.createdAt >= actor.priorCutoff) {
throw new BadRequestException('این معامله در بایگانی نیست.');
}
const updated = await this.prisma.deal.update({
where: { id },
data: { promotedFromPriorAt: new Date() },
include: /* same as get */,
});
return this.pipelines.toDealDto(updated);
}
```
Mirror for activities with `activityAccessWhere`.
- [ ] **Step 2: Controllers** — `POST :id/promote-from-prior` before generic `:id` routes if needed (Nest order: static segments already fine as long as path is under `:id/...`).
- [ ] **Step 3: Verify** with a prior deal: after promote, appears in current lens lists; `createdAt` unchanged.
---
### Task 6: Teams settings UI — cutoff date + user multi-select
**Files:**
- Modify: `apps/web/src/components/TeamsSettingsPanel.vue`
- Possibly refresh auth after cutoff change so `priorArchive.cutoffAt` updates for the owner session
**Interfaces:**
- Consumes: `GET /organizations/current` → `priorArchiveCutoffAt`; `PATCH .../prior-archive-cutoff`; existing `PATCH /users/:id/prior-archive`
- Produces: compact card UI
- [ ] **Step 1: Header row** — next to `<h3>بایگانی اطلاعات قبل</h3>`:
```vue
<header class="prior-head">
<h3>بایگانی اطلاعات قبل</h3>
<JalaliDateInput
:model-value="cutoffLocal"
mode="date"
:disabled="cutoffSaving"
@update:model-value="onCutoffChange"
/>
</header>
```
Load cutoff on mount from `/organizations/current`. On change, convert selected Jalali day to ISO **start of that day** (reuse helpers already used with `JalaliDateInput` elsewhere — same as deal expected-close date storage). PATCH cutoff. If cleared, send `null`.
- [ ] **Step 2: Replace checkbox list** with searchable multi-select:
- Show a `<select>` or combobox of active users not yet enabled; on pick, call `setPriorArchive(id, true)`.
- Show selected users as removable chips/rows; remove → `setPriorArchive(id, false)`.
- Keep existing API; only UX changes.
- Hint text stays: only selected users see the switch.
- [ ] **Step 3: Style** — keep card compact; date aligned with title (flex, gap); chips wrap.
- [ ] **Step 4: Manual check** — with many users, card height stays small; date saves; selected users see sidebar switch after refresh/`auth` reload.
---
### Task 7: Three-dot promote UI + PersonProfile client rules
**Files:**
- Modify: `apps/web/src/views/ActivitiesView.vue` (both desktop + mobile `UiDropdownMenu` blocks)
- Modify: `apps/web/src/views/PipelineBoardView.vue` (`menu-pop`)
- Modify: `apps/web/src/views/PersonProfileView.vue` (`isPriorDeal` / `isPriorActivity`)
**Interfaces:**
- Show «انتقال به کار جاری» only when:
- `auth.user?.priorArchive?.lens === 'archive'`
- item has no `promotedFromPriorAt`
- `createdAt < cutoffAt` (if cutoff missing, hide)
- POST promote endpoint; refresh list / close menu; toast/ok optional
- [ ] **Step 1: ActivitiesView** — inside each `UiDropdownMenu`, after ویرایش:
```vue
<button
v-if="canPromotePrior(item)"
type="button"
@click="promotePriorActivity(item.id)"
>
انتقال به کار جاری
</button>
```
```ts
function canPromotePrior(item: ActivityDto) {
const pa = auth.user?.priorArchive;
if (!pa || pa.lens !== 'archive' || !pa.cutoffAt) return false;
if (item.promotedFromPriorAt) return false;
return new Date(item.createdAt).getTime() < new Date(pa.cutoffAt).getTime();
}
async function promotePriorActivity(id: string) {
menuId.value = null;
await api.post(`/activities/${id}/promote-from-prior`);
// reload list the same way delete/complete does
}
```
- [ ] **Step 2: PipelineBoardView** — same gate using deal from board data; `api.post(`/deals/${id}/promote-from-prior`)`; reload board.
- [ ] **Step 3: PersonProfileView** — replace Didar-based helpers:
```ts
function isPriorDeal(row: DealDto) {
const cutoff = auth.user?.priorArchive?.cutoffAt;
if (!auth.user?.priorArchive || !cutoff) return false;
if (row.promotedFromPriorAt) return false;
return new Date(row.createdAt).getTime() < new Date(cutoff).getTime();
}
// same for activities
```
When prior archive is off for user, show all deals/activities in the normal sections (existing `priorArchiveOn` false path).
- [ ] **Step 4: Manual QA checklist**
1. User without grant: full deals/activities, no switch
2. Grant + no cutoff: full lists
3. Set cutoff: current empty of pre-cutoff deals/activities (even open future due)
4. Archive lens: only pre-cutoff non-promoted
5. Promote from menu: appears in current; dates unchanged; no reverse action
6. People/leads unchanged across lenses
---
### Task 8: Final verification + graphify
- [ ] **Step 1: Tests**
```powershell
cd apps/api; npm test
```
Expected: all green including `prior-archive.test.ts`.
- [ ] **Step 2: Builds**
```powershell
npm run build -w @mento/shared; npm run build -w @mento/api; npm run build -w @mento/web
```
- [ ] **Step 3: graphify**
```powershell
graphify update .
```
- [ ] **Step 4: Mark old design pointer** already done in `2026-10-14-...`; ensure new spec status stays accurate.
---
## Spec coverage (self-review)
| Spec requirement | Task |
|---|---|
| Org-wide Jalali cutoff | 1, 4, 6 |
| Filter only deals/activities by createdAt | 2, 3 |
| Promote tag only, no field mutation | 5 |
| One-way, any granted viewer | 5, 7 |
| No filter without grant | 3, jwt |
| No filter without cutoff | 2, 3 |
| Default lens current when granted | existing auth; unchanged |
| Teams UI date + multi-select | 6 |
| Three-dot promote in archive lens | 7 |
| Drop Didar + future-due exception | 2, 7 |
| Person/lead/rules unfiltered | 2, 3 |
No TBD placeholders. Signatures: `dealPriorWhere(lens, cutoff)` and `activityPriorWhere(lens, cutoff)` consistently; promote field name `promotedFromPriorAt` everywhere.
@@ -1,7 +1,7 @@
# بایگانی اطلاعات قبل
تاریخ: ۲۰۲۶-۱۰-۱۴
وضعیت: قفل‌شده توسط کاربر و پیاده‌سازی شروع شده است.
وضعیت: برای منطق طبقه‌بندی، محدودهٔ فیلتر، تاریخ قطع و انتقال، با [`2026-10-17-prior-data-archive-cutoff-design.md`](./2026-10-17-prior-data-archive-cutoff-design.md) جایگزین شده است. سه سطح دسترسی و نام‌گذاری UI هنوز مرجع است مگر سند جدید خلافش بگوید.
## هدف
@@ -0,0 +1,73 @@
# بایگانی اطلاعات قبل — تاریخ قطع و انتقال یک‌طرفه
تاریخ: ۲۰۲۶-۱۰-۱۷
وضعیت: تأیید شده در گفتگو؛ در انتظار دستور پیاده‌سازی.
جایگزین منطق طبقه‌بندی و محدودهٔ فیلتر در [`2026-10-14-prior-data-archive-design.md`](./2026-10-14-prior-data-archive-design.md) است. سه سطح دسترسی (سوپرادمین / مالک برای تیک کاربر / سوئیچ کاربر) همان سند قبلی می‌ماند مگر جایی که این سند صریحاً عوض کند.
## هدف
برای کاربرانی که این قابلیت برایشان روشن است، معامله‌ها و فعالیت‌های ساخته‌شده قبل از یک تاریخ قطع محیط، از «کار جاری» جدا شوند. کار جاری محیط ایزوله و پاک است. بایگانی فقط برای دیدن قبلی‌هاست. انتقال به جاری فقط با برچسب است؛ تاریخ و بقیهٔ فیلدها عوض نمی‌شوند.
کاربری که تیک بایگانی ندارد، محیط کامل را می‌بیند (قبل و جاری با هم) و سوئیچ را نمی‌بیند.
## مدل داده
- **تاریخ قطع محیط:** یک تاریخ برای کل سازمان (ورود شمسی در UI). اگر خالی باشد فیلتر اعمال نمی‌شود.
- **مجوز کاربر:** مثل قبل؛ فقط اعضای انتخاب‌شده سوئیچ را می‌بینند.
- **برچسب انتقال روی معامله و فعالیت:** فیلدی مثل `promotedFromPriorAt` (یا معادل). با انتقال پر می‌شود؛ یک‌طرفه؛ هیچ فیلد دیگری از جمله `createdAt` عوض نمی‌شود.
### قانون قبلی / جاری (فقط معامله و فعالیت)
| حالت | شرط |
|------|-----|
| قبلی | `createdAt` قبل از تاریخ قطع **و** برچسب انتقال ندارد |
| جاری | `createdAt` در/بعد از تاریخ قطع **یا** برچسب انتقال دارد |
- استثنای قبلی (باز + موعد آینده در کار جاری) حذف می‌شود.
- معیار منبع ورود «دیدار» برای این قابلیت دیگر استفاده نمی‌شود.
- شخص، شرکت، لید، قانون، یادداشت و بقیهٔ ماژول‌ها در هر دو لنز یکی‌اند (فیلتر لنز ندارند).
## لنز کاربر
| وضعیت مجوز | رفتار |
|------------|--------|
| ماژول محیط خاموش، یا تیک کاربر خاموش | لنز `off`؛ بدون فیلتر؛ سوئیچ مخفی |
| تیک روشن | سوئیچ دیده می‌شود؛ پیش‌فرض لنز `current` |
| لنز `current` | فقط معامله/فعالیت جاری (طبق جدول بالا) |
| لنز `archive` | فقط معامله/فعالیت قبلی |
انتخاب لنز روی عضویت ذخیره می‌شود. با قطع مجوز، انتخاب می‌ماند ولی تا بازگشت مجوز اثری ندارد.
## رابط کاربری
### کارت «بایگانی اطلاعات قبل» در دسترسی کاربران
- کنار عنوان (`h3`): انتخاب‌گر تاریخ شمسی محیط.
- به‌جای لیست بلند چک‌باکس: انتخاب کاربر به‌صورت انتخابی (جستجو/چندتایی). فقط انتخاب‌شده‌ها سوئیچ را دارند.
- ماژول محیط در سوپرادمین مثل قبل شرط لازم است.
### نوار کناری
- سوئیچ «کار جاری / بایگانی اطلاعات قبل» فقط وقتی مجوز کاربر برقرار است.
- پیش‌فرض برای کاربر مجاز: کار جاری.
### منوی سه‌نقطهٔ معامله و فعالیت
- فقط وقتی لنز روی بایگانی است و رکورد قبلی است (بدون برچسب انتقال): آیتم «انتقال به کار جاری».
- بعد از انتقال: رکورد در کار جاری دیده می‌شود؛ آیتم منو دیگر برای آن رکورد نمی‌آید.
- برگشت به بایگانی وجود ندارد.
## API و محدودهٔ فیلتر
- فیلتر لنز فقط روی معامله و فعالیت در فهرست، بورد، داشبورد، شمارش‌ها و گزارش‌هایی که این دو را می‌شمارند.
- endpoint انتقال: کاربر باید مجوز بایگانی داشته باشد، رکورد را ببیند، رکورد قبلی بدون برچسب باشد؛ فقط برچسب می‌زند.
- هر کسی که سوئیچ بایگانی دارد و آن رکورد را می‌بیند می‌تواند انتقال بزند.
## خارج از محدوده
- دو حساب یا دو محیط جدا.
- نمایش کلمهٔ «دیدار» در UI این قابلیت.
- تغییر `createdAt` یا کپی کردن رکورد هنگام انتقال.
- دکمهٔ برگشت به بایگانی.
- فیلتر لنز روی شخص، لید، قانون و ماژول‌های غیر از معامله/فعالیت.
- شروع پیاده‌سازی قبل از دستور صریح کاربر.
+9 -1
View File
@@ -43,7 +43,7 @@ export interface AuthUserDto {
/** خلاصه اشتراک مالک محیط (برای اعضا فقط جهت نمایش/گیت ورود) */
subscription?: SubscriptionSummaryDto | null;
/** اگر باشد، این کاربر سوئیچ «بایگانی اطلاعات قبل» را دارد */
priorArchive?: { lens: "current" | "archive" } | null;
priorArchive?: { lens: "current" | "archive"; cutoffAt: string | null } | null;
}
export type BillingPlanCode =
@@ -631,6 +631,12 @@ export interface OrganizationDto {
enabledCurrencies: string[];
exchangeRates: ExchangeRateDto[];
enabledModules: OrgModuleKey[];
priorArchiveCutoffAt?: string | null;
}
export interface UpdatePriorArchiveCutoffRequest {
/** ISO datetime (start of selected Jalali day) or null to clear */
cutoffAt: string | null;
}
export interface UpdateOrganizationRequest {
@@ -951,6 +957,7 @@ export interface DealDto {
code: string | null;
/** منبع ورود: manual | didar | excel */
importSource: string;
promotedFromPriorAt: string | null;
/** شناسه در مبدأ (کد دیدار) */
sourceRef: string | null;
amount: number | null;
@@ -1477,6 +1484,7 @@ export interface ActivityDto {
completedAt: string | null;
/** manual یا didar؛ برای جدا کردن سابقهٔ قبلی */
importSource?: string;
promotedFromPriorAt?: string | null;
tags: string[];
person: PersonSummaryDto | null;
company: CompanySummaryDto | null;