/// <summary>
        /// Ask user for approval for creation of another reversal if reversing <see cref="TaxAdjustment"/> already exists.
        /// </summary>
        /// <param name="taxAdjToReverse">The tax adjustment to reverse.</param>
        /// <returns/>
        private bool AskUserApprovalIfReversingDocumentAlreadyExists(TaxAdjustment taxAdjToReverse)
        {
            TaxAdjustment reversingTaxAdj =
                PXSelect <TaxAdjustment,
                          Where <TaxAdjustment.docType, Equal <Required <TaxAdjustment.docType> >,
                                 And <TaxAdjustment.origRefNbr, Equal <Required <TaxAdjustment.origRefNbr> > > >,
                          OrderBy <
                              Desc <TaxAdjustment.createdDateTime> > >
                .SelectSingleBound(this, currents : null, pars : new[] { taxAdjToReverse.DocType, taxAdjToReverse.RefNbr });

            if (reversingTaxAdj == null)
            {
                return(true);
            }

            string docTypeDescr;

            TaxAdjustmentType.ListAttribute labelsListAttribute = new TaxAdjustmentType.ListAttribute();

            if (!labelsListAttribute.ValueLabelDic.TryGetValue(reversingTaxAdj.DocType, out docTypeDescr))
            {
                docTypeDescr = taxAdjToReverse.DocType;
                PXTrace.WriteWarning("Failed to retrieve tax adjustment type {0} description from {1} attribute.", reversingTaxAdj.DocType,
                                     nameof(TaxAdjustmentType.ListAttribute));
            }

            string localizedMsg = PXMessages.LocalizeFormatNoPrefix(AR.Messages.ReversingDocumentExists, docTypeDescr, reversingTaxAdj.RefNbr);

            return(Document.Ask(Messages.Reverse, localizedMsg, MessageButtons.YesNo).IsPositive());
        }
Esempio n. 2
0
        public virtual IEnumerable <ApproveInfo> Assign(Table item, EPAssignmentMap map, bool isApprove)
        {
            path.Clear();

            processMapType = GraphHelper.GetType(map.EntityType);
            Type itemType = item.GetType();

            PXSelectBase <EPAssignmentRoute> rs = new
                                                  PXSelectReadonly <EPAssignmentRoute,
                                                                    Where <EPAssignmentRoute.assignmentMapID, Equal <Required <EPAssignmentMap.assignmentMapID> >,
                                                                           And <EPAssignmentRoute.parent, IsNull> >,
                                                                    OrderBy <Asc <EPAssignmentRoute.sequence> > >(this);

            PXResultset <EPAssignmentRoute> routes = rs.Select(map.AssignmentMapID, null);
            Type mapgraphtype = GraphHelper.GetType(map.GraphType);

            //impossible, but written to support purpose of legacy db states
            if (mapgraphtype == null)
            {
                mapgraphtype = EntityHelper.GetPrimaryGraphType(this, processMapType);
            }

            if (_Graph != null && mapgraphtype.IsAssignableFrom(_Graph.GetType()))
            {
                processGraph = _Graph;
            }
            else
            {
                processGraph = CreateInstance(GraphHelper.GetType(map.GraphType) ?? mapgraphtype);
            }

            if (processGraph != null && processMapType != null)
            {
                if (processMapType.IsAssignableFrom(itemType))
                {
                    this.processGraph.Caches[itemType].Current = item;
                }
                else if (itemType.IsAssignableFrom(processMapType))
                {
                    object  placed = this.processGraph.Caches[processMapType].CreateInstance();
                    PXCache cache  = (PXCache)Activator.CreateInstance(typeof(PXCache <>).MakeGenericType(itemType), this);
                    cache.RestoreCopy(placed, item);
                    this.processGraph.Caches[processMapType].Current = placed;
                }
                else
                {
                    return(null);
                }
            }

            var result = ProcessLevel(item, map.AssignmentMapID, routes).ToList();

            if (result.Any())
            {
                return(result);
            }

            PXTrace.WriteWarning(Messages.DocumentPreApproved);
            throw new RequestApproveException();
        }
        protected virtual void RecalculatePackagesForOrder(Document doc)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (string.IsNullOrEmpty(doc.ShipVia))
            {
                throw new PXException(Messages.ShipViaMustBeSet);
            }

            ClearPackages(doc);

            IList <SOPackageEngine.PackSet> packsets = CalculatePackages(doc, doc.ShipVia);

            foreach (SOPackageEngine.PackSet ps in packsets)
            {
                if (ps.Packages.Count > 1000)
                {
                    PXTrace.WriteWarning("During autopackaging more than 1000 packages were generated. Please check your configuration.");
                }

                InsertPackages(ps.Packages);
            }
            if (packsets.Count > 0)
            {
                Documents.Cache.SetValue <Document.isPackageValid>(doc, true);
            }
        }
Esempio n. 4
0
        public const int FileNameMaxLength = 208;         //2^7 + 2^6 + 2^4
        public FileDto(Guid entityId, string name, byte[] content, Guid?fileId = null, string contentId = null)
        {
            EntityNoteId = entityId;
            Content      = content ?? throw new ArgumentNullException(nameof(content));
            Name         = name ?? throw new ArgumentNullException(nameof(name));
            try
            {
                var extension = System.IO.Path.GetExtension(Name);
                if (Name.Length > FileNameMaxLength)
                {
                    if (extension.IsNullOrEmpty())
                    {
                        var newName = Name.Substring(0, FileNameMaxLength);
                        PXTrace.WriteWarning("Trying to save file with too long name. The name was cut off. Original value: {0}, new value: {1}", name, newName);
                        Name = newName;
                    }
                    else
                    {
                        var newName = Name.Substring(0, FileNameMaxLength + extension.Length);
                        PXTrace.WriteWarning("Trying to save file with too long name. The name was cut off. Original value: {0}, new value: {1}", name, newName);
                        Name = newName + extension;
                    }
                }
            }
            catch
            {
                PXTrace.WriteWarning("Trying to save file with invalid file name. The name will be replaced with default: \'file\'.");
                Name = "file";
            }

            FileId    = fileId ?? Guid.NewGuid();
            ContentId = contentId;
        }
Esempio n. 5
0
        public virtual List <BoxInfo> PackByWeight(List <INItemBoxEx> boxes, decimal baseWeight, decimal baseQty, int inventoryID)
        {
            boxes.Sort((INItemBoxEx x, INItemBoxEx y) => decimal.Compare(x.MaxWeight.GetValueOrDefault(), y.MaxWeight.GetValueOrDefault()));
            List <BoxInfo> list = new List <BoxInfo>();

            if (baseQty == 0)
            {
                PXTrace.WriteWarning("Packing Engine failed to execute. BaseQty supplied is zero.");

                return(list);
            }

            decimal unitWeight = baseWeight / baseQty;

            if (baseWeight > 0 && boxes.Count > 0)
            {
                INItemBoxEx box = GetBoxThatCanFitWeight(boxes, baseWeight);
                if (box != null)
                {
                    BoxInfo p = new BoxInfo();
                    p.Box   = box;
                    p.Value = baseWeight;
                    list.Add(p);
                }
                else
                {
                    //Distribute qty among Biggest boxes available:
                    INItemBoxEx biggestBox = boxes[boxes.Count - 1];

                    if (biggestBox.MaxNetWeight > 0)
                    {
                        if (biggestBox.MaxNetWeight < unitWeight)
                        {
                            throw new PXException(Messages.PackagesRecalcErrorNoBoxesThatFitItem, InventoryItem.PK.Find(graph, (int?)inventoryID)?.InventoryCD);
                        }

                        int numberOfMaxBoxes = (int)Math.Floor(baseWeight / biggestBox.MaxNetWeight);

                        int itemsPerBox = (int)Math.Floor(biggestBox.MaxNetWeight / unitWeight);

                        for (int i = 0; i < numberOfMaxBoxes; i++)
                        {
                            BoxInfo p = new BoxInfo();
                            p.Box   = biggestBox;
                            p.Value = itemsPerBox * unitWeight;
                            list.Add(p);

                            baseWeight -= itemsPerBox * unitWeight;
                            baseQty    -= itemsPerBox;
                        }

                        //remainder
                        list.AddRange(PackByWeight(boxes, baseWeight, baseQty, inventoryID));
                    }
                }
            }

            return(list);
        }
Esempio n. 6
0
        public virtual void CheckPartiallyReceiptedPOServices(PXCache sender, PXFieldUpdatedEventArgs e, string poOrderType)
        {
            POSetup row = (POSetup)e.Row;

            if (row != null)
            {
                PXResultset <POLine> partiallyReceiptedPOServices = PXSelectReadonly2 <POLine,
                                                                                       InnerJoin <IN.InventoryItem,
                                                                                                  On <POLine.FK.InventoryItem> >,
                                                                                       Where <POLine.orderType, Equal <Required <POLine.orderType> >,
                                                                                              And <POLine.lineType, Equal <POLineType.service>, And <POLine.completed, NotEqual <True>,
                                                                                                                                                     And <POLine.receivedQty, NotEqual <decimal0> > > > > > .SelectWindowed(this, 0, 1000, poOrderType);

                if (partiallyReceiptedPOServices.Count > 0)
                {
                    if (poOrderType == POOrderType.RegularOrder)
                    {
                        if (row.AddServicesFromNormalPOtoPR == true)
                        {
                            PXUIFieldAttribute.SetWarning <POSetup.addServicesFromNormalPOtoPR>(sender, row, Messages.PossibleOverbillingAPNormalPO);
                        }
                        else
                        {
                            PXUIFieldAttribute.SetWarning <POSetup.addServicesFromNormalPOtoPR>(sender, row, Messages.PossibleOverbillingPRNormalPO);
                        }
                    }
                    else
                    {
                        if (row.AddServicesFromDSPOtoPR == true)
                        {
                            PXUIFieldAttribute.SetWarning <POSetup.addServicesFromDSPOtoPR>(sender, row, Messages.PossibleOverbillingAPDSPO);
                        }
                        else
                        {
                            PXUIFieldAttribute.SetWarning <POSetup.addServicesFromDSPOtoPR>(sender, row, Messages.PossibleOverbillingPRDSPO);
                        }
                    }

                    string overbillingMessage = Messages.PossibleOverbillingTraceList + " \n";
                    int    i = 0;
                    foreach (PXResult <POLine, IN.InventoryItem> line in partiallyReceiptedPOServices)
                    {
                        POLine           poline = (POLine)line;
                        IN.InventoryItem item   = (IN.InventoryItem)line;
                        overbillingMessage += string.Format(Messages.PossibleOverbillingTraceMessage, (poOrderType == POOrderType.RegularOrder ? Messages.RegularOrder : Messages.DropShip), poline.OrderNbr, poline.LineNbr, item.InventoryCD) + "\n";
                        i++;
                        if (i >= 1000)
                        {
                            break;
                        }
                    }
                    PXTrace.WriteWarning(overbillingMessage);
                }
            }
        }
Esempio n. 7
0
        public virtual IEnumerable trainFaceRecongnition(PXAdapter adapter)
        {
            Save.Press();

            PXLongOperation.StartOperation(this, delegate()
            {
                IFaceClient client = Trainer.Authenticate(MasterView.Current.FaceApiEndpoint, MasterView.Current.FaceApiSubscriptionKey);
                var trainer        = new Trainer(client, MasterView.Current.FaceApiGroupID);
                bool uploaded      = false;
                foreach (EPEmployee emp in PXSelect <EPEmployee> .Select(this))
                {
                    bool deleted  = false;
                    Person person = null;
                    Guid[] files  = PXNoteAttribute.GetFileNotes(this.Caches[typeof(EPEmployee)], emp);

                    foreach (Guid fileID in files)
                    {
                        var fm            = new PX.SM.UploadFileMaintenance();
                        PX.SM.FileInfo fi = fm.GetFile(fileID);
                        string ext        = System.IO.Path.GetExtension(fi.Name).ToLower();
                        PXTrace.WriteWarning(emp.AcctCD.TrimEnd() + " " + ext);
                        if (ext.IsIn(".png", ".jpg", ".bmp"))
                        {
                            if (!deleted)
                            {
                                var utilities = new Utilities(client, MasterView.Current.FaceApiGroupID);
                                utilities.DeleteEmployee(emp.AcctCD.TrimEnd());
                                deleted = true;
                            }

                            if (person == null)
                            {
                                person = trainer.GetEmployee_CreateIfNonExistent(emp.AcctCD.TrimEnd());
                            }


                            using (var stream = new System.IO.MemoryStream(fi.BinData))
                            {
                                PXTrace.WriteWarning(emp.AcctCD.TrimEnd() + " " + fi.Name + " " + stream.Length);
                                trainer.UploadTrainingImageStream(person, stream);
                                Thread.Sleep(1000);
                                uploaded = true;
                            }
                        }
                    }
                }
                if (uploaded)
                {
                    trainer.InvokeTraining();
                }
            });


            return(adapter.Get());
        }
        public string GetOrCreateSublevelFolder(UserTokenHandler tokenHandler, string screenID, string parentFolderID, Guid?refNoteID, bool throwOnError)
        {
            BoxFolderSublevelCache sublevelFolder;
            var subLevelGrouping = GetSublevelName(refNoteID);

            if (string.IsNullOrEmpty(subLevelGrouping))
            {
                if (throwOnError)
                {
                    ScreenUtils.TraceAndThrowException(Messages.SubLevelConfigurationInvalid);
                }
                else
                {
                    PXTrace.WriteWarning(string.Format("No sublevel grouping found for note ID {0} (screen {1}, parent folder {2})", refNoteID, screenID, parentFolderID));
                    return(null);
                }
            }

            sublevelFolder = (BoxFolderSublevelCache)SubLevelByScreenAndGrouping.Select(screenID, subLevelGrouping);
            if (sublevelFolder == null)
            {
                var subLevelFolderInfo = GetOrCreateFolder(tokenHandler, parentFolderID, null, null, subLevelGrouping);

                sublevelFolder          = (BoxFolderSublevelCache)SubLevelByScreenAndGrouping.Cache.CreateInstance();
                sublevelFolder.FolderID = subLevelFolderInfo.ID;
                sublevelFolder.Grouping = subLevelGrouping;
                sublevelFolder.ScreenID = screenID;
                SubLevelByScreenAndGrouping.Insert(sublevelFolder);
            }
            else
            {
                try
                {
                    // Folder was found in BoxFolderCache, retrieve it by ID
                    var sublevelFolderInfo = BoxUtils.GetFolderInfo(tokenHandler, sublevelFolder.FolderID).Result;
                }
                catch (AggregateException ae)
                {
                    ScreenUtils.HandleAggregateException(ae, HttpStatusCode.NotFound, (exception) =>
                    {
                        using (new PXConnectionScope())
                        {
                            // Delete entry from BoxFolderCache so that it gets created again.
                            SubLevelByScreenAndGrouping.Delete(sublevelFolder);
                            Actions.PressSave();
                        }

                        throw new PXException(Messages.BoxFolderNotFoundTryAgain, sublevelFolder.FolderID, exception);
                    });
                }
            }

            return(sublevelFolder.FolderID);
        }
Esempio n. 9
0
        protected static void LogMessages(BaseResult result)
        {
            foreach (AvaMessage msg in result.Messages)
            {
                switch (result.ResultCode)
                {
                case SeverityLevel.Exception:
                case SeverityLevel.Error:
                    PXTrace.WriteError(msg.Summary + ": " + msg.Details);
                    break;

                case SeverityLevel.Warning:
                    PXTrace.WriteWarning(msg.Summary + ": " + msg.Details);
                    break;
                }
            }
        }
Esempio n. 10
0
        public void Emit(LogEvent logEvent)
        {
            switch (logEvent.Level)
            {
            case LogEventLevel.Information:
            case LogEventLevel.Debug:
                PXTrace.WriteInformation(logEvent.ToTraceMessage(_formatProvider));
                break;

            case LogEventLevel.Error:
            case LogEventLevel.Fatal:
                PXTrace.WriteError(logEvent.ToTraceMessage(_formatProvider));
                break;

            case LogEventLevel.Warning:
                PXTrace.WriteWarning(logEvent.ToTraceMessage(_formatProvider));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Process Costs for a BOM.
        /// Copy standard method and add one more parameter to control qty round-up.
        /// </summary>
        protected virtual bool ProcessCost(AMBomItem bomItem, int level, bool isDefault, bool roundup = true)
        {
            var successful = true;

            if (bomItem?.BOMID == null)
            {
                return(false);
            }

            var bomcostrec = new AMBomCost
            {
                InventoryID       = bomItem.InventoryID,
                SubItemID         = bomItem.SubItemID,
                BOMID             = bomItem.BOMID,
                RevisionID        = bomItem.RevisionID,
                SiteID            = bomItem.SiteID,
                MultiLevelProcess = Settings.Current.SnglMlti == RollupSettings.SelectOptSM.Multi,
                UserID            = this.Accessinfo.UserID,
                Level             = level,
                // Might have to update later for subitem indication - currently only looks at INItemSite default BOM ID
                IsDefaultBom = isDefault
            };

            var invItem = JAMS.AM.InventoryHelper.CacheQueryInventoryItem(InvItemRecs.Cache, bomcostrec.InventoryID);

            bomcostrec.ItemClassID = invItem?.ItemClassID;

            //Set the Current and Pending cost from INItemSite
            var inItemSite = JAMS.AM.InventoryHelper.CacheQueryINItemSite(ItemSiteRecs.Cache, bomcostrec.InventoryID, bomcostrec.SiteID);

            bomcostrec.StdCost        = inItemSite?.StdCost;
            bomcostrec.PendingStdCost = inItemSite?.PendingStdCost;

            // Set Lot Size based on Filter Settings
            if (Settings.Current.IgnoreMinMaxLotSizeValues == true)
            {
                bomcostrec.LotSize = 1;
            }
            else if (bomcostrec.BOMID == Settings.Current.BOMID && Settings.Current.LotSize.GetValueOrDefault() != 0 &&
                     Settings.Current.IgnoreMinMaxLotSizeValues == false)
            {
                bomcostrec.LotSize = Settings.Current.LotSize.GetValueOrDefault();
            }
            else
            {
                bomcostrec.LotSize = invItem == null
                                     ? JAMS.AM.InventoryHelper.GetMfgReorderQty(this, bomcostrec.InventoryID, bomcostrec.SiteID)
                                     : JAMS.AM.InventoryHelper.GetMfgReorderQty(this, invItem, inItemSite);
            }

            if (bomcostrec.LotSize.GetValueOrDefault() <= 0)
            {
                bomcostrec.LotSize = 1;
            }

            bomcostrec.FLaborCost = 0;
            bomcostrec.VLaborCost = 0;
            var laborCostAndHours = SetLaborCost(ref bomcostrec, Settings.Current?.IncFixed == true);

            bomcostrec.MachCost = GetMachineCost(bomcostrec);
            bomcostrec.ToolCost = GetToolCost(bomcostrec);

            var allMaterial = PXSelectReadonly2 <AMBomMatl, InnerJoin <InventoryItem, On <AMBomMatl.inventoryID, Equal <InventoryItem.inventoryID> >,
                                                                       LeftJoin <INItemSite, On <AMBomMatl.inventoryID, Equal <INItemSite.inventoryID>,
                                                                                                 And <INItemSite.siteID, Equal <Required <INItemSite.siteID> > > > > >,
                                                 Where <AMBomMatl.bOMID, Equal <Required <AMBomMatl.bOMID> >,
                                                        And <AMBomMatl.revisionID, Equal <Required <AMBomMatl.revisionID> > > > > .Select(this, bomcostrec.SiteID, bomcostrec.BOMID, bomcostrec.RevisionID);

            //Merge of Regular Material and Subcontract Material (excluding Reference/vendor supplied material)
            OperationCosts matlTotal = new OperationCosts();

            if (allMaterial.Count > 0)
            {
                var purchase     = new List <PXResult <AMBomMatl, InventoryItem> >();
                var manufactured = new List <PXResult <AMBomMatl, InventoryItem> >();
                var subcontract  = new List <PXResult <AMBomMatl, InventoryItem> >();
                var refMaterial  = new List <PXResult <AMBomMatl, InventoryItem> >();

                foreach (PXResult <AMBomMatl, InventoryItem, INItemSite> result in allMaterial)
                {
                    var bomMatl = (AMBomMatl)result;
                    if (bomMatl == null ||
                        (bomMatl.EffDate != null && bomMatl.EffDate > Accessinfo.BusinessDate) ||
                        (bomMatl.ExpDate != null && bomMatl.ExpDate <= Accessinfo.BusinessDate))
                    {
                        continue;
                    }

                    // Check for COMP BOMID, if exists, item is Manufactured
                    if (bomMatl.CompBOMID != null)
                    {
                        manufactured.Add(result);
                        continue;
                    }

                    if (bomMatl.MaterialType == AMMaterialType.Subcontract && bomMatl.SubcontractSource != AMSubcontractSource.VendorSupplied)
                    {
                        subcontract.Add(result);
                        continue;
                    }

                    if (bomMatl.MaterialType == AMMaterialType.Subcontract && bomMatl.SubcontractSource == AMSubcontractSource.VendorSupplied)
                    {
                        refMaterial.Add(result);
                        continue;
                    }

                    var replenishmentSource = JAMS.AM.InventoryHelper.GetReplenishmentSource((InventoryItem)result, (INItemSite)result);
                    if (replenishmentSource == INReplenishmentSource.Manufactured)
                    {
                        manufactured.Add(result);
                        continue;
                    }

                    if (replenishmentSource == INReplenishmentSource.Purchased)
                    {
                        purchase.Add(result);
                    }
                }

                var purchaseCost     = GetMaterialCost(bomcostrec, purchase, IsMultiLevel, out var purchaseMatlMessages, roundup);
                var manufacturedCost = GetMaterialCost(bomcostrec, manufactured, IsMultiLevel, out var manufacturedMatlMessages, roundup);
                var subcontractCost  = GetMaterialCost(bomcostrec, subcontract, IsMultiLevel, out var subContractMatlMessages, roundup);
                var refmaterialCost  = GetMaterialCost(bomcostrec, refMaterial, IsMultiLevel, out var refMaterialMatlMessages, roundup);

                if (purchaseMatlMessages != null)
                {
                    foreach (var matlMessage in purchaseMatlMessages)
                    {
                        successful = false;
                        PXTrace.WriteWarning(matlMessage);
                    }
                }

                if (manufacturedMatlMessages != null)
                {
                    foreach (var matlMessage in manufacturedMatlMessages)
                    {
                        successful = false;
                        PXTrace.WriteWarning(matlMessage);
                    }
                }

                if (subContractMatlMessages != null)
                {
                    foreach (var matlMessage in subContractMatlMessages)
                    {
                        successful = false;
                        PXTrace.WriteWarning(matlMessage);
                    }
                }

                if (refMaterialMatlMessages != null)
                {
                    foreach (var matlMessage in refMaterialMatlMessages)
                    {
                        successful = false;
                        PXTrace.WriteWarning(matlMessage);
                    }
                }

                bomcostrec.MatlManufacturedCost    = manufacturedCost?.TotalCost ?? 0m;
                bomcostrec.MatlNonManufacturedCost = purchaseCost?.TotalCost ?? 0m;
                bomcostrec.SubcontractMaterialCost = subcontractCost?.TotalCost ?? 0m;
                bomcostrec.ReferenceMaterialCost   = refmaterialCost?.TotalCost ?? 0m;

                matlTotal = new OperationCosts(manufacturedCost);
                matlTotal.Add(purchaseCost, true);
                matlTotal.Add(subcontractCost, true);
            }

            bomcostrec.FOvdCost = 0;
            bomcostrec.VOvdCost = 0;
            SetOverheadCosts(ref bomcostrec, Settings.Current.IncFixed.GetValueOrDefault(), matlTotal, laborCostAndHours.Item1, laborCostAndHours.Item2);

            bomcostrec.TotalCost = bomcostrec.FLaborCost.GetValueOrDefault()
                                   + bomcostrec.VLaborCost.GetValueOrDefault()
                                   + bomcostrec.MachCost.GetValueOrDefault()
                                   + bomcostrec.MatlManufacturedCost.GetValueOrDefault()
                                   + bomcostrec.MatlNonManufacturedCost.GetValueOrDefault()
                                   + bomcostrec.FOvdCost.GetValueOrDefault()
                                   + bomcostrec.VOvdCost.GetValueOrDefault()
                                   + bomcostrec.ToolCost.GetValueOrDefault()
                                   + bomcostrec.OutsideCost.GetValueOrDefault()
                                   + bomcostrec.DirectCost.GetValueOrDefault()
                                   + bomcostrec.SubcontractMaterialCost.GetValueOrDefault()
                                   + bomcostrec.ReferenceMaterialCost.GetValueOrDefault();

            bomcostrec.UnitCost = UomHelper.PriceCostRound(bomcostrec.TotalCost.GetValueOrDefault() / bomcostrec.LotSize.GetValueOrDefault());

            try
            {
                BomCostRecs.Insert(bomcostrec);
            }
            catch (Exception e)
            {
                if (e is PXOuterException)
                {
                    PXTraceHelper.PxTraceOuterException((PXOuterException)e, PXTraceHelper.ErrorLevel.Error);
                }

                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, bomcostrec.InventoryID);

                if (item == null)
                {
                    PXTrace.WriteInformation(JAMS.AM.Messages.InvalidInventoryIDOnBOM, bomItem.BOMID);
                    successful = false;
                }
                else
                {
                    throw new PXException(JAMS.AM.Messages.GetLocal(JAMS.AM.Messages.UnableToSaveRecordForInventoryID), JAMS.AM.Messages.GetLocal(JAMS.AM.Messages.BOMCost), item.InventoryCD.Trim(), e.Message);
                }
            }

            return(successful);
        }
 public virtual void WriteWarning(string message)
 {
     PXTrace.WriteWarning(message);
 }
Esempio n. 13
0
        public static string GetTaxZoneByZip(PXGraph graph, string zipCode)
        {
            if (graph == null)
            {
                throw new ArgumentNullException("graph");
            }

            if (string.IsNullOrEmpty(zipCode))
            {
                throw new ArgumentNullException("zipCode");
            }

            //System.Text.RegularExpressions.Regex regexobject = new System.Text.RegularExpressions.Regex(regex);
            //return regexobject.IsMatch(val);

            PXResultset <TaxZoneZip> resultset = null;

            if (zipCode.Length == 5)
            {
                resultset = PXSelect <TaxZoneZip, Where <TaxZoneZip.zipCode, Equal <Required <TaxZoneZip.zipCode> > > > .Select(graph, zipCode);
            }
            else if (zipCode.Length == 10)
            {
                string zip     = zipCode.Substring(0, 5);
                string zipPlus = zipCode.Substring(6);


                int plus;

                if (int.TryParse(zipPlus, out plus))
                {
                    resultset = PXSelect <TaxZoneZip, Where <TaxZoneZip.zipCode, Equal <Required <TaxZoneZip.zipCode> >,
                                                             And <Required <TaxZoneZip.zipCode>, Between <TaxZoneZip.zipMin, TaxZoneZip.zipMax> > > > .Select(graph, zip, plus);
                }
                else
                {
                    PXTrace.WriteWarning("Failed to extract a valid zip+4 code (XXXXX-XXXX) from the following:{0}", zipCode);
                    return(null);
                }
            }
            else
            {
                PXTrace.WriteWarning("Failed to extract a valid zip code (XXXXX or XXXXX-XXXX) from the following:{0}", zipCode);
                return(null);
            }


            if (resultset.Count == 0)
            {
                PXTrace.WriteWarning("Failed to find record in TaxZoneZip for the given zip code:{0}", zipCode);
                return(null);
            }
            else if (resultset.Count > 1)
            {
                PXTrace.WriteWarning("{0} records returned from TaxZoneZip for the given zip code:{1}. Only first will be used.", resultset.Count, zipCode);

                return(((TaxZoneZip)resultset).TaxZoneID);
            }
            else
            {
                return(((TaxZoneZip)resultset).TaxZoneID);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Override the parent method to add additional conditions to control the quantity round-up logic.
        /// </summary>
        protected override AMMultiLevelBomData CreateDetailRow(AMBomMatl amBomMatl, AMBomOper amBomOper, AMBomItem amBomItem, InventoryItem inventoryItem, AMBomItem parentBomItem,
                                                               int lineID, int level, decimal totalQtyReq, AMMultiLevelBomFilter filter, string levelBomid, string levelRevisionID)
        {
            var itemExt = inventoryItem.GetExtension <JAMS.AEF.InventoryItemAMExtension>();

            var qtyRequired = amBomMatl.QtyReq.GetValueOrDefault() * (1 + amBomMatl.ScrapFactor.GetValueOrDefault()) *
                              (amBomMatl.BatchSize.GetValueOrDefault() == 0m ? 1m : 1 / amBomMatl.BatchSize.GetValueOrDefault());

            var totalQtyRequired = amBomMatl.QtyReq.GetValueOrDefault() * (1 + amBomMatl.ScrapFactor.GetValueOrDefault()) *
                                   (amBomMatl.BatchSize.GetValueOrDefault() == 0m ? 1m : totalQtyReq / amBomMatl.BatchSize.GetValueOrDefault());

            var baseTotalQtyRequired = amBomMatl.BaseQty.GetValueOrDefault() * (1 + amBomMatl.ScrapFactor.GetValueOrDefault()) *
                                       (amBomMatl.BatchSize.GetValueOrDefault() == 0m ? 1m : totalQtyReq / amBomMatl.BatchSize.GetValueOrDefault());

            // Add one custom field to determine the round-up logic.
            AMMultiLevelBomFilterExt filterExt = filter.GetExtension <AMMultiLevelBomFilterExt>();

            if (filterExt.UsrEnblItemRoundUp == true)
            {
                qtyRequired          = itemExt.AMQtyRoundUp == false ? qtyRequired : Math.Ceiling(qtyRequired);
                totalQtyRequired     = itemExt.AMQtyRoundUp == false ? totalQtyRequired : Math.Ceiling(totalQtyRequired);
                baseTotalQtyRequired = itemExt.AMQtyRoundUp == false ? baseTotalQtyRequired : Math.Ceiling(baseTotalQtyRequired);
            }

            var row = new AMMultiLevelBomData
            {
                ParentBOMID       = parentBomItem.BOMID,
                RevisionID        = parentBomItem.RevisionID,
                LineID            = lineID,
                Level             = level,
                InventoryID       = amBomMatl.InventoryID,
                Descr             = amBomMatl.Descr,
                ParentInventoryID = parentBomItem.InventoryID,
                ParentSubItemID   = parentBomItem.SubItemID,
                ParentDescr       = parentBomItem.Descr,
                SubItemID         = amBomMatl.SubItemID,
                UOM                  = amBomMatl.UOM,
                ScrapFactor          = amBomMatl.ScrapFactor.GetValueOrDefault(),
                BatchSize            = amBomMatl.BatchSize.GetValueOrDefault(),
                BOMQtyReq            = amBomMatl.QtyReq.GetValueOrDefault(),
                BaseQtyReq           = amBomMatl.BaseQty.GetValueOrDefault(),
                QtyReq               = qtyRequired,
                TotalQtyReq          = totalQtyRequired,
                BaseTotalQtyReq      = baseTotalQtyRequired,
                UnitCost             = amBomMatl.UnitCost.GetValueOrDefault(),
                ExtCost              = qtyRequired * amBomMatl.UnitCost.GetValueOrDefault(),
                TotalExtCost         = totalQtyRequired * amBomMatl.UnitCost.GetValueOrDefault(),
                LineBOMID            = amBomMatl.BOMID,
                LineRevisionID       = amBomMatl.RevisionID,
                OperationID          = amBomOper.OperationID,
                OperationCD          = amBomOper.OperationCD,
                EffStartDate         = parentBomItem.EffStartDate,
                EffEndDate           = parentBomItem.EffEndDate,
                SiteID               = parentBomItem.SiteID,
                Status               = parentBomItem.Status,
                LineStatus           = amBomItem.Status,
                MaterialStatus       = amBomItem.Status,
                OperationDescription = amBomOper.Descr,
                WcID                 = amBomOper.WcID,
                IsHeaderRecord       = false,
                SortOrder            = amBomMatl.SortOrder
            };

            var materialSiteID = amBomMatl.SiteID ?? amBomItem.SiteID;

            if (filter.IgnoreReplenishmentSettings.GetValueOrDefault() ||
                JAMS.AM.InventoryHelper.GetReplenishmentSource(this, row.InventoryID, materialSiteID) == INReplenishmentSource.Manufactured)
            {
                levelBomid      = amBomMatl.CompBOMID;
                levelRevisionID = amBomMatl.CompBOMRevisionID;

                if (!string.IsNullOrWhiteSpace(levelBomid) && !string.IsNullOrWhiteSpace(levelRevisionID))
                {
                    AMBomItem bomItem = null;

                    if (Filter.Current.IncludeBomsOnHold.GetValueOrDefault())
                    {
                        bomItem = PXSelect <AMBomItem, Where <AMBomItem.bOMID, Equal <Required <AMBomItem.bOMID> >,
                                                              And <AMBomItem.revisionID, Equal <Required <AMBomItem.revisionID> >,
                                                                   And2 <Where <AMBomItem.status, Equal <AMBomStatus.hold>,
                                                                                Or <AMBomItem.status, Equal <AMBomStatus.active> > >,
                                                                         And <Where <Required <AMBomItem.effStartDate>, Between <AMBomItem.effStartDate, AMBomItem.effEndDate>,
                                                                                     Or <Where <AMBomItem.effStartDate, LessEqual <Required <AMBomItem.effStartDate> >,
                                                                                                And <AMBomItem.effEndDate, IsNull> > > > > > > > >
                                  .Select(this, levelBomid, levelRevisionID, Filter.Current.BOMDate.GetValueOrDefault(), Filter.Current.BOMDate.GetValueOrDefault());
                    }
                    else
                    {
                        bomItem = PXSelect <AMBomItem, Where <AMBomItem.bOMID, Equal <Required <AMBomItem.bOMID> >,
                                                              And <AMBomItem.revisionID, Equal <Required <AMBomItem.revisionID> >,
                                                                   And <AMBomItem.status, Equal <AMBomStatus.active>,
                                                                        And <Where <Required <AMBomItem.effStartDate>, Between <AMBomItem.effStartDate, AMBomItem.effEndDate>,
                                                                                    Or <Where <AMBomItem.effStartDate, LessEqual <Required <AMBomItem.effStartDate> >,
                                                                                               And <AMBomItem.effEndDate, IsNull> > > > > > > > >
                                  .Select(this, levelBomid, levelRevisionID, Filter.Current.BOMDate.GetValueOrDefault(), Filter.Current.BOMDate.GetValueOrDefault());
                    }

                    if (bomItem == null)
                    {
                        PXTrace.WriteWarning(JAMS.AM.Messages.GetLocal(JAMS.AM.Messages.ComponentBOMRevisionNotActive, levelBomid, levelRevisionID, inventoryItem.InventoryCD));
                        return(row);
                    }
                }

                if (!string.IsNullOrWhiteSpace(levelBomid) && string.IsNullOrWhiteSpace(levelRevisionID))
                {
                    var compBomItem = filter.IncludeBomsOnHold == false
                                      ? PrimaryBomIDManager.GetActiveRevisionBomItemByDate(this, levelBomid, filter.BOMDate.GetValueOrDefault())
                                      : PrimaryBomIDManager.GetNotArchivedRevisionBomItemByDate(this, levelBomid, filter.BOMDate.GetValueOrDefault());

                    if (compBomItem == null)
                    {
                        PXTrace.WriteWarning(JAMS.AM.Messages.GetLocal(JAMS.AM.Messages.NoActiveRevisionForBom, parentBomItem.BOMID));
                        return(row);
                    }

                    levelRevisionID = compBomItem.RevisionID;
                }

                if (string.IsNullOrWhiteSpace(levelBomid))
                {
                    var bomItem = filter.IncludeBomsOnHold == false
                                  ? PrimaryBomIDManager.GetActiveRevisionBomItemByDate(this, new PrimaryBomIDManager(this).GetPrimaryAllLevels(row.InventoryID,
                                                                                                                                               materialSiteID, row.SubItemID), filter.BOMDate.GetValueOrDefault())
                                  : PrimaryBomIDManager.GetNotArchivedRevisionBomItemByDate(this, new PrimaryBomIDManager(this).GetPrimaryAllLevels(row.InventoryID,
                                                                                                                                                    materialSiteID, row.SubItemID), filter.BOMDate.GetValueOrDefault());

                    if (bomItem == null)
                    {
                        PXTrace.WriteWarning(JAMS.AM.Messages.GetLocal(JAMS.AM.Messages.NoActiveRevisionForBom, parentBomItem.BOMID));
                        return(row);
                    }

                    levelBomid      = bomItem.BOMID;
                    levelRevisionID = bomItem.RevisionID;
                }

                row.ManufacturingBOMID      = levelBomid;
                row.ManufacturingRevisionID = levelRevisionID;
            }

            return(row);
        }
        public virtual void UpdateRates()
        {
            if (Documents.Current != null)
            {
                CarrierRates.Cache.Clear();

                ValidatePackages();
                bool autoPackWarning = false;

                List <CarrierRequestInfo> requests = new List <CarrierRequestInfo>();
                foreach (CarrierPlugin plugin in GetApplicableCarrierPlugins())
                {
                    ICarrierService cs = CarrierPluginMaint.CreateCarrierService(Base, plugin);
                    if (cs != null)
                    {
                        CarrierRequest cRequest = BuildQuoteRequest(Documents.Current, plugin);
                        if (cRequest.PackagesEx.Count == 0)
                        {
                            PXTrace.WriteWarning(Messages.AutoPackagingZeroPackWarning, plugin.CarrierPluginID);
                            autoPackWarning = true;
                            continue;
                        }

                        requests.Add(new CarrierRequestInfo
                        {
                            Plugin  = plugin,
                            Service = cs,
                            Request = cRequest
                        });
                    }
                }

                Parallel.ForEach(requests, info => info.Result = info.Service.GetRateList(info.Request));

                int           cx            = 0;
                StringBuilder errorMessages = new StringBuilder();
                foreach (CarrierRequestInfo info in requests)
                {
                    CarrierResult <IList <RateQuote> > result = info.Result;

                    if (result.IsSuccess)
                    {
                        foreach (RateQuote item in result.Result)
                        {
                            if (item.IsSuccess && item.Currency != Documents.Current.CuryID)
                            {
                                if (string.IsNullOrEmpty(arsetup.Current.DefaultRateTypeID))
                                {
                                    throw new PXException(Messages.RateTypeNotSpecified);
                                }
                            }

                            PXSelectBase <Carrier> selectCarrier = new PXSelectReadonly <Carrier,
                                                                                         Where <Carrier.carrierPluginID, Equal <Required <Carrier.carrierPluginID> >,
                                                                                                And <Carrier.pluginMethod, Equal <Required <Carrier.pluginMethod> >,
                                                                                                     And <Carrier.isExternal, Equal <True> > > > >(Base);

                            foreach (Carrier shipVia in selectCarrier.Select(info.Plugin.CarrierPluginID, item.Method.Code))
                            {
                                var r = new SOCarrierRate
                                {
                                    LineNbr      = cx++,
                                    Method       = shipVia.CarrierID,
                                    Description  = item.Method.Description,
                                    Amount       = ConvertAmt(item.Currency, Documents.Current.CuryID, arsetup.Current.DefaultRateTypeID, Documents.Current.DocumentDate.Value, item.Amount),
                                    DeliveryDate = item.DeliveryDate
                                };

                                r.Selected = r.Method == Documents.Current.ShipVia;
                                if (item.DaysInTransit > 0)
                                {
                                    r.DaysInTransit = item.DaysInTransit;
                                }
                                r = CarrierRates.Insert(r);

                                if (!item.IsSuccess)
                                {
                                    CarrierRates.Cache.RaiseExceptionHandling(typeof(SOCarrierRate.method).Name, r, null, new PXSetPropertyException("{0}: {1}", PXErrorLevel.RowError, item.Messages[0].Code, item.Messages[0].Description));
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (Message message in result.Messages)
                        {
                            errorMessages.AppendFormat(PXMessages.LocalizeNoPrefix(Messages.ReturnedError), info.Plugin.CarrierPluginID, message.ToString());
                        }

                        if (!string.IsNullOrEmpty(result.RequestData))
                        {
                            PXTrace.WriteInformation(result.RequestData);
                        }
                    }
                }


                if (errorMessages.Length > 0)
                {
                    throw new PXException(Messages.CarrierServiceError, errorMessages.ToString());
                }

                if (autoPackWarning)
                {
                    throw new PXException(Messages.AutoPackagingIssuesCheckTrace);
                }
            }
        }
Esempio n. 16
0
		public static void ProcessDoc(ARPaymentEntry graph, ARStatementCycle cycle, ARAutoApplyParameters filter)
		{
			List<ARRegister> toRelease = new List<ARRegister>();

			HashSet<string> trace = new HashSet<string>();
			string warningRefNbr = String.Empty;

			int?[] branches = PXAccess.GetBranchIDs().Select(i => (int?)i).ToArray<int?>();

			foreach (Customer customer in GetCustomersForAutoApplication(graph, cycle, filter))
			{
				List<ARInvoice> arInvoiceList = new List<ARInvoice>();

				var invoiceQuery = new PXSelectJoin<ARInvoice,
					InnerJoin<Customer, On<ARInvoice.customerID, Equal<Customer.bAccountID>>>,
					Where<ARInvoice.released, Equal<True>,
						And<ARInvoice.openDoc, Equal<True>,
						And<ARInvoice.pendingPPD, NotEqual<True>, 
						And<Where<ARInvoice.docType, Equal<ARDocType.invoice>,
							Or<ARInvoice.docType, Equal<ARDocType.finCharge>,
							Or<ARInvoice.docType, Equal<ARDocType.debitMemo>>>>>>>>,
					OrderBy<Asc<ARInvoice.dueDate>>>(graph);

				if(filter.LoadChildDocuments == LoadChildDocumentsOptions.None || customer.ParentBAccountID != null)
				{
					invoiceQuery.WhereAnd<Where<Customer.bAccountID, Equal<Required<ARInvoice.customerID>>>>();
				}
				else
				{
					invoiceQuery.WhereAnd<Where<Customer.consolidatingBAccountID, Equal<Required<ARInvoice.customerID>>>>();
				}

				PXResultset<ARInvoice> invoices;
				using (new PXReadBranchRestrictedScope(null, branches, true, false))
				{
					invoices = invoiceQuery.Select(customer.BAccountID);
				}

				foreach (ARInvoice invoice in invoices)
				{
					arInvoiceList.Add(invoice);
				}

				arInvoiceList.Sort(new Comparison<ARInvoice>(delegate(ARInvoice a, ARInvoice b)
					{
						if ((bool)graph.arsetup.Current.FinChargeFirst)
						{
							int aSortOrder = (a.DocType == ARDocType.FinCharge ? 0 : 1);
							int bSortOrder = (b.DocType == ARDocType.FinCharge ? 0 : 1);
							int ret = ((IComparable)aSortOrder).CompareTo(bSortOrder);
							if (ret != 0)
							{
								return ret;
							}
						}

						{
							object aDueDate = a.DueDate;
							object bDueDate = b.DueDate;
							int ret = ((IComparable)aDueDate).CompareTo(bDueDate);

							return ret;
						}
					}
				));

				if (arInvoiceList.Count > 0)
				{
					PXSelectBase<ARPayment> getPaymentsQuery =
						new PXSelectJoin<ARPayment,
								InnerJoin<Branch,
									On<ARPayment.branchID, Equal<Branch.branchID>>,
								InnerJoin<OrganizationFinPeriod,
									On<Branch.organizationID, Equal<OrganizationFinPeriod.organizationID>,
										And<OrganizationFinPeriod.finPeriodID, Equal<Required<OrganizationFinPeriod.finPeriodID>>>>>>,
								Where<
									OrganizationFinPeriod.status, NotEqual<FinPeriod.status.locked>,
									And<OrganizationFinPeriod.status, NotEqual<FinPeriod.status.inactive>,
									And<ARPayment.released, Equal<True>,
									And<ARPayment.openDoc, Equal<True>,
									And<ARPayment.customerID, Equal<Required<ARPayment.customerID>>,
									And2<Not<HasUnreleasedVoidPayment<ARPayment.docType, ARPayment.refNbr>>,
									And<Where<
											ARPayment.docType, Equal<ARDocType.payment>,
											Or<ARPayment.docType, Equal<ARDocType.prepayment>,
											Or<ARPayment.docType, Equal<Required<ARPayment.docType>>>>>>>>>>>>,
								OrderBy<
									Asc<ARPayment.docDate>>>(graph);

					if (!graph.FinPeriodUtils.CanPostToClosedPeriod())
					{
						getPaymentsQuery.WhereAnd<Where<OrganizationFinPeriod.status, NotEqual<FinPeriod.status.closed>>>();
					}

					foreach (ARPayment payment in 
						getPaymentsQuery.Select(filter.FinPeriodID,
												customer.BAccountID,
												filter.ApplyCreditMemos == true ? ARDocType.CreditMemo : ARDocType.Payment))
					{
						ApplyPayment(graph, filter, payment, arInvoiceList, toRelease, out warningRefNbr);
						trace.Add(warningRefNbr);
					}
				}

				var remainingParentInvoices = arInvoiceList.Where(inv => inv.CustomerID == customer.BAccountID).ToList();

				if (remainingParentInvoices.Count > 0
					&& filter.ApplyCreditMemos == true 
					&& filter.LoadChildDocuments == LoadChildDocumentsOptions.IncludeCRM)
				{
					PXSelectBase<ARPayment> getCreditMemosQuery =
						new PXSelectJoin<ARPayment,
							InnerJoin<Customer, 
								On<ARPayment.customerID, Equal<Customer.bAccountID>>,
							InnerJoin<Branch,
								On<ARPayment.branchID, Equal<Branch.branchID>>,
							InnerJoin<OrganizationFinPeriod,
								On<Branch.organizationID, Equal<OrganizationFinPeriod.organizationID>,
									And<OrganizationFinPeriod.finPeriodID, Equal<Required<OrganizationFinPeriod.finPeriodID>>>>>>>,
							Where<
								OrganizationFinPeriod.status, NotEqual<FinPeriod.status.locked>,
								And<OrganizationFinPeriod.status, NotEqual<FinPeriod.status.inactive>,
								And<ARPayment.released, Equal<True>,
								And<ARPayment.openDoc, Equal<True>,
								And<Customer.consolidatingBAccountID, Equal<Required<Customer.consolidatingBAccountID>>,
								And<ARPayment.docType, Equal<ARDocType.creditMemo>,
								And<Not<HasUnreleasedVoidPayment<ARPayment.docType, ARPayment.refNbr>>>>>>>>>,
							OrderBy<
								Asc<ARPayment.docDate>>>(graph);

					if (!graph.FinPeriodUtils.CanPostToClosedPeriod())
					{
						getCreditMemosQuery.WhereAnd<Where<OrganizationFinPeriod.status, NotEqual<FinPeriod.status.closed>>>();
					}

					foreach (ARPayment payment in 
						getCreditMemosQuery.Select(filter.FinPeriodID, customer.BAccountID))
					{
						ApplyPayment(graph, filter, payment, remainingParentInvoices, toRelease, out warningRefNbr);
						trace.Add(warningRefNbr);
					}
				}
			}

			if (trace != null && trace.Count != 0)
			{
				PXTrace.WriteWarning(String.Format(Messages.FuturePayments, trace.Where(x => !x.IsNullOrEmpty()).JoinToString("; ")));
				trace.Clear();
			}

			if (toRelease.Count > 0)
			{
				ARDocumentRelease.ReleaseDoc(toRelease, false);
			}
		}
Esempio n. 17
0
        public static string GetTaxZoneByZip(PXGraph graph, string zipCode)
        {
            if (graph == null)
            {
                throw new ArgumentNullException("graph");
            }

            if (string.IsNullOrEmpty(zipCode))
            {
                throw new ArgumentNullException("zipCode");
            }

            PXResultset <TaxZoneZip> resultset = null;

            bool isZipPlusFour = false;

            if (zipCode.Length == 10)
            {
                Regex zipPlusFourDigits = new Regex(@"^\w{5}-\d{4}\b");                 //five letters or digits dash four digits with total length of 10 symbols
                isZipPlusFour = zipPlusFourDigits.IsMatch(zipCode);
            }

            if (isZipPlusFour)
            {
                string zip     = zipCode.Substring(0, 5);
                string zipPlus = zipCode.Substring(6);

                int plus;

                if (int.TryParse(zipPlus, out plus))
                {
                    resultset = PXSelect <TaxZoneZip, Where <TaxZoneZip.zipCode, Equal <Required <TaxZoneZip.zipCode> >,
                                                             And <Required <TaxZoneZip.zipCode>, Between <TaxZoneZip.zipMin, TaxZoneZip.zipMax> > > > .Select(graph, zip, plus);
                }
                else
                {
                    PXTrace.WriteWarning("Failed to extract a valid zip+4 code (XXXXX-XXXX) from the following: {0}", zipCode);
                    return(null);
                }
            }
            else
            {
                resultset = PXSelect <TaxZoneZip, Where <TaxZoneZip.zipCode, Equal <Required <TaxZoneZip.zipCode> > > > .Select(graph, zipCode);
            }


            if (resultset.Count == 0)
            {
                PXTrace.WriteWarning("Failed to find record in TaxZoneZip for the given zip code: {0}", zipCode);
                return(null);
            }
            else if (resultset.Count > 1)
            {
                PXTrace.WriteWarning("{0} records returned from TaxZoneZip for the given zip code: {1}. Only first will be used.", resultset.Count, zipCode);

                return(((TaxZoneZip)resultset).TaxZoneID);
            }
            else
            {
                return(((TaxZoneZip)resultset).TaxZoneID);
            }
        }
        private void SynchronizeFolderContentsWithScreen(string screenID, string folderID, bool isForcingSync)
        {
            // Retrieve top-level folder list
            var tokenHandler = PXGraph.CreateInstance <UserTokenHandler>();
            List <BoxUtils.FileFolderInfo> boxFolderList = new List <BoxUtils.FileFolderInfo>();

            if (FieldsGroupingByScreenID.Select(screenID).Any())
            {
                boxFolderList = BoxUtils.GetFolderList(tokenHandler, folderID, (int)BoxUtils.RecursiveDepth.FirstSubLevel).Result;
                boxFolderList = boxFolderList.Where(x => x.Name.Contains("\\")).ToList();
            }
            else
            {
                boxFolderList = BoxUtils.GetFolderList(tokenHandler, folderID, (int)BoxUtils.RecursiveDepth.NoDepth).Result;
            }

            foreach (BoxUtils.FileFolderInfo boxFolderInfo in boxFolderList)
            {
                BoxFolderCache bfc = FoldersByFolderID.Select(boxFolderInfo.ID);
                if (bfc != null)
                {
                    //Make sure NoteDoc still exists
                    NoteDoc nd = NoteDocs.Select(bfc.RefNoteID);
                    if (nd == null)
                    {
                        //NoteDoc can't be found; this is likely a file coming from a record that was deleted.
                        //Since an existing folder may be renamed to something which exists, we want to force system to treat it as if it was a new folder
                        FoldersByFolderID.Delete(bfc);
                        bfc = null;
                    }
                }

                if (bfc == null)
                {
                    // We've never seen this folder; sync it
                    Guid?refNoteID;

                    if (screenID == ActivityMaintScreenId)
                    {
                        //Activity folders use custom naming defined in GetFolderNameForActivityRow() - just look for GUID inside it.
                        refNoteID = ExtractGuidFromString(boxFolderInfo.Name);
                    }
                    else
                    {
                        refNoteID = FindMatchingNoteIDForFolder(screenID, boxFolderInfo.Name);
                    }

                    if (refNoteID == null)
                    {
                        // User may have created some folder manually with a name not matching to any record, or record
                        // may have been deleted in Acumatica. We can safely ignore it, but let's write to trace.
                        PXTrace.WriteWarning(string.Format("No record found for folder {0} (screen {1}, ID {2})", boxFolderInfo.Name, screenID, boxFolderInfo.ID));
                        continue;
                    }

                    bfc = (BoxFolderCache)FoldersByNote.Select(refNoteID);
                    if (bfc != null)
                    {
                        // A folder existed before for this record; clear the previous entry for this refNoteID
                        FoldersByNote.Delete(bfc);
                    }

                    // Store folder in cache for future reference
                    bfc                      = (BoxFolderCache)FoldersByFolderID.Cache.CreateInstance();
                    bfc.FolderID             = boxFolderInfo.ID;
                    bfc.ParentFolderID       = boxFolderInfo.ParentFolderID;
                    bfc.RefNoteID            = refNoteID;
                    bfc.LastModifiedDateTime = null; //To force initial sync
                    bfc                      = FoldersByFolderID.Insert(bfc);
                }

                if (isForcingSync || bfc.LastModifiedDateTime != boxFolderInfo.ModifiedAt)
                {
                    RefreshRecordFileList(screenID, boxFolderInfo.Name, boxFolderInfo.ID, bfc.RefNoteID, isForcingSync);
                    bfc.LastModifiedDateTime = boxFolderInfo.ModifiedAt;
                    FoldersByFolderID.Update(bfc);
                    PXContext.SetSlot <bool>("BoxDisableLoad", true);
                    try
                    {
                        Actions.PressSave();
                    }
                    finally
                    {
                        PXContext.SetSlot <bool>("BoxDisableLoad", false);
                    }
                }
            }
        }
        public void RefreshRecordFileList(string screenID, string folderName, string folderID, Guid?refNoteID, bool isForcingSync)
        {
            var tokenHandler = PXGraph.CreateInstance <UserTokenHandler>();

            //Get list of files contained in the record folder. RecurseDepth=0 will retrieve all subfolders
            List <BoxUtils.FileFolderInfo> boxFileList = BoxUtils.GetFileList(tokenHandler, folderID, (int)BoxUtils.RecursiveDepth.Unlimited).Result;

            // Remove files from cache if they don't exist on Box server
            foreach (PXResult <BoxFileCache, UploadFileRevisionNoData, UploadFile, NoteDoc> result in FilesByNoteID.Select(refNoteID))
            {
                BoxUtils.FileFolderInfo boxFile = boxFileList.FirstOrDefault(f => f.ID == ((BoxFileCache)result).FileID);
                if (boxFile == null)
                {
                    //File was deleted
                    FilesByNoteID.Delete(result);
                    UploadFiles.Delete(result);
                    UploadFileRevisions.Delete(result);
                    NoteDocs.Delete(result);
                }
                else
                {
                    // File still exists, remove it from in-memory list
                    // so we don't process it as a new file in the next loop
                    boxFileList.Remove(boxFile);
                }
            }

            // Remove any files/folders coming from activities stored beneath the current record, they've been processed above
            var filesFoundOnlyOnServer = boxFileList.Where(x => !x.Name.StartsWith(Messages.ActivitiesFolderName)).ToList();

            //Check for underlying activities records
            BoxFolderCache currentFolder = FoldersByFolderID.Select(folderID);

            if (currentFolder != null && boxFileList.Any(x => x.Name.StartsWith(Messages.ActivitiesFolderName)))
            {
                // If nullOrEmpty, Folder may have been created manually
                if (string.IsNullOrEmpty(currentFolder.ActivityFolderID))
                {
                    //Find actual folder ID and save in BoxFolderCache's ActivityFolderID field
                    BoxUtils.FileFolderInfo activityFolderinfo = BoxUtils.FindFolder(tokenHandler, folderID, Messages.ActivitiesFolderName).Result;
                    if (activityFolderinfo != null)
                    {
                        currentFolder.ActivityFolderID = activityFolderinfo?.ID;
                        FoldersByFolderID.Update(currentFolder);
                    }
                }

                if (currentFolder.ActivityFolderID != null)
                {
                    SynchronizeFolderContentsWithScreen(ActivityMaintScreenId, currentFolder.ActivityFolderID, isForcingSync);
                }
            }

            //Remaining files aren't found in cache but are in Box server.
            if (filesFoundOnlyOnServer.Any())
            {
                if (refNoteID == null)
                {
                    // User may have created some folder manually with a name not matching to any record, or record
                    // may have been deleted in Acumatica. We can safely ignore it, but let's write to trace.
                    PXTrace.WriteWarning(string.Format("No record found for folder {0} (screen {1}, ID {2})", folderName, screenID, folderID));
                    return;
                }

                UploadFileMaintenance ufm = PXGraph.CreateInstance <UploadFileMaintenance>();
                ufm.IgnoreFileRestrictions = true;

                ufm.RowInserting.AddHandler <UploadFileRevision>(delegate(PXCache sender, PXRowInsertingEventArgs e)
                {
                    ((UploadFileRevision)e.Row).BlobHandler = Guid.NewGuid();
                });
                //Add files to the caches
                foreach (BoxUtils.FileFolderInfo boxFile in filesFoundOnlyOnServer)
                {
                    ufm.Clear();
                    string   fileName = string.Format("{0}\\{1}", folderName, boxFile.Name.Replace(Path.GetInvalidPathChars(), ' '));
                    FileInfo fileInfo = ufm.GetFileWithNoData(fileName);
                    Guid?    blobHandlerGuid;
                    if (fileInfo == null)
                    {
                        fileInfo = new FileInfo(fileName, null, new byte[0]);
                        //The SaveFile call will trigger a Load() on the BoxBlobStorageProvider which can be skipped
                        PXContext.SetSlot <bool>("BoxDisableLoad", true);
                        try
                        {
                            if (!ufm.SaveFile(fileInfo))
                            {
                                throw new PXException(Messages.ErrorAddingFileSaveFileFailed, fileName);
                            }
                        }
                        finally
                        {
                            PXContext.SetSlot <bool>("BoxDisableLoad", false);
                        }

                        if (!fileInfo.UID.HasValue)
                        {
                            throw new PXException(Messages.ErrorAddingFileUIDNull, fileName);
                        }

                        UploadFileMaintenance.SetAccessSource(fileInfo.UID.Value, null, screenID);
                        NoteDoc noteDoc = (NoteDoc)NoteDocs.Cache.CreateInstance();
                        noteDoc.NoteID = refNoteID;
                        noteDoc.FileID = fileInfo.UID;
                        NoteDocs.Insert(noteDoc);

                        blobHandlerGuid = ufm.Revisions.Current.BlobHandler;
                    }
                    else
                    {
                        //File already exists in the database, retrieve BlobHandler
                        if (!fileInfo.UID.HasValue)
                        {
                            throw new PXException(Messages.GetFileWithNoDataReturnedUIDNull, fileName);
                        }
                        blobHandlerGuid = GetBlobHandlerForFileID(fileInfo.UID.Value);

                        //Clear old references of this blob handler from cache; it will be reinserted with up-to-date info
                        var bfcOrphan = (BoxFileCache)FilesByBlobHandler.Select(blobHandlerGuid);
                        if (bfcOrphan != null)
                        {
                            FilesByBlobHandler.Delete(bfcOrphan);
                        }

                        //Update NoteDoc entry if existing file was moved to new NoteID or create it if not there
                        NoteDoc nd = (NoteDoc)NoteDocsByFileID.Select(fileInfo.UID);
                        if (nd == null)
                        {
                            nd        = (NoteDoc)NoteDocs.Cache.CreateInstance();
                            nd.NoteID = refNoteID;
                            nd.FileID = fileInfo.UID;
                            NoteDocs.Insert(nd);
                        }
                        else if (nd.NoteID != refNoteID)
                        {
                            nd.NoteID = refNoteID;
                            NoteDocs.Update(nd);
                        }
                    }

                    var bfc = (BoxFileCache)FilesByBlobHandler.Cache.CreateInstance();
                    bfc.BlobHandler    = blobHandlerGuid;
                    bfc.FileID         = boxFile.ID;
                    bfc.ParentFolderID = boxFile.ParentFolderID;
                    bfc = FilesByBlobHandler.Insert(bfc);
                }
            }
        }