Untitled
unknown
plain_text
23 days ago
15 kB
2
Indexable
Never
async function GetBankAdvice( req: Request, model: GetBankAdviceModel ): Promise<ServiceResponse<BankAdviceModel[]>> { try { const token = req.headers.authorization?.split(" ")[1]; const key = process.env.TOKEN_SECRET; const decode = jwt.verify(token, key); const userId = decode.userId; const startDate = model.startDate; const endDate = model.endDate; const bmcId = model.bmcId; const milkCollections = await AppDataSource.getRepository( entities.MilkCollections ) .createQueryBuilder("milkCollections") .where("DATE(milkCollections.CollectionDateTime) >= :startDate", { startDate, }) .andWhere("DATE(milkCollections.CollectionDateTime) <= :endDate", { endDate, }) .andWhere("milkCollections.IsActive = :isActive", { isActive: true }) .getMany(); const milkCollectionIds = milkCollections.map((milk) => milk.Id); if (milkCollectionIds.length === 0) { return { status: 200, message: ERROR_MESSAGES.NO_DATA, data: null, }; } const bmc = await AppDataSource.getRepository(entities.Organization) .createQueryBuilder("organization") .innerJoinAndSelect("organization.OrganizationType", "organizationType") .where("organization.Id =:id", { id: bmcId }) .andWhere("organization.IsActive =:cond", { cond: true }) .andWhere("organizationType.Id =:bmcid", { bmcid: 4 }) .getOne(); if (!bmc) { return { status: 200, message: ERROR_MESSAGES.NO_DATA, data: null, }; } const collectionDetails = await AppDataSource.getRepository( entities.MilkCollectionDetails ) .createQueryBuilder("milkCollectionDetails") .leftJoinAndSelect( "milkCollectionDetails.OrganizationUnitId", "organization" ) .leftJoinAndSelect("organization.ParentId", "organizationParent") .leftJoinAndSelect("organization.OrganizationType", "organizationType") .leftJoinAndSelect( "milkCollectionDetails.MilkCollectionId", "collections" ) .leftJoinAndSelect("milkCollectionDetails.RouteId", "route") .leftJoinAndSelect("route.RouteOwner", "routeOwner") .where( "milkCollectionDetails.MilkCollectionId IN (:...milkCollectionIds)", { milkCollectionIds } ) .andWhere("milkCollectionDetails.IsActive = :isActive", { isActive: true, }) .andWhere("organizationType.Id = :id", { id: 5 }) .andWhere("milkCollectionDetails.Fat IS NOT NULL") .andWhere("milkCollectionDetails.Snf IS NOT NULL") .andWhere("milkCollectionDetails.Clr IS NOT NULL") .andWhere("organizationParent.Id =:bmcid", { bmcid: bmc.Id }) .orderBy("milkCollectionDetails.RouteId") .getMany(); const rateMaster = await AppDataSource.getRepository(entities.RateMaster) .createQueryBuilder("ratemaster") .where("ratemaster.Wef < :currDate", { currDate: new Date() }) .orderBy("ratemaster.SeqNo", "ASC") .getMany(); if (rateMaster.length === 0) { return { status: 200, message: ERROR_MESSAGES.NO_DATA, data: null, }; } const productsSoldToAgent = await AppDataSource.getRepository( entities.ProductSalesToAgent ) .createQueryBuilder("productSalesToAgent") .leftJoinAndSelect("productSalesToAgent.SoldToAgent", "agent") .leftJoinAndSelect("agent.ParentId", "parent") .where("DATE(productSalesToAgent.CreatedAt) >= :startDate", { startDate: model.startDate, }) .andWhere("DATE(productSalesToAgent.CreatedAt) <= :endDate", { endDate: model.endDate, }) .getMany(); const complaints = await AppDataSource.getRepository(entities.Complaints) .createQueryBuilder("complaints") .leftJoinAndSelect("complaints.AgentId", "agent") .where("agent.ParentId =:bmcId", { bmcId: bmcId }) .andWhere("DATE(complaints.TobeSettledStartDate) =:startDate", { startDate: model.startDate, }) .andWhere("DATE(complaints.TobeSettledEndDate) =:endDate", { endDate: model.endDate, }) .getMany(); const dueAmountDetails = await AppDataSource.getRepository( entities.ProductAmountDue ) .createQueryBuilder("dueAmount") .leftJoinAndSelect("dueAmount.AgentId", "agent") .where("DATE(dueAmount.cycle_start_date) >= :startDate", { startDate: model.startDate, }) .andWhere("DATE(dueAmount.cycle_end_date) <= :endDate", { endDate: model.endDate, }) .getMany(); const aggregatedData: Record< string, { MilkType: string; Fat: number; Snf: number; Clr: number; Weight: number; CollectedAt: Date; OrganizationUnitId: entities.Organization; MilkCollectionId: entities.MilkCollections; RouteId: entities.RouteMaster; KGFat: number; KGSnf: number; count: number; } > = {}; collectionDetails.forEach((item: entities.MilkCollectionDetails) => { const key = `${moment(item.MilkCollectionId.CollectionDateTime).format( "YYYY-MM-DD" )}-${item.MilkType}-${item.OrganizationUnitId.Id}-${ item.MilkCollectionId.Shift }`; if (!aggregatedData[key]) { aggregatedData[key] = { MilkType: item.MilkType, Fat: item.Fat, Snf: item.Snf, Clr: item.Clr, Weight: item.Weight, CollectedAt: item.MilkCollectionId.CollectionDateTime, OrganizationUnitId: item.OrganizationUnitId, MilkCollectionId: item.MilkCollectionId, RouteId: item.RouteId, KGFat: (item.Weight / 100) * item.Fat, KGSnf: (item.Weight / 100) * item.Snf, count: 1, }; } else { aggregatedData[key].Weight += item.Weight; aggregatedData[key].Fat += item.Fat; aggregatedData[key].Snf += item.Snf; aggregatedData[key].Clr += item.Clr; aggregatedData[key].KGFat += (item.Weight / 100) * item.Fat; aggregatedData[key].KGSnf += (item.Weight / 100) * item.Snf; aggregatedData[key].count++; } }); const milkCollectionDetails = Object.values(aggregatedData).map((item) => { const resultItem = { ...item, }; if (item.count === 1) { resultItem.Fat = item.Fat; resultItem.Snf = item.Snf; resultItem.Clr = item.Clr; } else { resultItem.Fat = (item.KGFat / item.Weight) * 100; resultItem.Snf = (item.KGSnf / item.Weight) * 100; // console.log(item.KGFat.toFixed(2), " ", item.KGSnf, " ", "details : ", item.Weight, " ", parseFloat(((item.KGFat / item.Weight) * 100).toFixed(1)), " ", (item.KGSnf / item.Weight) * 100) resultItem.Clr = item.Clr / item.count; } return resultItem; }); if (milkCollectionDetails.length === 0) { return { status: 200, message: ERROR_MESSAGES.NO_DATA, data: null, }; } let orgArr: any[] = []; for (let iter = 0; iter < milkCollectionDetails.length; iter++) { if (!orgArr.includes(milkCollectionDetails[iter].OrganizationUnitId.Id)) { orgArr.push(milkCollectionDetails[iter].OrganizationUnitId.Id); } } const org: any = []; for (let iteration = 0; iteration < orgArr.length; iteration++) { const route: any[] = []; for ( let routeIteration = 0; routeIteration < milkCollectionDetails.length; routeIteration++ ) { if ( orgArr[iteration] === milkCollectionDetails[routeIteration].OrganizationUnitId.Id ) { const item = { id: milkCollectionDetails[routeIteration]?.OrganizationUnitId.Id, name: milkCollectionDetails[routeIteration]?.OrganizationUnitId .Name, headload: milkCollectionDetails[routeIteration]?.OrganizationUnitId .HeadLoad, commision: milkCollectionDetails[routeIteration]?.OrganizationUnitId .Commission, routeId: milkCollectionDetails[routeIteration]?.RouteId.Id, accountNumber: milkCollectionDetails[routeIteration]?.OrganizationUnitId .AccountNumber, routeName: milkCollectionDetails[routeIteration]?.RouteId.RouteName, ifscCode: milkCollectionDetails[routeIteration]?.OrganizationUnitId .IfscCode, accHolderName: milkCollectionDetails[routeIteration]?.OrganizationUnitId .AccHolderName, collectionDetails: [], }; if ( !route.some((ele) => { return ele.id === item.id && ele.routeId === item.routeId; }) ) { route.push(item); } } } org.push({ org: orgArr[iteration], route }); } for (let orgIteration = 0; orgIteration < org.length; orgIteration++) { for ( let routeIteration = 0; routeIteration < org[orgIteration].route.length; routeIteration++ ) { milkCollectionDetails.forEach((milkDetail) => { const item = { id: milkDetail.OrganizationUnitId.Id, routeId: milkDetail.RouteId.Id, }; if ( org[orgIteration].route[routeIteration]?.id === item.id && org[orgIteration].route[routeIteration]?.routeId === item.routeId ) { org[orgIteration].route[routeIteration]?.collectionDetails.push( milkDetail ); } }); } } const data: BankAdviceModel[] = []; let earning = 0; let id; let totalAmountDetails: any[] = []; function getDueAmountById(id: number): number | null { const obj = dueAmountDetails.find( (item: any) => item?.AgentId?.Id === id ); return obj ? obj.DueAmount : null; } for (let orgIteration = 0; orgIteration < org.length; orgIteration++) { let totalAmount = 0; let deduction = 0; for (let i = 0; i < productsSoldToAgent.length; i++) { // console.log(org[orgIteration].org,deduction,productsSoldToAgent[i].SoldToAgent?.Id ); if (productsSoldToAgent[i].SoldToAgent?.Id == org[orgIteration].org) { deduction += productsSoldToAgent[i].Balance; totalAmount = totalAmount - deduction; } // console.log('id:',productsSoldToAgent[i].SoldToAgent?.Id,'Due:',productsSoldToAgent[i].Balance); } let settlementAmount = 0; complaints.forEach((complaint) => { if (complaint.AgentId.Id === org[orgIteration].org) { settlementAmount = complaint.SettlementAmount; } }); for ( let routeIteration = 0; routeIteration < org[orgIteration].route.length; routeIteration++ ) { let kgFat = 0; let kgSnf = 0; const details = org[orgIteration].route[routeIteration].collectionDetails; details.forEach((detail: any) => { kgFat += (detail.Weight.toFixed(1) / 100) * detail.Fat.toFixed(1); kgSnf += (detail.Weight.toFixed(1) / 100) * detail.Snf.toFixed(1); totalAmount += Number( calculateValue( detail.Fat.toFixed(1), detail.Snf.toFixed(1), rateMaster ) * detail.Weight.toFixed(1) ); }); // if (productsSoldToAgent.length) { // for (let i = 0; i < productsSoldToAgent.length; i++) { // if ( // productsSoldToAgent[i].SoldToAgent?.Id == org[orgIteration].org // ) { // deduction = productsSoldToAgent[i]?.Balance; // } // } // } earning = parseInt( ( ((kgFat + kgSnf) / 12) * 100 * org[orgIteration].route[routeIteration].headload ).toFixed(2) ) + parseInt( ( ((kgFat + kgSnf) / 12) * 100 * org[orgIteration].route[routeIteration]?.commision ).toFixed(2) ); let prevtotal = totalAmount; let dueamount: any | null = getDueAmountById(org[orgIteration].org); totalAmount = totalAmount + earning + settlementAmount; if (getDueAmountById(org[orgIteration].org) !== null) { totalAmount = totalAmount - dueamount; } // console.log('______________________________________') // console.log('Id: ',org[orgIteration].org ); // console.log('Due Amount: ',getDueAmountById(org[orgIteration].org) ); // console.log('total amount : ', totalAmount ,"( ( prevTotal :",prevtotal, "- deduction :", deduction,") + Earning :" ,earning ,"+ settlement :",settlementAmount,")"); // console.log('earning : ', earning); // console.log('deduction : ', deduction); // console.log('settlement amount', totalAmount); // console.log('______________________________________') const item: BankAdviceModel = { organization: { id: org[orgIteration].route[routeIteration].id, name: org[orgIteration].route[routeIteration].name, accHolderName: org[orgIteration].route[routeIteration]?.accHolderName, ifscCode: org[orgIteration].route[routeIteration]?.ifscCode, accNumber: org[orgIteration].route[routeIteration]?.accountNumber, routeName: org[orgIteration].route[routeIteration].routeName, }, amount: totalAmount, }; data.push(item); } } // console.log(data); return { status: 200, message: SUCCESS_MESSAGES.SUCCESS, data, }; } catch (error) { console.log(error); return { status: 400, message: ERROR_MESSAGES.INTERNAL_SERVER, data: null, }; } }
Leave a Comment