/Apttus.SNowPS/Apttus.SNowPS.Repository/Products/ProdQuoteRepository.cs
C# | 1411 lines | 971 code | 178 blank | 262 comment | 259 complexity | a2d4d3ab98388a4c4e3c9f6bcd0a1e53 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- /****************************************************************************************
- @Name: QuoteRepository.cs
- @Author: Asha Tank
- @CreateDate: 11 Oct 2017
- @Description: Quote header related process
- @UsedBy: This will be used by ProdQuoteRepository controller
- @ModifiedBy:
- @ModifiedDate:
- @ChangeDescription:
- *****************************************************************************************/
- using Apttus.DataAccess.Common.Enums;
- using Apttus.DataAccess.Common.Model;
- using Apttus.SNowPS.Common;
- using Apttus.SNowPS.Model;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Xml.Linq;
- using System.IO;
- using System.Reflection;
- namespace Apttus.SNowPS.Respository
- {
- public class ProdQuoteRepository
- {
- /// <summary>
- /// Calculate financial fields of quote header for paased quote id
- /// </summary>
- /// <param name="QuoteId"></param>
- /// <param name="accessToken"></param>
- /// <returns></returns>
- public HttpResponseMessage GetQuoteDetail(string QuoteId, string accessToken)
- {
- var errors = new List<Model.ErrorInfo>();
- try
- {
- //Build AQL Query to fetch Quote,Quote Line Items & Product details
- var query = new Query(Constants.OBJ_QUOTE);
- query.AddColumns(Constants.OBJ_FIELDQUOTELINEITEM.Split(Constants.CHAR_COMMA));
- Expression exp = new Expression(ExpressionOperator.AND);
- exp.AddCondition(new Condition(Constants.FIELD_ID, FilterOperator.Equal, QuoteId));
- query.SetCriteria(exp);
- Join quoteLineItem = new Join(Constants.OBJ_QUOTE, Constants.OBJ_CPQ_QUOTELINEITEM, Constants.FIELD_ID, Constants.FIELD_QUOTEID, JoinType.LEFT);
- quoteLineItem.EntityAlias = Constants.OBJ_CPQ_QUOTELINEITEM;
- query.AddJoin(quoteLineItem);
- Join lineItem = new Join(Constants.OBJ_CPQ_QUOTELINEITEM, Constants.OBJ_LINEITEM, Constants.FIELD_DERIVEDFROMId, Constants.FIELD_ID, JoinType.LEFT);
- lineItem.EntityAlias = Constants.OBJ_LINEITEM;
- query.AddJoin(lineItem);
- Join product = new Join(Constants.OBJ_CPQ_QUOTELINEITEM, Constants.OBJ_PRODUCT, Constants.FIELD_PRODUCTID, Constants.FIELD_ID, JoinType.LEFT);
- product.EntityAlias = Constants.OBJ_PRODUCT;
- query.AddJoin(product);
- var jsonQuery = query.Serialize();
- //
- var reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.searchType = SearchType.AQL;
- reqConfig.objectName = Constants.OBJ_QUOTE;
- var response = Utilities.Search(jsonQuery, reqConfig);
- ResultQuoteHeaderModel resultQuoteHeaderModel = new ResultQuoteHeaderModel();
- if (response != null && response.IsSuccessStatusCode)
- {
- var responseString = JObject.Parse(response.Content.ReadAsStringAsync().Result).SelectToken(Constants.NODE_SERIALIZEDRESULTENTITIES).ToString();
- List<QuoteQuoteLineDetails> QuoteLineList = new List<QuoteQuoteLineDetails>();
- QuoteLineList = JsonConvert.DeserializeObject<List<QuoteQuoteLineDetails>>(responseString);
- if (QuoteLineList != null && QuoteLineList.Count > 0)
- {
- DailyExcnageRate objDailyExcnageRate = new DailyExcnageRate();
- objDailyExcnageRate = GetExchangeRateDetails(QuoteLineList.FirstOrDefault().cpq_lineitem.CurrencyId, accessToken);
- decimal EstimatedTotal = 0;
- decimal ProfesionalServiceTotal = 0;
- //Calculate quote fields
- for (int i = 0; i < QuoteLineList.Count; i++)
- {
- switch (QuoteLineList[i].crm_Product.ContributesTo.Value)
- {
- case Constants.TOTALPSREVENUE:
- resultQuoteHeaderModel.ext_EducationalServicesandKnowledgeandOther = resultQuoteHeaderModel.ext_EducationalServicesandKnowledgeandOther + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- resultQuoteHeaderModel.ext_TotalServicesRevenue = resultQuoteHeaderModel.ext_TotalServicesRevenue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- resultQuoteHeaderModel.ext_TotalPSRevenue = resultQuoteHeaderModel.ext_TotalPSRevenue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- break;
- case Constants.SUBSCRIPTIONANDLICENSEREVENUE:
- resultQuoteHeaderModel.ext_TotalLicenseValue = resultQuoteHeaderModel.ext_TotalLicenseValue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- resultQuoteHeaderModel.ext_TotalSubscriptionACV = resultQuoteHeaderModel.ext_TotalSubscriptionACV + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.AnnualContractValue);
- break;
- case Constants.LICENSEREVENUE:
- resultQuoteHeaderModel.ext_TotalLicenseValue = resultQuoteHeaderModel.ext_TotalLicenseValue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- break;
- case Constants.TRAININGREVENUE:
- resultQuoteHeaderModel.ext_TotalServicesRevenue = resultQuoteHeaderModel.ext_TotalServicesRevenue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- resultQuoteHeaderModel.ext_TotalTrainingRevenue = resultQuoteHeaderModel.ext_TotalTrainingRevenue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- break;
- case Constants.OTHERREVENUE:
- resultQuoteHeaderModel.ext_TotalOtherRevenue = resultQuoteHeaderModel.ext_TotalOtherRevenue + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- break;
- }
- if (QuoteLineList[i].crm_Product.Family != null && QuoteLineList[i].crm_Product.Family.Value == "Professional Services")
- {
- ProfesionalServiceTotal = ProfesionalServiceTotal + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- }
- resultQuoteHeaderModel.ext_TotalAnnualListPrice = resultQuoteHeaderModel.ext_TotalAnnualListPrice + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.AnnualContractValue);
- EstimatedTotal = EstimatedTotal + Convert.ToDecimal(QuoteLineList[i].cpq_QuoteLineItem.EstimatedTotal);
- }
- resultQuoteHeaderModel.ext_PreTaxTotals = Convert.ToDecimal(resultQuoteHeaderModel.ext_TotalLicenseValue + resultQuoteHeaderModel.ext_TotalServicesRevenue + resultQuoteHeaderModel.ext_TotalOtherRevenue);
- if (ProfesionalServiceTotal != 0)
- {
- resultQuoteHeaderModel.ext_EstimatedTravelExpenseFees = (ProfesionalServiceTotal * 10) / 100;
- }
- resultQuoteHeaderModel.ext_EstimatedTotal = EstimatedTotal + resultQuoteHeaderModel.ext_EstimatedTravelExpenseFees;
- resultQuoteHeaderModel.Id = QuoteLineList.FirstOrDefault().Id;
- //Calculation of USD fields
- resultQuoteHeaderModel.ext_USDTotalAnnualListPrice = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalAnnualListPrice);
- resultQuoteHeaderModel.ext_USDTotalLicenseValue = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalLicenseValue);
- resultQuoteHeaderModel.ext_USDTotalOtherRevenue = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalOtherRevenue);
- resultQuoteHeaderModel.ext_USDTotalPSRevenue = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalPSRevenue);
- resultQuoteHeaderModel.ext_USDTotalServicesRevenue = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalServicesRevenue);
- resultQuoteHeaderModel.ext_USDTotalSubscriptionACV = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalSubscriptionACV);
- resultQuoteHeaderModel.ext_USDTotalTrainingRevenue = Convert.ToDecimal(objDailyExcnageRate.ext_Rate * resultQuoteHeaderModel.ext_TotalTrainingRevenue);
- //Calculation of USD fields end
- }
- //return response
- List<ResultQuoteHeaderModel> quoteHeaderList = new List<ResultQuoteHeaderModel>();
- quoteHeaderList.Add(resultQuoteHeaderModel);
- var responseResult = UpdateQuoteHeader(quoteHeaderList, accessToken);
- return responseResult;
- }
- else
- {
- HttpResponseMessage jsonResponse = new HttpResponseMessage();
- Model.ErrorInfo errorInfo = new Model.ErrorInfo();
- errorInfo.Message = "Error";
- var dict = new Dictionary<string, object>
- {
- {"Message", "Fail to update records"}
- };
- errorInfo.Record = dict;
- errors.Add(errorInfo);
- Utilities.CreateResponse(jsonResponse, errors);
- return jsonResponse;
- }
- }
- catch (Exception ex)
- {
- var resp = new HttpResponseMessage
- {
- Content = new StringContent("Message :" + ex.Message + " " + "StackStrace :" + ex.StackTrace, System.Text.Encoding.UTF8, "application/json"),
- StatusCode = System.Net.HttpStatusCode.BadRequest
- };
- return resp;
- }
- }
- /// <summary>
- /// Get Currency exchange rate based on currency code
- /// </summary>
- /// <param name="currencyCode"></param>
- /// <returns></returns>
- public DailyExcnageRate GetExchangeRateDetails(string currencyId, string accessToken)
- {
- //currencyCode = "USD";
- DailyExcnageRate ExchangeRates = new DailyExcnageRate();
- accessToken = accessToken != null ? accessToken : Utilities.GetAuthToken();
- var reqExchangeRateLineItem = Utilities.GetRequestConfiguration(Constants.OBJ_DAILYEXCHANGERATE, Constants.FIELD_CURRENCYCODE, Constants.FIELD_CURRENCYCODE);
- var dictContent = new List<Dictionary<string, object>> { new Dictionary<string, object>() { { "ext_CurrencyCode", currencyId } } };
- var resExchangeRate = Utilities.Search(dictContent, reqExchangeRateLineItem);
- if (resExchangeRate != null && resExchangeRate.IsSuccessStatusCode)
- {
- var responseString = JObject.Parse(resExchangeRate.Content.ReadAsStringAsync().Result).SelectToken("SerializedResultEntities").ToString();
- List<DailyExcnageRate> ListExchgRates = JsonConvert.DeserializeObject<List<DailyExcnageRate>>(responseString);
- // Getting last Created/Modified currency rate
- ExchangeRates = ListExchgRates.OrderByDescending(x => x.ModifiedOn).FirstOrDefault();
- }
- return ExchangeRates;
- }
- /// <summary>
- /// Update Quote Line Items
- /// </summary>
- /// <param name="lineItems"></param>
- /// <param name="accessToken"></param>
- /// <returns></returns>
- public HttpResponseMessage UpdateQuoteHeader(List<ResultQuoteHeaderModel> quoteHeaderList, string accessToken)
- {
- var reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.objectName = Constants.OBJ_QUOTE;
- var lstQuoteToUpdate = new List<dynamic>();
- foreach (var lstQuoteItems in quoteHeaderList)
- {
- lstQuoteToUpdate.Add(new
- {
- Id = lstQuoteItems.Id,
- ext_EducationalServicesandKnowledgeandOther = lstQuoteItems.ext_EducationalServicesandKnowledgeandOther,
- ext_TotalServicesRevenue = lstQuoteItems.ext_TotalServicesRevenue,
- ext_TotalPSRevenue = lstQuoteItems.ext_TotalPSRevenue,
- ext_TotalSubscriptionACV = lstQuoteItems.ext_TotalSubscriptionACV,
- ext_TotalLicenseValue = lstQuoteItems.ext_TotalLicenseValue,
- ext_TotalTrainingRevenue = lstQuoteItems.ext_TotalTrainingRevenue,
- ext_TotalOtherRevenue = lstQuoteItems.ext_TotalOtherRevenue,
- ext_TotalAnnualListPrice = lstQuoteItems.ext_TotalAnnualListPrice,
- ext_PreTaxTotals = lstQuoteItems.ext_PreTaxTotals,
- ext_EstimatedTravelExpenseFees = lstQuoteItems.ext_EstimatedTravelExpenseFees,
- ext_EstimatedTotal = lstQuoteItems.ext_EstimatedTotal,
- ext_USDTotalAnnualListPrice = lstQuoteItems.ext_USDTotalAnnualListPrice,
- ext_USDTotalLicenseValue = lstQuoteItems.ext_USDTotalLicenseValue,
- ext_USDTotalOtherRevenue = lstQuoteItems.ext_USDTotalOtherRevenue,
- ext_USDTotalPSRevenue = lstQuoteItems.ext_USDTotalPSRevenue,
- ext_USDTotalServicesRevenue = lstQuoteItems.ext_USDTotalServicesRevenue,
- ext_USDTotalSubscriptionACV = lstQuoteItems.ext_USDTotalSubscriptionACV,
- ext_USDTotalTrainingRevenue = lstQuoteItems.ext_USDTotalTrainingRevenue
- });
- }
- var responseString = Utilities.Update(lstQuoteToUpdate, reqConfig);
- return responseString;
- }
- #region Commented Code
- ///// <summary>
- ///// Calculate financial fields of Quote line items for given QuoteId
- ///// </summary>
- ///// <param name="QuoteId"></param>
- ///// <param name="accessToken"></param>
- ///// <returns></returns>
- //public HttpResponseMessage UpdateQuoteLineItemFields(string QuoteId, string accessToken)
- //{
- // var errors = new List<Model.ErrorInfo>();
- // try
- // {
- // //Build AQL Query to fetch Quote,Quote Line Items & Product details
- // var query = new Query(Constants.OBJ_QUOTE);
- // query.AddColumns(Constants.OBJ_FIELDQUOTELINEITEMFINANCIAL.Split(Constants.CHAR_COMMA));
- // Expression exp = new Expression(ExpressionOperator.AND);
- // exp.AddCondition(new Condition(Constants.FIELD_ID, FilterOperator.Equal, QuoteId));
- // query.SetCriteria(exp);
- // Join quoteLineItem = new Join(Constants.OBJ_QUOTE, Constants.OBJ_CPQ_QUOTELINEITEM, Constants.FIELD_ID, Constants.FIELD_QUOTEID, JoinType.LEFT);
- // quoteLineItem.EntityAlias = Constants.OBJ_CPQ_QUOTELINEITEM;
- // query.AddJoin(quoteLineItem);
- // Join lineItem = new Join(Constants.OBJ_CPQ_QUOTELINEITEM, Constants.OBJ_LINEITEM, Constants.FIELD_DERIVEDFROMId, Constants.FIELD_ID, JoinType.LEFT);
- // lineItem.EntityAlias = Constants.OBJ_LINEITEM;
- // query.AddJoin(lineItem);
- // Join product = new Join(Constants.OBJ_CPQ_QUOTELINEITEM, Constants.OBJ_PRODUCT, Constants.FIELD_PRODUCTID, Constants.FIELD_ID, JoinType.LEFT);
- // product.EntityAlias = Constants.OBJ_PRODUCT;
- // query.AddJoin(product);
- // var jsonQuery = query.Serialize();
- // var reqConfig = new RequestConfigModel();
- // reqConfig.accessToken = accessToken;
- // reqConfig.searchType = SearchType.AQL;
- // reqConfig.objectName = Constants.OBJ_QUOTE;
- // var response = Utilities.Search(jsonQuery, reqConfig);
- // ResultUSDQuoteHeaderLineItemFields resultQuoteHeaderAndLIneItems = new ResultUSDQuoteHeaderLineItemFields();
- // ResultQuoteHeaderModel resultQuoteHeaderModel = new ResultQuoteHeaderModel();
- // List<ResultQuoteLineItem> lstResultQuoteLineItem = new List<ResultQuoteLineItem>();
- // if (response != null && response.IsSuccessStatusCode)
- // {
- // var responseString = JObject.Parse(response.Content.ReadAsStringAsync().Result).SelectToken(Constants.NODE_SERIALIZEDRESULTENTITIES).ToString();
- // List<QuoteQuoteLineDetails> QuoteLineList = new List<QuoteQuoteLineDetails>();
- // QuoteLineList = JsonConvert.DeserializeObject<List<QuoteQuoteLineDetails>>(responseString);
- // if (QuoteLineList != null && QuoteLineList.Count > 0)
- // {
- // LineItemRepository lineItemRepo = new LineItemRepository();
- // //Calculate quote line item USD fields
- // for (int i = 0; i < QuoteLineList.Count; i++)
- // {
- // ResultQuoteLineItem objResultQuoteLineItem = new ResultQuoteLineItem();
- // objResultQuoteLineItem.Id = QuoteLineList[i].cpq_QuoteLineItem.Id;
- // //get daily currenct exchange rates based on currency code
- // DailyExcnageRate objDailyExcnageRate = lineItemRepo.GetExchangeRateDetails(QuoteLineList[i].cpq_lineitem.CurrencyId, accessToken);
- // //USD fields
- // if (objDailyExcnageRate != null)
- // {
- // objResultQuoteLineItem.ext_USDAdjustment = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.Ext_AdjustmentAmount;
- // objResultQuoteLineItem.ext_USDBasePrice = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.BasePrice;
- // objResultQuoteLineItem.ext_USDTotalValue = objDailyExcnageRate.ext_Rate * (QuoteLineList[i].cpq_QuoteLineItem.NetPrice);
- // objResultQuoteLineItem.ext_USDListPrice = objDailyExcnageRate.ext_Rate * (QuoteLineList[i].cpq_QuoteLineItem.ListPrice);
- // objResultQuoteLineItem.ext_USDSalesPrice = objDailyExcnageRate.ext_Rate * (QuoteLineList[i].cpq_QuoteLineItem.NetUnitPrice);
- // objResultQuoteLineItem.ext_USDAnnualContractValue = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.AnnualContractValue;
- // objResultQuoteLineItem.ext_USDAnnualListPrice = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.AnnualListPrice;
- // }
- // lstResultQuoteLineItem.Add(objResultQuoteLineItem);
- // }
- // }
- // resultQuoteHeaderAndLIneItems.ListQuoteLineItemFinFields = lstResultQuoteLineItem;
- // var responseResult = UpdateQuoteLineItems(lstResultQuoteLineItem, accessToken);
- // return responseResult;
- // }
- // else
- // {
- // HttpResponseMessage jsonResponse = new HttpResponseMessage();
- // Model.ErrorInfo errorInfo = new Model.ErrorInfo();
- // errorInfo.Message = "Error";
- // var dict = new Dictionary<string, object>
- // {
- // {"Message", "Fail to update records"}
- // };
- // errorInfo.Record = dict;
- // errors.Add(errorInfo);
- // Utilities.CreateResponse(jsonResponse, errors);
- // return jsonResponse;
- // }
- // //return response
- // }
- // catch (Exception ex)
- // {
- // var resp = new HttpResponseMessage
- // {
- // Content = new StringContent("Message :" + ex.Message + " " + "StackStrace :" + ex.StackTrace, System.Text.Encoding.UTF8, "application/json"),
- // StatusCode = System.Net.HttpStatusCode.BadRequest
- // };
- // return resp;
- // }
- //}
- #endregion
- /// <summary>
- /// Calculate financial fields of Quote line items for given QuoteId
- /// </summary>
- /// <param name="QuoteId"></param>
- /// <param name="accessToken"></param>
- /// <returns></returns>
- public HttpResponseMessage UpdateQuoteLineItemFields(string QuoteId, string accessToken)
- {
- var errors = new List<Model.ErrorInfo>();
- try
- {
- //Build AQL Query to fetch Quote,Quote Line Items & Product details
- var query = new Query(Constants.OBJ_QUOTE);
- query.AddColumns(Constants.OBJ_FIELDQUOTELINEITEMFINANCIAL.Split(Constants.CHAR_COMMA));
- Expression exp = new Expression(ExpressionOperator.AND);
- exp.AddCondition(new Condition(Constants.FIELD_ID, FilterOperator.Equal, QuoteId));
- query.SetCriteria(exp);
- Join quoteLineItem = new Join(Constants.OBJ_QUOTE, Constants.OBJ_CPQ_QUOTELINEITEM, Constants.FIELD_ID, Constants.FIELD_QUOTEID, JoinType.LEFT);
- quoteLineItem.EntityAlias = Constants.OBJ_CPQ_QUOTELINEITEM;
- query.AddJoin(quoteLineItem);
- Join lineItem = new Join(Constants.OBJ_CPQ_QUOTELINEITEM, Constants.OBJ_LINEITEM, Constants.FIELD_DERIVEDFROMId, Constants.FIELD_ID, JoinType.LEFT);
- lineItem.EntityAlias = Constants.OBJ_LINEITEM;
- query.AddJoin(lineItem);
- Join product = new Join(Constants.OBJ_CPQ_QUOTELINEITEM, Constants.OBJ_PRODUCT, Constants.FIELD_PRODUCTID, Constants.FIELD_ID, JoinType.LEFT);
- product.EntityAlias = Constants.OBJ_PRODUCT;
- query.AddJoin(product);
- var jsonQuery = query.Serialize();
- var reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.searchType = SearchType.AQL;
- reqConfig.objectName = Constants.OBJ_QUOTE;
- var response = Utilities.Search(jsonQuery, reqConfig);
- ResultUSDQuoteHeaderLineItemFields resultQuoteHeaderAndLIneItems = new ResultUSDQuoteHeaderLineItemFields();
- ResultQuoteHeaderModel resultQuoteHeaderModel = new ResultQuoteHeaderModel();
- List<ResultQuoteLineItem> lstResultQuoteLineItem = new List<ResultQuoteLineItem>();
- if (response != null && response.IsSuccessStatusCode)
- {
- var responseString = JObject.Parse(response.Content.ReadAsStringAsync().Result).SelectToken(Constants.NODE_SERIALIZEDRESULTENTITIES).ToString();
- List<QuoteQuoteLineDetails> QuoteLineList = new List<QuoteQuoteLineDetails>();
- QuoteLineList = JsonConvert.DeserializeObject<List<QuoteQuoteLineDetails>>(responseString);
- if (QuoteLineList != null && QuoteLineList.Count > 0)
- {
- LineItemRepository lineItemRepo = new LineItemRepository();
- //Calculate quote line item USD fields
- for (int i = 0; i < QuoteLineList.Count; i++)
- {
- ResultQuoteLineItem objResultQuoteLineItem = new ResultQuoteLineItem();
- objResultQuoteLineItem.Id = QuoteLineList[i].cpq_QuoteLineItem.Id;
- objResultQuoteLineItem.ext_ListPriceWithAdjustments = QuoteLineList[i].cpq_QuoteLineItem.BasePrice.ConvertToDecimal();
- if (QuoteLineList[i].cpq_QuoteLineItem.ListPrice != 0)
- {
- objResultQuoteLineItem.ext_AdjustmentAmount = (QuoteLineList[i].cpq_QuoteLineItem.ListPrice.ConvertToDecimal() * QuoteLineList[i].cpq_QuoteLineItem.Quantity2.ConvertToDecimal() * QuoteLineList[i].cpq_QuoteLineItem.Term.ConvertToDecimal()) - QuoteLineList[i].cpq_QuoteLineItem.NetPrice.ConvertToDecimal();
- objResultQuoteLineItem.ext_AdjustmentDiscountPercent = objResultQuoteLineItem.ext_AdjustmentAmount * 100 / (QuoteLineList[i].cpq_QuoteLineItem.ListPrice.ConvertToDecimal() * QuoteLineList[i].cpq_QuoteLineItem.Quantity2.ConvertToDecimal() * QuoteLineList[i].cpq_QuoteLineItem.Term.ConvertToDecimal());
- }
- if (QuoteLineList[i].crm_Product.Family != null && QuoteLineList[i].crm_Product.Family.Value.ConvertToStringNull() != null && QuoteLineList[i].cpq_QuoteLineItem.ProductId.Ext_Family.Value.ToString() != Constants.STR_SUBSCRIPTION)
- {
- objResultQuoteLineItem.ext_AnnualContractValue = 0;
- objResultQuoteLineItem.ext_AnnualListPrice = 0;
- }
- else
- {
- if (QuoteLineList[i].cpq_QuoteLineItem.SellingFrequency != null && QuoteLineList[i].cpq_QuoteLineItem.SellingFrequency.ConvertToStringNull() != null && QuoteLineList[i].cpq_QuoteLineItem.SellingFrequency.Value.ToString() == Constants.STR_YEARLY)
- {
- objResultQuoteLineItem.ext_AnnualContractValue = QuoteLineList[i].cpq_QuoteLineItem.NetUnitPrice.ConvertToDecimal() * QuoteLineList[i].cpq_QuoteLineItem.Quantity2;
- objResultQuoteLineItem.ext_AnnualListPrice = QuoteLineList[i].cpq_QuoteLineItem.ListPrice.ConvertToDecimal() * QuoteLineList[i].cpq_QuoteLineItem.Quantity2;
- }
- else
- {
- objResultQuoteLineItem.ext_AnnualContractValue = QuoteLineList[i].cpq_QuoteLineItem.NetUnitPrice.ConvertToDecimal() * 12 * QuoteLineList[i].cpq_QuoteLineItem.Quantity2;
- objResultQuoteLineItem.ext_AnnualListPrice = QuoteLineList[i].cpq_QuoteLineItem.ListPrice.ConvertToDecimal() * 12 * QuoteLineList[i].cpq_QuoteLineItem.Quantity2;
- }
- }
- objResultQuoteLineItem.ext_EstimatedTax = QuoteLineList[i].cpq_QuoteLineItem.ext_EstimatedTax.ConvertToDecimal();
- //Estimated Total: Total Value + EstimatedTax
- objResultQuoteLineItem.ext_EstimatedTotal = QuoteLineList[i].cpq_QuoteLineItem.NetPrice.ConvertToDecimal() + objResultQuoteLineItem.ext_EstimatedTax.ConvertToDecimal();
- //Sales Price
- objResultQuoteLineItem.ext_SalesPrice = QuoteLineList[i].cpq_QuoteLineItem.NetUnitPrice.ConvertToDecimal();
- //get daily currenct exchange rates based on currency code
- DailyExcnageRate objDailyExcnageRate = lineItemRepo.GetExchangeRateDetails(QuoteLineList[i].cpq_lineitem.CurrencyId, accessToken);
- //USD fields
- if (objDailyExcnageRate != null)
- {
- objResultQuoteLineItem.ext_USDAdjustment = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.Ext_AdjustmentAmount.ConvertToDecimal();
- objResultQuoteLineItem.ext_USDBasePrice = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.BasePrice.ConvertToDecimal();
- objResultQuoteLineItem.ext_USDTotalValue = objDailyExcnageRate.ext_Rate * (QuoteLineList[i].cpq_QuoteLineItem.NetPrice.ConvertToDecimal());
- objResultQuoteLineItem.ext_USDListPrice = objDailyExcnageRate.ext_Rate * (QuoteLineList[i].cpq_QuoteLineItem.ListPrice.ConvertToDecimal());
- objResultQuoteLineItem.ext_USDSalesPrice = objDailyExcnageRate.ext_Rate * (QuoteLineList[i].cpq_QuoteLineItem.NetUnitPrice.ConvertToDecimal());
- objResultQuoteLineItem.ext_USDAnnualContractValue = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.AnnualContractValue.ConvertToDecimal();
- objResultQuoteLineItem.ext_USDAnnualListPrice = objDailyExcnageRate.ext_Rate * QuoteLineList[i].cpq_QuoteLineItem.AnnualListPrice.ConvertToDecimal();
- }
- lstResultQuoteLineItem.Add(objResultQuoteLineItem);
- }
- }
- resultQuoteHeaderAndLIneItems.ListQuoteLineItemFinFields = lstResultQuoteLineItem;
- var responseResult = UpdateQuoteLineItems(lstResultQuoteLineItem, accessToken);
- return responseResult;
- }
- else
- {
- HttpResponseMessage jsonResponse = new HttpResponseMessage();
- Model.ErrorInfo errorInfo = new Model.ErrorInfo();
- errorInfo.Message = "Error";
- var dict = new Dictionary<string, object>
- {
- {"Message", "Fail to update records"}
- };
- errorInfo.Record = dict;
- errors.Add(errorInfo);
- Utilities.CreateResponse(jsonResponse, errors);
- return jsonResponse;
- }
- //return response
- }
- catch (Exception ex)
- {
- var resp = new HttpResponseMessage
- {
- Content = new StringContent("Message :" + ex.Message + " " + "StackStrace :" + ex.StackTrace, System.Text.Encoding.UTF8, "application/json"),
- StatusCode = System.Net.HttpStatusCode.BadRequest
- };
- return resp;
- }
- }
- /// <summary>
- /// Update calculated Quote line items details
- /// </summary>
- /// <param name="lineItems">list of fileds to be update</param>
- /// <returns></returns>
- public HttpResponseMessage UpdateQuoteLineItems(List<ResultQuoteLineItem> quoteLineItems, string accessToken)
- {
- var reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.objectName = Constants.OBJ_CPQ_QUOTELINEITEM;
- var lstLineItemsToUpdate = new List<dynamic>();
- foreach (var lstLineItems in quoteLineItems)
- {
- lstLineItemsToUpdate.Add(new
- {
- Id = lstLineItems.Id,
- ext_ListPriceWithAdjustments = lstLineItems.ext_ListPriceWithAdjustments,
- ext_AdjustmentAmount = lstLineItems.ext_AdjustmentAmount,
- ext_AdjustmentDiscountPercent = lstLineItems.ext_AdjustmentDiscountPercent,
- ext_EstimatedTax = lstLineItems.ext_EstimatedTax,
- ext_AnnualContractValue = lstLineItems.ext_AnnualContractValue,
- ext_AnnualListPrice = lstLineItems.ext_AnnualListPrice,
- ext_EstimatedTotal = lstLineItems.ext_EstimatedTotal,
- ext_SalesPrice = lstLineItems.ext_SalesPrice,
- ext_USDAdjustment = lstLineItems.ext_USDAdjustment,
- ext_USDBasePrice = lstLineItems.ext_USDBasePrice,
- ext_USDTotalValue = lstLineItems.ext_USDTotalValue,
- ext_USDListPrice = lstLineItems.ext_USDListPrice,
- ext_USDSalesPrice = lstLineItems.ext_USDSalesPrice,
- ext_USDAnnualContractValue = lstLineItems.ext_USDAnnualContractValue,
- ext_USDAnnualListPrice = lstLineItems.ext_USDAnnualListPrice,
- });
- }
- var responseString = Utilities.Update(lstLineItemsToUpdate, reqConfig);
- return responseString;
- }
- /// <summary>
- /// Default quote details based on rule conditions
- /// </summary>
- /// <param name="QuoteId"></param>
- /// <param name="accessToken"></param>
- /// <returns></returns>
- public HttpResponseMessage DefaultQuoteDetails(string QuoteId, string accessToken)
- {
- try
- {
- //Build AQL Query to fetch Quote's opprtunityID
- var updateResult = new HttpResponseMessage();
- var query = new Query(Constants.OBJ_QUOTE);
- query.AddColumns(Constants.OBJ_QUOTEVALIDATE_DEFAULT_SELECTFIELD.Split(Constants.CHAR_COMMA));
- Expression exp = new Expression(ExpressionOperator.AND);
- exp.AddCondition(new Condition(Constants.FIELD_ID, FilterOperator.Equal, QuoteId));
- Join account = new Join(Constants.OBJ_QUOTE, Constants.OBJ_ACCOUNT, Constants.FIELD_ACCOUNTID, Constants.FIELD_ID, JoinType.LEFT);
- account.EntityAlias = Constants.OBJ_ACCOUNT;
- query.AddJoin(account);
- query.SetCriteria(exp);
- var jsonQuery = query.Serialize();
- var reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.searchType = SearchType.AQL;
- reqConfig.objectName = Constants.OBJ_QUOTE;
- var response = Utilities.Search(jsonQuery, reqConfig);
- ValidateDefaultQuoteResult objValidateDefaultQuoteResult = new ValidateDefaultQuoteResult();
- List<Dictionary<string, object>> ListQuoteFieldToUpdate = new List<Dictionary<string, object>>();
- if (response != null && response.IsSuccessStatusCode)
- {
- var responseString = JObject.Parse(response.Content.ReadAsStringAsync().Result).SelectToken(Constants.NODE_SERIALIZEDRESULTENTITIES).ToString();
- List<QuoteValidate> objQuoteOppoDetails = new List<QuoteValidate>();
- objQuoteOppoDetails = JsonConvert.DeserializeObject<List<QuoteValidate>>(responseString);
- if (objQuoteOppoDetails != null && objQuoteOppoDetails.Count > 0)
- {
- #region "Set default data center based on Country"
- if (objQuoteOppoDetails.FirstOrDefault().crm_Account != null && objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country != null)
- {
- #region get country and data center mapping data from xml file
- Dictionary<string, string> countryDCDict = new Dictionary<string, string>();
- string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"XMLFiles\DataCenterCountryMapping.xml");
- XDocument XDoc = XDocument.Load(path);
- try
- {
- countryDCDict = XDoc.Descendants("Country").ToDictionary(d => (string)d.Attribute("Name"), d => (string)d);
- if (countryDCDict.ContainsKey(objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country))
- {
- objValidateDefaultQuoteResult.ext_datacenter = countryDCDict[objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country];
- }
- else
- { //setting default data center to United States
- objValidateDefaultQuoteResult.ext_datacenter = countryDCDict[Constants.STR_UNITEDSTATES];
- }
- }
- catch (Exception ex)
- {
- objValidateDefaultQuoteResult.ErrorMessage = "DataCenterCountryMapping :" + ex.Message;
- }
- #endregion
- }
- #endregion
- #region "Set Selling entity"
- if (objQuoteOppoDetails.FirstOrDefault().crm_Account != null && objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country != null)
- {
- #region get country and selling entity mapping data from xml file
- Dictionary<string, string> countryDCDict = new Dictionary<string, string>();
- string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"XMLFiles\CountryandSellingEntityMapping.xml");
- XDocument XDoc = XDocument.Load(path);
- try
- {
- countryDCDict = XDoc.Descendants("Country").ToDictionary(d => (string)d.Attribute("Name"), d => (string)d);
- if (countryDCDict.ContainsKey(objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country))
- {
- objValidateDefaultQuoteResult.ext_SellingEntity = countryDCDict[objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country];
- }
- else
- {
- objValidateDefaultQuoteResult.ext_SellingEntity = countryDCDict[Constants.STR_NEDERLAND];
- }
- }
- catch (Exception ex)
- {
- objValidateDefaultQuoteResult.ErrorMessage += " CountryandSellingEntityMapping :" + ex.Message;
- }
- #endregion
- }
- #endregion
- #region "Set PriceList based on currency and vice versa"
- //Build AQL Query to fetch pricelist details
- var priceListId = objQuoteOppoDetails.FirstOrDefault().PriceListId != null ? objQuoteOppoDetails.FirstOrDefault().PriceListId.Id : null;
- if (!string.IsNullOrEmpty(priceListId))
- {
- var queryPricelist = new Query(Constants.OBJ_PRICELIST);
- queryPricelist.AddColumns(Constants.OBJ_PRICELIST_SELECTFIELD.Split(Constants.CHAR_COMMA));
- Expression expPriceList = new Expression(ExpressionOperator.AND);
- expPriceList.AddCondition(new Condition(Constants.FIELD_ID, FilterOperator.Equal, priceListId));
- queryPricelist.SetCriteria(expPriceList);
- jsonQuery = queryPricelist.Serialize();
- reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.searchType = SearchType.AQL;
- reqConfig.objectName = Constants.OBJ_PRICELIST;
- var responsePricelistDetail = Utilities.Search(jsonQuery, reqConfig);
- if (responsePricelistDetail != null && responsePricelistDetail.IsSuccessStatusCode)
- {
- var responsePriceListString = JObject.Parse(responsePricelistDetail.Content.ReadAsStringAsync().Result).SelectToken(Constants.NODE_SERIALIZEDRESULTENTITIES).ToString();
- List<QQuoteLineItem> objPriceListResult = new List<QQuoteLineItem>();
- objPriceListResult = JsonConvert.DeserializeObject<List<QQuoteLineItem>>(responsePriceListString);
- if (objPriceListResult != null && objPriceListResult.Count > 0)
- {
- if (!string.IsNullOrEmpty(objPriceListResult.FirstOrDefault().CurrencyId))
- {
- objValidateDefaultQuoteResult.BaseCurrency = objPriceListResult.FirstOrDefault().CurrencyId;
- }
- }
- }
- }
- // PricelistId will be null when Quote is created outside Apttus
- if (!string.IsNullOrEmpty(objQuoteOppoDetails.FirstOrDefault().ext_BaseCurrency) && string.IsNullOrEmpty(priceListId))
- {
- if (objQuoteOppoDetails.FirstOrDefault().ext_Type.Value.ToLower() == Constants.SERVICES || objQuoteOppoDetails.FirstOrDefault().ext_Type.Value.ToLower() == Constants.STR_TRAINING.ToLower())
- {
- #region get Currency and Pricelist mapping data from xml file for Services
- Dictionary<string, string> currencyDCDict = new Dictionary<string, string>();
- string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"XMLFiles\CurrencyandPriceListMappingServices.xml");
- XDocument XDoc = XDocument.Load(path);
- try
- {
- currencyDCDict = XDoc.Descendants("Currency").ToDictionary(d => (string)d.Attribute("Name"), d => (string)d);
- if (currencyDCDict.ContainsKey(objQuoteOppoDetails.FirstOrDefault().ext_BaseCurrency))
- {
- objValidateDefaultQuoteResult.PriceListName = currencyDCDict[objQuoteOppoDetails.FirstOrDefault().ext_BaseCurrency];
- if (objQuoteOppoDetails.FirstOrDefault().ext_BaseCurrency == Constants.STR_USD)
- {
- if (objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country == Constants.STR_AUSTRALIA)
- {
- objValidateDefaultQuoteResult.PriceListName = "Australian (USD) Services";
- }
- else if (objQuoteOppoDetails.FirstOrDefault().crm_Account.ext_Country == Constants.STR_JAPAN)
- {
- objValidateDefaultQuoteResult.PriceListName = "Japan (USD) Subscription";
- }
- }
- }
- else
- {
- objValidateDefaultQuoteResult.PriceListName = currencyDCDict[Constants.STR_USD];
- }
- }
- catch (Exception ex)
- {
- objValidateDefaultQuoteResult.ErrorMessage += " CurrencyandPriceListMappingServices :" + ex.Message;
- }
- #endregion
- }
- else// Remaining types will be for Subscription
- {
- #region get Currency and Pricelist mapping data from xml file for Subscription
- Dictionary<string, string> currencyDCDict = new Dictionary<string, string>();
- string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"XMLFiles\CurrencyandPriceListMapping.xml");
- XDocument XDoc = XDocument.Load(path);
- try
- {
- currencyDCDict = XDoc.Descendants("Currency").ToDictionary(d => (string)d.Attribute("Name"), d => (string)d);
- if (currencyDCDict.ContainsKey(objQuoteOppoDetails.FirstOrDefault().ext_BaseCurrency))
- {
- objValidateDefaultQuoteResult.PriceListName = currencyDCDict[objQuoteOppoDetails.FirstOrDefault().ext_BaseCurrency];
- }
- else
- {
- objValidateDefaultQuoteResult.PriceListName = currencyDCDict[Constants.STR_USD];
- }
- }
- catch (Exception ex)
- {
- objValidateDefaultQuoteResult.ErrorMessage += " CurrencyandPriceListMapping :" + ex.Message;
- }
- #endregion
- }
- }
- #endregion
- //Update Quote fileds to default values
- ListQuoteFieldToUpdate = new List<Dictionary<string, object>>();
- Dictionary<string, object> QuoteFieldToUpdate = new Dictionary<string, object>();
- QuoteFieldToUpdate.Add("Id", QuoteId);
- if (!string.IsNullOrEmpty(objValidateDefaultQuoteResult.ext_datacenter))
- {
- QuoteFieldToUpdate.Add("ext_datacenter", objValidateDefaultQuoteResult.ext_datacenter);
- }
- if (!string.IsNullOrEmpty(objValidateDefaultQuoteResult.ext_SellingEntity))
- {
- //Build AQL Query to fetch Account details
- var queryQuote = new Query(Constants.OBJ_ACCOUNT);
- queryQuote.AddColumns(Constants.OBJ_ACCOUNT_SELECTFIELD.Split(Constants.CHAR_COMMA));
- Expression expQuote = new Expression(ExpressionOperator.AND);
- expQuote.AddCondition(new Condition(Constants.FIELD_NAME, FilterOperator.Equal, objValidateDefaultQuoteResult.ext_SellingEntity));
- queryQuote.SetCriteria(expQuote);
- jsonQuery = queryQuote.Serialize();
- reqConfig = new RequestConfigModel();
- reqConfig.accessToken = accessToken;
- reqConfig.searchType = SearchType.AQL;
- reqConfig.objectName = Constants.OBJ_ACCOUNT;
- var responseAccountDetail = Utilities.Search(jsonQuery, reqConfig);
- if (responseAccountDetail != null && responseAccountDetail.IsSuccessStatusCode)
- {
- var responseAccountString = JObject.Parse(responseAccountDetail.Content.ReadAsStringAsync().Result).SelectToken(Constants.NODE_SERIALIZEDRESULTENTITIES).ToString();
- List<AccountCountry> objAccountResult = new List<AccountCountry>();
- objAccountResult = JsonConvert.DeserializeObject<List<AccountCountry>>(responseAccountString);
- if (objAccountResult != null && objAccountResult.Count > 0)
- {
- Dictionary<string, object> dictAccount = new Dictionary<string, object>();
- dictAccount.Add("Id", objAccountResult.FirstOrDefault().Id);
- dictAccount.Add("Name", objAccountResult.FirstOrDefault().Name);
- QuoteFieldToUpdate.Add("ext_SellingEntity", dictAccount);
- }
- }
- }
- if (!string.IsNullOrEmpty(objValidateDefaultQuoteResult.PriceListName))
- {
- //Build AQL Query to fetch Account details
- var queryPriceList = new Query(Constants.OBJ_PRICELIST);
- queryPriceList.AddColumns(Constants.OBJ_PRICELIST_SELECTFIELD.Split(Constants.CHAR_COMMA));
- Expression expPriceLIst = new Expression(ExpressionOperator.AND);
- expP…
Large files files are truncated, but you can click here to view the full file