Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 4x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 4x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x | import {
BadRequestException,
ConflictException,
HttpException,
HttpStatus,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { CommandBus, EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { pick, pickBy } from 'lodash-es';
import { DataSource, Repository } from 'typeorm';
import {
Company,
CompanyCreatedEvent,
CompanyUpdatedEvent,
CreateCompanyAdminCommand,
CreateCompanyCommonDesignerElementsCommand,
LoadSampleDataCommand,
type User,
} from '@amalia/core/models';
import { CurrencySymbolsEnum } from '@amalia/ext/iso-4217';
import { StringUtils } from '@amalia/ext/string';
import { isUniqueViolationError } from '@amalia/ext/typeorm';
import { assert, toError } from '@amalia/ext/typescript';
import { AuthenticatedContextFactory } from '@amalia/kernel/auth/core';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { DatabaseSetupService, FORBIDDEN_SLUGS } from '@amalia/kernel/bootstrap/database';
import { CompanyStatus } from '@amalia/tenants/companies/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { type CreateCompanyDto } from './dto/createCompany.dto';
import { type UpdateCompanyDto } from './dto/updateCompany.dto';
/**
* Service company.
*/
@Injectable()
export class CompaniesService {
private readonly logger = new Logger(CompaniesService.name);
public constructor(
private readonly defaultDataSource: DataSource,
private readonly commandBus: CommandBus,
private readonly eventBus: EventBus,
@InjectRepository(Company)
private readonly companyRepository: Repository<Company>,
private readonly databaseSetupService: DatabaseSetupService,
private readonly authenticatedContextFactory: AuthenticatedContextFactory,
) {}
/**
* Create new company with admin.
* @param company company to create
*/
public async create(company: CreateCompanyDto): Promise<Company> {
const companyToSave: Omit<Company, 'createdAt' | 'id' | 'updatedAt'> = {
...company,
// Set as a batch number a random number: 0, 1 or 2
batchNumber: Math.floor(Math.random() * 3),
nbBackwardRollingPeriods: 0,
nbForwardPaymentRollingPeriods: 0,
// Empty record but it'll be populated on fetch.
featureFlags: {} as Company['featureFlags'],
// Default some custimization values.
customization: {
...company.customization,
planAgreementsSharedWithManagers: true,
},
};
if (FORBIDDEN_SLUGS.includes(company.slug)) {
throw new BadRequestException(`The slug "${company.slug}" is invalid, please chose another one.`);
}
if (!StringUtils.isSlug(company.slug)) {
throw new BadRequestException('Slug invalid');
}
const queryRunner = this.defaultDataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
let createdCompany: Company;
let admin: User;
try {
// Create company.
createdCompany = await queryRunner.manager.getRepository<Company>(Company).save(companyToSave);
// Create admin.
admin = await this.commandBus.execute<CreateCompanyAdminCommand, User>(
new CreateCompanyAdminCommand(createdCompany, company.admin, queryRunner),
);
// If we got an issue with the CQRS handler, stop right here. Else it'll crash
// later but after the transaction has been commit.
assert(admin, new Error(`Could not create admin for company ${company.name}`));
// Setup partitions and views.
await this.databaseSetupService.setupDataDbForCompany(createdCompany);
// Commit now. We'll load sample data and default content outside the transaction since it's slow.
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
if (err instanceof HttpException) {
throw err;
}
if (isUniqueViolationError(err)) {
throw new ConflictException('This slug is already taken by another company');
}
const error = toError(err);
this.logger.error({
message: `Error on create company: ${error.message}`,
error,
company: pick(company, ['id', 'name']),
});
throw new HttpException('Error during Company creation, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
await queryRunner.release();
}
await this.eventBus.publish(new CompanyCreatedEvent(createdCompany, admin));
const authenticatedContext = await this.authenticatedContextFactory.makeAuthenticatedContext(admin);
if (company.createCommonFiltersAndQuotas && createdCompany.id) {
await this.commandBus.execute(new CreateCompanyCommonDesignerElementsCommand(authenticatedContext));
}
if (company.loadSampleData) {
// This is a synchronous event to load sample data in an uncoupled way;
await this.commandBus.execute(new LoadSampleDataCommand(createdCompany, admin, company.runCalculation));
}
this.logger.log({ message: 'Company creation complete!', company: pick(company, ['id', 'name']) });
return createdCompany;
}
/**
* Update company.
* @param companyToUpdate company to update
* @param updateCompanyDTO companyDTO with fields updated
* @param authenticatedContext
*/
public async update(
companyToUpdate: Company,
updateCompanyDTO: UpdateCompanyDto,
authenticatedContext: AuthenticatedContext,
): Promise<Company> {
if (updateCompanyDTO.currency !== undefined && updateCompanyDTO.currency !== companyToUpdate.currency) {
throw new BadRequestException('You cannot change your main currency.');
}
const finalCompany: Company = {
...companyToUpdate,
...pickBy(
pick(updateCompanyDTO, ['name', 'statementFrequency', 'currency', 'symbols', 'status']),
(value: CurrencySymbolsEnum[] | string | undefined) => value !== undefined,
),
customization: {
...companyToUpdate.customization,
...updateCompanyDTO.customization,
},
};
const result = await this.companyRepository.save(finalCompany);
await this.eventBus.publish(
new CompanyUpdatedEvent({
authenticatedContext,
object: RecordObject.COMPANY_SETTINGS,
type: RecordType.EDIT,
values: {
target: {
id: result.id,
name: result.name,
},
oldValues: {
name: companyToUpdate.name,
frequency: companyToUpdate.statementFrequency,
mainCurrency: companyToUpdate.currency,
currencies: companyToUpdate.symbols,
customization: companyToUpdate.customization,
},
newValues: {
name: result.name,
frequency: result.statementFrequency,
mainCurrency: result.currency,
currencies: result.symbols,
customization: companyToUpdate.customization,
},
},
}),
);
return result;
}
/**
* Find company by id.
*/
public async findById(id: string): Promise<Company> {
const company = await this.companyRepository.findOneBy({ id });
assert(company, new NotFoundException('Company not found'));
return company;
}
/**
* Count companies.
*/
public async count(): Promise<number> {
return this.companyRepository.count();
}
/**
* Get active companies.
*/
public async getActiveCompanies(): Promise<Company[]> {
return this.companyRepository.find({
where: { status: CompanyStatus.ACTIVE },
});
}
/**
* Get companies.
*/
public async getCompanies(): Promise<Company[]> {
return this.companyRepository.find({
order: {
name: 'ASC',
},
});
}
/**
* Get active companies by batch number
*/
public async getActiveCompaniesByBatchNumber(batchNumber: number): Promise<Company[]> {
return this.companyRepository.find({
where: { status: CompanyStatus.ACTIVE, batchNumber },
});
}
}
|