diff --git a/dictation_server/src/repositories/licenses/licenses.repository.service.ts b/dictation_server/src/repositories/licenses/licenses.repository.service.ts index 258da24..51d227c 100644 --- a/dictation_server/src/repositories/licenses/licenses.repository.service.ts +++ b/dictation_server/src/repositories/licenses/licenses.repository.service.ts @@ -409,42 +409,28 @@ export class LicensesRepositoryService { myAccountId: number, ): Promise { const nowDate = new DateWithZeroTime(); - - return await this.dataSource.transaction(async (entityManager) => { - const licenseRepo = entityManager.getRepository(License); - const allocatableLicenses = await licenseRepo.find({ - where: [ - { - account_id: myAccountId, - status: In([ - LICENSE_ALLOCATED_STATUS.UNALLOCATED, - LICENSE_ALLOCATED_STATUS.REUSABLE, - ]), - expiry_date: MoreThanOrEqual(nowDate), - }, - { - account_id: myAccountId, - status: In([ - LICENSE_ALLOCATED_STATUS.UNALLOCATED, - LICENSE_ALLOCATED_STATUS.REUSABLE, - ]), - expiry_date: IsNull(), - }, + const licenseRepo = this.dataSource.getRepository(License); + const queryBuilder = licenseRepo + .createQueryBuilder('license') + .where('license.account_id = :accountId', { accountId: myAccountId }) + .andWhere('license.status IN (:...statuses)', { + statuses: [ + LICENSE_ALLOCATED_STATUS.UNALLOCATED, + LICENSE_ALLOCATED_STATUS.REUSABLE, ], - order: { - expiry_date: { - direction: 'DESC', - nulls: 'FIRST', - }, - id: 'ASC', - }, - }); - - return allocatableLicenses.map((license) => ({ - licenseId: license.id, - expiryDate: license.expiry_date, - })); - }); + }) + .andWhere( + 'license.expiry_date >= :nowDate OR license.expiry_date IS NULL', + { nowDate }, + ) + .orderBy('license.expiry_date IS NULL', 'DESC') + .addOrderBy('license.expiry_date', 'DESC') + .addOrderBy('license.id', 'ASC'); + const allocatableLicenses = await queryBuilder.getMany(); + return allocatableLicenses.map((license) => ({ + licenseId: license.id, + expiryDate: license.expiry_date, + })); } /** * ライセンスをユーザーに割り当てる @@ -527,16 +513,20 @@ export class LicensesRepositoryService { }); let switchFromType = ''; - switch (oldLicenseType.license.type) { - case LICENSE_TYPE.CARD: - switchFromType = SWITCH_FROM_TYPE.CARD; - break; - case LICENSE_TYPE.TRIAL: - switchFromType = SWITCH_FROM_TYPE.TRIAL; - break; - default: - switchFromType = SWITCH_FROM_TYPE.NONE; - break; + if (oldLicenseType) { + switch (oldLicenseType.license.type) { + case LICENSE_TYPE.CARD: + switchFromType = SWITCH_FROM_TYPE.CARD; + break; + case LICENSE_TYPE.TRIAL: + switchFromType = SWITCH_FROM_TYPE.TRIAL; + break; + default: + switchFromType = SWITCH_FROM_TYPE.NONE; + break; + } + } else { + switchFromType = SWITCH_FROM_TYPE.NONE; } // ライセンス割り当て履歴テーブルへ登録