refactor(nestjs): wip

This commit is contained in:
Ahmed Bouhuolia
2025-05-27 15:42:27 +02:00
parent 83c9392b74
commit b7a3c42074
33 changed files with 186 additions and 72 deletions

View File

@@ -76,8 +76,13 @@ export class BranchesController {
status: 200,
description: 'The branches feature has been successfully activated.',
})
activateBranches() {
return this.branchesApplication.activateBranches();
async activateBranches() {
await this.branchesApplication.activateBranches();
return {
code: 200,
message: 'The branches activated successfully.',
};
}
@Put(':id/mark-as-primary')

View File

@@ -17,6 +17,8 @@ export class BranchesSettingsService {
const settingsStore = await this.settingsStore();
settingsStore.set({ group: 'features', key: Features.BRANCHES, value: 1 });
await settingsStore.save();
};
/**

View File

@@ -1,9 +1,9 @@
import { IsOptional } from '@/common/decorators/Validators';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsBoolean,
IsEmail,
IsNotEmpty,
IsOptional,
IsString,
IsUrl,
} from 'class-validator';

View File

@@ -37,15 +37,15 @@ export class CurrenciesController {
return this.currenciesApp.createCurrency(dto);
}
@Put(':code')
@Put(':id')
@ApiOperation({ summary: 'Edit an existing currency' })
@ApiParam({ name: 'id', type: Number, description: 'Currency ID' })
@ApiBody({ type: EditCurrencyDto })
@ApiOkResponse({ description: 'The currency has been successfully updated.' })
@ApiNotFoundResponse({ description: 'Currency not found.' })
@ApiBadRequestResponse({ description: 'Invalid input data.' })
edit(@Param('code') code: string, @Body() dto: EditCurrencyDto) {
return this.currenciesApp.editCurrency(code, dto);
edit(@Param('id') id: number, @Body() dto: EditCurrencyDto) {
return this.currenciesApp.editCurrency(id, dto);
}
@Delete(':code')

View File

@@ -27,8 +27,8 @@ export class CurrenciesApplication {
/**
* Edits an existing currency.
*/
public editCurrency(currencyCode: string, currencyDTO: EditCurrencyDto) {
return this.editCurrencyService.editCurrency(currencyCode, currencyDTO);
public editCurrency(currencyId: number, currencyDTO: EditCurrencyDto) {
return this.editCurrencyService.editCurrency(currencyId, currencyDTO);
}
/**

View File

@@ -12,21 +12,22 @@ export class EditCurrencyService {
/**
* Edit details of the given currency.
* @param {number} currencyCode - Currency code.
* @param {number} currencyId - Currency ID.
* @param {ICurrencyDTO} currencyDTO - Edit currency dto.
*/
public async editCurrency(
currencyCode: string,
currencyId: number,
currencyDTO: EditCurrencyDto,
): Promise<Currency> {
const foundCurrency = await this.currencyModel()
const foundCurrency = this.currencyModel()
.query()
.findOne('currencyCode', currencyCode)
.findById(currencyId)
.throwIfNotFound();
// Directly use the provided ID to update the currency
const currency = await this.currencyModel()
.query()
.patchAndFetchById(foundCurrency.id, {
.patchAndFetchById(currencyId, {
...currencyDTO,
});
return currency;

View File

@@ -1,12 +1,16 @@
import { IsString } from 'class-validator';
import { IsNotEmpty } from "class-validator";
import { IsString } from "class-validator";
export class CreateCurrencyDto {
@IsString()
@IsNotEmpty()
currencyName: string;
@IsString()
@IsNotEmpty()
currencyCode: string;
@IsString()
@IsNotEmpty()
currencySign: string;
}

View File

@@ -1,9 +1,12 @@
import { IsString } from 'class-validator';
import { IsNotEmpty } from "class-validator";
import { IsString } from "class-validator";
export class EditCurrencyDto {
@IsString()
@IsNotEmpty()
currencyName: string;
@IsString()
@IsNotEmpty()
currencySign: string;
}

View File

@@ -1,7 +1,6 @@
import {
IsString,
IsIn,
IsOptional,
IsBoolean,
IsNumber,
IsInt,
@@ -9,11 +8,10 @@ import {
ValidateIf,
MaxLength,
Min,
Max,
IsNotEmpty,
} from 'class-validator';
import { Type } from 'class-transformer';
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
export class CommandItemDto {
@IsString()
@@ -23,6 +21,7 @@ export class CommandItemDto {
name: string;
@IsString()
@IsNotEmpty()
@IsIn(['service', 'non-inventory', 'inventory'])
@ApiProperty({
description: 'Item type',
@@ -52,6 +51,7 @@ export class CommandItemDto {
purchasable?: boolean;
@IsOptional()
@ToNumber()
@IsNumber({ maxDecimalPlaces: 3 })
@Min(0)
@ValidateIf((o) => o.purchasable === true)
@@ -64,6 +64,7 @@ export class CommandItemDto {
costPrice?: number;
@IsOptional()
@ToNumber()
@IsInt()
@Min(0)
@ValidateIf((o) => o.purchasable === true)
@@ -86,6 +87,7 @@ export class CommandItemDto {
sellable?: boolean;
@IsOptional()
@ToNumber()
@IsNumber({ maxDecimalPlaces: 3 })
@Min(0)
@ValidateIf((o) => o.sellable === true)
@@ -98,6 +100,7 @@ export class CommandItemDto {
sellPrice?: number;
@IsOptional()
@ToNumber()
@IsInt()
@Min(0)
@ValidateIf((o) => o.sellable === true)
@@ -110,6 +113,7 @@ export class CommandItemDto {
sellAccountId?: number;
@IsOptional()
@ToNumber()
@IsInt()
@Min(0)
@ValidateIf((o) => o.type === 'inventory')
@@ -140,6 +144,7 @@ export class CommandItemDto {
purchaseDescription?: string;
@IsOptional()
@ToNumber()
@IsInt()
@ApiProperty({
description: 'ID of the tax rate applied to sales',
@@ -149,6 +154,7 @@ export class CommandItemDto {
sellTaxRateId?: number;
@IsOptional()
@ToNumber()
@IsInt()
@ApiProperty({
description: 'ID of the tax rate applied to purchases',
@@ -158,6 +164,7 @@ export class CommandItemDto {
purchaseTaxRateId?: number;
@IsOptional()
@ToNumber()
@IsInt()
@Min(0)
@ApiProperty({
@@ -189,7 +196,6 @@ export class CommandItemDto {
@IsOptional()
@IsArray()
@Type(() => Number)
@IsInt({ each: true })
@ApiProperty({
description: 'IDs of media files associated with the item',

View File

@@ -4,6 +4,7 @@ import { DeleteRoleService } from './commands/DeleteRole.service';
import { EditRoleService } from './commands/EditRole.service';
import { GetRoleService } from './queries/GetRole.service';
import { GetRolesService } from './queries/GetRoles.service';
import { RolePermissionsSchema } from './queries/RolePermissionsSchema';
@Injectable()
export class RolesApplication {
@@ -13,6 +14,7 @@ export class RolesApplication {
private readonly deleteRoleService: DeleteRoleService,
private readonly getRoleService: GetRoleService,
private readonly getRolesService: GetRolesService,
private readonly getRolePermissionsSchemaService: RolePermissionsSchema,
) {}
/**
@@ -59,4 +61,12 @@ export class RolesApplication {
async getRoles() {
return this.getRolesService.getRoles();
}
/**
* Gets the role permissions schema.
* @returns The role permissions schema.
*/
async getRolePermissionsSchema() {
return this.getRolePermissionsSchemaService.getRolePermissionsSchema();
}
}

View File

@@ -72,9 +72,7 @@ export class RolesController {
status: HttpStatus.OK,
description: 'Role deleted successfully',
})
async deleteRole(
@Param('id', ParseIntPipe) roleId: number,
) {
async deleteRole(@Param('id', ParseIntPipe) roleId: number) {
await this.rolesApp.deleteRole(roleId);
return {
@@ -83,24 +81,34 @@ export class RolesController {
};
}
@Get('permissions/schema')
@ApiOperation({ summary: 'Get role permissions schema' })
@ApiResponse({
status: HttpStatus.OK,
description: 'Role permissions schema',
})
async getRolePermissionsSchema() {
const schema = await this.rolesApp.getRolePermissionsSchema();
return schema;
}
@Get()
@ApiOperation({ summary: 'Get all roles' })
@ApiResponse({ status: HttpStatus.OK, description: 'List of all roles' })
async getRoles() {
const roles = await this.rolesApp.getRoles();
return { roles };
return roles;
}
@Get(':id')
@ApiOperation({ summary: 'Get a specific role by ID' })
@ApiParam({ name: 'id', description: 'Role ID' })
@ApiResponse({ status: HttpStatus.OK, description: 'Role details' })
async getRole(
@Param('id', ParseIntPipe) roleId: number,
) {
async getRole(@Param('id', ParseIntPipe) roleId: number) {
const role = await this.rolesApp.getRole(roleId);
return { role };
return role;
}
}

View File

@@ -9,6 +9,7 @@ import { Role } from './models/Role.model';
import { RolePermission } from './models/RolePermission.model';
import { RolesController } from './Roles.controller';
import { RolesApplication } from './Roles.application';
import { RolePermissionsSchema } from './queries/RolePermissionsSchema';
const models = [
RegisterTenancyModel(Role),
@@ -24,6 +25,7 @@ const models = [
GetRoleService,
GetRolesService,
RolesApplication,
RolePermissionsSchema
],
controllers: [RolesController],
exports: [...models],

View File

@@ -1,12 +1,12 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { IRoleCreatedPayload } from '../Roles.types';
import { Role } from './../models/Role.model';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { UnitOfWork } from '../../Tenancy/TenancyDB/UnitOfWork.service';
import { events } from '@/common/events/events';
import { CreateRoleDto } from '../dtos/Role.dto';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { Inject, Injectable } from '@nestjs/common';
import { validateInvalidPermissions } from '../utils';
@Injectable()

View File

@@ -1,12 +1,42 @@
import { AbilitySchema } from '../AbilitySchema';
import { Injectable } from '@nestjs/common';
import { I18nService } from 'nestjs-i18n';
import { cloneDeep } from 'lodash';
import { ISubjectAbilitiesSchema } from '../Roles.types';
@Injectable()
export class RolePermissionsSchema {
constructor(private readonly i18nService: I18nService) {}
/**
* Retrieve the role permissions schema.
* Retrieve the role permissions schema with translated labels.
* @returns {ISubjectAbilitiesSchema[]}
*/
getRolePermissionsSchema() {
return AbilitySchema;
getRolePermissionsSchema(): ISubjectAbilitiesSchema[] {
// Clone the schema to avoid modifying the original
const schema = cloneDeep(AbilitySchema);
// Apply translations to each subject and its abilities
return schema.map((subject: ISubjectAbilitiesSchema) => {
// Translate subject label
subject.subjectLabel = this.i18nService.t(subject.subjectLabel);
// Translate abilities labels
if (subject.abilities) {
subject.abilities = subject.abilities.map((ability) => ({
...ability,
label: this.i18nService.t(ability.label),
}));
}
// Translate extra abilities labels if they exist
if (subject.extraAbilities) {
subject.extraAbilities = subject.extraAbilities.map((ability) => ({
...ability,
label: this.i18nService.t(ability.label),
}));
}
return subject;
});
}
}

View File

@@ -6,6 +6,9 @@ import { ExportableModel } from '@/modules/Export/decorators/ExportableModel.dec
import { ImportableModel } from '@/modules/Import/decorators/Import.decorator';
import { InjectModelMeta } from '@/modules/Tenancy/TenancyModels/decorators/InjectModelMeta.decorator';
import { SaleEstimateMeta } from './SaleEstimate.meta';
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
import { Document } from '@/modules/ChromiumlyTenancy/models/Document';
import { Customer } from '@/modules/Customers/models/Customer';
@ExportableModel()
@ImportableModel()
@@ -40,6 +43,10 @@ export class SaleEstimate extends TenantBaseModel {
branchId?: number;
warehouseId?: number;
public entries!: ItemEntry[];
public attachments!: Document[];
public customer!: Customer;
/**
* Table name
*/

View File

@@ -1,10 +1,7 @@
// import { Transformer } from '@/lib/Transformer/Transformer';
// import { ItemEntryTransformer } from '../Invoices/ItemEntryTransformer';
// import { AttachmentTransformer } from '@/services/Attachments/AttachmentTransformer';
import { Transformer } from '@/modules/Transformer/Transformer';
import { SaleEstimate } from '../models/SaleEstimate';
import { ItemEntryTransformer } from '@/modules/TransactionItemEntry/ItemEntry.transformer';
import { AttachmentTransformer } from '@/modules/Attachments/Attachment.transformer';
export class SaleEstimateTransfromer extends Transformer {
/**
@@ -106,9 +103,9 @@ export class SaleEstimateTransfromer extends Transformer {
* @returns {}
*/
protected entries = (estimate: SaleEstimate) => {
// return this.item(estimate.entries, new ItemEntryTransformer(), {
// currencyCode: estimate.currencyCode,
// });
return this.item(estimate.entries, new ItemEntryTransformer(), {
currencyCode: estimate.currencyCode,
});
};
/**
@@ -117,6 +114,6 @@ export class SaleEstimateTransfromer extends Transformer {
* @returns
*/
protected attachments = (estimate: SaleEstimate) => {
// return this.item(estimate.attachments, new AttachmentTransformer());
return this.item(estimate.attachments, new AttachmentTransformer());
};
}

View File

@@ -57,7 +57,7 @@ export class WarehousesController {
return this.warehousesApplication.activateWarehouses();
}
@Post(':id/mark-primary')
@Put(':id/mark-primary')
@ApiOperation({ summary: 'Mark a warehouse as primary' })
markWarehousePrimary(@Param('id') warehouseId: string) {
return this.warehousesApplication.markWarehousePrimary(Number(warehouseId));

View File

@@ -17,6 +17,8 @@ export class WarehousesSettings {
const settings = await this.settingsStore();
settings.set({ group: 'features', key: Features.WAREHOUSES, value: 1 });
await settings.save();
};
/**

View File

@@ -1,16 +1,16 @@
import { CreateWarehouse } from './CreateWarehouse.service';
import { Injectable } from '@nestjs/common';
import { I18nContext } from 'nestjs-i18n';
import { I18nService } from 'nestjs-i18n';
@Injectable()
export class CreateInitialWarehouse {
/**
* @param {CreateWarehouse} createWarehouse - Create warehouse service.
* @param {I18nContext} i18n - I18n context.
* @param {I18nService} i18n - I18n service.
*/
constructor(
private readonly createWarehouse: CreateWarehouse,
private readonly i18n: I18nContext,
private readonly i18n: I18nService,
) {}
/**

View File

@@ -1,5 +1,6 @@
import { IsOptional } from "@/common/decorators/Validators";
import { ApiProperty } from "@nestjs/swagger";
import { IsBoolean, IsEmail, IsOptional, IsUrl } from "class-validator";
import { IsBoolean, IsEmail, IsUrl } from "class-validator";
import { IsNotEmpty } from "class-validator";
import { IsString } from "class-validator";