Esempio n. 1
0
/**
 * Make a ship depot section.
 * @param t    Tile to place the ship depot section.
 * @param o    Owner of the depot.
 * @param did  Depot ID.
 * @param part Depot part (either #DEPOT_PART_NORTH or #DEPOT_PART_SOUTH).
 * @param a    Axis of the depot.
 * @param original_water_class Original water class.
 */
/*inline*/

        public static void MakeShipDepot(TileIndex t, Owner o, DepotID did, DepotPart part, Axis a,
                                         WaterClass original_water_class)
        {
            TileMap.SetTileType(t, TileType.MP_WATER);
            TileMap.SetTileOwner(t, o);
            SetWaterClass(t, original_water_class);
            Map._m[t].m2 = did;
            Map._m[t].m3 = 0;
            Map._m[t].m4 = 0;
            Map._m[t].m5 =
                (byte)
                ((int)WaterTileTypeBitLayout.WBL_TYPE_DEPOT << (int)WaterTileTypeBitLayout.WBL_TYPE_BEGIN |
                    (int)part << (int)WaterTileTypeBitLayout.WBL_DEPOT_PART |
                    (int)a << (int)WaterTileTypeBitLayout.WBL_DEPOT_AXIS);
            BitMath.SB(ref Map._me[t].m6, 2, 4, 0);
            Map._me[t].m7 = 0;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="part"></param>
        /// <param name="forSds">indicate whether the SDS BOS is desired or the "normal" BOS</param>
        /// <param name="includeFragranceComposition">Break down perfumes if possible</param>
        /// <param name="requireSDSSpecific">indicate if SDS is desired but no SDS specific composition is found, should the "normal" calculation be returned instead (always null for assessment spec)</param>
        /// <param name="partTypesForAssessmentSpecs">Part types here will return a calculated assessment spec, otherwise will return a calculated BOS.</param>
        /// <param name="allowResultWhenBosErrors">Returns a result even if there are BOS errors.</param>
        /// <returns></returns>
        public async Task <ICalculatedComponentsResult> GetCalculatedComponentsForPartAsync(DepotPart part, bool forSds = false, bool includeFragranceComposition = false, bool includeGpsConfidentialComposition = false, bool requireSDSSpecific = false, IEnumerable <string> partTypesForAssessmentSpecs = null, bool allowResultWhenBosErrors = false)
        {
            var partKey = part?.PartKey;

            if (string.IsNullOrEmpty(partKey))
            {
                return new BillOfSubstance {
                           ProductPart = part, IsSDSSpecific = false, Errors = new List <string> {
                               "PartKey was empty"
                           }
                }
            }
            ;

            var usesAssessmentSpec = !string.IsNullOrEmpty(part?.PartTypeName) &&
                                     (partTypesForAssessmentSpecs ?? RAW_MATERIAL_PART_TYPE_NAMES)
                                     .Any(n => !string.IsNullOrEmpty(n) && n.Equals(part.PartTypeName, StringComparison.OrdinalIgnoreCase));

            if (usesAssessmentSpec)
            {
                // Calculate Assessment Spec
                var result = await GetCalculatedAssessmentSpecAsync(partKey, forSds, includeFragranceComposition, includeGpsConfidentialComposition);

                AssessmentSpecResult assessmentSpecResult = Mapper.Map <AssessmentSpecResult>(result);
                return(assessmentSpecResult);
            }
            else
            {
                // Calculate BOS
                var result = await GetCalculatedBosAsync(partKey, forSds, includeFragranceComposition, allowResultWhenBosErrors);

                //IMapper mapper = MapUtil.Mapper;
                BillOfSubstance billOfSubstance = Mapper.Map <BillOfSubstance>(result);
                return(billOfSubstance);               // as ICalculatedComponentsResult;
            }
        }
    }
Esempio n. 3
0
        public static async Task <List <DepotOperationResultStatus> > ProcessDepotRequest(string prodKeys, string sourceSystem, bool overrideBOSErrors, int formulaLowerPercentValidation, int formulaUpperPercentValidation, int?existingRequestId = 0, int?parentBOMRequestId = 0, string BOMRequestTargetKey = null)
        //public static List<DepotOperationResultStatus> ProcessDepotRequest(string prodKeys, string sourceSystem, int formulaLowerPercentValidation, int formulaUpperPercentValidation, int? existingRequestId = 0)
        {
            UpdatedBy = GetCurrentUser();

            //existingRequestId: is this a brand new request (existingRequestId = 0) or a request that was partially processed before
            List <DepotOperationResultStatus> request_ret = new List <DepotOperationResultStatus>();
            DepotOperationResultStatus        r;

            string[] lookupKeys;
            string   prodKeysCommaDelimited = Regex.Replace(prodKeys, @"\r\n?|\n", ",");

            if (existingRequestId == 0)
            {
                lookupKeys = prodKeysCommaDelimited.Replace(" ", "").Split(','); //allow only one or no spaces between commas
            }
            else
            {
                lookupKeys = DbEfFactory.GetUnprocessedRequestParts(existingRequestId.GetValueOrDefault()); //allow only one or no spaces between commas
            }
            //Dictionary<string, DepotPart> results;



            DepotOperationResultStatus bos_ret = new DepotOperationResultStatus();
            IMapper mapper    = MapUtil.Mapper;
            string  depotUser = depotAccessRecord.DepotUser;
            string  depotPwd  = depotAccessRecord.DepotPass;

            var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{depotUser}:{depotPwd}"));
            var depotAuth   = new AuthenticationHeaderValue("Basic", credentials);


            List <Part> bestpartsList = GetBestParts(prodKeysCommaDelimited);

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = depotAuth;
                var              depot                   = new GpsDepotClient(depotAccessRecord.DepotUrl, client);
                string           errorMsg                = "";
                List <DepotPart> depotPartsList          = mapper.Map <List <Part>, List <DepotPart> >(bestpartsList);
                Dictionary <string, DepotPart> bestparts = depotPartsList.ToDictionary(p => p.PartSrcKey, p => p, StringComparer.OrdinalIgnoreCase);
                //  Dictionary<string, DepotPart> bestparts = (mapper.Map<List<Part>, List<DepotPart>>().GetAwaiter().GetResult().ToList<Part>())
                //?? new List<DepotPart>(0)).ToDictionary(p => p.PartSrcKey, p => p, StringComparer.OrdinalIgnoreCase);

                if (bestparts.Count == 0)
                {
                    //bos_ret.RequestedPart = sourcekey;
                    if (parentBOMRequestId > 0)
                    {
                        bos_ret.ResultCount = 0;
                        bos_ret.RequestId   = parentBOMRequestId.GetValueOrDefault();
                        //bos_ret.ProcessedPartKey=
                        bos_ret.ErrorMessage  = "Error encountered, no bestparts found for " + prodKeysCommaDelimited + " in BOM Request# " + parentBOMRequestId.GetValueOrDefault().ToString() + " or service may not be available.";
                        bos_ret.ErrorReceived = true;
                        DbEfFactory.UpdateBOSLoadStatus("bom_load_failed", UpdatedBy, bos_ret);
                    }
                    else
                    {
                        bos_ret.ResultCount  = 0;
                        bos_ret.ErrorMessage = "Error encountered, no bestparts found for " + prodKeysCommaDelimited + ", or service may not be available.";
                        DbEfFactory.UpdateBOSLoadStatus("bos_load_failed", UpdatedBy, bos_ret);
                    }
                    request_ret.Add(new DepotOperationResultStatus(bos_ret));
                    return(request_ret);
                }

                if (bestparts.Count > 0 && bestparts.Count < lookupKeys.Length)
                {
                    errorMsg = "";
                    foreach (string mykey in lookupKeys)
                    {
                        if (!bestparts.ContainsKey(mykey))
                        {
                            errorMsg += mykey + ",";
                        }
                    }
                    errorMsg              = "The following key(s) are missing bestpart: " + errorMsg.TrimEnd(',');
                    bos_ret.ErrorMessage  = "Error encountered, " + errorMsg + " in BOM Request# " + parentBOMRequestId.GetValueOrDefault().ToString() + ".";
                    bos_ret.ErrorReceived = true;
                    //bos_ret.ResultCount = 0;
                    bos_ret.RequestId = parentBOMRequestId.GetValueOrDefault();
                    request_ret.Add(new DepotOperationResultStatus(bos_ret));


                    DbEfFactory.UpdateBOSLoadStatus("bom_load_failed", UpdatedBy, bos_ret);

                    //return request_ret;
                }
                if (parentBOMRequestId == 0)
                {
                    bos_ret = DbEfFactory.AddDepotFormulaRequest(prodKeysCommaDelimited, formulaLowerPercentValidation, formulaUpperPercentValidation, bestparts, "Depot", "Formula Request", UpdatedBy);
                }
                else
                {
                    //write PartName, PartType, etc. in the formula_request_queue table...
                    bos_ret            = DbEfFactory.UpdateBOMRequestDepotFormula(prodKeysCommaDelimited, formulaLowerPercentValidation, formulaUpperPercentValidation, bestparts, "Depot", parentBOMRequestId.GetValueOrDefault(), BOMRequestTargetKey, UpdatedBy);
                    bos_ret.RequestId  = parentBOMRequestId.GetValueOrDefault();
                    bos_ret.StatusCode = "0";
                }
                foreach (KeyValuePair <string, DepotPart> thispart in bestparts)
                {
                    //ICalculatedComponentsResult result = depot.BillOfSubstance.GetCalculatedComponentsForBestPart(sourcekey, forSds: true, requireSDSSpecific: false, includeFragranceComposition: true);
                    //thispart.PartKey = "91119915.004";
                    //ICalculatedComponentsResult result = depot.BillOfSubstance.GetCalculatedComponentsForPart(thispart.Value, forSds: true, includeFragranceComposition: true, requireSDSSpecific: false);
                    ICalculatedComponentsResult result = await depot.GetCalculatedComponentsForPartAsync(thispart.Value,
                                                                                                         forSds : true,
                                                                                                         includeFragranceComposition : true,
                                                                                                         requireSDSSpecific : false,
                                                                                                         partTypesForAssessmentSpecs : null,
                                                                                                         allowResultWhenBosErrors : overrideBOSErrors);

                    //use mypartTypesForAssessmentSpecs to override default values

                    bos_ret.ResultCount = result.CalculatedComponents?.Count() ?? 0;

                    if (bos_ret.ResultCount == 0)
                    {
                        //bos_ret.RequestedPart = sourcekey;
                        bos_ret.RequestedPart    = thispart.Key;
                        bos_ret.ProcessedPartKey = "";
                        //bos_ret.ErrorMessage = "No Parts Found for " + sourcekey;
                        bos_ret.ErrorMessage  = "No Parts Found for " + thispart.Key + " in BOM Request# " + parentBOMRequestId.GetValueOrDefault().ToString() + ".";
                        bos_ret.ErrorReceived = true;
                        bos_ret.ResultCount   = 0;
                        //request_ret.Add(new DepotOperationResultStatus(bos_ret));
                        DbEfFactory.UpdateBOSLoadStatus("bos_load_missing", UpdatedBy, bos_ret);
                        if ((result.Errors?.Any() ?? false) || (result.Warnings?.Any() ?? false))
                        {
                            r = DbEfFactory.SaveDepotRequestBos(bos_ret.RequestId, bos_ret.RequestedPart, sourceSystem, UpdatedBy, result, null);
                        }

                        request_ret.Add(new DepotOperationResultStatus(bos_ret));
                        continue; //fetch the next sourcekey in lookupKeys
                    }

                    else
                    {
                        try
                        {
                            DepotPart part = result?.SourceParts?.FirstOrDefault();
                            bos_ret.RequestedPart    = part.PartSrcKey;
                            bos_ret.ProcessedPartKey = part.PartKey; //part.PartSrcKey+"."+part.PartSrcRevision;
                            bos_ret.PartTypeName     = part.PartTypeName;
                            DbEfFactory.UpdateBOSLoadStatus("bos_load_started", UpdatedBy, bos_ret);

                            /*
                             * IEnumerable<string> attrNameFilter = new[]{"PRIMARY CAS #","Primary CAS Region", "CAS #"};
                             * //IEnumerable<string> partKeys = new[] { part.PartKey };
                             *
                             * IEnumerable<string> partKeys = GetFormulaComponentList(result.CalculatedComponents);
                             * List<DepotPartAttribute> partMultiCASAttributes=null;
                             * if ((partKeys?.Count() ?? 0) >0)
                             *  partMultiCASAttributes = depot.Parts.GetPartAttributesByPartKeys(partKeys, attrNameFilter);
                             */

                            r = DbEfFactory.SaveDepotRequestBos(bos_ret.RequestId, bos_ret.RequestedPart, sourceSystem, UpdatedBy, result, partMultiCASAttributes: null);
                            bos_ret.ResultCount = result.CalculatedComponents?.Count() ?? -1; // bos?.Count() ?? -1;
                            if (bos_ret.ResultCount == -1)
                            {
                                DbEfFactory.UpdateBOSLoadStatus("bos_load_completed_with_errors", UpdatedBy, bos_ret);
                            }
                            else
                            {
                                DbEfFactory.UpdateBOSLoadStatus("bos_load_completed", UpdatedBy, bos_ret);
                            }
                            bos_ret.SuccessMessage = r.SuccessMessage;
                            bos_ret.ErrorMessage   = r.ErrorMessage;
                            //bos_ret.RequestedPart = bos_ret.RequestedPart; //part.PartSrcKey;
                            //bos_ret.ProcessedPartKey = bos_ret.ProcessedPartKey; //part.PartKey; //part.PartSrcKey+"."+part.PartSrcRevision;
                            //request_ret.Add(bos_ret);
                        } //try


                        catch (Exception e)
                        {
                            bos_ret.SuccessMessage = null;
                            bos_ret.ErrorMessage   = "Message:" + e.Message + ". "; // InnerException:" + e.InnerException.Message;
                            Logger.Error(e, "Error Processing Depot Rquest");
                            //request_ret.Add(bos_ret);
                            DbEfFactory.UpdateBOSLoadStatus("bos_load_failed", UpdatedBy, bos_ret);
                            request_ret.Add(new DepotOperationResultStatus(bos_ret));
                            continue;
                        }
                    } //else

                    //request_ret.Add(bos_ret);
                    request_ret.Add(new DepotOperationResultStatus(bos_ret));
                } //foreach
            }     //using
            return(request_ret);
        }