Creating import&export excel
This commit is contained in:
@@ -7,12 +7,20 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UploadedFile,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { memoryStorage } from 'multer';
|
||||
import type { Response } from 'express';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import {
|
||||
CreateProjectBoardDto,
|
||||
CreateProjectCardDto,
|
||||
@@ -20,22 +28,25 @@ import {
|
||||
UpdateProjectCardDto,
|
||||
} from './dto';
|
||||
import { ProjectBoardsService } from './project-boards.service';
|
||||
|
||||
type AuthUser = { organizationId: string; userId: string; role: string };
|
||||
import { ProjectCardsExcelService } from './project-cards-excel.service';
|
||||
import { brand } from '@mento/shared';
|
||||
|
||||
@Controller()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class ProjectBoardsController {
|
||||
constructor(private readonly boards: ProjectBoardsService) {}
|
||||
constructor(
|
||||
private readonly boards: ProjectBoardsService,
|
||||
private readonly excelService: ProjectCardsExcelService,
|
||||
) {}
|
||||
|
||||
@Get('project-boards')
|
||||
listBoards(@CurrentUser() user: AuthUser) {
|
||||
listBoards(@CurrentUser() user: Actor) {
|
||||
return this.boards.list(user.organizationId);
|
||||
}
|
||||
|
||||
@Get('project-boards/board')
|
||||
board(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@CurrentUser() user: Actor,
|
||||
@Query('boardId') boardId?: string,
|
||||
) {
|
||||
return this.boards.getBoard(user.organizationId, boardId, user);
|
||||
@@ -44,20 +55,48 @@ export class ProjectBoardsController {
|
||||
@Post('project-boards')
|
||||
@Roles('owner', 'admin')
|
||||
createBoard(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@CurrentUser() user: Actor,
|
||||
@Body() dto: CreateProjectBoardDto,
|
||||
) {
|
||||
return this.boards.create(user.organizationId, dto.name);
|
||||
}
|
||||
|
||||
@Get('project-cards/export')
|
||||
async exportCards(
|
||||
@CurrentUser() user: Actor,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const buffer = await this.excelService.export(user);
|
||||
res.set({
|
||||
'Content-Type':
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${brand.filePrefix}-project-cards.xlsx"`,
|
||||
});
|
||||
return new StreamableFile(buffer);
|
||||
}
|
||||
|
||||
@Post('project-cards/import')
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
storage: memoryStorage(),
|
||||
limits: { fileSize: 15_000_000 },
|
||||
}),
|
||||
)
|
||||
importCards(
|
||||
@CurrentUser() user: Actor,
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
) {
|
||||
return this.excelService.import(user, file);
|
||||
}
|
||||
|
||||
@Get('project-cards/:id')
|
||||
getCard(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
getCard(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||
return this.boards.getCard(user.organizationId, id, user);
|
||||
}
|
||||
|
||||
@Post('project-cards')
|
||||
createCard(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@CurrentUser() user: Actor,
|
||||
@Body() dto: CreateProjectCardDto,
|
||||
) {
|
||||
return this.boards.createCard(user.organizationId, user, dto);
|
||||
@@ -65,7 +104,7 @@ export class ProjectBoardsController {
|
||||
|
||||
@Patch('project-cards/:id')
|
||||
updateCard(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@CurrentUser() user: Actor,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateProjectCardDto,
|
||||
) {
|
||||
@@ -74,7 +113,7 @@ export class ProjectBoardsController {
|
||||
|
||||
@Patch('project-cards/:id/move')
|
||||
moveCard(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@CurrentUser() user: Actor,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: MoveProjectCardDto,
|
||||
) {
|
||||
@@ -82,7 +121,7 @@ export class ProjectBoardsController {
|
||||
}
|
||||
|
||||
@Delete('project-cards/:id')
|
||||
async removeCard(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
async removeCard(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||
await this.boards.removeCard(user.organizationId, id, user);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@@ -2,11 +2,12 @@ import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { ProjectBoardsController } from './project-boards.controller';
|
||||
import { ProjectBoardsService } from './project-boards.service';
|
||||
import { ProjectCardsExcelService } from './project-cards-excel.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [ProjectBoardsController],
|
||||
providers: [ProjectBoardsService],
|
||||
providers: [ProjectBoardsService, ProjectCardsExcelService],
|
||||
exports: [ProjectBoardsService],
|
||||
})
|
||||
export class ProjectBoardsModule {}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { ImportContactsResult } from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { ownerWhere } from '../common/record-scope';
|
||||
import { normalizePhone } from '../contacts/normalize';
|
||||
import {
|
||||
formatJalaliDate,
|
||||
parseJalaliDateTime,
|
||||
readMappedRows,
|
||||
stripHtml,
|
||||
writeXlsx,
|
||||
} from '../common/excel';
|
||||
import { ProjectBoardsService } from './project-boards.service';
|
||||
|
||||
const CASE_COLUMNS = [
|
||||
{ header: '_type', key: '_type', width: 12 },
|
||||
{ header: 'کد دیدار کارت', key: 'didarId', width: 14 },
|
||||
{ header: 'عنوان کارت', key: 'title', width: 28 },
|
||||
{ header: 'توضیحات کارت', key: 'notes', width: 32 },
|
||||
{ header: 'وضعیت کارت', key: 'status', width: 12 },
|
||||
{ header: 'مسئول کارت', key: 'ownerName', width: 16 },
|
||||
{ header: 'مجوز مشاهده کارت', key: 'visibility', width: 18 },
|
||||
{ header: 'تاریخ ثبت کارت', key: 'createdAt', width: 16 },
|
||||
{ header: 'نام خانوادگی شخص کارت', key: 'personName', width: 22 },
|
||||
{ header: 'کد دیدار شخص', key: 'personCode', width: 14 },
|
||||
{ header: 'موبایل شخص کارت', key: 'personMobile', width: 16 },
|
||||
{ header: 'کاریز کارت', key: 'boardName', width: 20 },
|
||||
{ header: 'مرحله کاریز کارت', key: 'stageName', width: 18 },
|
||||
{ header: 'تاریخ انجام کارت', key: 'doneDate', width: 16 },
|
||||
{ header: 'برچسب', key: 'tag', width: 16 },
|
||||
];
|
||||
|
||||
const CASE_ALIASES: Record<string, string> = {
|
||||
_type: '_type',
|
||||
type: '_type',
|
||||
کددیدارکارت: 'didarId',
|
||||
عنوانکارت: 'title',
|
||||
عنوان: 'title',
|
||||
توضیحاتکارت: 'notes',
|
||||
وضعیتکارت: 'status',
|
||||
مسئولکارت: 'ownerName',
|
||||
مجوزمشاهدهکارت: 'visibility',
|
||||
تاریخثبتکارت: 'createdAt',
|
||||
نامخانوادگیشخصکارت: 'personName',
|
||||
کددیدارشخص: 'personCode',
|
||||
موبایلشخصکارت: 'personMobile',
|
||||
کاریزکارت: 'boardName',
|
||||
مرحلهکاریزکارت: 'stageName',
|
||||
تاریخانجامکارت: 'doneDate',
|
||||
برچسب: 'tag',
|
||||
};
|
||||
|
||||
function isClosedStatus(raw?: string) {
|
||||
return /بسته|انجام|done|closed/i.test(raw ?? '');
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ProjectCardsExcelService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly boards: ProjectBoardsService,
|
||||
) {}
|
||||
|
||||
async export(actor: Actor): Promise<Buffer> {
|
||||
const rows = await this.prisma.projectCard.findMany({
|
||||
where: { organizationId: actor.organizationId, ...ownerWhere(actor) },
|
||||
include: {
|
||||
person: {
|
||||
select: { id: true, firstName: true, lastName: true, mobile: true },
|
||||
},
|
||||
owner: { select: { fullName: true } },
|
||||
board: { select: { name: true } },
|
||||
stage: { select: { name: true } },
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }],
|
||||
take: 10000,
|
||||
});
|
||||
|
||||
return writeXlsx(
|
||||
'Case',
|
||||
CASE_COLUMNS,
|
||||
rows.map((row) => {
|
||||
const closed = /انجام|بسته|done/i.test(row.stage.name);
|
||||
return {
|
||||
_type: 'Case',
|
||||
didarId: row.id,
|
||||
title: row.title,
|
||||
notes: row.notes ?? '',
|
||||
status: closed ? 'بسته' : 'باز',
|
||||
ownerName: row.owner?.fullName ?? '',
|
||||
visibility: 'همه افراد شرکت',
|
||||
createdAt: formatJalaliDate(row.createdAt),
|
||||
personName: row.person
|
||||
? `${row.person.firstName} ${row.person.lastName}`.trim()
|
||||
: '',
|
||||
personCode: row.person?.id ?? '',
|
||||
personMobile: row.person?.mobile ?? '',
|
||||
boardName: row.board.name,
|
||||
stageName: row.stage.name,
|
||||
doneDate: closed ? formatJalaliDate(row.updatedAt) : '',
|
||||
tag: '',
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async import(actor: Actor, file: Express.Multer.File): Promise<ImportContactsResult> {
|
||||
const rows = await readMappedRows(file, CASE_ALIASES);
|
||||
const result: ImportContactsResult = { created: 0, skipped: 0, errors: [] };
|
||||
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const row = rows[i]!;
|
||||
const rowNum = i + 2;
|
||||
if ((row._type || '').trim() && row._type.trim().toLowerCase() !== 'case') {
|
||||
continue;
|
||||
}
|
||||
const title = (row.title || '').trim();
|
||||
if (title.length < 2) {
|
||||
result.errors.push({ row: rowNum, message: 'عنوان کارت الزامی است' });
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const { boardId, stageId } = await this.resolveBoardAndStage(
|
||||
actor.organizationId,
|
||||
row.boardName,
|
||||
row.stageName,
|
||||
isClosedStatus(row.status),
|
||||
);
|
||||
const duplicate = await this.prisma.projectCard.findFirst({
|
||||
where: { organizationId: actor.organizationId, boardId, title },
|
||||
select: { id: true },
|
||||
});
|
||||
if (duplicate) {
|
||||
result.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const personId = await this.findPersonId(actor.organizationId, row);
|
||||
const ownerId = await this.findUserId(actor.organizationId, row.ownerName);
|
||||
const notes = [stripHtml(row.notes ?? ''), row.tag, row.didarId ? `کد دیدار: ${row.didarId}` : '']
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
const doneAt = parseJalaliDateTime(row.doneDate);
|
||||
const notesWithDone = doneAt
|
||||
? `${notes}${notes ? '\n' : ''}تاریخ انجام: ${row.doneDate}`.trim()
|
||||
: notes;
|
||||
|
||||
await this.boards.createCard(actor.organizationId, actor, {
|
||||
title,
|
||||
boardId,
|
||||
stageId,
|
||||
notes: notesWithDone || undefined,
|
||||
personId,
|
||||
ownerId,
|
||||
});
|
||||
result.created += 1;
|
||||
} catch (e) {
|
||||
result.errors.push({
|
||||
row: rowNum,
|
||||
message: e instanceof Error ? e.message : 'خطای ناشناخته',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async resolveBoardAndStage(
|
||||
organizationId: string,
|
||||
boardName?: string,
|
||||
stageName?: string,
|
||||
closed = false,
|
||||
) {
|
||||
const name = boardName?.trim() || 'پروژه داخلی';
|
||||
const wanted = stageName?.trim();
|
||||
let board = await this.prisma.projectBoard.findFirst({
|
||||
where: { organizationId, name: { equals: name, mode: 'insensitive' } },
|
||||
include: { stages: { orderBy: { position: 'asc' } } },
|
||||
});
|
||||
if (!board) {
|
||||
const stageCreates = wanted
|
||||
? [{ name: wanted, position: 0 }]
|
||||
: [
|
||||
{ name: 'صف', position: 0 },
|
||||
{ name: 'در حال انجام', position: 1 },
|
||||
{ name: 'بازبینی', position: 2 },
|
||||
{ name: 'انجامشده', position: 3 },
|
||||
];
|
||||
board = await this.prisma.projectBoard.create({
|
||||
data: {
|
||||
organizationId,
|
||||
name,
|
||||
isDefault: false,
|
||||
stages: { create: stageCreates },
|
||||
},
|
||||
include: { stages: { orderBy: { position: 'asc' } } },
|
||||
});
|
||||
}
|
||||
|
||||
if (wanted) {
|
||||
const existing = board.stages.find(
|
||||
(s) => s.name.trim().toLowerCase() === wanted.toLowerCase(),
|
||||
);
|
||||
if (existing) return { boardId: board.id, stageId: existing.id };
|
||||
const maxPos = board.stages.reduce((m, s) => Math.max(m, s.position), -1);
|
||||
const stage = await this.prisma.projectBoardStage.create({
|
||||
data: { boardId: board.id, name: wanted, position: maxPos + 1 },
|
||||
});
|
||||
return { boardId: board.id, stageId: stage.id };
|
||||
}
|
||||
|
||||
const stage = closed
|
||||
? board.stages[board.stages.length - 1]
|
||||
: board.stages[0];
|
||||
if (!stage) throw new Error('برد مرحلهای ندارد');
|
||||
return { boardId: board.id, stageId: stage.id };
|
||||
}
|
||||
|
||||
private async findPersonId(organizationId: string, row: Record<string, string>) {
|
||||
const mobile = normalizePhone(row.personMobile);
|
||||
if (mobile) {
|
||||
const needle = mobile.replace(/^\+98|^98|^0/, '');
|
||||
const byMobile = await this.prisma.person.findFirst({
|
||||
where: { organizationId, mobile: { contains: needle } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (byMobile) return byMobile.id;
|
||||
}
|
||||
const name = (row.personName ?? '').trim();
|
||||
if (name) {
|
||||
const byName = await this.prisma.person.findFirst({
|
||||
where: {
|
||||
organizationId,
|
||||
OR: [
|
||||
{ lastName: { contains: name, mode: 'insensitive' } },
|
||||
{ firstName: { contains: name.split(/\s+/)[0]!, mode: 'insensitive' } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (byName) return byName.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async findUserId(organizationId: string, name?: string) {
|
||||
const n = name?.trim();
|
||||
if (!n) return null;
|
||||
const row = await this.prisma.user.findFirst({
|
||||
where: { organizationId, fullName: { contains: n, mode: 'insensitive' } },
|
||||
select: { id: true },
|
||||
});
|
||||
return row?.id ?? null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user