Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DR-862:added no_of_days for default setting in certificate generation #409

Merged
merged 9 commits into from
Sep 30, 2024
2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Apply `Prettier` to entire code base
c3d98ff4ececdd9041aea74d5db2be30dc089283
17 changes: 17 additions & 0 deletions apps/drec-api/migrations/1726558881946-certificate_setting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class certificateSetting1726558881946 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE certificate_setting (
id SERIAL PRIMARY KEY,
"no_of_days" integer NOT NULL DEFAULT 60,
"createdAt" timestamp with time zone NOT NULL DEFAULT now(),
"updatedAt" timestamp with time zone NOT NULL DEFAULT now()
)`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE IF EXISTS certificate_setting`);
}
}
16 changes: 16 additions & 0 deletions apps/drec-api/migrations/9999999999999-Seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export class Seed9999999999999 implements MigrationInterface {
await this.seedUsersRole(queryRunner);
await this.seedAdmin(queryRunner);
await this.seedACLModules(queryRunner);
await this.seedCertificateSetting(queryRunner); //set default no_of_days for generate certificate last day
await queryRunner.query(
`SELECT setval(
pg_get_serial_sequence('public.organization', 'id'),
Expand Down Expand Up @@ -126,6 +127,7 @@ export class Seed9999999999999 implements MigrationInterface {
}),
);
}

private async deployContracts(
deployer: Wallet,
provider: providers.FallbackProvider,
Expand Down Expand Up @@ -349,4 +351,18 @@ export class Seed9999999999999 implements MigrationInterface {
this.decimalFormPermission = decimalFormPermission;
return this.decimalFormPermission;
}
private async seedCertificateSetting(queryRunner: QueryRunner) {
const certificate_settingTable = await queryRunner.getTable(
'public.certificate_setting',
);

if (!certificate_settingTable) {
this.logger.verbose('certificate_setting table does not exist.');
return;
}
queryRunner.query(
`INSERT INTO public.certificate_setting ("id","no_of_days") VALUES (
1,60)`,
);
}
}
2 changes: 2 additions & 0 deletions apps/drec-api/src/drec.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import { OauthClientCredentials } from './pods/user/oauth_client_credentials.ent
import { ApiUserEntity } from './pods/user/api-user.entity';
import { UserLoginSessionEntity } from './pods/user/user_login_session.entity';
import { DeviceLateongoingIssueCertificateEntity } from './pods/device/device_lateongoing_certificate.entity';
import { CertificateSettingEntity } from './pods/device-group/certificate_setting.entity';
import { HttpModule } from '@nestjs/axios';

const getEnvFilePath = () => {
Expand Down Expand Up @@ -108,6 +109,7 @@ export const entities = [
IrecErrorLogInformationEntity,
UserLoginSessionEntity,
DeviceLateongoingIssueCertificateEntity,
CertificateSettingEntity,
...IssuerEntities,
...OnChainCertificateEntities,
...OffChainCertificateEntities,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -923,21 +923,17 @@ export class CertificateLogService {
); //going back 1 second in start and going forward 1 second in end
await Promise.all(
obj.deviceIds.map(async (deviceid: number) => {
// const device = await this.deviceService.findOne(deviceid);

// const device = await this.deviceService.findOne(deviceid);
let device: Device;
if (typeof deviceid === 'number') {
device = await this.deviceService.findOne(deviceid);
}
if (typeof deviceid === 'string') {
device = await this.deviceService.findReads(deviceid);
}

let devicelog;
if (role === 'OrganizationAdmin') {
if (
group.developerdeviceIds.find((ele) => ele === deviceid)
group.developerdeviceIds.find((ele) => ele === device.id)
) {
devicelog =
await this.getCheckCertificateIssueDateLogForDevice(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ export class BuyerReservationController {
@Query('orgId') orgId: number | null,
): Promise<ResponseDeviceGroupDTO | null> {
this.logger.verbose(`With in createOne`);
deviceGroupToRegister.api_user_id = user.api_user_id;
if (orgId) {
const organization = await this.organizationService.findOne(orgId);
const orguser = await this.userService.findByEmail(organization.orgEmail);
Expand All @@ -360,12 +361,10 @@ export class BuyerReservationController {
message: 'Organization requested belongs to other apiuser',
});
}

if (orguser.role === Role.Buyer) {
organizationId = orgId;
deviceGroupToRegister.api_user_id = user.api_user_id;
}

if (orguser.role != Role.Buyer) {
this.logger.error(`Unauthorized for ${orguser.role}`);
throw new UnauthorizedException({
Expand Down
14 changes: 14 additions & 0 deletions apps/drec-api/src/pods/device-group/certificate_setting.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ExtendedBaseEntity } from '@energyweb/origin-backend-utils';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

import { IsNumber } from 'class-validator';

@Entity('certificate_setting')
export class CertificateSettingEntity extends ExtendedBaseEntity {
@PrimaryGeneratedColumn()
id: number;

@Column()
@IsNumber()
no_of_days: number;
}
2 changes: 2 additions & 0 deletions apps/drec-api/src/pods/device-group/device-group.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { CertificateReadModelEntity } from '@energyweb/origin-247-certificate/di
import { CheckCertificateIssueDateLogForDeviceEntity } from '../device/check_certificate_issue_date_log_for_device.entity';
import { Certificate } from '@energyweb/issuer-api';
import { UserModule } from '../user/user.module';
import { CertificateSettingEntity } from './certificate_setting.entity';
@Module({
imports: [
TypeOrmModule.forFeature([
Expand All @@ -28,6 +29,7 @@ import { UserModule } from '../user/user.module';
CertificateReadModelEntity,
CheckCertificateIssueDateLogForDeviceEntity,
Certificate,
CertificateSettingEntity,
]),
forwardRef(() => DeviceModule),

Expand Down
21 changes: 14 additions & 7 deletions apps/drec-api/src/pods/device-group/device-group.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ import { Certificate } from '@energyweb/issuer-api';
import { UserService } from '../user/user.service';
import { ICertificateMetadata } from '../../utils/types';
import { FilterDTO } from '../certificate-log/dto';

import { CertificateSettingEntity } from './certificate_setting.entity';
@Injectable()
export class DeviceGroupService {
csvParser = csv({ separator: ',' });
Expand Down Expand Up @@ -112,6 +112,8 @@ export class DeviceGroupService {
CertificateReadModelEntity<ICertificateMetadata>
>,
private readonly userService: UserService,
@InjectRepository(CertificateSettingEntity)
private readonly certificate_settingrepository: Repository<CertificateSettingEntity>,
) {}

async getAll(
Expand Down Expand Up @@ -1242,8 +1244,16 @@ export class DeviceGroupService {
if (group.api_user_id) {
deviceGroup['api_user_id'] = group.api_user_id;
}
if (group.reservationExpiryDate) {
const configurationseting =
await this.certificate_settingrepository.find();
const lastCertifiableDate = new Date(group.reservationEndDate);
lastCertifiableDate.setDate(
lastCertifiableDate.getDate() + configurationseting[0].no_of_days,
);
if (group.reservationExpiryDate != null) {
deviceGroup['reservationExpiryDate'] = group.reservationExpiryDate;
} else {
deviceGroup['reservationExpiryDate'] = lastCertifiableDate;
}
const responseDeviceGroupDTO: ResponseDeviceGroupDTO = await this.create(
organizationId,
Expand Down Expand Up @@ -2342,14 +2352,12 @@ export class DeviceGroupService {
reservationActive: true,
});
if (group === null) {
this.logger.error(
`Group UId is not of this buyer, invalid value was sent`,
);
this.logger.error(`Reservation expired`);
return new Promise((resolve, reject) => {
reject(
new ConflictException({
success: false,
message: 'Group UId is not of this buyer, invalid value was sent',
message: 'Reservation expired',
}),
);
});
Expand Down Expand Up @@ -2650,7 +2658,6 @@ export class DeviceGroupService {
const totalCount = totalCountQuery.length;
this.logger.debug('totalCountQuery', totalCount);
const totalPages = Math.ceil(totalCount / pageSize);

let deviceGroups: any;
if (role === 'OrganizationAdmin') {
deviceGroups = groupedData.reduce((acc, curr) => {
Expand Down
6 changes: 5 additions & 1 deletion apps/drec-api/src/pods/device/device.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -998,7 +998,11 @@ export class DeviceController {
const group: DeviceGroup | null = await this.deviceGroupService.findOne({
devicegroup_uid: groupuId,
});
if (group === null || group.buyerId != user.id) {
if (
group === null ||
(group.buyerId != user.id && user.role != 'ApiUser') ||
group.api_user_id != user.api_user_id
) {
this.logger.error(
`Group UId is not of this buyer, invalid value was sent`,
);
Expand Down
23 changes: 17 additions & 6 deletions apps/drec-api/src/pods/device/device.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1054,14 +1054,12 @@ export class DeviceService {
...params,
});
}
public async findAllLateCycle(
groupid: number,
externalid: string,
): Promise<DeviceLateongoingIssueCertificateEntity[]> {
public async findAllLateCycle(): Promise<
DeviceLateongoingIssueCertificateEntity[]
> {
this.logger.verbose(`With in DeviceLateongoingIssueCertificateList`);
return await this.latedevciecertificaterepository.find({
where: {
groupId: groupid,
device_externalid: externalid,
certificate_issued: false,
},
order: {
Expand Down Expand Up @@ -1473,4 +1471,17 @@ export class DeviceService {
{ late_end_date: lateend_date, certificate_issued: true },
);
}
async updatelateongoingIfReservationInactive(
externalId: string,
): Promise<any> {
this.logger.verbose(`With in updatelateongoingIfReservationInactive`);
this.logger.verbose(
`With in updatelateongoingIfReservationInactive`,
externalId,
);
return await this.latedevciecertificaterepository.update(
{ device_externalid: externalId },
{ certificate_issued: true },
);
}
}
Loading
Loading