made the function to create ref number of activity and commented the unused api code

This commit is contained in:
2026-02-27 12:15:48 +05:30
parent 2b7b2b240f
commit 85437ebc2e
2 changed files with 158 additions and 93 deletions

View File

@@ -1,50 +1,50 @@
import { verifyHostToken } from '../../../../../common/middlewares/jwt/authForHost';
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
import { prismaClient } from '../../../../../common/database/prisma.lambda.service';
import { safeHandler } from '../../../../../common/utils/handlers/safeHandler';
import ApiError from '../../../../../common/utils/helper/ApiError';
import { HostService } from '../../../services/host.service';
// import { verifyHostToken } from '../../../../../common/middlewares/jwt/authForHost';
// import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
// import { prismaClient } from '../../../../../common/database/prisma.lambda.service';
// import { safeHandler } from '../../../../../common/utils/handlers/safeHandler';
// import ApiError from '../../../../../common/utils/helper/ApiError';
// import { HostService } from '../../../services/host.service';
const hostService = new HostService(prismaClient);
// const hostService = new HostService(prismaClient);
export const handler = safeHandler(async (
event: APIGatewayProxyEvent,
context?: Context
): Promise<APIGatewayProxyResult> => {
const token = event.headers['x-auth-token'] || event.headers['X-Auth-Token'];
if (!token) throw new ApiError(401, 'This is a protected route. Please provide a valid token.');
// export const handler = safeHandler(async (
// event: APIGatewayProxyEvent,
// context?: Context
// ): Promise<APIGatewayProxyResult> => {
// const token = event.headers['x-auth-token'] || event.headers['X-Auth-Token'];
// if (!token) throw new ApiError(401, 'This is a protected route. Please provide a valid token.');
const userInfo = await verifyHostToken(token);
// const userInfo = await verifyHostToken(token);
let body: any = {};
try {
body = event.body ? JSON.parse(event.body) : {};
} catch (err) {
throw new ApiError(400, 'Invalid JSON in request body');
}
// let body: any = {};
// try {
// body = event.body ? JSON.parse(event.body) : {};
// } catch (err) {
// throw new ApiError(400, 'Invalid JSON in request body');
// }
const { activityTypeXid, frequenciesXid } = body;
// const { activityTypeXid, frequenciesXid } = body;
if (!activityTypeXid) {
throw new ApiError(400, 'activityTypeXid is required');
}
// if (!activityTypeXid) {
// throw new ApiError(400, 'activityTypeXid is required');
// }
await hostService.createActivity(
userInfo.id,
Number(activityTypeXid),
frequenciesXid ? Number(frequenciesXid) : undefined,
);
// await hostService.createActivity(
// userInfo.id,
// Number(activityTypeXid),
// frequenciesXid ? Number(frequenciesXid) : undefined,
// );
return {
statusCode: 201,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
success: true,
message: 'Activity created successfully',
data: null,
}),
};
});
// return {
// statusCode: 201,
// headers: {
// 'Content-Type': 'application/json',
// 'Access-Control-Allow-Origin': '*',
// },
// body: JSON.stringify({
// success: true,
// message: 'Activity created successfully',
// data: null,
// }),
// };
// });

View File

@@ -58,20 +58,85 @@ interface HostDocumentInput {
documentName: string;
filePath: string; // S3 URL
}
export async function generateActivityRefNumber(tx: any) {
const lastrecord = await tx.activities.findFirst({
orderBy: {
id: 'desc',
},
select: {
id: true,
export async function generateActivityRefNumber(
tx: any,
hostXid: number,
activityTypeXid: number
) {
// 1⃣ Get ActivityType with Interest
const activityType = await tx.activityTypes.findUnique({
where: { id: activityTypeXid },
include: {
interest: true,
},
});
const nextId = lastrecord ? lastrecord.id + 1 : 1;
if (!activityType || !activityType.interest) {
throw new Error("Invalid activity type or interest not found");
}
return `ACT-${String(nextId).padStart(6, '0')}`;
const interestId = activityType.interest.id;
const interestCode = activityType.interest.interestCode;
// 2⃣ Check if this host already has activities under this interest
const existingActivityForInterest = await tx.activities.findFirst({
where: {
hostXid,
activityType: {
interestId: interestId,
},
},
select: {
activityRefNumber: true,
},
});
let interestSequence: number;
if (existingActivityForInterest?.activityRefNumber) {
// Extract existing interest sequence from ref number
const match =
existingActivityForInterest.activityRefNumber.match(
new RegExp(`E-${interestCode}(\\d{3})-`)
);
interestSequence = match ? parseInt(match[1], 10) : 1;
} else {
// Count distinct interests already used by this host
const distinctInterests = await tx.activities.findMany({
where: { hostXid },
include: {
activityType: {
select: {
interestId: true,
},
},
},
});
const uniqueInterestIds = new Set(
distinctInterests.map((a: any) => a.activityType.interestId)
);
interestSequence = uniqueInterestIds.size + 1;
}
// 3⃣ Count activities for same host + same interest + same activityType
const activityTypeCount = await tx.activities.count({
where: {
hostXid,
activityTypeXid,
},
});
const nextActivityTypeSequence = activityTypeCount + 1;
return `E-${interestCode}${String(interestSequence).padStart(
3,
"0"
)}-${String(nextActivityTypeSequence).padStart(2, "0")}`;
}
function round2(value: number) {
return Math.round(value);
@@ -2645,52 +2710,52 @@ export class HostService {
return activity;
}
async createActivity(
userId: number,
activityTypeXid: number,
frequenciesXid?: number,
) {
return await this.prisma.$transaction(async (tx) => {
// Fetch host
const host = await tx.hostHeader.findFirst({
where: { userXid: userId, isActive: true },
});
if (!host) throw new ApiError(404, 'Host not found for the user');
// async createActivity(
// userId: number,
// activityTypeXid: number,
// frequenciesXid?: number,
// ) {
// return await this.prisma.$transaction(async (tx) => {
// // Fetch host
// const host = await tx.hostHeader.findFirst({
// where: { userXid: userId, isActive: true },
// });
// if (!host) throw new ApiError(404, 'Host not found for the user');
// Validate activityType
const activityType = await tx.activityTypes.findUnique({
where: { id: activityTypeXid },
});
if (!activityType) throw new ApiError(404, 'Activity type not found');
// // Validate activityType
// const activityType = await tx.activityTypes.findUnique({
// where: { id: activityTypeXid },
// });
// if (!activityType) throw new ApiError(404, 'Activity type not found');
// Validate frequency
if (frequenciesXid) {
const freq = await tx.frequencies.findUnique({
where: { id: frequenciesXid },
});
if (!freq) throw new ApiError(404, 'Frequency not found');
}
// // Validate frequency
// if (frequenciesXid) {
// const freq = await tx.frequencies.findUnique({
// where: { id: frequenciesXid },
// });
// if (!freq) throw new ApiError(404, 'Frequency not found');
// }
// Generate reference number
const referenceNumber = await generateActivityRefNumber(tx);
// // Generate reference number
// const referenceNumber = await generateActivityRefNumber(tx);
// Create activity
const created = await tx.activities.create({
data: {
hostXid: host.id,
activityTypeXid,
frequenciesXid: frequenciesXid || null,
activityInternalStatus: ACTIVITY_INTERNAL_STATUS.DRAFT_PQ,
activityDisplayStatus: ACTIVITY_DISPLAY_STATUS.DRAFT_PQ,
amInternalStatus: ACTIVITY_AM_INTERNAL_STATUS.DRAFT_PQ,
amDisplayStatus: ACTIVITY_AM_DISPLAY_STATUS.DRAFT_PQ,
activityRefNumber: referenceNumber,
},
});
// // Create activity
// const created = await tx.activities.create({
// data: {
// hostXid: host.id,
// activityTypeXid,
// frequenciesXid: frequenciesXid || null,
// activityInternalStatus: ACTIVITY_INTERNAL_STATUS.DRAFT_PQ,
// activityDisplayStatus: ACTIVITY_DISPLAY_STATUS.DRAFT_PQ,
// amInternalStatus: ACTIVITY_AM_INTERNAL_STATUS.DRAFT_PQ,
// amDisplayStatus: ACTIVITY_AM_DISPLAY_STATUS.DRAFT_PQ,
// activityRefNumber: referenceNumber,
// },
// });
return created;
});
}
// return created;
// });
// }
async createActivityAndAllQuestionsEntry(
userId: number,
@@ -2715,7 +2780,7 @@ export class HostService {
if (!freq) throw new ApiError(404, 'Frequency not found');
}
const referenceNumber = await generateActivityRefNumber(tx);
const referenceNumber = await generateActivityRefNumber(tx, host.id, activityTypeXid);
const created = await tx.activities.create({
data: {