Exemplo n.º 1
0
        private async Task SaveResponse(PgPurchaseOrderResponse payload, Cost cost, SystemAdminUserIdentity adminUser)
        {
            var purchaseOrderData = await _customDataService
                                    .GetCustomData <PgPurchaseOrderResponse>(cost.LatestCostStageRevisionId.Value, CustomObjectDataKeys.PgPurchaseOrderResponse)
                                    ?? new PgPurchaseOrderResponse();

            _mapper.Map(payload, purchaseOrderData);
            if (string.Compare(payload.ApprovalStatus, ApprovalStatuses.Rejected, StringComparison.OrdinalIgnoreCase) == 0)
            {
                //null requisition ID should be allowed here
                purchaseOrderData.Requisition    = payload.Requisition;
                purchaseOrderData.ApprovalStatus = payload.ApprovalStatus;
            }

            await _customDataService.Save(cost.LatestCostStageRevisionId.Value, CustomObjectDataKeys.PgPurchaseOrderResponse, purchaseOrderData, adminUser);

            await UpdatePaymentDetails(cost.LatestCostStageRevisionId.Value, purchaseOrderData, adminUser);

            var logEntries = new List <IActivityLogEntry>
            {
                new PoCreated(cost.CostNumber, purchaseOrderData.PoNumber, adminUser),
                new GoodsReceiptAllocated(cost.CostNumber, purchaseOrderData.GrNumber, adminUser),
                new RequisitionNumber(cost.CostNumber, purchaseOrderData.Requisition, adminUser)
            };

            await _activityLogService.LogRange(logEntries);
        }
        public async Task UpdateLedgerMaterialCodes(Guid costStageRevisionId)
        {
            var costStageRevision = await _efContext.CostStageRevision
                                    .Include(csr => csr.StageDetails)
                                    .Include(csr => csr.ExpectedAssets)
                                    .Include(csr => csr.CostStage)
                                    .ThenInclude(cs => cs.Cost)
                                    .FirstOrDefaultAsync(csr => csr.Id == costStageRevisionId);

            var costType = costStageRevision.CostStage.Cost.CostType.ToString();

            var multipleOvalTypesOption = await _efContext.DictionaryEntry
                                          .Where(d => d.Dictionary.Name == Constants.DictionaryNames.OvalType && d.Key == MultipleOptions)
                                          .FirstAsync();

            var multipleMediaTypesOption = await _efContext.DictionaryEntry
                                           .Where(d => d.Dictionary.Name == Constants.DictionaryNames.MediaType && d.Key == MultipleOptions)
                                           .FirstAsync();

            var stageDetailsForm = JsonConvert.DeserializeObject <PgStageDetailsForm>(costStageRevision.StageDetails.Data);

            // Eligible for Production cost
            var  contentTypeId    = stageDetailsForm.ContentType?.Id;
            var  productionTypeId = stageDetailsForm.ProductionType?.Id;
            var  expectedAssets   = costStageRevision.ExpectedAssets;
            Guid?mediaTypeId      = null;
            Guid?ovalTypeId       = null;

            var mediaTypeIds = expectedAssets.Where(a => a.MediaTypeId != null).Select(a => a.MediaTypeId).Distinct().ToArray();

            if (mediaTypeIds.Length > 0)
            {
                mediaTypeId = mediaTypeIds.Length == 1 ? mediaTypeIds[0] : multipleMediaTypesOption.Id;
            }
            var ovalTypeIds = expectedAssets.Where(a => a.OvalTypeId != null).Select(a => a.OvalTypeId).Distinct().ToArray();

            if (ovalTypeIds.Length > 0)
            {
                ovalTypeId = ovalTypeIds.Length == 1 ? ovalTypeIds[0] : multipleOvalTypesOption.Id;
            }

            // Eligible for Usage/Buyout cost
            var usageTypeId = stageDetailsForm.UsageType?.Id;

            var ledgerMaterialCode = await _efContext.PgLedgerMaterialCode
                                     .OrderBy(c => c.ProductionTypeId)
                                     .FirstOrDefaultAsync(c =>
                                                          (c.CostType == costType &&
                                                           c.ContentTypeId == contentTypeId &&
                                                           c.ProductionTypeId == productionTypeId &&
                                                           c.MediaTypeId == mediaTypeId &&
                                                           c.OvalId == ovalTypeId &&
                                                           c.UsageTypeId == usageTypeId
                                                          )
                                                          ||
                                                          //Default values needed for AIPE
                                                          (costType == CostType.Production.ToString() &&
                                                           c.ContentTypeId == contentTypeId &&
                                                           c.ProductionTypeId == null &&
                                                           c.MediaTypeId == null &&
                                                           c.OvalId == null &&
                                                           c.UsageTypeId == null
                                                          )
                                                          ||
                                                          (c.CostType == CostType.Trafficking.ToString() &&
                                                           costType == CostType.Trafficking.ToString())
                                                          );

            var mgCode = ledgerMaterialCode?.MaterialGroupCode;
            var glCode = ledgerMaterialCode?.GeneralLedgerCode;

            var codeModel = new PgLedgerMaterialCodeModel {
                GlCode = glCode, MgCode = mgCode
            };

            var adminUser = await _efContext.CostUser.FirstOrDefaultAsync(u => u.Email == ApprovalMemberModel.BrandApprovalUserEmail);

            var adminUserIdentity = new SystemAdminUserIdentity(adminUser);
            await _customDataService.Save(costStageRevisionId, CustomObjectDataKeys.PgMaterialLedgerCodes, codeModel, adminUserIdentity);
        }
Exemplo n.º 3
0
        public async Task <PaymentAmountResult> CalculatePaymentAmount(Guid costStageRevisionId, bool persist = true)
        {
            var revision = await _efContext.CostStageRevision
                           .Include(csr => csr.CostFormDetails)
                           .Include(r => r.CostStage).ThenInclude(cs => cs.Cost)
                           .Include(r => r.CostStage).ThenInclude(cs => cs.CostStageRevisions)
                           .Include(r => r.StageDetails)
                           .Include(r => r.ProductDetails)
                           .Include(r => r.CostStageRevisionPaymentTotals)
                           //.AsNoTracking()
                           .FirstOrDefaultAsync(csr => csr.Id == costStageRevisionId);

            var costStage = revision.CostStage;
            var cost      = costStage.Cost;

            var stageDetailsForm      = _costStageRevisionService.GetStageDetails <PgStageDetailsForm>(revision);
            var productionDetailsForm = _costStageRevisionService.GetProductionDetails <PgProductionDetailsForm>(revision);

            //ADC-2690 revises paymentCostTotal calculation for re-opened Final Actual stage
            var previousPaymentCalculations = new List <CostStageRevisionPaymentTotal>();
            //get the latest costtotal from last approved final actual
            var previousPaymentCostTotal = new CostStageRevisionPaymentTotal();
            //flag to determine if this calculation is for the first FA or subsequent FAs
            bool isFirstFA = true;
            //check if the current cost has any Final Actual stage approved
            var approvedFinalActualStage = cost.CostStages.Find(x => x.Key == CostStages.FinalActual.ToString())?.CostStageRevisions.Find(a => a.Status == CostStageRevisionStatus.Approved);

            //if there is no final actual stage approve, then keep the current calculation as is, which is working correctly.
            if (approvedFinalActualStage == null)
            {
                previousPaymentCalculations = await _costStageRevisionService.GetAllCostPaymentTotals(cost.Id, revision.CostStage.Id);
            }
            else
            {
                //here is the area we do the calculation for re-opened FAs
                //Get All Cost Payment Totals for the current Final Actual stage
                previousPaymentCalculations = await _costStageRevisionService.GetAllCostPaymentTotalsFinalActual(cost.Id, revision.CostStage.Id);

                //extract values of CostTotal rowns of approved FA and order by calculated datetime
                var previousPaymentCostTotals = previousPaymentCalculations.Where(x => x.LineItemTotalType == Constants.CostSection.CostTotal &&
                                                                                  x.CostStageRevision.Status == CostStageRevisionStatus.Approved)
                                                .OrderBy(x => x.CalculatedAt).ToList();
                //check if there is at least 1 approved FA
                if (previousPaymentCalculations.Any() && previousPaymentCostTotals.Any())
                {
                    //if there is an approved FA, it means there is an inprogress FA, and we shall need to get the last FA for subtraction later: Grand total at Final actual -II minus Grand total in Final actual -I
                    previousPaymentCostTotal = previousPaymentCostTotals[previousPaymentCostTotals.Count() - 1];
                    //flag up this is not the first FA
                    isFirstFA = false;
                }
                else
                {
                    //otherwise, keep the calculation as is
                    previousPaymentCalculations = await _costStageRevisionService.GetAllCostPaymentTotals(cost.Id, revision.CostStage.Id);
                }
            }

            var costLineItems = await _costStageRevisionService.GetCostLineItems(costStageRevisionId);

            var totals = _pgTotalsBuilder.Build(stageDetailsForm, costLineItems, costStage.Key);
            var previousPaymentTotals = _pgTotalPaymentsBuilder.Build(previousPaymentCalculations);

            // these are totals of remaining balance
            //changed for ADC-2690
            var totalRemainingPayment = new PgPaymentRule()
            {
                StageTotals           = totals,
                BudgetRegion          = stageDetailsForm.BudgetRegion?.Key,
                ContentType           = stageDetailsForm.ContentType?.Key,
                CostType              = cost.CostType.ToString(),
                CostStages            = costStage.Key,
                ProductionType        = Constants.ProductionType.ProductionTypeList.FirstOrDefault(a => a == stageDetailsForm.ProductionType?.Key),
                DirectPaymentVendorId = productionDetailsForm.DirectPaymentVendor?.Id,
                IsAIPE = stageDetailsForm.IsAIPE,

                // we need this to match with the rules' TotalCostAmount field
                TotalCostAmount = totals.TotalCostAmountTotal,

                // this is for detailed split
                InsuranceCost      = totals.InsuranceCostTotal - previousPaymentTotals.InsuranceCostPayments,
                TechnicalFeeCost   = totals.TechnicalFeeCostTotal - previousPaymentTotals.TechnicalFeeCostPayments,
                TalentFeeCost      = totals.TalentFeeCostTotal - previousPaymentTotals.TalentFeeCostPayments,
                PostProductionCost = totals.PostProductionCostTotal - previousPaymentTotals.PostProductionCostPayments,
                ProductionCost     = totals.ProductionCostTotal - previousPaymentTotals.ProductionCostPayments,
                OtherCost          = totals.OtherCostTotal - previousPaymentTotals.OtherCostPayments,

                TargetBudgetTotalCost = totals.TargetBudgetTotal - previousPaymentTotals.TargetBudgetTotalCostPayments,
                CostCarryOverAmount   = previousPaymentTotals.CarryOverAmount
            };

            //check if this is not the calculation for the first FA then do the subtraction: Grand total at Final actual -II minus Grand total in Final actual -I
            //if not keep as is
            if (!isFirstFA)
            {
                //if this is not the first FA, it means we would have to calculated TotalCost AKA CostTotal equal Grand total at Final actual -II minus Grand total in Final actual -I
                totalRemainingPayment.TotalCost = totals.TotalCostAmountTotal - previousPaymentCostTotal.LineItemFullCost;
            }
            else
            {
                // we use this to calculate the outstanding balance where there is no detailed split
                totalRemainingPayment.TotalCost = totals.TotalCostAmountTotal - previousPaymentTotals.TotalCostPayments;
            }
            _logger.Information($"Calculating payment amount for cost: {cost.CostNumber} at stage: {costStage.Key} revision: {revision.Id}");

            // these are actual payment splits (percentages of totals)
            var paymentAmount = await GetPaymentAmount(totalRemainingPayment, previousPaymentTotals, totals, productionDetailsForm.DirectPaymentVendor?.ProductionCategory);

            if (paymentAmount != null)
            {
                if (!persist)
                {
                    return(paymentAmount);
                }
                var totalRemainingAmount = (PgPaymentRule)paymentAmount.TotalRemainingPayment;

                var nextStages = await _stageService.GetAllUpcomingStages(costStage.Key, BuType.Pg, cost.Id);

                if (nextStages != null)
                {
                    paymentAmount.ProjectedPayments = GetNextStagesPaymentAmounts(paymentAmount, totalRemainingPayment, nextStages);
                }

                var alreadySaved = await _costStageRevisionService.GetCostStageRevisionPaymentTotals(revision);

                if (alreadySaved == null || !alreadySaved.Any())
                {
                    await SaveTotals(costStageRevisionId, paymentAmount, totalRemainingAmount, isFirstFA);

                    foreach (var projectedPayment in paymentAmount.ProjectedPayments)
                    {
                        await SaveTotals(costStageRevisionId, projectedPayment, totalRemainingAmount, isFirstFA);
                    }
                }
                // UserIdentity in the parameters of below method is used only to log an activity when IO number gets changed.
                // Therefore we can pass any not null object here
                await _customObjectDataService.Save(costStageRevisionId, CustomObjectDataKeys.PgPaymentRuleInput, totalRemainingPayment, new UserIdentity());

                await _customObjectDataService.Save(costStageRevisionId, CustomObjectDataKeys.PgMatchedPaymentRule, paymentAmount.MatchedPaymentRule, new UserIdentity());

                return(paymentAmount);
            }

            _logger.Error($"Payment amount NOT calculated for cost: {cost.CostNumber} at stage: {costStage.Key} revision: {revision.Id} using rule: {totalRemainingPayment}!");
            return(null);
        }