feat(f6.2): add per-act representative signing and user smtp
Android CI / RC / Android · lint, tests, debug APK, release compile (push) Failing after 1m25s
DH V2 CI / API · typecheck, tests, build (push) Successful in 34s
DH V2 CI / WEB · typecheck, build (push) Successful in 20s
Production dependency audit / API · production dependencies (push) Successful in 9s
Production dependency audit / WEB · production dependencies (push) Successful in 9s
DH V2 CI / Docker / scripts contract (push) Successful in 1m16s
Android CI / RC / Android · lint, tests, debug APK, release compile (push) Failing after 1m25s
DH V2 CI / API · typecheck, tests, build (push) Successful in 34s
DH V2 CI / WEB · typecheck, build (push) Successful in 20s
Production dependency audit / API · production dependencies (push) Successful in 9s
Production dependency audit / WEB · production dependencies (push) Successful in 9s
DH V2 CI / Docker / scripts contract (push) Successful in 1m16s
This commit is contained in:
@@ -2,13 +2,14 @@ import { Module } from '@nestjs/common';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { PhaseADataModule } from '../core-data/phase-a-data.module';
|
||||
import { InspectionReportsModule } from '../inspection-reports/inspection-reports.module';
|
||||
import { RolesController } from './roles/roles.controller';
|
||||
import { RolesService } from './roles/roles.service';
|
||||
import { UsersController } from './users/users.controller';
|
||||
import { UsersService } from './users/users.service';
|
||||
|
||||
@Module({
|
||||
imports: [PhaseADataModule, AuditModule, AuthModule],
|
||||
imports: [PhaseADataModule, AuditModule, AuthModule, InspectionReportsModule],
|
||||
controllers: [UsersController, RolesController],
|
||||
providers: [UsersService, RolesService],
|
||||
})
|
||||
|
||||
@@ -28,10 +28,9 @@ export class CreateUserDto {
|
||||
@Transform(({ value }) =>
|
||||
typeof value === 'string' && value.trim() ? value.trim().toLowerCase() : null,
|
||||
)
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
email?: string | null;
|
||||
email!: string;
|
||||
|
||||
@Transform(({ value }) =>
|
||||
typeof value === 'string' && value.trim() ? value.replace(/\D/g, '') : null,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsEmail,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
const optionalText = ({ value }: { value: unknown }) =>
|
||||
typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
|
||||
export class UpdateSelfProfileDto {
|
||||
@Transform(({ value }) => typeof value === 'string' ? value.trim().toLowerCase() : value)
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
email!: string;
|
||||
|
||||
@Transform(optionalText)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
phone?: string | null;
|
||||
|
||||
@Transform(optionalText)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(160)
|
||||
jobTitle?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
MinLength,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { SmtpSecurityMode } from '../../../database/entities';
|
||||
|
||||
export enum UserSmtpMode {
|
||||
SYSTEM = 'SYSTEM',
|
||||
CUSTOM = 'CUSTOM',
|
||||
}
|
||||
|
||||
const trimmed = ({ value }: { value: unknown }) =>
|
||||
typeof value === 'string' ? value.trim() : value;
|
||||
|
||||
export class UpdateUserSmtpSettingsDto {
|
||||
@IsEnum(UserSmtpMode)
|
||||
mode!: UserSmtpMode;
|
||||
|
||||
@ValidateIf((dto: UpdateUserSmtpSettingsDto) => dto.mode === UserSmtpMode.CUSTOM)
|
||||
@Transform(trimmed)
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
@MaxLength(255)
|
||||
host?: string;
|
||||
|
||||
@ValidateIf((dto: UpdateUserSmtpSettingsDto) => dto.mode === UserSmtpMode.CUSTOM)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(65535)
|
||||
port?: number;
|
||||
|
||||
@ValidateIf((dto: UpdateUserSmtpSettingsDto) => dto.mode === UserSmtpMode.CUSTOM)
|
||||
@IsEnum(SmtpSecurityMode)
|
||||
securityMode?: SmtpSecurityMode;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(trimmed)
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
username?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
password?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(trimmed)
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
fromName?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
enabled = true;
|
||||
}
|
||||
@@ -10,23 +10,33 @@ import {
|
||||
Query,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { AuditService } from '../../audit/audit.service';
|
||||
import { RequirePermissions } from '../../authorization/decorators/require-permissions.decorator';
|
||||
import { CurrentAuth } from '../../auth/decorators/current-auth.decorator';
|
||||
import type {
|
||||
AuthPrincipal,
|
||||
RequestWithContext,
|
||||
} from '../../common/http/request-context';
|
||||
import { AuditAction } from '../../database/entities';
|
||||
import { SmtpDeliveryService } from '../../inspection-reports/smtp-delivery.service';
|
||||
import { administrationAuditContext } from '../common/administration-audit';
|
||||
import { ChangeUserStatusDto } from './dto/change-user-status.dto';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { ListUsersQueryDto } from './dto/list-users-query.dto';
|
||||
import { ReplaceUserRolesDto } from './dto/replace-user-roles.dto';
|
||||
import { ResetUserPasswordDto } from './dto/reset-user-password.dto';
|
||||
import { UpdateSelfProfileDto } from './dto/update-self-profile.dto';
|
||||
import { UpdateUserSmtpSettingsDto } from './dto/update-user-smtp-settings.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('users')
|
||||
export class UsersController {
|
||||
constructor(private readonly users: UsersService) {}
|
||||
constructor(
|
||||
private readonly users: UsersService,
|
||||
private readonly smtp: SmtpDeliveryService,
|
||||
private readonly audit: AuditService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermissions('users.read')
|
||||
@@ -34,6 +44,73 @@ export class UsersController {
|
||||
return this.users.list(query);
|
||||
}
|
||||
|
||||
@Get('self/profile')
|
||||
selfProfile(@CurrentAuth() principal: AuthPrincipal) {
|
||||
return this.users.getSelfProfile(principal.userId);
|
||||
}
|
||||
|
||||
@Patch('self/profile')
|
||||
updateSelfProfile(
|
||||
@Body() dto: UpdateSelfProfileDto,
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
return this.users.updateSelfProfile(dto, principal, request);
|
||||
}
|
||||
|
||||
@Get('self/smtp')
|
||||
selfSmtp(@CurrentAuth() principal: AuthPrincipal) {
|
||||
return this.smtp.publicUserSettings(principal.userId);
|
||||
}
|
||||
|
||||
@Put('self/smtp')
|
||||
async updateSelfSmtp(
|
||||
@Body() dto: UpdateUserSmtpSettingsDto,
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
const before = await this.smtp.publicUserSettings(principal.userId);
|
||||
const after = await this.smtp.saveUserSettings(principal.userId, dto);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.USER_SMTP_SETTINGS_UPDATED,
|
||||
entityType: 'user_smtp_settings',
|
||||
entityId: principal.userId,
|
||||
beforeData: before as Record<string, unknown>,
|
||||
afterData: after as Record<string, unknown>,
|
||||
metadata: { passwordNeverReturned: true, scope: 'SELF' },
|
||||
});
|
||||
return after;
|
||||
}
|
||||
|
||||
@Post('self/smtp/test')
|
||||
async testSelfSmtp(
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
const profile = await this.users.getSelfProfile(principal.userId);
|
||||
if (!profile.email) throw new Error('El usuario no tiene email configurado');
|
||||
const sent = await this.smtp.send({
|
||||
to: profile.email,
|
||||
subject: 'DH Inspección · Prueba de correo personal',
|
||||
text: 'Este correo confirma que tu configuración de correo en DH Inspección funciona correctamente.',
|
||||
attachment: {
|
||||
filename: 'dh-inspeccion-prueba-correo.txt',
|
||||
mimeType: 'text/plain',
|
||||
content: Buffer.from('DH Inspección · Correo personal OK\n', 'utf8'),
|
||||
},
|
||||
}, principal.userId);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.USER_SMTP_TEST_SENT,
|
||||
entityType: 'user_smtp_settings',
|
||||
entityId: principal.userId,
|
||||
afterData: { recipient: profile.email, messageId: sent.messageId },
|
||||
metadata: { scope: 'SELF' },
|
||||
});
|
||||
return { ok: true, recipient: profile.email, messageId: sent.messageId };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermissions('users.create')
|
||||
create(
|
||||
|
||||
@@ -29,6 +29,7 @@ import type { CreateUserDto } from './dto/create-user.dto';
|
||||
import type { ListUsersQueryDto } from './dto/list-users-query.dto';
|
||||
import type { ReplaceUserRolesDto } from './dto/replace-user-roles.dto';
|
||||
import type { ResetUserPasswordDto } from './dto/reset-user-password.dto';
|
||||
import type { UpdateSelfProfileDto } from './dto/update-self-profile.dto';
|
||||
import type { UpdateUserDto } from './dto/update-user.dto';
|
||||
|
||||
export interface UserRoleView {
|
||||
@@ -56,6 +57,7 @@ export interface AdministrativeUserView {
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
roles: UserRoleView[];
|
||||
smtpMode: 'SYSTEM' | 'CUSTOM';
|
||||
}
|
||||
|
||||
interface UserViewRow extends AdministrativeUserView {
|
||||
@@ -76,10 +78,10 @@ function roleSelectionInvalid(): BadRequestException {
|
||||
});
|
||||
}
|
||||
|
||||
function inspectorEmailRequired(): BadRequestException {
|
||||
function userEmailRequired(): BadRequestException {
|
||||
return new BadRequestException({
|
||||
code: 'INSPECTOR_EMAIL_REQUIRED',
|
||||
message: 'Los usuarios con rol Inspector deben tener un email válido para recibir la documentación de sus inspecciones',
|
||||
code: 'USER_EMAIL_REQUIRED',
|
||||
message: 'Cada usuario de Hidrocarburos debe tener un email válido',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,6 +146,7 @@ export class UsersService {
|
||||
user_account.password_changed_at AS "passwordChangedAt",
|
||||
user_account.created_at AS "createdAt",
|
||||
user_account.updated_at AS "updatedAt",
|
||||
COALESCE((SELECT mode FROM user_smtp_settings WHERE user_id=user_account.id),'SYSTEM') AS "smtpMode",
|
||||
COALESCE(
|
||||
JSONB_AGG(
|
||||
JSONB_BUILD_OBJECT(
|
||||
@@ -185,6 +188,24 @@ export class UsersService {
|
||||
);
|
||||
}
|
||||
|
||||
async getSelfProfile(userId: string): Promise<AdministrativeUserView> {
|
||||
return this.getById(userId);
|
||||
}
|
||||
|
||||
async updateSelfProfile(
|
||||
dto: UpdateSelfProfileDto,
|
||||
principal: AuthPrincipal,
|
||||
request: RequestWithContext,
|
||||
): Promise<AdministrativeUserView> {
|
||||
if (!dto.email?.trim()) throw userEmailRequired();
|
||||
return this.update(
|
||||
principal.userId,
|
||||
{ email: dto.email, phone: dto.phone, jobTitle: dto.jobTitle },
|
||||
principal,
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
async create(
|
||||
dto: CreateUserDto,
|
||||
principal: AuthPrincipal,
|
||||
@@ -195,10 +216,10 @@ export class UsersService {
|
||||
try {
|
||||
return await this.dataSource.transaction(async (manager) => {
|
||||
const roles = await this.resolveRoles(manager, dto.roleIds);
|
||||
this.assertInspectorHasEmail(roles, dto.email ?? null);
|
||||
if (!dto.email?.trim()) throw userEmailRequired();
|
||||
const user = manager.getRepository(User).create({
|
||||
username: dto.username.trim().toLowerCase(),
|
||||
email: dto.email?.trim().toLowerCase() || null,
|
||||
email: dto.email.trim().toLowerCase(),
|
||||
dni: dto.dni ?? null,
|
||||
phone: dto.phone ?? null,
|
||||
jobTitle: dto.jobTitle ?? null,
|
||||
@@ -268,15 +289,13 @@ export class UsersService {
|
||||
return await this.dataSource.transaction(async (manager) => {
|
||||
const user = await this.lockUser(manager, id);
|
||||
const before = await this.loadUserView(manager, id);
|
||||
if (dto.email !== undefined && !dto.email && before.roles.some((role) => role.code === 'inspector')) {
|
||||
throw inspectorEmailRequired();
|
||||
}
|
||||
if (dto.email !== undefined && !dto.email) throw userEmailRequired();
|
||||
|
||||
if (dto.username !== undefined) {
|
||||
user.username = dto.username.trim().toLowerCase();
|
||||
}
|
||||
if (dto.email !== undefined) {
|
||||
user.email = dto.email?.trim().toLowerCase() || null;
|
||||
user.email = dto.email!.trim().toLowerCase();
|
||||
}
|
||||
if (dto.dni !== undefined) user.dni = dto.dni ?? null;
|
||||
if (dto.phone !== undefined) user.phone = dto.phone ?? null;
|
||||
@@ -286,6 +305,13 @@ export class UsersService {
|
||||
if (dto.lastName !== undefined) user.lastName = dto.lastName.trim();
|
||||
user.updatedBy = principal.userId;
|
||||
await manager.getRepository(User).save(user);
|
||||
if (dto.email !== undefined && user.email) {
|
||||
await manager.query(`
|
||||
UPDATE user_smtp_settings
|
||||
SET from_email=$2,reply_to=$2,updated_by=$1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE user_id=$1 AND mode='CUSTOM'
|
||||
`, [id, user.email]);
|
||||
}
|
||||
|
||||
const updated = await this.loadUserView(manager, id);
|
||||
await this.audit.record(
|
||||
@@ -414,7 +440,6 @@ export class UsersService {
|
||||
await this.lockUser(manager, id);
|
||||
const roles = await this.resolveRoles(manager, dto.roleIds);
|
||||
const before = await this.loadUserView(manager, id);
|
||||
this.assertInspectorHasEmail(roles, before.email);
|
||||
const beforeIds = before.roles.map((role) => role.id).sort();
|
||||
const afterIds = roles.map((role) => role.id).sort();
|
||||
if (beforeIds.join(',') === afterIds.join(',')) return before;
|
||||
@@ -453,12 +478,6 @@ export class UsersService {
|
||||
return roles;
|
||||
}
|
||||
|
||||
private assertInspectorHasEmail(roles: Role[], email: string | null | undefined): void {
|
||||
if (roles.some((role) => role.code === 'inspector') && !email?.trim()) {
|
||||
throw inspectorEmailRequired();
|
||||
}
|
||||
}
|
||||
|
||||
private async insertUserRoles(
|
||||
manager: EntityManager,
|
||||
userId: string,
|
||||
@@ -511,6 +530,7 @@ export class UsersService {
|
||||
user_account.password_changed_at AS "passwordChangedAt",
|
||||
user_account.created_at AS "createdAt",
|
||||
user_account.updated_at AS "updatedAt",
|
||||
COALESCE((SELECT mode FROM user_smtp_settings WHERE user_id=user_account.id),'SYSTEM') AS "smtpMode",
|
||||
COALESCE(
|
||||
JSONB_AGG(
|
||||
JSONB_BUILD_OBJECT(
|
||||
|
||||
@@ -118,10 +118,9 @@ async function main(): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
email = (await prompt.question('Email (optional): ')).trim().toLowerCase();
|
||||
email = (await prompt.question('Email: ')).trim().toLowerCase();
|
||||
if (
|
||||
email &&
|
||||
(email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
||||
!email || email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
|
||||
) {
|
||||
throw new Error('Email is invalid');
|
||||
}
|
||||
@@ -189,7 +188,7 @@ async function main(): Promise<void> {
|
||||
OR ($2::text IS NOT NULL AND LOWER(email) = $2)
|
||||
LIMIT 1
|
||||
`,
|
||||
[username, email || null],
|
||||
[username, email],
|
||||
)) as unknown[];
|
||||
if (duplicate.length > 0) {
|
||||
throw new Error('Username or email already exists');
|
||||
@@ -202,7 +201,7 @@ async function main(): Promise<void> {
|
||||
|
||||
const user = manager.getRepository(User).create({
|
||||
username,
|
||||
email: email || null,
|
||||
email,
|
||||
passwordHash,
|
||||
firstName,
|
||||
lastName,
|
||||
|
||||
@@ -103,6 +103,8 @@ export enum AuditAction {
|
||||
INSPECTION_BUSINESS_CALENDAR_UPDATED = 'INSPECTION_BUSINESS_CALENDAR_UPDATED',
|
||||
SMTP_SETTINGS_UPDATED = 'SMTP_SETTINGS_UPDATED',
|
||||
SMTP_TEST_SENT = 'SMTP_TEST_SENT',
|
||||
USER_SMTP_SETTINGS_UPDATED = 'USER_SMTP_SETTINGS_UPDATED',
|
||||
USER_SMTP_TEST_SENT = 'USER_SMTP_TEST_SENT',
|
||||
DOCUMENT_DELIVERY_SETTINGS_UPDATED = 'DOCUMENT_DELIVERY_SETTINGS_UPDATED',
|
||||
DOCUMENT_DELIVERY_RETRY_REQUESTED = 'DOCUMENT_DELIVERY_RETRY_REQUESTED',
|
||||
DOCUMENT_DELIVERY_SENT = 'DOCUMENT_DELIVERY_SENT',
|
||||
|
||||
@@ -16,8 +16,8 @@ export class User extends TimestampedEntity {
|
||||
@Column({ type: 'varchar', length: 80 })
|
||||
username!: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 320, nullable: true })
|
||||
email!: string | null;
|
||||
@Column({ type: 'varchar', length: 320 })
|
||||
email!: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, nullable: true })
|
||||
dni!: string | null;
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
function quoteIdentifier(identifier: string): string {
|
||||
return `"${identifier.replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
export class F62UserSmtpAndActRepresentative1790117400000 implements MigrationInterface {
|
||||
name = 'F62UserSmtpAndActRepresentative1790117400000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM users WHERE email IS NULL OR btrim(email)='') THEN
|
||||
RAISE EXCEPTION 'USER_EMAIL_REQUIRED_BEFORE_F62';
|
||||
END IF;
|
||||
END $$
|
||||
`);
|
||||
await queryRunner.query(`ALTER TABLE users ALTER COLUMN email SET NOT NULL`);
|
||||
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE user_smtp_settings (
|
||||
user_id uuid PRIMARY KEY,
|
||||
mode varchar(16) NOT NULL DEFAULT 'SYSTEM',
|
||||
host varchar(255),
|
||||
port integer,
|
||||
security_mode varchar(24),
|
||||
username varchar(255),
|
||||
password_enc text,
|
||||
from_name varchar(200),
|
||||
from_email varchar(320),
|
||||
reply_to varchar(320),
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
updated_by uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT chk_user_smtp_mode CHECK (mode IN ('SYSTEM','CUSTOM')),
|
||||
CONSTRAINT chk_user_smtp_security CHECK (security_mode IS NULL OR security_mode IN ('NONE','STARTTLS','TLS')),
|
||||
CONSTRAINT chk_user_smtp_port CHECK (port IS NULL OR (port > 0 AND port <= 65535)),
|
||||
CONSTRAINT chk_user_smtp_custom_complete CHECK (
|
||||
mode='SYSTEM' OR (
|
||||
LENGTH(TRIM(COALESCE(host,''))) > 0
|
||||
AND port IS NOT NULL
|
||||
AND security_mode IS NOT NULL
|
||||
AND LENGTH(TRIM(COALESCE(from_email,''))) > 0
|
||||
)
|
||||
),
|
||||
CONSTRAINT fk_user_smtp_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_user_smtp_updated_by FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
DROP CONSTRAINT chk_inspection_act_responsibles_details
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
ADD CONSTRAINT chk_inspection_act_responsibles_details CHECK (
|
||||
(
|
||||
attendance_status = 'PRESENT'
|
||||
AND LENGTH(TRIM(COALESCE(full_name, ''))) > 0
|
||||
AND document_type IS NOT NULL
|
||||
AND LENGTH(TRIM(COALESCE(document_number, ''))) > 0
|
||||
AND LENGTH(TRIM(COALESCE(position, ''))) > 0
|
||||
AND LENGTH(TRIM(COALESCE(email, ''))) > 0
|
||||
AND absence_reason IS NULL
|
||||
) OR (
|
||||
attendance_status = 'ABSENT'
|
||||
AND LENGTH(TRIM(COALESCE(absence_reason, ''))) >= 10
|
||||
)
|
||||
)
|
||||
`);
|
||||
|
||||
const appRole = process.env.DB_APP_USER;
|
||||
if (!appRole) throw new Error('Missing required environment variable: DB_APP_USER');
|
||||
const applicationRole = quoteIdentifier(appRole);
|
||||
await queryRunner.query(`GRANT SELECT, INSERT, UPDATE ON TABLE user_smtp_settings TO ${applicationRole}`);
|
||||
await queryRunner.query(`REVOKE DELETE ON TABLE user_smtp_settings FROM ${applicationRole}`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
DROP CONSTRAINT chk_inspection_act_responsibles_details
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
ADD CONSTRAINT chk_inspection_act_responsibles_details CHECK (
|
||||
(
|
||||
attendance_status = 'PRESENT'
|
||||
AND LENGTH(TRIM(COALESCE(full_name, ''))) > 0
|
||||
AND document_type IS NOT NULL
|
||||
AND LENGTH(TRIM(COALESCE(document_number, ''))) > 0
|
||||
AND LENGTH(TRIM(COALESCE(position, ''))) > 0
|
||||
AND absence_reason IS NULL
|
||||
) OR (
|
||||
attendance_status = 'ABSENT'
|
||||
AND LENGTH(TRIM(COALESCE(absence_reason, ''))) >= 10
|
||||
)
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`DROP TABLE IF EXISTS user_smtp_settings`);
|
||||
await queryRunner.query(`ALTER TABLE users ALTER COLUMN email DROP NOT NULL`);
|
||||
}
|
||||
}
|
||||
@@ -213,14 +213,14 @@ export class CompanySignatureInviteService {
|
||||
|
||||
if (!publicUrl) {
|
||||
deliveryError = 'COMPANY_SIGNATURE_PUBLIC_BASE_URL no configurada';
|
||||
} else if (!(await this.smtp.configured())) {
|
||||
} else if (!(await this.smtp.configured(principal.userId))) {
|
||||
deliveryError = 'SMTP no configurado';
|
||||
} else {
|
||||
const body = [
|
||||
`Se solicita revisar y manifestarse sobre el Acta ${created.actCode}.`,
|
||||
`Inspección: ${created.inspectionCode}.`,
|
||||
'',
|
||||
'El enlace permite firmar en conformidad, firmar en disidencia o registrar una negativa a firmar.',
|
||||
'El enlace permite firmar en conformidad, firmar en disconformidad o registrar una negativa a firmar.',
|
||||
'El contenido del Acta está bloqueado y no puede modificarse desde este enlace.',
|
||||
'',
|
||||
`Enlace seguro: ${publicUrl}`,
|
||||
@@ -236,7 +236,7 @@ export class CompanySignatureInviteService {
|
||||
mimeType: 'text/plain',
|
||||
content: Buffer.from(body, 'utf8'),
|
||||
},
|
||||
});
|
||||
}, principal.userId);
|
||||
emailSent = true;
|
||||
await this.dataSource.query(`
|
||||
UPDATE inspection_act_company_signature_invites
|
||||
|
||||
@@ -54,7 +54,9 @@ export class UpsertInspectionResponsibleDto {
|
||||
@MaxLength(200)
|
||||
position?: string;
|
||||
|
||||
@IsOptional()
|
||||
@ValidateIf((dto: UpsertInspectionResponsibleDto) => (
|
||||
dto.attendanceStatus === InspectionResponsibleAttendanceStatus.PRESENT
|
||||
))
|
||||
@Transform(trimOrUndefined)
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
|
||||
@@ -152,6 +152,7 @@ export interface InspectionClosureView {
|
||||
actualClosedAt: Date | null;
|
||||
};
|
||||
responsible: ResponsibleView | null;
|
||||
representativeSuggestion: ResponsibleView | null;
|
||||
closure: null | {
|
||||
schemaVersion: string;
|
||||
preparedSha256: string;
|
||||
@@ -1022,6 +1023,7 @@ export class InspectionClosingService {
|
||||
}>;
|
||||
if (!context) throw actNotFound();
|
||||
const responsible = await this.loadResponsible(manager, actId);
|
||||
const representativeSuggestion = responsible ? null : await this.loadResponsibleSuggestion(manager, actId);
|
||||
const closure = await this.loadClosure(manager, actId);
|
||||
const signatures = await this.loadSignatures(manager, actId);
|
||||
return {
|
||||
@@ -1051,6 +1053,7 @@ export class InspectionClosingService {
|
||||
actualClosedAt: context.visitActualClosedAt,
|
||||
},
|
||||
responsible,
|
||||
representativeSuggestion,
|
||||
closure: closure ? {
|
||||
schemaVersion: closure.schemaVersion,
|
||||
preparedSha256: closure.preparedSha256,
|
||||
@@ -1083,12 +1086,30 @@ export class InspectionClosingService {
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
private async loadResponsibleSuggestion(manager: EntityManager, actId: string): Promise<ResponsibleView | null> {
|
||||
const [row] = await manager.query(`
|
||||
SELECT responsible.act_id AS "actId",responsible.attendance_status AS "attendanceStatus",
|
||||
responsible.full_name AS "fullName",responsible.document_type AS "documentType",
|
||||
responsible.document_number AS "documentNumber",responsible.position,responsible.email,responsible.phone,
|
||||
responsible.absence_reason AS "absenceReason",responsible.updated_by AS "updatedBy",
|
||||
responsible.created_at AS "createdAt",responsible.updated_at AS "updatedAt"
|
||||
FROM inspection_acts current_act
|
||||
JOIN inspection_acts previous_act
|
||||
ON previous_act.visit_id=current_act.visit_id AND previous_act.id<>current_act.id
|
||||
JOIN inspection_act_responsibles responsible ON responsible.act_id=previous_act.id
|
||||
WHERE current_act.id=$1 AND responsible.attendance_status='PRESENT'
|
||||
ORDER BY responsible.updated_at DESC,previous_act.created_at DESC
|
||||
LIMIT 1
|
||||
`, [actId]) as ResponsibleView[];
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
private async requireResponsible(manager: EntityManager, actId: string): Promise<ResponsibleView> {
|
||||
const responsible = await this.loadResponsible(manager, actId);
|
||||
if (!responsible) {
|
||||
throw new ConflictException({
|
||||
code: 'INSPECTION_ACT_RESPONSIBLE_REQUIRED',
|
||||
message: 'Debe identificarse al responsable o documentar su ausencia antes de finalizar el acta',
|
||||
message: 'Debe identificarse al representante de la empresa o documentar su ausencia antes de cerrar el Acta',
|
||||
});
|
||||
}
|
||||
return responsible;
|
||||
|
||||
@@ -99,8 +99,10 @@ function lines(snapshot: Record<string, unknown>): string[] {
|
||||
`Fecha: ${date(act.occurredAt)}`,
|
||||
`Urgencia: ${urgencyLabel(act.urgency)}`,
|
||||
`Plazo: ${deadlineText}`,
|
||||
`Responsable empresa: ${text(responsible.fullName)}`,
|
||||
`Cargo: ${text(responsible.position)}`,
|
||||
`Representante de la empresa: ${text(responsible.fullName)}`,
|
||||
`DNI: ${text(responsible.documentNumber)}`,
|
||||
`Cargo / funcion: ${text(responsible.position)}`,
|
||||
`Email: ${text(responsible.email)}`,
|
||||
'',
|
||||
'RESUMEN',
|
||||
...wrap(text(act.summary)),
|
||||
@@ -136,7 +138,7 @@ function lines(snapshot: Record<string, unknown>): string[] {
|
||||
out.push('Manifestacion de empresa: pendiente.');
|
||||
} else if (text(companySignature.status, '') === 'SIGNED') {
|
||||
const manifestation = text(companySignature.companyManifestation, 'CONFORMITY');
|
||||
out.push(manifestation === 'DISSENT' ? 'Empresa: firma en disidencia' : 'Empresa: firma en conformidad');
|
||||
out.push(manifestation === 'DISSENT' ? 'Empresa: firma en disconformidad' : 'Empresa: firma en conformidad');
|
||||
if (manifestation === 'DISSENT') out.push(...wrap(text(companySignature.companyStatement)));
|
||||
} else {
|
||||
out.push(...wrap(`Empresa: ${text(companySignature.status)} - ${text(companySignature.reason)}`));
|
||||
|
||||
@@ -281,7 +281,7 @@ export class InspectionDocumentDeliveryService {
|
||||
email = company?.email ?? null;
|
||||
} else if (row.recipientKind === 'INSPECTOR' && row.recipientUserId) {
|
||||
const [inspector] = await this.dataSource.query(`
|
||||
SELECT email FROM users WHERE id=$1 AND is_active=true
|
||||
SELECT email FROM users WHERE id=$1 AND status='ACTIVE'
|
||||
`, [row.recipientUserId]) as Array<{ email: string | null }>;
|
||||
email = inspector?.email ?? null;
|
||||
} else {
|
||||
@@ -305,7 +305,14 @@ export class InspectionDocumentDeliveryService {
|
||||
await this.setStatus(row.id,'WAITING_RECIPIENT','Destinatario no configurado');
|
||||
return;
|
||||
}
|
||||
if (!await this.smtp.configured()) {
|
||||
const [sender] = await this.dataSource.query(`
|
||||
SELECT visit.lead_inspector_user_id AS "userId"
|
||||
FROM inspection_acts act
|
||||
JOIN inspection_visits visit ON visit.id=act.visit_id
|
||||
WHERE act.id=$1
|
||||
`, [row.actId]) as Array<{ userId: string | null }>;
|
||||
const senderUserId = sender?.userId ?? undefined;
|
||||
if (!await this.smtp.configured(senderUserId)) {
|
||||
await this.setStatus(row.id,'WAITING_TRANSPORT','SMTP no configurado');
|
||||
return;
|
||||
}
|
||||
@@ -348,7 +355,7 @@ export class InspectionDocumentDeliveryService {
|
||||
: `Se adjunta el acta sellada e inmutable ${row.actCode}.`;
|
||||
const sent = await this.smtp.send({
|
||||
to:row.recipientEmail,subject:`DH Inspección · ${label}`,text,attachment,
|
||||
});
|
||||
}, senderUserId);
|
||||
await this.dataSource.query(`
|
||||
UPDATE inspection_document_deliveries
|
||||
SET status='SENT',sent_at=CURRENT_TIMESTAMP,provider_message_id=$2,
|
||||
|
||||
@@ -147,8 +147,10 @@ function documentXml(input: ReportWordInput): string {
|
||||
paragraph('El bloque siguiente reproduce información proveniente del Acta sellada. Debe conservarse sin alterar su sentido ni sustituir los Hallazgos originales.'),
|
||||
labelValue('Resumen del Acta', text(snapshot.act.summary)),
|
||||
labelValue('Observaciones del Acta', text(snapshot.act.observations)),
|
||||
labelValue('Responsable de empresa', text(snapshot.responsible.fullName)),
|
||||
labelValue('Cargo', text(snapshot.responsible.position)),
|
||||
labelValue('Representante de la empresa', text(snapshot.responsible.fullName)),
|
||||
labelValue('DNI', text(snapshot.responsible.documentNumber)),
|
||||
labelValue('Cargo / función', text(snapshot.responsible.position)),
|
||||
labelValue('Email', text(snapshot.responsible.email)),
|
||||
paragraph('Inventario inspeccionado', 'Heading1'),
|
||||
inventoryRows.length
|
||||
? table(['Código', 'Nombre', 'Tipo'], inventoryRows)
|
||||
|
||||
@@ -11,7 +11,7 @@ interface MailInput { to:string; subject:string; text:string; attachment:MailAtt
|
||||
interface Reply { code:number; text:string; }
|
||||
|
||||
export interface EffectiveSmtpSettings {
|
||||
source: 'DATABASE' | 'ENVIRONMENT';
|
||||
source: 'USER' | 'DATABASE' | 'ENVIRONMENT';
|
||||
host: string;
|
||||
port: number;
|
||||
securityMode: SmtpSecurityMode;
|
||||
@@ -47,10 +47,10 @@ export class SmtpDeliveryService {
|
||||
private readonly config:ConfigService,
|
||||
){}
|
||||
|
||||
async configured():Promise<boolean>{return Boolean(await this.resolveSettings());}
|
||||
async configured(userId?:string):Promise<boolean>{return Boolean(await this.resolveSettings(userId));}
|
||||
|
||||
async fromAddress():Promise<string|null>{
|
||||
const settings=await this.resolveSettings();
|
||||
async fromAddress(userId?:string):Promise<string|null>{
|
||||
const settings=await this.resolveSettings(userId);
|
||||
if(!settings)return null;
|
||||
return settings.fromName?`${settings.fromName} <${settings.fromEmail}>`:settings.fromEmail;
|
||||
}
|
||||
@@ -73,6 +73,56 @@ export class SmtpDeliveryService {
|
||||
}:{source:'NONE',enabled:false};
|
||||
}
|
||||
|
||||
async publicUserSettings(userId:string){
|
||||
const [user]=await this.dataSource.query(`
|
||||
SELECT email,first_name AS "firstName",last_name AS "lastName" FROM users WHERE id=$1
|
||||
`,[userId]) as Array<{email:string;firstName:string;lastName:string}>;
|
||||
if(!user)throw new Error('Usuario no encontrado');
|
||||
const [row]=await this.dataSource.query(`
|
||||
SELECT mode,host,port,security_mode AS "securityMode",username,
|
||||
(password_enc IS NOT NULL) AS "hasPassword",from_name AS "fromName",
|
||||
from_email AS "fromEmail",enabled,updated_at AS "updatedAt"
|
||||
FROM user_smtp_settings WHERE user_id=$1
|
||||
`,[userId]) as Array<Record<string,unknown>>;
|
||||
return {
|
||||
mode:row?.mode??'SYSTEM',email:user.email,generalConfigured:Boolean(await this.resolveSystemSettings()),
|
||||
custom:row?{
|
||||
host:row.host??'',port:row.port??587,securityMode:row.securityMode??'STARTTLS',
|
||||
username:row.username??'',hasPassword:Boolean(row.hasPassword),
|
||||
fromName:row.fromName??`${user.firstName} ${user.lastName}`,fromEmail:row.fromEmail??user.email,
|
||||
enabled:row.enabled!==false,updatedAt:row.updatedAt??null,
|
||||
}:null,
|
||||
};
|
||||
}
|
||||
|
||||
async saveUserSettings(userId:string,input:{
|
||||
mode:'SYSTEM'|'CUSTOM';host?:string;port?:number;securityMode?:SmtpSecurityMode;
|
||||
username?:string|null;password?:string|null;fromName?:string|null;enabled?:boolean;
|
||||
}){
|
||||
const [user]=await this.dataSource.query(`SELECT email,first_name AS "firstName",last_name AS "lastName" FROM users WHERE id=$1`,[userId]) as Array<{email:string;firstName:string;lastName:string}>;
|
||||
if(!user?.email)throw new Error('El usuario debe tener un email configurado');
|
||||
const [existing]=await this.dataSource.query(`SELECT password_enc AS "passwordEnc" FROM user_smtp_settings WHERE user_id=$1`,[userId]) as Array<{passwordEnc:string|null}>;
|
||||
if(input.mode==='SYSTEM'){
|
||||
await this.dataSource.query(`
|
||||
INSERT INTO user_smtp_settings(user_id,mode,updated_by) VALUES($1,'SYSTEM',$1)
|
||||
ON CONFLICT(user_id) DO UPDATE SET mode='SYSTEM',updated_by=$1,updated_at=CURRENT_TIMESTAMP
|
||||
`,[userId]);
|
||||
return this.publicUserSettings(userId);
|
||||
}
|
||||
if(!input.host||!input.port||!input.securityMode)throw new Error('La configuración SMTP propia está incompleta');
|
||||
const passwordEnc=input.password===undefined?existing?.passwordEnc??null:input.password?this.encryptSecret(input.password):null;
|
||||
const fromName=input.fromName?.trim()||`${user.firstName} ${user.lastName}`.trim();
|
||||
await this.dataSource.query(`
|
||||
INSERT INTO user_smtp_settings(user_id,mode,host,port,security_mode,username,password_enc,from_name,from_email,reply_to,enabled,updated_by)
|
||||
VALUES($1,'CUSTOM',$2,$3,$4,$5,$6,$7,$8,$8,$9,$1)
|
||||
ON CONFLICT(user_id) DO UPDATE SET mode='CUSTOM',host=EXCLUDED.host,port=EXCLUDED.port,
|
||||
security_mode=EXCLUDED.security_mode,username=EXCLUDED.username,password_enc=EXCLUDED.password_enc,
|
||||
from_name=EXCLUDED.from_name,from_email=EXCLUDED.from_email,reply_to=EXCLUDED.reply_to,
|
||||
enabled=EXCLUDED.enabled,updated_by=$1,updated_at=CURRENT_TIMESTAMP
|
||||
`,[userId,input.host,input.port,input.securityMode,input.username?.trim()||null,passwordEnc,fromName,user.email,input.enabled!==false]);
|
||||
return this.publicUserSettings(userId);
|
||||
}
|
||||
|
||||
async saveSettings(input:{
|
||||
host:string;port:number;securityMode:SmtpSecurityMode;username?:string|null;
|
||||
password?:string|null;fromName:string;fromEmail:string;replyTo?:string|null;enabled:boolean;
|
||||
@@ -96,8 +146,8 @@ export class SmtpDeliveryService {
|
||||
return this.publicSettings();
|
||||
}
|
||||
|
||||
async send(input:MailInput):Promise<{messageId:string}>{
|
||||
const settings=await this.resolveSettings();
|
||||
async send(input:MailInput,userId?:string):Promise<{messageId:string}>{
|
||||
const settings=await this.resolveSettings(userId);
|
||||
if(!settings)throw new Error('SMTP no configurado');
|
||||
const {host,port,securityMode,userName,password}= {
|
||||
host:settings.host,port:settings.port,securityMode:settings.securityMode,
|
||||
@@ -137,7 +187,33 @@ export class SmtpDeliveryService {
|
||||
return {messageId:match?.[1]??randomUUID()};
|
||||
}
|
||||
|
||||
private async resolveSettings():Promise<EffectiveSmtpSettings|null>{
|
||||
private async resolveSettings(userId?:string):Promise<EffectiveSmtpSettings|null>{
|
||||
if(userId){
|
||||
const [row]=await this.dataSource.query(`
|
||||
SELECT settings.mode,settings.host,settings.port,settings.security_mode AS "securityMode",
|
||||
settings.username,settings.password_enc AS "passwordEnc",settings.from_name AS "fromName",
|
||||
settings.enabled,user_account.email AS "userEmail"
|
||||
FROM users user_account
|
||||
LEFT JOIN user_smtp_settings settings ON settings.user_id=user_account.id
|
||||
WHERE user_account.id=$1
|
||||
`,[userId]) as Array<{
|
||||
mode:'SYSTEM'|'CUSTOM'|null;host:string|null;port:number|null;securityMode:SmtpSecurityMode|null;
|
||||
username:string|null;passwordEnc:string|null;fromName:string|null;enabled:boolean|null;userEmail:string;
|
||||
}>;
|
||||
if(row?.mode==='CUSTOM'&&row.enabled!==false&&row.host&&row.port&&row.securityMode&&row.userEmail){
|
||||
return {
|
||||
source:'USER',host:row.host,port:Number(row.port),securityMode:row.securityMode,
|
||||
username:row.username,password:row.passwordEnc?this.decryptSecret(row.passwordEnc):'',
|
||||
fromName:row.fromName,fromEmail:row.userEmail,replyTo:row.userEmail,
|
||||
};
|
||||
}
|
||||
const general=await this.resolveSystemSettings();
|
||||
return general&&row?.userEmail?{...general,replyTo:row.userEmail}:general;
|
||||
}
|
||||
return this.resolveSystemSettings();
|
||||
}
|
||||
|
||||
private async resolveSystemSettings():Promise<EffectiveSmtpSettings|null>{
|
||||
const [row]=await this.dataSource.query(`
|
||||
SELECT host,port,security_mode AS "securityMode",username,password_enc AS "passwordEnc",
|
||||
from_name AS "fromName",from_email AS "fromEmail",reply_to AS "replyTo",enabled
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const API_VERSION = '0.29.0-3';
|
||||
export const API_PHASE = 'F6.1';
|
||||
export const API_VERSION = '0.29.0-4';
|
||||
export const API_PHASE = 'F6.2';
|
||||
|
||||
Reference in New Issue
Block a user