Compare commits
48 Commits
1.6.16-alp
...
developmen
Author | SHA1 | Date |
---|---|---|
|
b96d24de1a | |
|
5d3f9d7bff | |
|
831593e743 | |
|
162bd0918f | |
|
13b5838393 | |
|
63bb55b04b | |
|
9d1c240b6b | |
|
83f3377465 | |
|
69c2ee06cf | |
|
42060384aa | |
|
62cfb1f1a8 | |
|
08a35dfdf4 | |
|
8df836ff3e | |
|
822cfe606a | |
|
de43f0f28b | |
|
09b0133bf4 | |
|
a77e6b0381 | |
|
a5da557dd9 | |
|
afad02ba52 | |
|
6636c596f4 | |
|
01fb358875 | |
|
f9dc49f7d5 | |
|
1d9cdfe8e6 | |
|
ccc363f74f | |
|
af1ee2fbee | |
|
ec5229645f | |
|
47d45cb65c | |
|
d6717c9c60 | |
|
d995982203 | |
|
56e475d61f | |
|
3116acd5ab | |
|
068c4ce349 | |
|
79c9139c3c | |
|
d4e8e72af0 | |
|
7dd29c2a70 | |
|
0b5b0ce09b | |
|
e1d3ee7188 | |
|
838670c822 | |
|
34d8882ec3 | |
|
8fb8aac0f9 | |
|
3a0efb00a9 | |
|
737575176e | |
|
f0e8fbddc9 | |
|
d8fa72ba20 | |
|
ab9db39a5f | |
|
7c45a20866 | |
|
7ff0040f9e | |
|
9bbd37ba38 |
|
@ -106,6 +106,7 @@ import { OtpVerificationModule } from './modules/configuration/otp-verification/
|
|||
import { OtpVerificationModel } from './modules/configuration/otp-verification/data/models/otp-verification.model';
|
||||
import { OtpVerifierModel } from './modules/configuration/otp-verification/data/models/otp-verifier.model';
|
||||
import { RescheduleVerificationModel } from './modules/booking-online/order/data/models/reschedule-verification.model';
|
||||
import { OtpCheckerGuard } from './core/guards/domain/otp-checker.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
|
@ -246,6 +247,8 @@ import { RescheduleVerificationModel } from './modules/booking-online/order/data
|
|||
providers: [
|
||||
AuthService,
|
||||
PrivilegeService,
|
||||
OtpCheckerGuard,
|
||||
|
||||
/**
|
||||
* By default all request from client will protect by JWT
|
||||
* if there is some endpoint/function that does'nt require authentication
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnprocessableEntityException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectDataSource } from '@nestjs/typeorm';
|
||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||
import { OtpVerificationModel } from 'src/modules/configuration/otp-verification/data/models/otp-verification.model';
|
||||
import { OtpVerificationEntity } from 'src/modules/configuration/otp-verification/domain/entities/otp-verification.entity';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class OtpCheckerGuard implements CanActivate {
|
||||
constructor(
|
||||
@InjectDataSource(CONNECTION_NAME.DEFAULT)
|
||||
protected readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
get otpRepository() {
|
||||
return this.dataSource.getRepository(OtpVerificationModel);
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const verificationCode = request.headers['x-verification-code'];
|
||||
console.log({ verificationCode });
|
||||
|
||||
if (verificationCode) {
|
||||
const decoded = Buffer.from(verificationCode, 'base64').toString('ascii');
|
||||
const [dataIdentity, otpCode] = decoded.split('|');
|
||||
|
||||
let otpData: OtpVerificationEntity;
|
||||
|
||||
otpData = await this.otpRepository.findOne({
|
||||
where: {
|
||||
otp_code: otpCode,
|
||||
target_id: dataIdentity,
|
||||
},
|
||||
});
|
||||
|
||||
if (!otpData) {
|
||||
otpData = await this.otpRepository.findOne({
|
||||
where: {
|
||||
otp_code: otpCode,
|
||||
reference: dataIdentity,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// console.log({ dataIdentity, otpCode, otpData });
|
||||
if (otpData && otpData?.verified_at) return true;
|
||||
}
|
||||
|
||||
throw new UnprocessableEntityException('OTP not verified.');
|
||||
}
|
||||
}
|
|
@ -31,4 +31,6 @@ export enum MODULE_NAME {
|
|||
|
||||
TIME_GROUPS = 'time-groups',
|
||||
OTP_VERIFICATIONS = 'otp-verification',
|
||||
|
||||
OTP_VERIFIER = 'otp-verifier',
|
||||
}
|
||||
|
|
|
@ -0,0 +1,55 @@
|
|||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddEnumOtpActionTypeAndUpdateColumnOtpVerifier1750045520332
|
||||
implements MigrationInterface
|
||||
{
|
||||
name = 'AddEnumOtpActionTypeAndUpdateColumnOtpVerifier1750045520332';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "otp_verifier" ADD "is_all_action" boolean NOT NULL DEFAULT false`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TYPE "public"."otp_verifier_action_types_enum" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION', 'ACTIVATE_ITEM', 'ACTIVATE_USER', 'UPDATE_ITEM_PRICE', 'UPDATE_ITEM_DETAILS', 'CONFIRM_TRANSACTION')`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "otp_verifier" ADD "action_types" "public"."otp_verifier_action_types_enum" array`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TYPE "public"."otp_verifications_action_type_enum" RENAME TO "otp_verifications_action_type_enum_old"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TYPE "public"."otp_verifications_action_type_enum" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION', 'ACTIVATE_ITEM', 'ACTIVATE_USER', 'UPDATE_ITEM_PRICE', 'UPDATE_ITEM_DETAILS', 'CONFIRM_TRANSACTION')`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "otp_verifications" ALTER COLUMN "action_type" TYPE "public"."otp_verifications_action_type_enum" USING "action_type"::"text"::"public"."otp_verifications_action_type_enum"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`DROP TYPE "public"."otp_verifications_action_type_enum_old"`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TYPE "public"."otp_verifications_action_type_enum_old" AS ENUM('CREATE_DISCOUNT', 'CANCEL_TRANSACTION', 'REJECT_RECONCILIATION')`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "otp_verifications" ALTER COLUMN "action_type" TYPE "public"."otp_verifications_action_type_enum_old" USING "action_type"::"text"::"public"."otp_verifications_action_type_enum_old"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`DROP TYPE "public"."otp_verifications_action_type_enum"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TYPE "public"."otp_verifications_action_type_enum_old" RENAME TO "otp_verifications_action_type_enum"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "otp_verifier" DROP COLUMN "action_types"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`DROP TYPE "public"."otp_verifier_action_types_enum"`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "otp_verifier" DROP COLUMN "is_all_action"`,
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddUsageTypeToItem1750319148269 implements MigrationInterface {
|
||||
name = 'AddUsageTypeToItem1750319148269';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TYPE "public"."item_queues_usage_type_enum" AS ENUM('one_time', 'multiple')`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "item_queues" ADD "usage_type" "public"."item_queues_usage_type_enum" NOT NULL DEFAULT 'one_time'`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE TYPE "public"."items_usage_type_enum" AS ENUM('one_time', 'multiple')`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "items" ADD "usage_type" "public"."items_usage_type_enum" NOT NULL DEFAULT 'one_time'`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "items" DROP COLUMN "usage_type"`);
|
||||
await queryRunner.query(`DROP TYPE "public"."items_usage_type_enum"`);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "item_queues" DROP COLUMN "usage_type"`,
|
||||
);
|
||||
await queryRunner.query(`DROP TYPE "public"."item_queues_usage_type_enum"`);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { RelationParam } from 'src/core/modules/domain/entities/base-filter.entity';
|
||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
||||
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
|
||||
import { IndexItemManager } from 'src/modules/item-related/item/domain/usecases/managers/index-item.manager';
|
||||
import { SelectQueryBuilder } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class BookingItemManager extends IndexItemManager {
|
||||
get relations(): RelationParam {
|
||||
return {
|
||||
// relation only join (for query purpose)
|
||||
joinRelations: [],
|
||||
|
||||
// relation join and select (relasi yang ingin ditampilkan),
|
||||
selectRelations: [
|
||||
'item_category',
|
||||
'bundling_items',
|
||||
'tenant',
|
||||
'time_group',
|
||||
'item_rates',
|
||||
],
|
||||
|
||||
// relation yang hanya ingin dihitung (akan return number)
|
||||
countRelations: [],
|
||||
};
|
||||
}
|
||||
|
||||
get selects(): string[] {
|
||||
const parent = super.selects;
|
||||
return [
|
||||
...parent,
|
||||
`${this.tableName}.image_url`,
|
||||
'item_rates.id',
|
||||
'item_rates.price',
|
||||
'item_rates.season_period_id',
|
||||
];
|
||||
}
|
||||
|
||||
getResult(): PaginationResponse<ItemEntity> {
|
||||
const result = super.getResult();
|
||||
const { data, total } = result;
|
||||
const hasRates = (this.filterParam.season_period_ids?.length ?? 0) > 0;
|
||||
const items = data.map((item) => {
|
||||
const currentRate = item.item_rates.find((rate) =>
|
||||
this.filterParam.season_period_ids?.includes(rate.season_period_id),
|
||||
);
|
||||
const { item_rates, ...rest } = item;
|
||||
const rate = currentRate?.['price'] ?? rest.base_price;
|
||||
return {
|
||||
...rest,
|
||||
base_price: hasRates ? rate : rest.base_price,
|
||||
};
|
||||
});
|
||||
return { total, data: items };
|
||||
}
|
||||
|
||||
setQueryFilter(
|
||||
queryBuilder: SelectQueryBuilder<ItemEntity>,
|
||||
): SelectQueryBuilder<ItemEntity> {
|
||||
const query = super.setQueryFilter(queryBuilder);
|
||||
|
||||
query.andWhere(`${this.tableName}.status = 'active'`);
|
||||
|
||||
return query;
|
||||
}
|
||||
}
|
|
@ -1,19 +1,19 @@
|
|||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from 'src/core/guards';
|
||||
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
|
||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||
import { ItemReadService } from 'src/modules/item-related/item/data/services/item-read.service';
|
||||
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
|
||||
import { IndexItemManager } from 'src/modules/item-related/item/domain/usecases/managers/index-item.manager';
|
||||
import { FilterItemDto } from 'src/modules/item-related/item/infrastructure/dto/filter-item.dto';
|
||||
import { BookingItemManager } from '../domain/usecases/managers/booking-item.manager';
|
||||
|
||||
@ApiTags('Booking Item')
|
||||
@Controller('v1/booking-item')
|
||||
@Public(true)
|
||||
export class ItemController {
|
||||
constructor(
|
||||
private indexManager: IndexItemManager,
|
||||
private indexManager: BookingItemManager,
|
||||
private serviceData: ItemReadService,
|
||||
) {}
|
||||
|
||||
|
@ -23,6 +23,7 @@ export class ItemController {
|
|||
): Promise<PaginationResponse<ItemEntity>> {
|
||||
params.limit = 1000;
|
||||
params.show_to_booking = true;
|
||||
params.all_item = true;
|
||||
this.indexManager.setFilterParam(params);
|
||||
this.indexManager.setService(this.serviceData, TABLE_NAME.ITEM);
|
||||
await this.indexManager.execute();
|
||||
|
|
|
@ -26,6 +26,7 @@ import { RescheduleVerificationManager } from '../domain/usecases/managers/resch
|
|||
import { RescheduleManager } from '../domain/usecases/managers/reschedule.manager';
|
||||
import { STATUS } from 'src/core/strings/constants/base.constants';
|
||||
import * as moment from 'moment';
|
||||
import { WhatsappService } from 'src/services/whatsapp/whatsapp.service';
|
||||
|
||||
@ApiTags('Booking Order')
|
||||
@Controller('v1/booking')
|
||||
|
@ -131,11 +132,17 @@ export class BookingOrderController {
|
|||
@Get(':id')
|
||||
async get(@Param('id') transactionId: string) {
|
||||
const data = await this.serviceData.getOneByOptions({
|
||||
relations: ['items', 'items.item', 'items.item.time_group'],
|
||||
relations: [
|
||||
'items',
|
||||
'parent_transaction',
|
||||
'items.item',
|
||||
'items.item.time_group',
|
||||
],
|
||||
where: { id: transactionId },
|
||||
});
|
||||
|
||||
const {
|
||||
parent_id,
|
||||
customer_name,
|
||||
customer_phone,
|
||||
booking_date,
|
||||
|
@ -143,12 +150,30 @@ export class BookingOrderController {
|
|||
status,
|
||||
id,
|
||||
items,
|
||||
parent_transaction,
|
||||
} = data;
|
||||
|
||||
let timeGroup = null;
|
||||
|
||||
const usageItems = items.map((item) => {
|
||||
const itemData = item.item;
|
||||
const timeGroupData = itemData.time_group;
|
||||
const { id: groupId, name, start_time, end_time } = timeGroupData;
|
||||
if (itemData.time_group) {
|
||||
const timeGroupData = itemData.time_group;
|
||||
const {
|
||||
id: groupId,
|
||||
name,
|
||||
start_time,
|
||||
end_time,
|
||||
max_usage_time,
|
||||
} = timeGroupData;
|
||||
timeGroup = {
|
||||
id: groupId,
|
||||
name,
|
||||
start_time,
|
||||
end_time,
|
||||
max_usage_time,
|
||||
};
|
||||
}
|
||||
const {
|
||||
id,
|
||||
item_id,
|
||||
|
@ -170,12 +195,6 @@ export class BookingOrderController {
|
|||
total_net_price,
|
||||
qty,
|
||||
qty_remaining,
|
||||
time_group: {
|
||||
id: groupId,
|
||||
name,
|
||||
start_time,
|
||||
end_time,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
|
@ -186,6 +205,20 @@ export class BookingOrderController {
|
|||
maskedCustomerPhone = '*'.repeat(customer_phone.length - 4) + last4;
|
||||
}
|
||||
|
||||
let parentTransaction = undefined;
|
||||
if (parent_transaction) {
|
||||
const {
|
||||
id: parentId,
|
||||
invoice_code: parentInvoiceCode,
|
||||
invoice_date: parentInvoiceDate,
|
||||
} = parent_transaction;
|
||||
parentTransaction = {
|
||||
id: parentId,
|
||||
invoice_code: parentInvoiceCode,
|
||||
invoice_date: parentInvoiceDate,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
customer_name,
|
||||
customer_phone: maskedCustomerPhone,
|
||||
|
@ -193,7 +226,10 @@ export class BookingOrderController {
|
|||
invoice_code,
|
||||
status,
|
||||
id,
|
||||
is_reschedule: !!parent_id,
|
||||
items: usageItems,
|
||||
time_group: timeGroup,
|
||||
parent: parentTransaction,
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -208,4 +244,31 @@ export class BookingOrderController {
|
|||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
res.send(buffer);
|
||||
}
|
||||
|
||||
@Post('resend-notification/:id')
|
||||
async resendNotification(@Param('id') id: string) {
|
||||
try {
|
||||
const transaction = await this.serviceData.getOneByOptions({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
const whatsappService = new WhatsappService();
|
||||
const formattedDate = moment(transaction.booking_date);
|
||||
const payload = {
|
||||
id: transaction.id,
|
||||
phone: transaction.customer_phone,
|
||||
code: transaction.invoice_code,
|
||||
name: transaction.customer_name,
|
||||
time: formattedDate.valueOf(),
|
||||
};
|
||||
await whatsappService.bookingCreated(payload);
|
||||
return {
|
||||
message: 'Notification sent successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new UnprocessableEntityException({
|
||||
message: 'Failed to send notification',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,6 +14,7 @@ import { CqrsModule } from '@nestjs/cqrs';
|
|||
import { RescheduleVerificationModel } from './data/models/reschedule-verification.model';
|
||||
import { RescheduleVerificationManager } from './domain/usecases/managers/reschedule-verification.manager';
|
||||
import { RescheduleManager } from './domain/usecases/managers/reschedule.manager';
|
||||
import { BookingItemManager } from './domain/usecases/managers/booking-item.manager';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
|
@ -31,6 +32,7 @@ import { RescheduleManager } from './domain/usecases/managers/reschedule.manager
|
|||
CreateBookingManager,
|
||||
RescheduleVerificationManager,
|
||||
RescheduleManager,
|
||||
BookingItemManager,
|
||||
],
|
||||
})
|
||||
export class BookingOrderModule {}
|
||||
|
|
|
@ -10,7 +10,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
|||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||
import { TransactionItemModel } from 'src/modules/transaction/transaction/data/models/transaction-item.model';
|
||||
import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/models/transaction-tax.model';
|
||||
|
||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
|
@ -19,6 +19,7 @@ import { TransactionTaxModel } from 'src/modules/transaction/transaction/data/mo
|
|||
CONNECTION_NAME.DEFAULT,
|
||||
),
|
||||
CqrsModule,
|
||||
CouchModule,
|
||||
],
|
||||
controllers: [GoogleCalendarController],
|
||||
providers: [
|
||||
|
|
|
@ -10,7 +10,7 @@ import { TransactionDataService } from 'src/modules/transaction/transaction/data
|
|||
import { PaymentTransactionHandler } from './domain/handlers/payment-transaction.handler';
|
||||
import { MailTemplateController } from './infrastructure/mail.controller';
|
||||
import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
||||
|
||||
import { CouchModule } from '../couch/couch.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
|
@ -19,6 +19,7 @@ import { PdfMakeManager } from '../export/domain/managers/pdf-make.manager';
|
|||
CONNECTION_NAME.DEFAULT,
|
||||
),
|
||||
CqrsModule,
|
||||
CouchModule,
|
||||
],
|
||||
controllers: [MailTemplateController],
|
||||
providers: [
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||
import { OtpVerifierEntity } from '../../domain/entities/otp-verification.entity';
|
||||
import {
|
||||
OTP_ACTION_TYPE,
|
||||
OtpVerifierEntity,
|
||||
} from '../../domain/entities/otp-verification.entity';
|
||||
import { Column, Entity } from 'typeorm';
|
||||
import { BaseModel } from 'src/core/modules/data/model/base.model';
|
||||
|
||||
|
@ -13,4 +16,10 @@ export class OtpVerifierModel
|
|||
|
||||
@Column({ type: 'varchar', nullable: false })
|
||||
phone_number: string;
|
||||
|
||||
@Column({ default: false })
|
||||
is_all_action: boolean;
|
||||
|
||||
@Column({ type: 'enum', enum: OTP_ACTION_TYPE, array: true, nullable: true })
|
||||
action_types: OTP_ACTION_TYPE[] | null;
|
||||
}
|
||||
|
|
|
@ -3,6 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
|
|||
import { Repository } from 'typeorm';
|
||||
import { OtpVerificationModel } from '../models/otp-verification.model';
|
||||
import {
|
||||
OTP_ACTION_TYPE,
|
||||
OtpRequestEntity,
|
||||
OtpVerificationEntity,
|
||||
OtpVerifierEntity,
|
||||
|
@ -37,14 +38,81 @@ export class OtpVerificationService {
|
|||
return moment().valueOf(); // epoch millis verification time (now)
|
||||
}
|
||||
|
||||
async requestOTP(payload: OtpRequestEntity) {
|
||||
private generateHeaderTemplate(payload) {
|
||||
const label = payload.action_type;
|
||||
|
||||
// Optional logic to override label based on action type.
|
||||
// e.g., if (payload.action_type === OTP_ACTION_TYPE.CONFIRM_TRANSACTION) label = 'CONFIRM_BOOKING_TRANSACTION'
|
||||
|
||||
const header = label.split('_').join(' ');
|
||||
const type = label
|
||||
.split('_')
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
||||
.join(' ');
|
||||
|
||||
return { header, type };
|
||||
}
|
||||
|
||||
private generateOTPMsgTemplate(payload) {
|
||||
const { userRequest, newOtp } = payload;
|
||||
const { header, type } = this.generateHeaderTemplate(newOtp);
|
||||
|
||||
const otpCode = newOtp?.otp_code;
|
||||
const username = userRequest?.username;
|
||||
|
||||
return {
|
||||
name: 'general_flow',
|
||||
language: { code: 'id' },
|
||||
components: [
|
||||
{
|
||||
type: 'header',
|
||||
parameters: [
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'header',
|
||||
text: header,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'body',
|
||||
parameters: [
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'name',
|
||||
text: username,
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'code',
|
||||
text: otpCode,
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'type',
|
||||
text: type,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'footer',
|
||||
parameters: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'Kode berlaku selama 5 menit.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async requestOTP(payload: OtpRequestEntity, req: any) {
|
||||
const otpService = new OtpService({ length: 4 });
|
||||
const otpCode = otpService.generateSecureOTP();
|
||||
const dateNow = this.generateTimestamp();
|
||||
const expiredAt = this.generateOtpExpiration();
|
||||
|
||||
//TODO implementation from auth
|
||||
const creator = { id: null, name: null };
|
||||
const userRequest = req?.user;
|
||||
|
||||
const newOtp: OtpVerificationEntity = {
|
||||
otp_code: otpCode,
|
||||
|
@ -56,13 +124,13 @@ export class OtpVerificationService {
|
|||
is_replaced: false,
|
||||
expired_at: expiredAt,
|
||||
|
||||
creator_id: creator.id,
|
||||
creator_name: creator.name,
|
||||
creator_id: userRequest?.id,
|
||||
creator_name: userRequest?.name,
|
||||
created_at: dateNow,
|
||||
verified_at: null,
|
||||
|
||||
editor_id: creator.id,
|
||||
editor_name: creator.name,
|
||||
editor_id: userRequest?.id,
|
||||
editor_name: userRequest?.name,
|
||||
updated_at: dateNow,
|
||||
};
|
||||
|
||||
|
@ -91,13 +159,15 @@ export class OtpVerificationService {
|
|||
|
||||
// save otp to database
|
||||
await this.otpVerificationRepo.save(newOtp);
|
||||
const verifiers: OtpVerifierEntity[] = await this.otpVerifierRepo.find();
|
||||
const verifiers: OtpVerifierEntity[] = await this.getVerifier([
|
||||
payload.action_type,
|
||||
]);
|
||||
const notificationService = new WhatsappService();
|
||||
|
||||
verifiers.map((v) => {
|
||||
notificationService.sendOtpNotification({
|
||||
verifiers?.map((v) => {
|
||||
notificationService.sendTemplateMessage({
|
||||
phone: v.phone_number,
|
||||
code: otpCode,
|
||||
templateMsg: this.generateOTPMsgTemplate({ userRequest, newOtp }),
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -108,7 +178,8 @@ export class OtpVerificationService {
|
|||
};
|
||||
}
|
||||
|
||||
async verifyOTP(payload: OtpVerifyEntity) {
|
||||
async verifyOTP(payload: OtpVerifyEntity, req: any) {
|
||||
const userRequest = req?.user;
|
||||
const { otp_code, action_type, target_id, reference, source } = payload;
|
||||
const dateNow = this.generateTimestamp();
|
||||
|
||||
|
@ -154,6 +225,9 @@ export class OtpVerificationService {
|
|||
|
||||
otp.is_used = true;
|
||||
otp.verified_at = dateNow;
|
||||
otp.editor_id = userRequest?.id;
|
||||
otp.editor_name = userRequest?.name;
|
||||
otp.updated_at = dateNow;
|
||||
|
||||
// update otp to database
|
||||
await this.otpVerificationRepo.save(otp);
|
||||
|
@ -179,4 +253,14 @@ export class OtpVerificationService {
|
|||
)
|
||||
.getOne();
|
||||
}
|
||||
|
||||
async getVerifier(actions: OTP_ACTION_TYPE[]) {
|
||||
const tableALias = TABLE_NAME.OTP_VERIFIER;
|
||||
const results = await this.otpVerifierRepo
|
||||
.createQueryBuilder(tableALias)
|
||||
.where(`${tableALias}.is_all_action = :isAll`, { isAll: true })
|
||||
.orWhere(`${tableALias}.action_types && :actions`, { actions })
|
||||
.getMany();
|
||||
return results ?? [];
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { OtpVerifierModel } from '../models/otp-verifier.model';
|
||||
import { OtpVerifierCreateDto } from '../../infrastructure/dto/otp-verification.dto';
|
||||
import * as moment from 'moment';
|
||||
|
||||
@Injectable()
|
||||
export class OtpVerifierService {
|
||||
constructor(
|
||||
@InjectRepository(OtpVerifierModel)
|
||||
private readonly otpVerifierRepo: Repository<OtpVerifierModel>,
|
||||
) {}
|
||||
|
||||
async create(payload: OtpVerifierCreateDto) {
|
||||
const dateNow = moment().valueOf();
|
||||
|
||||
return this.otpVerifierRepo.save({
|
||||
...payload,
|
||||
created_at: dateNow,
|
||||
updated_at: dateNow,
|
||||
});
|
||||
}
|
||||
}
|
|
@ -4,6 +4,14 @@ export enum OTP_ACTION_TYPE {
|
|||
CREATE_DISCOUNT = 'CREATE_DISCOUNT',
|
||||
CANCEL_TRANSACTION = 'CANCEL_TRANSACTION',
|
||||
REJECT_RECONCILIATION = 'REJECT_RECONCILIATION',
|
||||
|
||||
ACTIVATE_USER = 'ACTIVATE_USER',
|
||||
|
||||
ACTIVATE_ITEM = 'ACTIVATE_ITEM',
|
||||
UPDATE_ITEM_PRICE = 'UPDATE_ITEM_PRICE',
|
||||
UPDATE_ITEM_DETAILS = 'UPDATE_ITEM_DETAILS',
|
||||
|
||||
CONFIRM_TRANSACTION = 'CONFIRM_TRANSACTION',
|
||||
}
|
||||
|
||||
export enum OTP_SOURCE {
|
||||
|
@ -37,4 +45,6 @@ export interface OtpVerifyEntity extends OtpRequestEntity {
|
|||
export interface OtpVerifierEntity {
|
||||
name: string;
|
||||
phone_number: string;
|
||||
is_all_action?: boolean;
|
||||
action_types?: OTP_ACTION_TYPE[] | null;
|
||||
}
|
||||
|
|
|
@ -1,4 +1,13 @@
|
|||
import { IsNotEmpty, IsString, ValidateIf } from 'class-validator';
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsPhoneNumber,
|
||||
IsString,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import {
|
||||
OTP_ACTION_TYPE,
|
||||
OTP_SOURCE,
|
||||
|
@ -6,6 +15,7 @@ import {
|
|||
OtpVerifyEntity,
|
||||
} from '../../domain/entities/otp-verification.entity';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class OtpRequestDto implements OtpRequestEntity {
|
||||
@ApiProperty({
|
||||
|
@ -53,3 +63,50 @@ export class OtpVerifyDto extends OtpRequestDto implements OtpVerifyEntity {
|
|||
@IsNotEmpty()
|
||||
otp_code: string;
|
||||
}
|
||||
|
||||
export class OtpVerifierCreateDto {
|
||||
@ApiProperty({
|
||||
example: 'Item Manager',
|
||||
description: 'Nama verifier, opsional.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: '6281234567890',
|
||||
description: 'Nomor telepon verifier dalam format internasional (E.164).',
|
||||
})
|
||||
@IsString()
|
||||
@IsPhoneNumber('ID')
|
||||
phone_number: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: false,
|
||||
description:
|
||||
'True jika verifier boleh memverifikasi semua aksi tanpa batas.',
|
||||
})
|
||||
@IsBoolean()
|
||||
is_all_action: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
isArray: true,
|
||||
enum: OTP_ACTION_TYPE,
|
||||
example: [
|
||||
'CREATE_DISCOUNT',
|
||||
'CANCEL_TRANSACTION',
|
||||
'REJECT_RECONCILIATION',
|
||||
'ACTIVATE_ITEM',
|
||||
'ACTIVATE_USER',
|
||||
'UPDATE_ITEM_PRICE',
|
||||
'UPDATE_ITEM_DETAILS',
|
||||
'CONFIRM_TRANSACTION',
|
||||
],
|
||||
description: 'Daftar tipe aksi yang boleh diverifikasi, jika bukan semua.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsEnum(OTP_ACTION_TYPE, { each: true })
|
||||
@Type(() => String)
|
||||
action_types?: OTP_ACTION_TYPE[];
|
||||
}
|
||||
|
|
|
@ -0,0 +1,80 @@
|
|||
// auth/otp-auth.guard.ts
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnprocessableEntityException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { InjectDataSource } from '@nestjs/typeorm';
|
||||
import { validatePassword } from 'src/core/helpers/password/bcrypt.helpers';
|
||||
import {
|
||||
CONNECTION_NAME,
|
||||
STATUS,
|
||||
} from 'src/core/strings/constants/base.constants';
|
||||
import { UserRole } from 'src/modules/user-related/user/constants';
|
||||
import { UserModel } from 'src/modules/user-related/user/data/models/user.model';
|
||||
import { DataSource, Not } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class OtpAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
|
||||
@InjectDataSource(CONNECTION_NAME.DEFAULT)
|
||||
protected readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
get userRepository() {
|
||||
return this.dataSource.getRepository(UserModel);
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const jwtAuth = request.headers['authorization'];
|
||||
const basicAuth = request.headers['x-basic-authorization'];
|
||||
|
||||
// 1. Cek OTP Auth (basic_authorization header)
|
||||
if (basicAuth) {
|
||||
try {
|
||||
const decoded = Buffer.from(basicAuth, 'base64').toString('ascii');
|
||||
const [username, password] = decoded.split('|');
|
||||
|
||||
const userLogin = await this.userRepository.findOne({
|
||||
where: {
|
||||
username: username,
|
||||
status: STATUS.ACTIVE,
|
||||
role: Not(UserRole.QUEUE_ADMIN),
|
||||
},
|
||||
});
|
||||
|
||||
const valid = await validatePassword(password, userLogin?.password);
|
||||
|
||||
if (userLogin && valid) {
|
||||
request.user = userLogin;
|
||||
return true;
|
||||
} else {
|
||||
throw new UnprocessableEntityException('Invalid OTP credentials');
|
||||
}
|
||||
} catch (err) {
|
||||
throw new UnprocessableEntityException('Invalid OTP encoding');
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Cek JWT (Authorization: Bearer <token>)
|
||||
if (jwtAuth && jwtAuth.startsWith('Bearer ')) {
|
||||
const token = jwtAuth.split(' ')[1];
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync(token);
|
||||
request.user = payload;
|
||||
return true;
|
||||
} catch (err) {
|
||||
throw new UnprocessableEntityException('Invalid JWT token');
|
||||
}
|
||||
}
|
||||
|
||||
throw new UnprocessableEntityException(
|
||||
'No valid authentication method found',
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1,11 +1,24 @@
|
|||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from 'src/core/guards';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { ExcludePrivilege, Public } from 'src/core/guards';
|
||||
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
||||
import { OtpVerificationService } from '../data/services/otp-verification.service';
|
||||
import { OtpRequestDto, OtpVerifyDto } from './dto/otp-verification.dto';
|
||||
import {
|
||||
OtpRequestDto,
|
||||
OtpVerifierCreateDto,
|
||||
OtpVerifyDto,
|
||||
} from './dto/otp-verification.dto';
|
||||
import { OtpAuthGuard } from './guards/otp-auth.guard';
|
||||
import { OtpVerifierService } from '../data/services/otp-verifier.service';
|
||||
|
||||
//TODO implementation auth
|
||||
@ApiTags(`${MODULE_NAME.OTP_VERIFICATIONS.split('-').join(' ')} - data`)
|
||||
@Controller(`v1/${MODULE_NAME.OTP_VERIFICATIONS}`)
|
||||
@Public()
|
||||
|
@ -15,13 +28,15 @@ export class OtpVerificationController {
|
|||
) {}
|
||||
|
||||
@Post('request')
|
||||
async request(@Body() body: OtpRequestDto) {
|
||||
return await this.otpVerificationService.requestOTP(body);
|
||||
@UseGuards(OtpAuthGuard)
|
||||
async request(@Body() body: OtpRequestDto, @Req() req) {
|
||||
return await this.otpVerificationService.requestOTP(body, req);
|
||||
}
|
||||
|
||||
@Post('verify')
|
||||
async verify(@Body() body: OtpVerifyDto) {
|
||||
return await this.otpVerificationService.verifyOTP(body);
|
||||
@UseGuards(OtpAuthGuard)
|
||||
async verify(@Body() body: OtpVerifyDto, @Req() req) {
|
||||
return await this.otpVerificationService.verifyOTP(body, req);
|
||||
}
|
||||
|
||||
@Get(':ref_or_target_id')
|
||||
|
@ -29,3 +44,17 @@ export class OtpVerificationController {
|
|||
return this.otpVerificationService.getActiveOtp(ref_or_target_id);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags(`${MODULE_NAME.OTP_VERIFIER.split('-').join(' ')} - data`)
|
||||
@Controller(`v1/${MODULE_NAME.OTP_VERIFIER}`)
|
||||
@ApiBearerAuth('JWT')
|
||||
@Public(false)
|
||||
export class OtpVerifierController {
|
||||
constructor(private readonly otpVerifierService: OtpVerifierService) {}
|
||||
|
||||
@Post()
|
||||
@ExcludePrivilege()
|
||||
async create(@Body() body: OtpVerifierCreateDto) {
|
||||
return await this.otpVerifierService.create(body);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,18 +4,34 @@ import { ConfigModule } from '@nestjs/config';
|
|||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { OtpVerificationModel } from './data/models/otp-verification.model';
|
||||
import { OtpVerificationController } from './infrastructure/otp-verification-data.controller';
|
||||
import {
|
||||
OtpVerificationController,
|
||||
OtpVerifierController,
|
||||
} from './infrastructure/otp-verification-data.controller';
|
||||
import { OtpVerificationService } from './data/services/otp-verification.service';
|
||||
import { OtpVerifierModel } from './data/models/otp-verifier.model';
|
||||
import { OtpAuthGuard } from './infrastructure/guards/otp-auth.guard';
|
||||
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { JWT_EXPIRED } from 'src/core/sessions/constants';
|
||||
import { JWT_SECRET } from 'src/core/sessions/constants';
|
||||
import { OtpVerifierService } from './data/services/otp-verifier.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
|
||||
TypeOrmModule.forFeature(
|
||||
[OtpVerificationModel, OtpVerifierModel],
|
||||
CONNECTION_NAME.DEFAULT,
|
||||
),
|
||||
|
||||
JwtModule.register({
|
||||
secret: JWT_SECRET,
|
||||
signOptions: { expiresIn: JWT_EXPIRED },
|
||||
}),
|
||||
],
|
||||
controllers: [OtpVerificationController],
|
||||
providers: [OtpVerificationService],
|
||||
controllers: [OtpVerificationController, OtpVerifierController],
|
||||
providers: [OtpAuthGuard, OtpVerificationService, OtpVerifierService],
|
||||
})
|
||||
export class OtpVerificationModule {}
|
||||
|
|
|
@ -5,3 +5,8 @@ export enum ItemType {
|
|||
FREE_GIFT = 'free gift',
|
||||
OTHER = 'other',
|
||||
}
|
||||
|
||||
export enum UsageType {
|
||||
ONE_TIME = 'one_time',
|
||||
MULTIPLE = 'multiple',
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
|||
import { ItemQueueEntity } from '../../domain/entities/item-queue.entity';
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { BaseStatusModel } from 'src/core/modules/data/model/base-status.model';
|
||||
import { ItemType } from '../../constants';
|
||||
import { ItemType, UsageType } from '../../constants';
|
||||
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
|
||||
|
||||
@Entity(TABLE_NAME.ITEM_QUEUE)
|
||||
|
@ -29,6 +29,13 @@ export class ItemQueueModel
|
|||
})
|
||||
item_type: ItemType;
|
||||
|
||||
@Column('enum', {
|
||||
name: 'usage_type',
|
||||
enum: UsageType,
|
||||
default: UsageType.ONE_TIME,
|
||||
})
|
||||
usage_type: UsageType;
|
||||
|
||||
@OneToMany(() => ItemModel, (model) => model.item_queue, {
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
|
||||
import { ItemType } from '../../constants';
|
||||
import { ItemType, UsageType } from '../../constants';
|
||||
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
|
||||
|
||||
export interface ItemQueueEntity extends BaseStatusEntity {
|
||||
|
@ -11,4 +11,5 @@ export interface ItemQueueEntity extends BaseStatusEntity {
|
|||
items: ItemEntity[];
|
||||
use_notification?: boolean;
|
||||
requiring_notification?: boolean;
|
||||
usage_type?: UsageType;
|
||||
}
|
||||
|
|
|
@ -40,6 +40,7 @@ export class DetailItemQueueManager extends BaseDetailManager<ItemQueueEntity> {
|
|||
`${this.tableName}.call_preparation`,
|
||||
`${this.tableName}.use_notification`,
|
||||
`${this.tableName}.requiring_notification`,
|
||||
`${this.tableName}.usage_type`,
|
||||
|
||||
`items.id`,
|
||||
`items.created_at`,
|
||||
|
|
|
@ -43,7 +43,7 @@ export class IndexItemQueueManager extends BaseIndexManager<ItemQueueEntity> {
|
|||
`${this.tableName}.call_preparation`,
|
||||
`${this.tableName}.use_notification`,
|
||||
`${this.tableName}.requiring_notification`,
|
||||
|
||||
`${this.tableName}.usage_type`,
|
||||
`items.id`,
|
||||
`items.created_at`,
|
||||
`items.status`,
|
||||
|
|
|
@ -18,6 +18,7 @@ import { ItemRateModel } from 'src/modules/item-related/item-rate/data/models/it
|
|||
import { GateModel } from 'src/modules/web-information/gate/data/models/gate.model';
|
||||
import { ItemQueueModel } from 'src/modules/item-related/item-queue/data/models/item-queue.model';
|
||||
import { TimeGroupModel } from 'src/modules/item-related/time-group/data/models/time-group.model';
|
||||
import { UsageType } from 'src/modules/item-related/item-queue/constants';
|
||||
|
||||
@Entity(TABLE_NAME.ITEM)
|
||||
export class ItemModel
|
||||
|
@ -43,6 +44,13 @@ export class ItemModel
|
|||
})
|
||||
item_type: ItemType;
|
||||
|
||||
@Column('enum', {
|
||||
name: 'usage_type',
|
||||
enum: UsageType,
|
||||
default: UsageType.ONE_TIME,
|
||||
})
|
||||
usage_type: UsageType;
|
||||
|
||||
@Column('bigint', { name: 'hpp', nullable: true })
|
||||
hpp: number;
|
||||
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import { BaseStatusEntity } from 'src/core/modules/domain/entities/base-status.entity';
|
||||
import { ItemType } from 'src/modules/item-related/item-category/constants';
|
||||
import { LimitType } from '../../constants';
|
||||
|
||||
import { ItemRateEntity } from 'src/modules/item-related/item-rate/domain/entities/item-rate.entity';
|
||||
import { UsageType } from 'src/modules/item-related/item-queue/constants';
|
||||
export interface ItemEntity extends BaseStatusEntity {
|
||||
name: string;
|
||||
item_type: ItemType;
|
||||
|
@ -19,4 +20,7 @@ export interface ItemEntity extends BaseStatusEntity {
|
|||
show_to_booking: boolean;
|
||||
breakdown_bundling?: boolean;
|
||||
booking_description?: string;
|
||||
usage_type?: UsageType;
|
||||
|
||||
item_rates?: ItemRateEntity[] | any[];
|
||||
}
|
||||
|
|
|
@ -53,6 +53,7 @@ export class DetailItemManager extends BaseDetailManager<ItemEntity> {
|
|||
`${this.tableName}.total_price`,
|
||||
`${this.tableName}.base_price`,
|
||||
`${this.tableName}.use_queue`,
|
||||
`${this.tableName}.usage_type`,
|
||||
`${this.tableName}.show_to_booking`,
|
||||
`${this.tableName}.breakdown_bundling`,
|
||||
`${this.tableName}.play_estimation`,
|
||||
|
|
|
@ -55,6 +55,7 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
|
|||
`${this.tableName}.play_estimation`,
|
||||
`${this.tableName}.show_to_booking`,
|
||||
`${this.tableName}.booking_description`,
|
||||
`${this.tableName}.usage_type`,
|
||||
|
||||
`item_category.id`,
|
||||
`item_category.name`,
|
||||
|
@ -110,7 +111,7 @@ export class IndexItemManager extends BaseIndexManager<ItemEntity> {
|
|||
|
||||
if (this.filterParam.time_group_ids?.length) {
|
||||
queryBuilder.andWhere(
|
||||
`${this.tableName}.time_group_id In (:...timeGroupIds) OR ${this.tableName}.time_group_id Is Null`,
|
||||
`(${this.tableName}.time_group_id In (:...timeGroupIds) OR ${this.tableName}.time_group_id Is Null)`,
|
||||
{
|
||||
timeGroupIds: this.filterParam.time_group_ids,
|
||||
},
|
||||
|
|
|
@ -6,6 +6,7 @@ import {
|
|||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ItemDataOrchestrator } from '../domain/usecases/item-data.orchestrator';
|
||||
import { ItemDto } from './dto/item.dto';
|
||||
|
@ -16,6 +17,7 @@ import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
|||
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
|
||||
import { Public } from 'src/core/guards';
|
||||
import { UpdateItemPriceDto } from './dto/update-item-price.dto';
|
||||
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
|
||||
|
||||
@ApiTags(`${MODULE_NAME.ITEM.split('-').join(' ')} - data`)
|
||||
@Controller(`v1/${MODULE_NAME.ITEM}`)
|
||||
|
@ -29,6 +31,7 @@ export class ItemDataController {
|
|||
return await this.orchestrator.create(data);
|
||||
}
|
||||
|
||||
@Public(true)
|
||||
@Post('update-price')
|
||||
async updatePrice(@Body() body: UpdateItemPriceDto): Promise<any> {
|
||||
return await this.orchestrator.updatePrice(body);
|
||||
|
@ -40,6 +43,7 @@ export class ItemDataController {
|
|||
}
|
||||
|
||||
@Patch(':id/active')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async active(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.active(dataId);
|
||||
}
|
||||
|
@ -50,6 +54,7 @@ export class ItemDataController {
|
|||
}
|
||||
|
||||
@Patch(':id/confirm')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.confirm(dataId);
|
||||
}
|
||||
|
@ -70,6 +75,7 @@ export class ItemDataController {
|
|||
}
|
||||
|
||||
@Put(':id')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async update(
|
||||
@Param('id') dataId: string,
|
||||
@Body() data: ItemDto,
|
||||
|
|
|
@ -39,7 +39,7 @@ import { ItemQueueModel } from '../item-related/item-queue/data/models/item-queu
|
|||
import { QueueTimeFormula } from './domain/usecases/formula/queue-time.formula';
|
||||
import { QueueJobController } from './infrastructure/controllers/queue-job.controller';
|
||||
import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
|
||||
|
||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
|
@ -57,6 +57,7 @@ import { GenerateQueueManager } from './domain/usecases/generate-queue.manager';
|
|||
CONNECTION_NAME.DEFAULT,
|
||||
),
|
||||
CqrsModule,
|
||||
CouchModule,
|
||||
],
|
||||
controllers: [QueueController, QueueAdminController, QueueJobController],
|
||||
providers: [
|
||||
|
|
|
@ -6,6 +6,7 @@ import {
|
|||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { SeasonPeriodDataOrchestrator } from '../domain/usecases/season-period-data.orchestrator';
|
||||
import { SeasonPeriodDto } from './dto/season-period.dto';
|
||||
|
@ -18,6 +19,7 @@ import { Public } from 'src/core/guards';
|
|||
import { UpdateSeasonPeriodDto } from './dto/update-season-period.dto';
|
||||
import { UpdateSeasonPeriodItemDto } from './dto/update-season-period-item.dto';
|
||||
import { UpdateSeasonPriceDto } from './dto/update-season-price.dto';
|
||||
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
|
||||
|
||||
@ApiTags(`${MODULE_NAME.SEASON_PERIOD.split('-').join(' ')} - data`)
|
||||
@Controller(`v1/${MODULE_NAME.SEASON_PERIOD}`)
|
||||
|
@ -27,11 +29,13 @@ export class SeasonPeriodDataController {
|
|||
constructor(private orchestrator: SeasonPeriodDataOrchestrator) {}
|
||||
|
||||
@Post()
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async create(@Body() data: SeasonPeriodDto): Promise<SeasonPeriodEntity> {
|
||||
return await this.orchestrator.create(data);
|
||||
}
|
||||
|
||||
@Post('/update-price')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async updatePrice(@Body() body: UpdateSeasonPriceDto): Promise<BatchResult> {
|
||||
return await this.orchestrator.updatePrice(body);
|
||||
}
|
||||
|
@ -80,7 +84,9 @@ export class SeasonPeriodDataController {
|
|||
}
|
||||
|
||||
// pemisahan update data dengan update items dikarenakan payload (based on tampilan) berbeda
|
||||
// TODO => simpan OTP update yang disikim dari request ini
|
||||
@Put(':id/items')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async updateItems(
|
||||
@Param('id') dataId: string,
|
||||
@Body() data: UpdateSeasonPeriodItemDto,
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { IsString, ValidateIf } from 'class-validator';
|
||||
|
||||
export class OtpVerifyDto {
|
||||
@ApiProperty({
|
||||
|
@ -9,6 +9,6 @@ export class OtpVerifyDto {
|
|||
example: '2345',
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ValidateIf((body) => body.otp_code)
|
||||
otp_code: string;
|
||||
}
|
||||
|
|
|
@ -19,13 +19,13 @@ import { BatchCancelReconciliationManager } from './domain/usecases/managers/bat
|
|||
import { BatchConfirmReconciliationManager } from './domain/usecases/managers/batch-confirm-reconciliation.manager';
|
||||
import { RecapReconciliationManager } from './domain/usecases/managers/recap-reconciliation.manager';
|
||||
import { RecapPosTransactionHandler } from './domain/usecases/handlers/recap-pos-transaction.handler';
|
||||
import { SalesPriceFormulaDataService } from '../sales-price-formula/data/services/sales-price-formula-data.service';
|
||||
|
||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
TypeOrmModule.forFeature([TransactionModel], CONNECTION_NAME.DEFAULT),
|
||||
CqrsModule,
|
||||
CouchModule,
|
||||
],
|
||||
controllers: [ReconciliationDataController, ReconciliationReadController],
|
||||
providers: [
|
||||
|
|
|
@ -31,6 +31,10 @@ export class DetailRefundManager extends BaseDetailManager<RefundEntity> {
|
|||
'items.bundling_items',
|
||||
'items.refunds item_refunds',
|
||||
'item_refunds.refund item_refunds_refund',
|
||||
|
||||
'transaction.items transaction_items',
|
||||
'transaction_items.item transaction_items_item',
|
||||
'transaction_items_item.time_group transaction_items_item_time_group',
|
||||
],
|
||||
|
||||
// relation yang hanya ingin dihitung (akan return number)
|
||||
|
@ -65,6 +69,10 @@ export class DetailRefundManager extends BaseDetailManager<RefundEntity> {
|
|||
'item_refunds',
|
||||
'item_refunds_refund.id',
|
||||
'item_refunds_refund.status',
|
||||
|
||||
'transaction_items',
|
||||
'transaction_items_item',
|
||||
'transaction_items_item_time_group',
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
@ -23,7 +23,7 @@ import { CancelRefundManager } from './domain/usecases/managers/cancel-refund.ma
|
|||
import { RefundItemModel } from './data/models/refund-item.model';
|
||||
import { TransactionDataService } from '../transaction/data/services/transaction-data.service';
|
||||
import { TransactionModel } from '../transaction/data/models/transaction.model';
|
||||
|
||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
|
@ -32,6 +32,7 @@ import { TransactionModel } from '../transaction/data/models/transaction.model';
|
|||
CONNECTION_NAME.DEFAULT,
|
||||
),
|
||||
CqrsModule,
|
||||
CouchModule,
|
||||
],
|
||||
controllers: [RefundDataController, RefundReadController],
|
||||
providers: [
|
||||
|
|
|
@ -4,12 +4,14 @@ import { InjectRepository } from '@nestjs/typeorm';
|
|||
import { TransactionModel } from '../models/transaction.model';
|
||||
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CouchService } from 'src/modules/configuration/couch/data/services/couch.service';
|
||||
|
||||
@Injectable()
|
||||
export class TransactionDataService extends BaseDataService<TransactionModel> {
|
||||
constructor(
|
||||
@InjectRepository(TransactionModel, CONNECTION_NAME.DEFAULT)
|
||||
private repo: Repository<TransactionModel>,
|
||||
private couchService: CouchService,
|
||||
) {
|
||||
super(repo);
|
||||
}
|
||||
|
@ -20,4 +22,14 @@ export class TransactionDataService extends BaseDataService<TransactionModel> {
|
|||
where: { id: booking_id },
|
||||
});
|
||||
}
|
||||
|
||||
async saveTransactionToCouch(transaction) {
|
||||
const id = transaction.id ?? transaction._id;
|
||||
const couchData = await this.couchService.getDoc(id, 'transaction');
|
||||
if (!couchData) {
|
||||
await this.couchService.createDoc(transaction, 'transaction');
|
||||
} else {
|
||||
await this.couchService.updateDoc(transaction, 'transaction');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,4 +30,64 @@ export class TransactionReadService extends BaseReadService<TransactionEntity> {
|
|||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
async getSummary(posId: string, startDate: string) {
|
||||
const query = `select payment_type_counter, payment_type_method_name, sum(payment_total) payment_total, sum(payment_total_pay) payment_total_pay
|
||||
from transactions t
|
||||
where 1=1
|
||||
and t.creator_counter_no IN (${posId})
|
||||
and invoice_date = '${startDate}'
|
||||
and status = 'settled'
|
||||
group by payment_type_counter, payment_type_method_name;`;
|
||||
const transactions = await this.repo.query(query);
|
||||
|
||||
const qtyQuery = `select ti.item_id, ti.item_name, sum(ti.qty) total_qty, count(ti.item_name), sum(ti.qty), string_agg(distinct ti.item_price::text, '') price,
|
||||
sum(payment_total) payment_total, sum(payment_total_pay) payment_total_pay
|
||||
from transactions t
|
||||
inner join transaction_items ti on t.id = ti.transaction_id
|
||||
where t.creator_counter_no IN (${posId})
|
||||
and invoice_date = '${startDate}'
|
||||
and t.status = 'settled'
|
||||
group by ti.item_name, ti.item_id`;
|
||||
const qtyTransactions = await this.repo.query(qtyQuery);
|
||||
|
||||
const totalSalesQuery = `select sum(payment_total) payment_total
|
||||
from transactions t
|
||||
where 1=1
|
||||
and t.creator_counter_no IN (${posId})
|
||||
and invoice_date = '${startDate}'
|
||||
and status = 'settled'`;
|
||||
const totalSales = await this.repo.query(totalSalesQuery);
|
||||
|
||||
return {
|
||||
payment: transactions,
|
||||
qty: qtyTransactions,
|
||||
totalSales: totalSales?.[0]?.payment_total ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
async getLastTransactionByPos(
|
||||
posId: string,
|
||||
): Promise<TransactionEntity | null> {
|
||||
const transaction = await this.repo.findOne({
|
||||
select: [
|
||||
'id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'status',
|
||||
'invoice_code',
|
||||
'creator_counter_no',
|
||||
'invoice_date',
|
||||
'payment_total',
|
||||
],
|
||||
where: {
|
||||
creator_counter_no: parseInt(posId),
|
||||
},
|
||||
order: {
|
||||
created_at: 'DESC',
|
||||
},
|
||||
});
|
||||
|
||||
return transaction;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -77,6 +77,22 @@ export class MidtransCallbackHandler
|
|||
await whatsappService.bookingCreated(payload);
|
||||
}
|
||||
|
||||
if (
|
||||
transaction.status === STATUS.EXPIRED &&
|
||||
transaction.type === TransactionType.ONLINE
|
||||
) {
|
||||
const whatsappService = new WhatsappService();
|
||||
const formattedDate = moment(transaction.booking_date);
|
||||
const payload = {
|
||||
id: transaction.id,
|
||||
phone: transaction.customer_phone,
|
||||
code: transaction.invoice_code,
|
||||
name: transaction.customer_name,
|
||||
time: formattedDate.valueOf(),
|
||||
};
|
||||
await whatsappService.bookingExpired(payload);
|
||||
}
|
||||
|
||||
this.eventBus.publish(
|
||||
new TransactionChangeStatusEvent({
|
||||
id: data_id,
|
||||
|
|
|
@ -31,6 +31,9 @@ export class DetailTransactionManager extends BaseDetailManager<TransactionEntit
|
|||
'items.refunds item_refunds',
|
||||
'item_refunds.refund item_refunds_refund',
|
||||
'refunds',
|
||||
|
||||
'items.item items_item',
|
||||
'items_item.time_group items_item_time_group',
|
||||
],
|
||||
|
||||
// relation yang hanya ingin dihitung (akan return number)
|
||||
|
@ -92,6 +95,8 @@ export class DetailTransactionManager extends BaseDetailManager<TransactionEntit
|
|||
'item_refunds_refund.status',
|
||||
|
||||
'refunds',
|
||||
'items_item',
|
||||
'items_item_time_group',
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
@ -43,6 +43,8 @@ export function mappingTransaction(data, refundId?: string) {
|
|||
if (refundId)
|
||||
refund = itemData.refunds?.find((item) => item.refund.id == refundId);
|
||||
|
||||
const timeGroup = itemData?.item?.time_group;
|
||||
|
||||
return {
|
||||
item: {
|
||||
id: itemData.item_id,
|
||||
|
@ -57,6 +59,7 @@ export function mappingTransaction(data, refundId?: string) {
|
|||
},
|
||||
breakdown_bundling: itemData.breakdown_bundling,
|
||||
bundling_items: itemData.bundling_items,
|
||||
time_group: timeGroup,
|
||||
},
|
||||
id: itemData.id,
|
||||
refund: refund,
|
||||
|
|
|
@ -141,4 +141,10 @@ export class TransactionDataOrchestrator {
|
|||
await this.batchConfirmDataManager.execute();
|
||||
return this.batchConfirmDataManager.getResult();
|
||||
}
|
||||
|
||||
async saveTransactionToCouch(transaction: any[]) {
|
||||
for (const t of transaction) {
|
||||
await this.serviceData.saveTransactionToCouch(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,6 +7,8 @@ import { BaseReadOrchestrator } from 'src/core/modules/domain/usecase/orchestrat
|
|||
import { DetailTransactionManager } from './managers/detail-transaction.manager';
|
||||
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
|
||||
import { PriceCalculator } from './calculator/price.calculator';
|
||||
import { In } from 'typeorm';
|
||||
import * as moment from 'moment';
|
||||
|
||||
@Injectable()
|
||||
export class TransactionReadOrchestrator extends BaseReadOrchestrator<TransactionEntity> {
|
||||
|
@ -26,6 +28,16 @@ export class TransactionReadOrchestrator extends BaseReadOrchestrator<Transactio
|
|||
return this.indexManager.getResult();
|
||||
}
|
||||
|
||||
async summary(posId: string) {
|
||||
const today = moment().format('YYYY-MM-DD');
|
||||
const summary = await this.serviceData.getSummary(posId, today);
|
||||
const lastTransaction = await this.serviceData.getLastTransactionByPos(
|
||||
posId,
|
||||
);
|
||||
|
||||
return { summary, lastTransaction };
|
||||
}
|
||||
|
||||
async detail(dataId: string): Promise<TransactionEntity> {
|
||||
this.detailManager.setData(dataId);
|
||||
this.detailManager.setService(this.serviceData, TABLE_NAME.TRANSACTION);
|
||||
|
@ -50,17 +62,24 @@ export class TransactionReadOrchestrator extends BaseReadOrchestrator<Transactio
|
|||
transaction.payment_total_dpp = price.dpp_value;
|
||||
transaction.payment_total_share = price.other.total_profit_share;
|
||||
transaction.payment_total_tax = price.other.payment_total_tax;
|
||||
console.log({ price }, transaction.payment_total);
|
||||
console.log(transaction.id);
|
||||
await this.serviceData.getRepository().save(transaction);
|
||||
}
|
||||
|
||||
ids = [];
|
||||
|
||||
async calculatePrice(): Promise<void> {
|
||||
const transactions = await this.serviceData.getManyByOptions({
|
||||
where: {
|
||||
is_recap_transaction: false,
|
||||
// is_recap_transaction: false,
|
||||
id: In(this.ids),
|
||||
},
|
||||
relations: ['items', 'items.bundling_items'],
|
||||
});
|
||||
|
||||
console.log(transactions.length);
|
||||
// return;
|
||||
|
||||
for (const transaction of transactions) {
|
||||
try {
|
||||
const price = await this.calculator.calculate(transaction);
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
|
@ -7,17 +8,20 @@ import {
|
|||
Post,
|
||||
Put,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { TransactionDataOrchestrator } from '../domain/usecases/transaction-data.orchestrator';
|
||||
import { TransactionDto } from './dto/transaction.dto';
|
||||
import { MODULE_NAME } from 'src/core/strings/constants/module.constants';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { ApiBearerAuth, ApiBody, ApiTags } from '@nestjs/swagger';
|
||||
import { TransactionEntity } from '../domain/entities/transaction.entity';
|
||||
import { BatchResult } from 'src/core/response/domain/ok-response.interface';
|
||||
import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto';
|
||||
import { Public } from 'src/core/guards';
|
||||
import { DownloadPdfDto } from './dto/donwload-pdf.dto';
|
||||
import { OtpAuthGuard } from 'src/modules/configuration/otp-verification/infrastructure/guards/otp-auth.guard';
|
||||
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
|
||||
|
||||
@ApiTags(`${MODULE_NAME.TRANSACTION.split('-').join(' ')} - data`)
|
||||
@Controller(`v1/${MODULE_NAME.TRANSACTION}`)
|
||||
|
@ -50,6 +54,7 @@ export class TransactionDataController {
|
|||
}
|
||||
|
||||
@Patch(':id/confirm-data')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async confirmData(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.confirmData(dataId);
|
||||
}
|
||||
|
@ -60,6 +65,7 @@ export class TransactionDataController {
|
|||
}
|
||||
|
||||
@Patch(':id/confirm')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.confirm(dataId);
|
||||
}
|
||||
|
@ -91,4 +97,29 @@ export class TransactionDataController {
|
|||
async delete(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.delete(dataId);
|
||||
}
|
||||
|
||||
@Post('save-to-couch')
|
||||
@ApiBody({
|
||||
schema: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
},
|
||||
},
|
||||
})
|
||||
@Public(true)
|
||||
// @UseGuards(OtpAuthGuard)
|
||||
async saveToCouch(@Body() body: any[]) {
|
||||
try {
|
||||
await this.orchestrator.saveTransactionToCouch(body);
|
||||
return {
|
||||
message: 'Success',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new BadRequestException({
|
||||
message: error.message,
|
||||
error: error.stack,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -28,6 +28,12 @@ export class TransactionReadController {
|
|||
return await this.orchestrator.detail(id);
|
||||
}
|
||||
|
||||
@Public(true)
|
||||
@Get('summary/:posId')
|
||||
async summary(@Param('posId') posId: string) {
|
||||
return await this.orchestrator.summary(posId);
|
||||
}
|
||||
|
||||
@Public(true)
|
||||
@Get('dummy/:id')
|
||||
async calculate(@Param('id') id: string): Promise<string> {
|
||||
|
|
|
@ -47,6 +47,9 @@ import { TransactionDemographyModel } from './data/models/transaction-demography
|
|||
import { PriceCalculator } from './domain/usecases/calculator/price.calculator';
|
||||
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';
|
||||
import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
||||
import { JWT_EXPIRED } from 'src/core/sessions/constants';
|
||||
import { JWT_SECRET } from 'src/core/sessions/constants';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
@Module({
|
||||
exports: [
|
||||
|
@ -56,6 +59,10 @@ import { CouchModule } from 'src/modules/configuration/couch/couch.module';
|
|||
],
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
JwtModule.register({
|
||||
secret: JWT_SECRET,
|
||||
signOptions: { expiresIn: JWT_EXPIRED },
|
||||
}),
|
||||
TypeOrmModule.forFeature(
|
||||
[
|
||||
TransactionModel,
|
||||
|
|
|
@ -6,6 +6,7 @@ import {
|
|||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UserDataOrchestrator } from '../domain/usecases/user-data.orchestrator';
|
||||
import { UserDto } from './dto/user.dto';
|
||||
|
@ -17,6 +18,7 @@ import { BatchIdsDto } from 'src/core/modules/infrastructure/dto/base-batch.dto'
|
|||
import { Public } from 'src/core/guards';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { UpdatePasswordUserDto } from './dto/update-password-user.dto';
|
||||
import { OtpCheckerGuard } from 'src/core/guards/domain/otp-checker.guard';
|
||||
|
||||
@ApiTags(`${MODULE_NAME.USER.split('-').join(' ')} - data`)
|
||||
@Controller(`v1/${MODULE_NAME.USER}`)
|
||||
|
@ -36,6 +38,7 @@ export class UserDataController {
|
|||
}
|
||||
|
||||
@Patch(':id/active')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async active(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.active(dataId);
|
||||
}
|
||||
|
@ -46,6 +49,7 @@ export class UserDataController {
|
|||
}
|
||||
|
||||
@Patch(':id/confirm')
|
||||
@UseGuards(OtpCheckerGuard)
|
||||
async confirm(@Param('id') dataId: string): Promise<string> {
|
||||
return await this.orchestrator.confirm(dataId);
|
||||
}
|
||||
|
|
|
@ -198,6 +198,57 @@ export class WhatsappService {
|
|||
);
|
||||
}
|
||||
|
||||
async bookingExpired(data: WhatsappBookingCreate) {
|
||||
const momentDate = moment(data.time);
|
||||
const fallbackValue = momentDate.locale('id').format('dddd, DD MMMM YYYY');
|
||||
// const dayOfWeek = momentDate.day();
|
||||
// const dayOfMonth = momentDate.date();
|
||||
// const year = momentDate.year();
|
||||
// const month = momentDate.month() + 1;
|
||||
// const hour = momentDate.hour();
|
||||
// const minute = momentDate.minute();
|
||||
|
||||
const payload = {
|
||||
messaging_product: 'whatsapp',
|
||||
to: phoneNumberOnly(data.phone), // recipient's phone number
|
||||
type: 'template',
|
||||
template: {
|
||||
name: 'booking_expired',
|
||||
language: {
|
||||
code: 'id', // language code
|
||||
},
|
||||
components: [
|
||||
{
|
||||
type: 'body',
|
||||
parameters: [
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'customer',
|
||||
text: data.name, // replace with name variable
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'code',
|
||||
text: data.code, // replace with queue_code variable
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
parameter_name: 'booking_date',
|
||||
text: fallbackValue,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const response = await this.sendMessage(payload);
|
||||
if (response)
|
||||
Logger.log(
|
||||
`Notification register Booking for ${data.code} send to ${data.phone}`,
|
||||
);
|
||||
}
|
||||
|
||||
async rescheduleCreated(data: WhatsappBookingCreate) {
|
||||
const imageUrl = `${BOOKING_QR_URL}${data.id}`;
|
||||
|
||||
|
@ -429,6 +480,22 @@ export class WhatsappService {
|
|||
}
|
||||
}
|
||||
|
||||
async sendTemplateMessage(data: { phone: string; templateMsg: any }) {
|
||||
const payload = {
|
||||
messaging_product: 'whatsapp',
|
||||
to: data.phone,
|
||||
type: 'template',
|
||||
template: data?.templateMsg,
|
||||
};
|
||||
|
||||
const response = await this.sendMessage(payload);
|
||||
if (response) {
|
||||
Logger.log(
|
||||
`OTP notification for template ${data.templateMsg} sent to ${data.phone}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async queueProcess(data: WhatsappQueue) {
|
||||
const queueUrl = `${WHATSAPP_BUSINESS_QUEUE_URL}?id=${data.id}`;
|
||||
const payload = {
|
||||
|
|
Loading…
Reference in New Issue