Ejemplo n.º 1
0
        public virtual void FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            if (e.Cancel || e.Row == null || this._inventoryType == (Type)null)
            {
                return;
            }

            object obj = sender.GetValue(e.Row, this._inventoryType.Name);

            if (obj == null)
            {
                return;
            }

            string attributeID = "BUSINESSUN";
            string attrValue   = "Distribution";

            InventoryItem inventoryItem = InventoryItem.PK.Find(sender.Graph, new int?((int)obj));
            CSAnswers     csAnswers     = CSAnswers.PK.Find(sender.Graph, inventoryItem.NoteID, attributeID);

            if (csAnswers != null)
            {
                SOLine row = e.Row as SOLine;

                if (SelectFrom <CSAttributeDetail> .Where <CSAttributeDetail.attributeID.IsEqual <P.AsString>
                                                           .And <CSAttributeDetail.valueID.IsEqual <P.AsString> > > .View.SelectSingleBound(sender.Graph, null, csAnswers.AttributeID, csAnswers.Value).TopFirst.Description == attrValue &&
                    row != null)
                {
                    e.NewValue = row.CustomerID;
                }
            }
        }
Ejemplo n.º 2
0
        public override void ProccessItem(PXGraph graph, TPrimary item)
        {
            PXCache  cache   = graph.Caches[typeof(TPrimary)];
            TPrimary newItem = (TPrimary)cache.CreateInstance();

            PXCache <TPrimary> .RestoreCopy(newItem, item);

            string entityType = CSAnswerType.GetAnswerType(cache.GetItemType());
            string entityID   = CSAnswerType.GetEntityID(cache.GetItemType());

            PXView primaryView = graph.Views[graph.PrimaryView];

            object[] searches    = new object[primaryView.Cache.BqlKeys.Count];
            string[] sortcolumns = new string[primaryView.Cache.BqlKeys.Count];
            for (int i = 0; i < cache.BqlKeys.Count(); i++)
            {
                sortcolumns[i] = cache.BqlKeys[i].Name;
                searches[i]    = cache.GetValue(newItem, sortcolumns[i]);
            }
            int startRow = 0, totalRows = 0;

            List <object> result = primaryView.Select(null, null, searches, sortcolumns, null, null, ref startRow, 1, ref totalRows);

            newItem = (TPrimary)cache.CreateCopy(PXResult.Unwrap <TPrimary>(result[0]));

            foreach (FieldValue fieldValue in Fields.Cache.Cached.Cast <FieldValue>().Where(o => o.AttributeID == null && o.Selected == true))
            {
                PXFieldState  state    = cache.GetStateExt(newItem, fieldValue.Name) as PXFieldState;
                PXIntState    intState = state as PXIntState;
                PXStringState strState = state as PXStringState;
                if ((intState != null && intState.AllowedValues != null && intState.AllowedValues.Length > 0 &&
                     intState.AllowedValues.All(v => v != int.Parse(fieldValue.Value)))
                    ||
                    (strState != null && strState.AllowedValues != null && strState.AllowedValues.Length > 0 &&
                     strState.AllowedValues.All(v => v != fieldValue.Value)))
                {
                    throw new PXSetPropertyException(ErrorMessages.UnallowedListValue, fieldValue.Value, fieldValue.Name);
                }
                if (state != null && !Equals(state.Value, fieldValue.Value))
                {
                    cache.SetValueExt(newItem, fieldValue.Name, fieldValue.Value);
                    cache.Update(newItem);
                }

                result  = primaryView.Select(null, null, searches, sortcolumns, null, null, ref startRow, 1, ref totalRows);
                newItem = (TPrimary)cache.CreateCopy(PXResult.Unwrap <TPrimary>(result[0]));
            }

            PXCache attrCache = cache.Graph.Caches[typeof(CSAnswers)];

            foreach (FieldValue attrValue in Attributes.Cache.Cached.Cast <FieldValue>().Where(o => o.AttributeID != null && o.Selected == true))
            {
                CSAnswers attr = (CSAnswers)attrCache.CreateInstance();
                attr.AttributeID = attrValue.AttributeID;
                attr.EntityID    = cache.GetValue(newItem, entityID) as int?;
                attr.EntityType  = entityType;
                attr.Value       = attrValue.Value;
                attrCache.Update(attr);
            }
        }
Ejemplo n.º 3
0
        protected void _(Events.FieldUpdated <APInvoice.vendorID> e)
        {
            var row    = e.Row as APInvoice;
            var vendor = Base.vendor.Current;

            if (vendor == null || activateGUI == false)
            {
                return;
            }

            switch (row.DocType)
            {
            case APDocType.DebitAdj:
                PXCache <APRegister> .GetExtension <APRegisterExt>(row).UsrVATInCode = TWGUIFormatCode.vATInCode23;

                break;

            case APDocType.Invoice:
                CSAnswers cSAnswers = SelectCSAnswers(Base, vendor.NoteID);

                PXCache <APRegister> .GetExtension <APRegisterExt>(row).UsrVATInCode = cSAnswers?.Value;

                break;
            }
        }
 public static T GetReservedProductAttributeValue <T>(KCAttributesMappingMaint graph, InventoryItem product, string ReservedAttributeName)
 {
     try
     {
         PXResult <KCAttribute> resAttr = graph.ReservedAttribute.Select(ReservedAttributeName, product.NoteID).FirstOrDefault();
         CSAnswers ans = resAttr?.GetItem <CSAnswers>();
         return(resAttr != null && ans != null ? (T)Convert.ChangeType(ans.Value, typeof(T)) : default);
 private void UpdateAnswer(object newValue, CSAnswers updatedAnswer)
 {
     updatedAnswer.Value = newValue?.ToString();
     if (updatedAnswer.GetType() != answers.Cache.GetItemType())
     {
         var castAnswer = CastAnswerToViewType(updatedAnswer);
         castAnswer.NoteId = updatedAnswer.GetExtension <CSAnswersExt>()?.NoteID;
         answers.Cache.Update(castAnswer);
     }
     answers.Cache.Update(updatedAnswer);
 }
        private void RaiseExceptionForDocumentAttribute(CSAnswers attribute,
                                                        object document)
        {
            var message   = string.Format(CommonMessages.FieldIsEmpty, attribute.AttributeID);
            var fieldName = document.GetType().GetProperties()
                            .FirstOrDefault(x => x.GetCustomAttributes(typeof(UiInformationFieldAttribute)).Any())?.Name;

            documentCache.RaiseExceptionHandling(fieldName,
                                                 document, true, new PXSetPropertyException(message, PXErrorLevel.RowError));
            PXUIFieldAttribute.SetError <CSAnswers.value>(answers.Cache, attribute, message);
        }
        private void RaiseExceptionForEmptyAttributeValue(CSAnswers attribute)
        {
            var message      = string.Format(CommonMessages.FieldIsEmpty, attribute.AttributeID);
            var documentType = documentCache.GetItemType();
            var document     = entityHelper.GetEntityRow(documentType, attribute.RefNoteID);
            var fieldName    = document.GetType().GetProperties()
                               .FirstOrDefault(x => x.GetCustomAttributes(typeof(UiInformationFieldAttribute)).Any())?.Name;

            documentCache.RaiseExceptionHandling(fieldName,
                                                 document, true, new PXSetPropertyException(message, PXErrorLevel.RowError));
        }
        private void ValidateDocumentAttribute(CSAnswers attribute, ICollection <string> emptyRequired,
                                               object document)
        {
            var group = attributeGroups.Search <CSAttributeGroup.attributeID>(attribute.AttributeID)
                        .FirstTableItems.Single();

            if (group.Required.GetValueOrDefault() && string.IsNullOrEmpty(attribute.Value))
            {
                emptyRequired.Add(attribute.AttributeID);
                RaiseExceptionForDocumentAttribute(attribute, document);
            }
        }
        protected List <(string imagePlacement, string imageUrl)> HandleImages(InventoryItem product, KCBulkProductMaint graph)
        {
            List <(string, string)>        images = new List <(string, string)>();
            PXResultset <KCImagePlacement> mappedImagePlacements = graph.MappedImagePlacements.Select(product.NoteID);

            foreach (PXResult <KCImagePlacement> mappedImagePlacement in mappedImagePlacements)
            {
                KCImagePlacement image     = mappedImagePlacement.GetItem <KCImagePlacement>();
                CSAnswers        attribute = mappedImagePlacement.GetItem <CSAnswers>();

                images.Add((image.ImagePlacement, attribute.Value));
            }

            return(images);
        }
Ejemplo n.º 10
0
        private bool IsAttributeRuleTrue(object item, EPAssignmentRule rule)
        {
            string      field     = rule.FieldName.Substring(0, rule.FieldName.Length - "_Attribute".Length - 1);
            CSAttribute attribute = PXSelectReadonly <CSAttribute> .Search <CSAttribute.attributeID>(this, field);

            if (attribute == null || rule.Condition == null)
            {
                //Field Name is not a valid question.
                return(false);
            }

            var noteId = new EntityHelper(_Graph).GetEntityNoteID(item);

            CSAnswers ans = PXSelect <CSAnswers,
                                      Where <CSAnswers.refNoteID, Equal <Required <CSAnswers.refNoteID> >,
                                             And <CSAnswers.attributeID, Equal <Required <CSAnswers.attributeID> > > > > .Select(_Graph ?? this, noteId, field);

            if (ans == null)
            {
                //Answer for the given question doesnot exist.
                switch (rule.Condition.Value)
                {
                case (int)PXCondition.ISNULL:
                    return(true);

                case (int)PXCondition.ISNOTNULL:
                    return(false);

                case (int)PXCondition.EQ:
                    return(string.IsNullOrEmpty(rule.FieldValue));

                case (int)PXCondition.NE:
                    return(!string.IsNullOrEmpty(rule.FieldValue));
                }
                return(false);
            }

            this.currentAttribute = ans;

            PXFilterRow filter    = new PXFilterRow(typeof(CSAnswers.value).Name, (PXCondition)rule.Condition.Value, rule.FieldValue, null);
            int         startRow  = 0;
            int         totalRows = 0;

            List <object> result = attributeView.Select(null, null, null, null, null, new PXFilterRow[] { filter }, ref startRow, 1, ref totalRows);

            return(result.Count > 0);
        }
Ejemplo n.º 11
0
        public virtual void Recalculate(InventoryItem template)
        {
            if (template == null)
            {
                throw new PXArgumentException(nameof(template));
            }
            if (template.InventoryID == null)
            {
                throw new PXArgumentException(nameof(template.InventoryID));
            }

            _template = template;

            DeleteOldRows();
            GetAttributes();

            _combinations         = new Dictionary <string[], int>(new StringArrayComparer());
            _numberOfCombination  = 0;
            _lastInventoryID      = null;
            _attributeValues      = new string[_templateAttributes.Keys.Count];
            _columnAttributeValue = null;
            _rowAttributeValue    = null;

            var select = new PXSelectReadonly2 <CSAnswers,
                                                InnerJoin <CSAttributeGroup, On <CSAnswers.attributeID, Equal <CSAttributeGroup.attributeID> >,
                                                           InnerJoin <InventoryItem, On <CSAnswers.refNoteID, Equal <InventoryItem.noteID>,
                                                                                         And <CSAttributeGroup.entityClassID, Equal <InventoryItem.itemClassID> > > > >,
                                                Where <CSAttributeGroup.isActive, Equal <True>,
                                                       And <CSAttributeGroup.entityType, Equal <Constants.DACName <InventoryItem> >,
                                                            And <CSAttributeGroup.attributeCategory, Equal <CSAttributeGroup.attributeCategory.variant>,
                                                                 And <InventoryItem.templateItemID, Equal <Required <InventoryItem.inventoryID> > > > > >,
                                                OrderBy <Asc <InventoryItem.inventoryID, Asc <CSAttributeGroup.sortOrder, Asc <CSAttributeGroup.attributeID> > > > >(_graph);

            int attributesAreFilled = 0;

            using (new PXFieldScope(select.View, typeof(InventoryItem.inventoryID), typeof(CSAnswers.attributeID), typeof(CSAnswers.value)))
            {
                foreach (PXResult <CSAnswers, CSAttributeGroup, InventoryItem> result in select.Select(_template.InventoryID))
                {
                    InventoryItem inventoryItem = result;
                    CSAnswers     answer        = result;

                    RecalculateItem(inventoryItem, answer, ref attributesAreFilled);
                }
            }
        }
        private PXResultset <CSAnswers, CSAttributeGroup, CSAttributeDetail2> GenerateAttributeList(int attributeNum)
        {
            PXResultset <CSAnswers, CSAttributeGroup, CSAttributeDetail2> list = new PXResultset <CSAnswers, CSAttributeGroup, CSAttributeDetail2>();

            PXSelectBase <CSAttributeGroup> query = new PXSelectJoin <CSAttributeGroup,
                                                                      InnerJoin <CSAttributeDetail2, On <CSAttributeGroupExt.usrCategory, Equal <CSAttributeDetail2.valueID>,
                                                                                                         And <CSAttributeDetail2.attributeID, Equal <Required <INSetupExt.usrCategoryAttribute> >,
                                                                                                              And <CSAttributeDetail2.sortOrder, Equal <Required <CSAttributeDetail2.sortOrder> >,
                                                                                                                   And <CSAttributeDetail2.disabled, Equal <False> > > > > >,
                                                                      Where <CSAttributeGroup.entityClassID, Equal <Required <InventoryItem.itemClassID> >
                                                                             , And <CSAttributeGroup.entityType, Equal <PCBConst.entityTypeIN> >
                                                                             >,
                                                                      OrderBy <Asc <CSAttributeGroup.sortOrder> > >(Base);

            InventoryItem current  = Base.Item.Current;
            INSetupExt    setupExt = Base.insetup.Current.GetExtension <INSetupExt>();

            if (current != null && current.InventoryID != null && setupExt != null) //&& current.InventoryID > 0
            {
                foreach (PXResult <CSAttributeGroup, CSAttributeDetail2> item in query.Select(setupExt.UsrCategoryAttribute, attributeNum, current.ItemClassID))
                {
                    CSAttributeGroup   attribute = item;
                    CSAttributeDetail2 detail    = item;

                    CSAnswers answerCheck = PXSelect <CSAnswers, Where <CSAnswers.refNoteID, Equal <Required <CSAnswers.refNoteID> >,
                                                                        And <CSAnswers.attributeID, Equal <Required <CSAnswers.attributeID> > > > >
                                            .Select(Base, current.NoteID, attribute.AttributeID);

                    if (answerCheck == null)
                    {
                        CSAnswers newAnswer = new CSAnswers();
                        newAnswer.AttributeID = attribute.AttributeID;
                        newAnswer.Value       = string.Empty;
                        newAnswer.Order       = attribute.SortOrder;
                        newAnswer.IsRequired  = attribute.Required;
                        newAnswer.RefNoteID   = current.NoteID;
                        list.Add(new PXResult <CSAnswers, CSAttributeGroup, CSAttributeDetail2>(newAnswer, attribute, detail));
                    }
                    else
                    {
                        list.Add(new PXResult <CSAnswers, CSAttributeGroup, CSAttributeDetail2>(answerCheck, attribute, detail));
                    }
                }
            }
            return(list);
        }
        protected virtual void CSAnswers_RowPersisting(PXCache sender, PXRowPersistingEventArgs e, PXRowPersisting del)
        {
            if (del != null)
            {
                del.Invoke(sender, e);
            }

            CSAnswers     row     = (CSAnswers)e.Row;
            InventoryItem current = Base.Item.Current;

            if (row == null)
            {
                return;
            }

            if (current == null)
            {
                e.Cancel = true;
            }
        }
Ejemplo n.º 14
0
        protected virtual void RecalculateItem(InventoryItem inventoryItem, CSAnswers answer, ref int attributesAreFilled)
        {
            if (_lastInventoryID != inventoryItem.InventoryID)
            {
                _lastInventoryID    = inventoryItem.InventoryID;
                _attributeValues    = new string[_templateAttributes.Keys.Count];
                attributesAreFilled = 0;
            }

            if (string.Equals(answer.AttributeID, _template.DefaultColumnMatrixAttributeID, StringComparison.OrdinalIgnoreCase))
            {
                _columnAttributeValue = answer.Value;
            }
            else if (string.Equals(answer.AttributeID, _template.DefaultRowMatrixAttributeID, StringComparison.OrdinalIgnoreCase))
            {
                _rowAttributeValue = answer.Value;
            }
            else if (_templateAttributes.TryGetValue(answer.AttributeID, out Attribute templateAttribute) &&
                     _attributeValues[templateAttribute.AttributeIndex] == null)
            {
                attributesAreFilled++;
                _attributeValues[templateAttribute.AttributeIndex] = answer.Value;
            }

            if (attributesAreFilled == _templateAttributes.Keys.Count && _columnAttributeValue != null && _rowAttributeValue != null)
            {
                if (_combinations.TryGetValue(_attributeValues, out int combinationNumber))
                {
                    SetInventoryCombinationNumber(inventoryItem.InventoryID, combinationNumber);
                }
                else
                {
                    SetInventoryCombinationNumber(inventoryItem.InventoryID, _numberOfCombination);
                    _combinations.Add(_attributeValues, _numberOfCombination);
                    OnNewCombination();
                    _numberOfCombination++;
                }

                _lastInventoryID = null;
            }
        }
Ejemplo n.º 15
0
        protected void _(Events.RowInserting <APInvoice> e)
        {
            if (e.Row == null || Base.vendor.Current == null || activateGUI.Equals(false))
            {
                return;
            }

            APRegisterExt regisExt = PXCache <APRegister> .GetExtension <APRegisterExt>(e.Row);

            string vATIncode = regisExt.UsrVATInCode ?? string.Empty;

            if (string.IsNullOrEmpty(vATIncode))
            {
                CSAnswers cSAnswers = SelectCSAnswers(Base, Base.vendor.Current.NoteID);

                vATIncode = (e.Row.IsRetainageDocument == true || cSAnswers == null) ? null : cSAnswers.Value;
            }

            regisExt.UsrVATInCode = e.Row.DocType.Equals(APDocType.DebitAdj, System.StringComparison.CurrentCulture) &&
                                    !string.IsNullOrEmpty(vATIncode) ? TWGUIFormatCode.vATInCode23 /*(int.Parse(vATIncode) + 2).ToString()*/ : vATIncode;
        }
Ejemplo n.º 16
0
        protected void _(Events.FieldUpdated <ARInvoice.customerID> e)
        {
            ARInvoice row = e.Row as ARInvoice;

            if (row != null && activateGUI && row.DocType == ARDocType.CreditMemo)
            {
                PXCache <ARRegister> .GetExtension <ARRegisterExt>(row).UsrVATOutCode = TWGUIFormatCode.vATOutCode33;
            }
            else if (row != null && activateGUI &&
                     (row.DocType == ARDocType.Invoice || row.DocType == ARDocType.CashSale)
                     )
            {
                CSAnswers cSAnswers = SelectFrom <CSAnswers> .Where <CSAnswers.refNoteID.IsEqual <@P.AsGuid>
                                                                     .And <CSAnswers.attributeID.IsEqual <ARRegisterExt.VATOUTFRMTNameAtt> > >
                                      .View.ReadOnly.Select(Base, Base.customer.Current.NoteID);

                if (cSAnswers != null)
                {
                    PXCache <ARRegister> .GetExtension <ARRegisterExt>(row).UsrVATOutCode = cSAnswers.Value;
                }
            }
        }
Ejemplo n.º 17
0
        protected virtual int?FindInventoryItem(MatrixInventoryItem row)
        {
            int?lastInventoryId = null;

            string[] attributeValues = new string[row.AttributeIDs.Length];

            foreach (PXResult <CSAnswers, CSAttributeGroup, InventoryItem> result in SelectInventoryWithAttributes())
            {
                InventoryItem inventoryItem = result;
                CSAnswers     attribute     = result;

                if (lastInventoryId != inventoryItem.InventoryID)
                {
                    lastInventoryId = inventoryItem.InventoryID;
                    for (int attributeIndex = 0; attributeIndex < attributeValues.Length; attributeIndex++)
                    {
                        attributeValues[attributeIndex] = null;
                    }
                }

                for (int attributeIndex = 0; attributeIndex < attributeValues.Length; attributeIndex++)
                {
                    if (string.Equals(row.AttributeIDs[attributeIndex], attribute.AttributeID, StringComparison.OrdinalIgnoreCase) &&
                        row.AttributeValues[attributeIndex] == attribute.Value)
                    {
                        attributeValues[attributeIndex] = attribute.Value;
                        break;
                    }
                }


                if (lastInventoryId != null && attributeValues.All(v => v != null))
                {
                    return(lastInventoryId);
                }
            }

            return(null);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Returns collection to map Inventory Item to row and column attributes values.
        /// Key contains: row attribute value, column attribute value.
        /// Value of dictionary contains: InventoryID or null if for those values inventory doesn't exist.
        /// Method uses MatrixHeader.Current (group id, column attribute, row attribute) to make result.
        /// </summary>
        protected virtual IDictionary <InventoryMapKey, InventoryMapValue> GetInventoryMap()
        {
            var inventoryMatrix = new Dictionary <InventoryMapKey, InventoryMapValue>();

            if (!AllAdditionalAttributesArePopulated())
            {
                return(inventoryMatrix);
            }

            int?   lastInventoryId      = null;
            string rowAttributeValue    = null;
            string columnAttributeValue = null;

            string[] additionalAttributeValues = new string[AdditionalAttributes.Current.AttributeIdentifiers.Length];

            foreach (PXResult <CSAnswers, CSAttributeGroup, InventoryItem> result in SelectInventoryWithAttributes())
            {
                InventoryItem inventoryItem = result;
                CSAnswers     attribute     = result;

                if (lastInventoryId != inventoryItem.InventoryID)
                {
                    lastInventoryId      = inventoryItem.InventoryID;
                    rowAttributeValue    = null;
                    columnAttributeValue = null;
                    for (int attributeIndex = 0; attributeIndex < additionalAttributeValues.Length; attributeIndex++)
                    {
                        additionalAttributeValues[attributeIndex] = null;
                    }
                }

                if (string.Equals(attribute.AttributeID, Header.Current.RowAttributeID, StringComparison.OrdinalIgnoreCase))
                {
                    rowAttributeValue = attribute.Value;
                }
                else if (string.Equals(attribute.AttributeID, Header.Current.ColAttributeID, StringComparison.OrdinalIgnoreCase))
                {
                    columnAttributeValue = attribute.Value;
                }
                else
                {
                    for (int attributeIndex = 0; attributeIndex < additionalAttributeValues.Length; attributeIndex++)
                    {
                        if (string.Equals(AdditionalAttributes.Current.AttributeIdentifiers[attributeIndex], attribute.AttributeID, StringComparison.OrdinalIgnoreCase) &&
                            AdditionalAttributes.Current.Values[attributeIndex] == attribute.Value)
                        {
                            additionalAttributeValues[attributeIndex] = attribute.Value;
                            break;
                        }
                    }
                }

                if (lastInventoryId != null && rowAttributeValue != null && columnAttributeValue != null &&
                    additionalAttributeValues.All(v => v != null))
                {
                    inventoryMatrix.Add(
                        new InventoryMapKey(columnAttributeValue, rowAttributeValue),
                        CreateInventoryMapValue(lastInventoryId, result));
                    lastInventoryId = null;
                }
            }

            return(inventoryMatrix);
        }
Ejemplo n.º 19
0
        protected void MergeDuplicates(int targetID, List <TMain> duplicateEntities, List <FieldValue> values, bool IsContractBasedAPI)
        {
            TMain targetEntity = GetTargetEntity(targetID);

            object realTargetEntity = targetEntity;
            var    graphType        = new EntityHelper(Base).GetPrimaryGraphType(ref realTargetEntity, false);

            if (graphType == null)
            {
                return;
            }

            PXGraph targetGraph = PXGraph.CreateInstance(graphType);

            PXCache cache = targetGraph.Caches[typeof(TMain)];

            var refNoteIdField = EntityHelper.GetNoteField(cache.GetItemType());

            realTargetEntity = cache.CreateCopy(realTargetEntity);

            Contact targetContact = GetTargetContact(targetEntity);
            Address targetAddress = GetTargetAddress(targetEntity);

            Dictionary <Type, object> targets = new Dictionary <Type, object>
            {
                [typeof(TMain)]   = realTargetEntity,
                [typeof(Contact)] = targetContact,
                [typeof(Address)] = targetAddress
            };

            foreach (FieldValue fieldValue in values)
            {
                if (fieldValue.AttributeID == null)
                {
                    Type         type  = Type.GetType(fieldValue.CacheName);
                    PXFieldState state = (PXFieldState)targetGraph.Caches[type].GetStateExt(targets[type], fieldValue.Name);
                    if (state == null || !Equals(state.Value, fieldValue.Value))
                    {
                        targetGraph.Caches[type].SetValueExt(targets[type], fieldValue.Name, fieldValue.Value);
                        targets[type] = targetGraph.Caches[type].CreateCopy(targetGraph.Caches[type].Update(targets[type]));
                    }
                }
                else
                {
                    PXCache   attrCache = cache.Graph.Caches[typeof(CSAnswers)];
                    CSAnswers attr      = new CSAnswers
                    {
                        AttributeID = fieldValue.AttributeID,
                        RefNoteID   = cache.GetValue(targetEntity, refNoteIdField) as Guid?,
                        Value       = fieldValue.Value,
                    };

                    Dictionary <string, object> keys = new Dictionary <string, object>();
                    foreach (string key in attrCache.Keys.ToArray())
                    {
                        keys[key] = attrCache.GetValue(attr, key);
                    }


                    if (attrCache.Locate(keys) == 0)
                    {
                        attrCache.Insert(attr);
                    }
                    else
                    {
                        var located = attrCache.Locate(attr) as CSAnswers;
                        located.Value = attr.Value;
                        attrCache.Update(located);
                    }
                }
            }

            PXPrimaryGraphCollection primaryGraph = new PXPrimaryGraphCollection(targetGraph);

            using (PXTransactionScope scope = new PXTransactionScope())
            {
                foreach (TMain duplicateEntity in duplicateEntities)
                {
                    // only int, only single field
                    if (cache.GetValue(duplicateEntity, cache.Keys[0]) as int? == targetID)
                    {
                        continue;
                    }

                    targetGraph.Caches[realTargetEntity.GetType()].Current = realTargetEntity;

                    MergeEntities(targetGraph, realTargetEntity as TMain, duplicateEntity);

                    targetGraph.Actions.PressSave();

                    PXGraph operGraph = primaryGraph[duplicateEntity];

                    RunActionWithAppliedAutomation(operGraph, duplicateEntity, nameof(CloseAsDuplicate));

                    operGraph.Actions.PressSave();
                }

                scope.Complete();
            }

            // should become validated if no possible duplicates
            Base.Views[Base.PrimaryView].Cache.Current = targetEntity;

            Base.Actions.PressCancel();

            RunActionWithAppliedAutomation(Base, targetEntity, nameof(CheckForDuplicates));

            if (!IsContractBasedAPI)
            {
                RunActionWithAppliedAutomation(targetGraph, realTargetEntity, "Cancel");

                throw new PXRedirectRequiredException(targetGraph, "");
            }
        }
        protected IEnumerable <CSAnswers> SelectInternal(PXGraph graph, object row)
        {
            if (row == null)
            {
                yield break;
            }

            var noteId = GetNoteId(row);

            if (!noteId.HasValue)
            {
                yield break;
            }

            var answerCache = graph.Caches[typeof(CSAnswers)];
            var entityCache = graph.Caches[row.GetType()];

            List <CSAnswers> answerList;

            var status = entityCache.GetStatus(row);

            if (status == PXEntryStatus.Inserted || status == PXEntryStatus.InsertedDeleted)
            {
                answerList = answerCache.Inserted.Cast <CSAnswers>().Where(x => x.RefNoteID == noteId).ToList();
            }
            else
            {
                answerList = PXSelect <CSAnswers, Where <CSAnswers.refNoteID, Equal <Required <CSAnswers.refNoteID> > > >
                             .Select(graph, noteId).FirstTableItems.ToList();
            }

            var classId = base.GetClassId(row);

            CRAttribute.ClassAttributeList classAttributeList = new CRAttribute.ClassAttributeList();

            if (classId != null)
            {
                classAttributeList = CRAttribute.EntityAttributes(base.GetEntityTypeFromAttribute(row), classId);
            }
            //when coming from Import scenarios there might be attributes which don't belong to entity's current attribute class or the entity might not have any attribute class at all
            if (graph.IsImport && PXView.SortColumns.Any() && PXView.Searches.Any())
            {
                var columnIndex = Array.FindIndex(PXView.SortColumns,
                                                  x => x.Equals(typeof(CSAnswers.attributeID).Name, StringComparison.OrdinalIgnoreCase));

                if (columnIndex >= 0 && columnIndex < PXView.Searches.Length)
                {
                    var searchValue = PXView.Searches[columnIndex];

                    if (searchValue != null)
                    {
                        //searchValue can be either AttributeId or Description
                        var attributeDefinition = CRAttribute.Attributes[searchValue.ToString()] ??
                                                  CRAttribute.AttributesByDescr[searchValue.ToString()];

                        if (attributeDefinition == null)
                        {
                            throw new PXSetPropertyException(PX.Objects.CR.Messages.AttributeNotValid);
                        }
                        //avoid duplicates
                        else if (classAttributeList[attributeDefinition.ToString()] == null)
                        {
                            classAttributeList.Add(new CRAttribute.AttributeExt(attributeDefinition, null, false, true));
                        }
                    }
                }
            }

            if (answerList.Count == 0 && classAttributeList.Count == 0)
            {
                yield break;
            }

            //attribute identifiers that are contained in CSAnswers cache/table but not in class attribute list
            List <string> attributeIdListAnswers =
                answerList.Select(x => x.AttributeID)
                .Except(classAttributeList.Select(x => x.ID))
                .Distinct()
                .ToList();

            //attribute identifiers that are contained in class attribute list but not in CSAnswers cache/table
            List <string> attributeIdListClass =
                classAttributeList.Select(x => x.ID)
                .Except(answerList.Select(x => x.AttributeID))
                .ToList();

            //attribute identifiers which belong to both lists
            List <string> attributeIdListIntersection =
                classAttributeList.Select(x => x.ID)
                .Intersect(answerList.Select(x => x.AttributeID))
                .Distinct()
                .ToList();


            var cacheIsDirty = answerCache.IsDirty;

            List <CSAnswers> output = new List <CSAnswers>();

            //attributes contained only in CSAnswers cache/table should be added "as is"
            output.AddRange(answerList.Where(x => attributeIdListAnswers.Contains(x.AttributeID)));

            //attributes contained only in class attribute list should be created and initialized with default value
            foreach (var attributeId in attributeIdListClass)
            {
                var classAttributeDefinition = classAttributeList[attributeId];

                if (PXSiteMap.IsPortal && classAttributeDefinition.IsInternal)
                {
                    continue;
                }

                if (!classAttributeDefinition.IsActive)
                {
                    continue;
                }

                CSAnswers answer = (CSAnswers)answerCache.CreateInstance();
                answer.AttributeID = classAttributeDefinition.ID;
                answer.RefNoteID   = noteId;
                answer.Value       = GetDefaultAnswerValue(classAttributeDefinition);
                if (classAttributeDefinition.ControlType == CSAttribute.CheckBox)
                {
                    bool value;
                    if (bool.TryParse(answer.Value, out value))
                    {
                        answer.Value = Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
                    }
                    else if (answer.Value == null)
                    {
                        answer.Value = 0.ToString();
                    }
                }

                answer.IsRequired = classAttributeDefinition.Required;

                Dictionary <string, object> keys = new Dictionary <string, object>();
                foreach (string key in answerCache.Keys.ToArray())
                {
                    keys[key] = answerCache.GetValue(answer, key);
                }

                if (answerCache.Locate(keys) == 0)
                {
                    answer = (CSAnswers)(answerCache.Locate(answer) ?? answerCache.Insert(answer));
                    output.Add(answer);
                }
            }

            //attributes belonging to both lists should be selected from CSAnswers cache/table with and additional IsRequired check against class definition
            foreach (CSAnswers answer in answerList.Where(x => attributeIdListIntersection.Contains(x.AttributeID)).ToList())
            {
                var classAttributeDefinition = classAttributeList[answer.AttributeID];

                if (PXSiteMap.IsPortal && classAttributeDefinition.IsInternal)
                {
                    continue;
                }

                if (!classAttributeDefinition.IsActive)
                {
                    continue;
                }

                if (answer.Value == null && classAttributeDefinition.ControlType == CSAttribute.CheckBox)
                {
                    answer.Value = bool.FalseString;
                }

                if (answer.IsRequired == null || classAttributeDefinition.Required != answer.IsRequired)
                {
                    answer.IsRequired = classAttributeDefinition.Required;

                    var fieldState = View.Cache.GetValueExt <CSAnswers.isRequired>(answer) as PXFieldState;
                    var fieldValue = fieldState != null && ((bool?)fieldState.Value).GetValueOrDefault();

                    answer.IsRequired = classAttributeDefinition.Required || fieldValue;
                }



                output.Add(answer);
            }

            answerCache.IsDirty = cacheIsDirty;

            output =
                output.OrderBy(
                    x =>
                    classAttributeList.Contains(x.AttributeID)
                            ? classAttributeList.IndexOf(x.AttributeID)
                            : (x.Order ?? 0))
                .ThenBy(x => x.AttributeID)
                .ToList();

            short attributeOrder = 0;

            foreach (CSAnswers answer in output)
            {
                answer.Order = attributeOrder++;
                yield return(answer);
            }
        }
        private dynamic CastAnswerToViewType(CSAnswers answer)
        {
            var type = answers.Cache.GetItemType();

            return(answer.Cast(type));
        }
Ejemplo n.º 22
0
        public static DataTable LoadRowsToTable(GIDesign genericInq, DataTable structureTable, Dictionary <string, DateTime?> parameters)
        {
            //Define la fila que se generará y la variable de autoincremento
            DataRow row;
            int     i = 0;

            //Crea la instancia al graph de las consultas genericas
            PXGenericInqGrph graphGetRows = PXGenericInqGrph.CreateInstance(genericInq.DesignID.Value);

            //Define los parametros del filtro de la consulta genérica
            foreach (var itemParameters in parameters)
            {
                graphGetRows.Caches[typeof(GenericFilter)].SetValueExt(graphGetRows.Filter.Current, itemParameters.Key, itemParameters.Value);
            }

            //Recorre los renglones recuperados
            foreach (GenericResult resultRow in graphGetRows.Views["Results"].SelectMulti())
            {
                //Genera las filas de la tabla
                row        = structureTable.NewRow();
                row["_id"] = i++;

                //Recorre las llaves del renglon (DAC's de los que se componen los renglones)
                foreach (string key in resultRow.Values.Keys)
                {
                    //Determina si son DAC's mapeados y genericos(formulas)
                    if (key != "GenericResult")
                    {
                        //Si son DAC´s nativos, recorre las columnas definidas en la consulta genérica
                        foreach (GIResult resultMap in PXSelectReadonly <GIResult, Where <GIResult.designID, Equal <Required <GIResult.designID> >, And <GIResult.objectName, Equal <Required <GIResult.objectName> > > > > .Select(graphGetRows, new object[] { genericInq.DesignID.Value, key }))
                        {
                            //Inicializa la variable result
                            var result = new object();
                            //Inicializa el campo como vacío
                            string fieldValue = string.Empty;

                            //Recupera el valor de esa columna en el renglón vigente
                            if (resultMap.Field.Contains("Attributes"))
                            {
                                //Recupera el NoteID del registro
                                result = graphGetRows.Caches[resultRow.Values[key].GetType()].GetValue(resultRow.Values[key], "NoteID");
                                Guid dresult = (Guid)result;

                                //Descompone la columna del atributo y recupera el nombre (llave)
                                string[] values        = resultMap.Field.Split('_');
                                string   attributeName = values[0];

                                //Rastrea el valor del atributo
                                CSAnswers resultAttribute = PXSelectReadonly <CSAnswers, Where <CSAnswers.refNoteID, Equal <Required <CSAnswers.refNoteID> >, And <CSAnswers.attributeID, Equal <Required <CSAnswers.attributeID> > > > > .Select(graphGetRows, new object[] { dresult, attributeName });

                                //Coloca la descripción del atributo en el valor del campo
                                if (resultAttribute != null)
                                {
                                    fieldValue = resultAttribute.Value;
                                }
                            }
                            else
                            {
                                result = graphGetRows.Caches[resultRow.Values[key].GetType()].GetValue(resultRow.Values[key], resultMap.Field);

                                //Si el resultado es diferente de nulo permite la conversión a texto
                                if (result != null)
                                {
                                    //Realiza la conversión del valor recuperado
                                    fieldValue = result.ToString();

                                    //Determina si es tipo Fecha
                                    if (graphGetRows.Caches[resultRow.Values[key].GetType()].GetValue(resultRow.Values[key], resultMap.Field).GetType() == typeof(DateTime))
                                    {
                                        fieldValue = ((DateTime)result).ToString("yyyy-MM-dd");
                                    }

                                    //Determina si es tipo decimal
                                    if (graphGetRows.Caches[resultRow.Values[key].GetType()].GetValue(resultRow.Values[key], resultMap.Field).GetType() == typeof(Decimal))
                                    {
                                        fieldValue = ((Decimal)result).ToString("0.00");
                                    }
                                }
                            }

                            // Agrega el valor de la fila a la columna definida por el número de línea en la definición de la tabla
                            // pero solo agregamos si el titulo no está vacío
                            if (!string.IsNullOrWhiteSpace(resultMap?.Caption))
                            {
                                row[resultMap.Caption.ToString()] = fieldValue;
                            }
                        }
                    }
                    else
                    {
                        //Recupera los registros dinámicos (fórmulas)
                        Dictionary <string, object> resGI = (Dictionary <string, object>)resultRow.Values[key];

                        //Recorre todos esos campos calculados
                        foreach (var entry in resGI)
                        {
                            //Obtiene llave y valor de cada fórmula
                            string keyGI   = entry.Key;
                            var    valueGI = entry.Value;

                            //La llave es un valor compuesto, se separa e identifica el RowID para saber a que columna le corresponde y lo convierte en su respectivo RowID
                            string[] words      = keyGI.Split('_');
                            string   objectName = words[0];
                            string   rowId      = words[1];
                            rowId = rowId.Replace("Formula", "");
                            Guid createRowId = Guid.ParseExact(rowId, "N");

                            //Rastrea la línea (posición de la columna)
                            GIResult resultMapRowId = PXSelectReadonly <GIResult, Where <GIResult.designID, Equal <Required <GIResult.designID> >, And <GIResult.rowID, Equal <Required <GIResult.rowID> > > > > .Select(graphGetRows, new object[] { genericInq.DesignID.Value, createRowId });

                            string fieldValueRowId = string.Empty;
                            if (fieldValueRowId != null)
                            {
                                fieldValueRowId = valueGI.ToString();
                            }

                            //Agrega el valor de la fila a la columna definida por el número de línea en la definición de la tabla
                            // pero solo agregamos si el titulo no está vacío
                            if (!string.IsNullOrWhiteSpace(resultMapRowId?.Caption))
                            {
                                row[resultMapRowId.Caption.ToString()] = fieldValueRowId;
                            }
                        }
                    }
                }

                //Agrega el renglon completo a la tabla
                structureTable.Rows.Add(row);
            }

            //Regresa la estructura completa de la tabla
            return(structureTable);
        }