Ejemplo n.º 1
0
        public void ExecutePattern()
        {
            DocumentList d = new DocumentList();
            d.Add(new TextDocument());
            d.Add(new TextDocument());
            d.Add(new XMLDocument());
            d.Add(new XMLDocument());

            d.GetDocument();
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Обновить лист документов
 /// </summary>
 public void updateDocumentlList()
 {
     DocumentList.Clear();
     foreach (var el in getResourseService.UpdateOpenDoc(userSettings))
     {
         DocumentList.Add(el);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Browse for a document to associate with this instance
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bnAddDocument_Click(object sender, EventArgs e)
        {
            FormAddDocument form = new FormAddDocument();

            if (form.ShowDialog() == DialogResult.OK)
            {
                string documentFile = form.DocumentPath;
                string documentName = form.DocumentName;

                if (form.CopyToLocal)
                {
                    string destinationFile = "";
                    try
                    {
                        // Create a hopefully unique name for this document based on the current time
                        destinationFile = Path.Combine(Application.StartupPath, "Documents");

                        Directory.CreateDirectory(destinationFile);

                        string filename = Path.GetFileNameWithoutExtension(documentFile) + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(documentFile);
                        destinationFile = destinationFile + @"\" + filename;
                        File.Copy(documentFile, destinationFile);
                        documentFile = destinationFile;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Failed to copy " + documentFile + " to " + destinationFile + "\nThe error was " + ex.Message);
                        return;
                    }
                }

                // Add the document to the database and to the list of documents
                Document newDocument = new Document();
                newDocument.Scope    = _scope;
                newDocument.Name     = documentName;
                newDocument.Path     = documentFile;
                newDocument.ParentID = _parentID;
                //
                newDocument.Add();
                AddDocumentToListView(newDocument);

                _documents.Add(newDocument);

                if (_application != null)
                {
                    AuditTrailEntry ate = new AuditTrailEntry();
                    ate.Date      = DateTime.Now;
                    ate.Class     = AuditTrailEntry.CLASS.application_changes;
                    ate.Type      = AuditTrailEntry.TYPE.added;
                    ate.Key       = _application.Name + "|Documents";
                    ate.AssetID   = 0;
                    ate.AssetName = "";
                    ate.Username  = System.Environment.UserName;
                    ate.NewValue  = newDocument.Name;
                    new AuditTrailDAO().AuditTrailAdd(ate);
                }
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Инициализируем файл
 /// </summary>
 private void Initialize()
 {
     _docModelList = CreateDocModelList();
     foreach (var el in _docModelList)
     {
         if (!el.IsFamilyModel)
         {
             DocumentList.Add(el);
         }
     }
 }
Ejemplo n.º 5
0
        private static void SegregateBatch(JournalEntry je, string CuryID, DateTime?DocDate, string FinPeriodID, DocumentList <Batch> created)
        {
            if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
            {
                je.Save.Press();

                if (created.Find(je.BatchModule.Current) == null)
                {
                    created.Add(je.BatchModule.Current);
                }
            }

            Batch arbatch = created.Find <Batch.curyID, Batch.finPeriodID>(CuryID, FinPeriodID) ?? new Batch();

            if (arbatch.BatchNbr != null)
            {
                je.BatchModule.Current = je.BatchModule.Search <Batch.batchNbr>(arbatch.BatchNbr, arbatch.Module);
                je.TimeStamp           = arbatch.tstamp;
            }
            else
            {
                je.Clear();

                CurrencyInfo info = new CurrencyInfo();
                info.CuryID      = CuryID;
                info.CuryEffDate = DocDate;
                info             = je.currencyinfo.Insert(info) ?? info;

                arbatch              = new Batch();
                arbatch.Module       = "GL";
                arbatch.Status       = "U";
                arbatch.Released     = true;
                arbatch.Hold         = false;
                arbatch.DateEntered  = DocDate;
                arbatch.FinPeriodID  = FinPeriodID;
                arbatch.TranPeriodID = FinPeriodID;
                arbatch.CuryID       = CuryID;
                arbatch.CuryInfoID   = info.CuryInfoID;
                arbatch.DebitTotal   = 0m;
                arbatch.CreditTotal  = 0m;
                je.BatchModule.Insert(arbatch);

                CurrencyInfo b_info = je.currencyinfo.Select();
                if (b_info != null)
                {
                    b_info.CuryID      = CuryID;
                    b_info.CuryEffDate = DocDate;
                    je.currencyinfo.Update(b_info);
                }
            }
        }
Ejemplo n.º 6
0
        public void FillDocumentList(string table)
        {
            List <string[]> documentData = DataLayer.GetTableData(table);

            foreach (String[] row in documentData)
            {
                Guid uid = Guid.NewGuid();
                GenericFactory <IDocument> .Register(uid, () => new Document(Convert.ToInt16(row[0]), row[1], DateTime.ParseExact(row[2], "dd/MM/yyyy", null)));

                IDocument doc = GenericFactory <IDocument> .Create(uid);

                DocumentList.Add(doc);
            }
        }
Ejemplo n.º 7
0
        private void NewDocument()
        {
            var document = new Document {
                IssueDate = DateTime.Today
            };
            var vm = new EditDocumentViewModel(new UnitOfWorkFactory(), document);

            vm.Init();
            var window = new EditDocumentView(vm);

            if (window.ShowDialog() ?? false)
            {
                DocumentList.Add(document);
            }
        }
Ejemplo n.º 8
0
        public void FillDocumentList(string table, bool criteria)
        {
            DataLayer.RemoveCriteria();
            DataLayer.SetCriteria("responded", criteria);
            List <string[]> documentData = DataLayer.GetTableData(table);

            foreach (String[] row in documentData)
            {
                Guid uid = Guid.NewGuid();
                GenericFactory <IDocument> .Register(uid, () => new Document(Convert.ToInt16(row[0]), row[1], DateTime.ParseExact(row[2], "dd/MM/yyyy", null), Convert.ToBoolean(row[3])));

                IDocument doc = GenericFactory <IDocument> .Create(uid);

                DocumentList.Add(doc);
            }
        }
Ejemplo n.º 9
0
        ////Search By Number
        public void FilterResults(DocumentList list, bool truncate, bool answers, bool proofs, bool allDocs, int searchTerm)
        {
            DocumentList resultList = new DocumentList();

            foreach (Document document in list)
            {
                if (document.ChNumber == searchTerm)
                {
                    resultList.Add(document);
                }
            }

            list = resultList;
            list.Sort();
            this.documentList = list;
        }
Ejemplo n.º 10
0
        //Modify existing methods in original app
        public void FilterResults(DocumentList list, bool truncate, bool answers, bool proofs, bool allDocs, string searchTerm)
        {
            DocumentList resultList = new DocumentList();

            Log.Info("Filter", "Filtering Confession Results");
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Reset();
            stopwatch.Start();
            Log.Debug("Timer", "Timer Started");
            Regex regex = new Regex(searchTerm, RegexOptions.IgnoreCase);

            Log.Info("Filter Results", "Filtering has begun");
            foreach (Document document in list)
            {
                string[] searchEntries = new string[4];
                searchEntries[0] = document.ChName;
                searchEntries[1] = document.DocumentText;
                searchEntries[2] = document.ChProofs;
                searchEntries[3] = document.Tags;

                foreach (string word in searchEntries) //this[i].Split(' '))
                {
                    string[] pieces = word.Split(' ');
                    foreach (string chunks in pieces)
                    {
                        if (regex.IsMatch(chunks))
                        {
                            document.Matches++;
                        }
                    }
                }
                if (document.Matches >= 1)
                {
                    resultList.Add(document);
                }
                stopwatch.Stop();
                Log.Debug("Timer", String.Format("{0}ms Passed", stopwatch.ElapsedMilliseconds.ToString()));
                stopwatch.Reset();
            }

            list = resultList;
            list.Sort(Document.CompareMatches);
            //   list.Reverse();
            this.documentList = (DocumentList)list;
        }
Ejemplo n.º 11
0
        public static void SegregateRegister(PXGraph graph, int BranchID, string Origin, string PeriodID, DateTime?DocDate, string descr, DocumentList <FARegister> created)
        {
            PXCache doccache  = graph.Caches[typeof(FARegister)];
            PXCache trancache = graph.Caches[typeof(FATran)];

            if (trancache.IsInsertedUpdatedDeleted)
            {
                graph.Actions.PressSave();
                if (doccache.Current != null && created.Find(doccache.Current) == null)
                {
                    created.Add((FARegister)doccache.Current);
                }
                graph.Clear();
            }

            FARegister register = created.Find <FARegister.branchID, FARegister.origin, FARegister.finPeriodID>(BranchID, Origin, PeriodID) ?? new FARegister();

            if (register.RefNbr != null)
            {
                FARegister newreg = PXSelect <FARegister, Where <FARegister.refNbr, Equal <Current <FARegister.refNbr> > > > .SelectSingleBound(graph, new object[] { register });

                if (newreg.DocDesc != descr)
                {
                    newreg.DocDesc = string.Empty;
                    doccache.Update(newreg);
                }
                doccache.Current = newreg;
            }
            else
            {
                graph.Clear();

                register = new FARegister
                {
                    Hold        = false,
                    BranchID    = BranchID,
                    Origin      = Origin,
                    FinPeriodID = PeriodID,
                    DocDate     = DocDate,
                    DocDesc     = descr
                };
                doccache.Insert(register);
            }
        }
Ejemplo n.º 12
0
        public void UpdatePublishedCopyTest()
        {
            var retriever = new DocumentList();
            var list = new DocumentList();
            var item = new DocumentList();

            Mock.Arrange(() => item.IsChild).Returns(true);

            Mock.Arrange(() => DocumentList.GetDocumentList(Arg.IsAny<IEnumerable<SectionViewDocumentDto>>())).IgnoreInstance().Returns(item);

            new PrivateAccessor(retriever).CallMethod("Child_Fetch", new List<SectionViewDocumentDto> { new SectionViewDocumentDto() });
            new PrivateAccessor(list).CallMethod("Child_Fetch", new List<SectionViewDocumentDto> { new SectionViewDocumentDto() });

            Mock.Arrange(() => list.Remove(Arg.IsAny<DocumentEdit>())).DoNothing().MustBeCalled();
            Mock.Arrange(() => list.Add(Arg.IsAny<DocumentEdit>())).DoNothing().MustBeCalled();

            retriever.UpdatePublishedCopy(list);

            Mock.Assert(list);
        }
Ejemplo n.º 13
0
        public void AddDocumentSummary(Guid docId, byte[] pubKey, byte[]?privKey, string contentSeed, StorageSource storageSource)
        {
            var existing = DocumentList.Where(x => x.Id == docId).FirstOrDefault();

            if (existing != null)
            {
                return;
            }

            DocumentSummary sum = new DocumentSummary()
            {
                Id            = docId,
                PublicKey     = pubKey,
                PrivateKey    = privKey,
                ContentSeed   = contentSeed,
                CreatedDate   = DateTimeOffset.UtcNow,
                ModifiedDate  = DateTimeOffset.UtcNow,
                Title         = "Shared document",
                StorageSource = storageSource
            };

            DocumentList.Add(sum);
        }
Ejemplo n.º 14
0
    /// <summary>
    /// Interaction slip send button click event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(hdnAdmissionID.Value))
        {
            foreach (GridViewRow row in gvtemplate.Rows)
            {
                RadioButton Rb = (RadioButton)row.FindControl("Rbtemplate");
                if (Rb.Checked)
                {
                    Label LblTemplateName = (Label)row.FindControl("GV_LblTemplateName");
                    TemplateName = LblTemplateName.Text;
                }
            }
            foreach (GridViewRow row in GvDocument.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chkdocument");
                if (chk.Checked)
                {
                    Label LblDocumentName = (Label)row.FindControl("GV_LblDocumentName");
                    DocumentList.Add(LblDocumentName.Text);
                }
            }

            string InteractionDateTime = string.Empty;
            string FeedBack            = string.Empty;
            string Remarks             = string.Empty;

            string    MailFrom      = EmailUtility.SMTPEmailAddress;
            string    MailTo        = hdnEmailID.Value;
            string    MailSubject   = string.Empty;
            string    MailBody      = string.Empty;
            string    FailiurReason = string.Empty;
            ArrayList ArrMailTo     = new ArrayList();

            switch (hdnAdmissionStatus.Value)
            {
            case "Interaction":

                InteractionDate     = TxtDate.Text.Trim();
                InteractionTime     = TxtTime.Text.Trim();
                InteractionDateTime = TxtDate.Text.Trim() + " " + TxtTime.Text.Trim();

                DocumentFileList = GenerateDocument(DocumentList, hdnAdmissionID.Value);
                GetMailSubjectAndBody(TemplateName, out MailSubject, out MailBody);

                #region Insert in AdmissionPipeline

                oAdmission_BLogic  = new Admission_BLogic();
                oAdmissionPipeline = new AdmissionPipeline();

                oAdmissionPipeline.AdmissionId            = hdnAdmissionID.Value;
                oAdmissionPipeline.AdmissionStatus        = hdnAdmissionStatus.Value;
                oAdmissionPipeline.InteractionTime        = InteractionDateTime;
                oAdmissionPipeline.FeedBack               = null;
                oAdmissionPipeline.Remarks                = null;
                oAdmissionPipeline.GeneratedDocumentCount = Convert.ToString(AutoGeneratedDocumentList.Count);
                oAdmissionPipeline.MailFrom               = MailFrom;
                oAdmissionPipeline.MailTo         = MailTo;
                oAdmissionPipeline.MailSubject    = MailSubject;
                oAdmissionPipeline.MailBody       = MailBody;
                oAdmissionPipeline.MailDocument   = (!string.IsNullOrEmpty(GetMailDocumentString(AutoGeneratedDocumentList))) ? GetMailDocumentString(AutoGeneratedDocumentList) : null;
                oAdmissionPipeline.IsSendSuccess  = false;
                oAdmissionPipeline.FailureReasons = null;
                oAdmissionPipeline.CreatedBy      = Convert.ToString(AppSessions.EmpolyeeID);

                bool IsInsert = oAdmission_BLogic.AdmissionPipeline_Insert(oAdmissionPipeline);

                #endregion

                if (IsInsert)
                {
                    ArrMailTo.Add(MailTo);
                    bool IsSendSuccess = EmailUtility.SendEmail(ArrMailTo, MailSubject, MailBody, out FailiurReason, DocumentFileList);

                    #region Update Mail Status

                    oAdmission_BLogic  = new Admission_BLogic();
                    oAdmissionPipeline = new AdmissionPipeline();

                    oAdmissionPipeline.AdmissionId     = hdnAdmissionID.Value;
                    oAdmissionPipeline.AdmissionStatus = hdnAdmissionStatus.Value;
                    oAdmissionPipeline.IsSendSuccess   = IsSendSuccess;
                    oAdmissionPipeline.FailureReasons  = (!string.IsNullOrEmpty(FailiurReason)) ? FailiurReason : null;

                    oAdmission_BLogic.AdmissionPipeline_UpdateMailStatus(oAdmissionPipeline);

                    #endregion

                    if (IsSendSuccess)
                    {
                        WebMsg.Show("Interaction slip sent successfully.");
                    }
                    else
                    {
                        WebMsg.Show("Interaction slip sent failed.");
                    }
                }
                else
                {
                    WebMsg.Show("Send Admission in pipeline failed.");
                }
                break;

            case "confirm":

                FeedBack = TxtFeedBack.InnerText;
                Remarks  = TxtRemarks.InnerText;

                DocumentFileList = GenerateDocument(DocumentList, hdnAdmissionID.Value);
                GetMailSubjectAndBody(TemplateName, out MailSubject, out MailBody);

                #region Insert in AdmissionPipeline

                oAdmission_BLogic  = new Admission_BLogic();
                oAdmissionPipeline = new AdmissionPipeline();

                oAdmissionPipeline.AdmissionId            = hdnAdmissionID.Value;
                oAdmissionPipeline.AdmissionStatus        = hdnAdmissionStatus.Value;
                oAdmissionPipeline.InteractionTime        = null;
                oAdmissionPipeline.FeedBack               = FeedBack;
                oAdmissionPipeline.Remarks                = Remarks;
                oAdmissionPipeline.GeneratedDocumentCount = Convert.ToString(AutoGeneratedDocumentList.Count);
                oAdmissionPipeline.MailFrom               = MailFrom;
                oAdmissionPipeline.MailTo         = MailTo;
                oAdmissionPipeline.MailSubject    = MailSubject;
                oAdmissionPipeline.MailBody       = MailBody;
                oAdmissionPipeline.MailDocument   = (!string.IsNullOrEmpty(GetMailDocumentString(AutoGeneratedDocumentList))) ? GetMailDocumentString(AutoGeneratedDocumentList) : null;
                oAdmissionPipeline.IsSendSuccess  = false;
                oAdmissionPipeline.FailureReasons = null;
                oAdmissionPipeline.CreatedBy      = Convert.ToString(AppSessions.EmpolyeeID);

                IsInsert = oAdmission_BLogic.AdmissionPipeline_Insert(oAdmissionPipeline);

                #endregion

                if (IsInsert)
                {
                    ArrMailTo.Add(MailTo);

                    bool IsSendSuccess = EmailUtility.SendEmail(ArrMailTo, MailSubject, MailBody, out FailiurReason, DocumentFileList);

                    #region Update Mail Status

                    oAdmission_BLogic  = new Admission_BLogic();
                    oAdmissionPipeline = new AdmissionPipeline();

                    oAdmissionPipeline.AdmissionId     = hdnAdmissionID.Value;
                    oAdmissionPipeline.AdmissionStatus = hdnAdmissionStatus.Value;
                    oAdmissionPipeline.IsSendSuccess   = IsSendSuccess;
                    oAdmissionPipeline.FailureReasons  = (!string.IsNullOrEmpty(FailiurReason)) ? FailiurReason : null;;

                    oAdmission_BLogic.AdmissionPipeline_UpdateMailStatus(oAdmissionPipeline);

                    #endregion

                    if (IsSendSuccess)
                    {
                        WebMsg.Show("Admission is confirmed.");
                    }
                    else if (IsSendSuccess)
                    {
                        WebMsg.Show("Admission confirm failed.");
                    }
                }
                else
                {
                    WebMsg.Show("Send Admission in pipeline failed.");
                }
                break;

            case "onhold":

                FeedBack = TxtFeedBack.InnerText;
                Remarks  = TxtRemarks.InnerText;

                #region Insert in AdmissionPipeline

                oAdmission_BLogic  = new Admission_BLogic();
                oAdmissionPipeline = new AdmissionPipeline();

                oAdmissionPipeline.AdmissionId            = hdnAdmissionID.Value;
                oAdmissionPipeline.AdmissionStatus        = hdnAdmissionStatus.Value;
                oAdmissionPipeline.InteractionTime        = null;
                oAdmissionPipeline.FeedBack               = FeedBack;
                oAdmissionPipeline.Remarks                = Remarks;
                oAdmissionPipeline.GeneratedDocumentCount = Convert.ToString(AutoGeneratedDocumentList.Count);
                oAdmissionPipeline.MailFrom               = null;
                oAdmissionPipeline.MailTo         = null;
                oAdmissionPipeline.MailSubject    = null;
                oAdmissionPipeline.MailBody       = null;
                oAdmissionPipeline.MailDocument   = (!string.IsNullOrEmpty(GetMailDocumentString(AutoGeneratedDocumentList))) ? GetMailDocumentString(AutoGeneratedDocumentList) : null;
                oAdmissionPipeline.IsSendSuccess  = false;
                oAdmissionPipeline.FailureReasons = null;
                oAdmissionPipeline.CreatedBy      = Convert.ToString(AppSessions.EmpolyeeID);

                IsInsert = oAdmission_BLogic.AdmissionPipeline_Insert(oAdmissionPipeline);

                #endregion

                if (IsInsert)
                {
                    WebMsg.Show("Admission is on hold.");
                }
                else
                {
                    WebMsg.Show("Admission onhold failed.");
                }

                break;

            case "reject":

                FeedBack = TxtFeedBack.InnerText;
                Remarks  = TxtRemarks.InnerText;

                #region Insert in AdmissionPipeline

                oAdmission_BLogic  = new Admission_BLogic();
                oAdmissionPipeline = new AdmissionPipeline();

                oAdmissionPipeline.AdmissionId            = hdnAdmissionID.Value;
                oAdmissionPipeline.AdmissionStatus        = hdnAdmissionStatus.Value;
                oAdmissionPipeline.InteractionTime        = null;
                oAdmissionPipeline.FeedBack               = FeedBack;
                oAdmissionPipeline.Remarks                = Remarks;
                oAdmissionPipeline.GeneratedDocumentCount = Convert.ToString(AutoGeneratedDocumentList.Count);
                oAdmissionPipeline.MailFrom               = null;
                oAdmissionPipeline.MailTo         = null;
                oAdmissionPipeline.MailSubject    = null;
                oAdmissionPipeline.MailBody       = null;
                oAdmissionPipeline.MailDocument   = (!string.IsNullOrEmpty(GetMailDocumentString(AutoGeneratedDocumentList))) ? GetMailDocumentString(AutoGeneratedDocumentList) : null;
                oAdmissionPipeline.IsSendSuccess  = false;
                oAdmissionPipeline.FailureReasons = null;
                oAdmissionPipeline.CreatedBy      = Convert.ToString(AppSessions.EmpolyeeID);

                IsInsert = oAdmission_BLogic.AdmissionPipeline_Insert(oAdmissionPipeline);

                #endregion

                if (IsInsert)
                {
                    WebMsg.Show("Admission is rejected.");
                }
                else
                {
                    WebMsg.Show("Admission reject failed.");
                }

                break;

            default:
                break;
            }
            BindAdmissionGrid("");
        }
        else
        {
            WebMsg.Show("Please reload page and try again.");
        }
    }
Ejemplo n.º 15
0
        public void Revalue(RevalueFilter filter, List <RevaluedGLHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      basecache = je.Caches[typeof(AcctHist)];

            je.Views.Caches.Add(typeof(AcctHist));

            string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID;

            if (string.IsNullOrEmpty(extRefNbrNumbering) == false)
            {
                RevaluationRefNbrHelper helper = new RevaluationRefNbrHelper(extRefNbrNumbering);
                helper.Subscribe(je);
            }

            DocumentList <Batch> created = new DocumentList <Batch>(je);

            Currency currency = PXSelect <Currency, Where <Currency.curyID, Equal <Required <Currency.curyID> > > > .Select(je, filter.CuryID);

            bool hasErrors = false;

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (RevaluedGLHistory hist in list)
                {
                    PXProcessing <RevaluedGLHistory> .SetCurrentItem(hist);

                    if (hist.FinPtdRevalued == 0m)
                    {
                        PXProcessing <RevaluedGLHistory> .SetProcessed();

                        continue;
                    }

                    string FinPeriod =
                        FinPeriodRepository.GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(hist.BranchID), filter.FinPeriodID)
                        .Result
                        .FinPeriodID;

                    ProcessingResult result = CheckFinPeriod(FinPeriod, hist.BranchID);
                    if (!result.IsSuccess)
                    {
                        hasErrors = true;
                        continue;
                    }

                    if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                    {
                        je.Save.Press();

                        if (created.Find(je.BatchModule.Current) == null)
                        {
                            created.Add(je.BatchModule.Current);
                        }
                    }

                    Batch cmbatch = created.Find <Batch.branchID>(hist.BranchID) ?? new Batch();
                    if (cmbatch.BatchNbr == null)
                    {
                        je.Clear();

                        CurrencyInfo info = new CurrencyInfo();
                        info.CuryID      = hist.CuryID;
                        info.CuryEffDate = hist.CuryEffDate;
                        info.BaseCalc    = false;
                        info             = je.currencyinfo.Insert(info) ?? info;

                        cmbatch             = new Batch();
                        cmbatch.BranchID    = hist.BranchID;
                        cmbatch.Module      = "CM";
                        cmbatch.Status      = "U";
                        cmbatch.AutoReverse = false;
                        cmbatch.Released    = true;
                        cmbatch.Hold        = false;
                        cmbatch.DateEntered = filter.CuryEffDate;
                        FinPeriodIDAttribute.SetPeriodsByMaster <Batch.finPeriodID>(je.BatchModule.Cache, cmbatch, filter.FinPeriodID);

                        cmbatch.CuryID      = hist.CuryID;
                        cmbatch.CuryInfoID  = info.CuryInfoID;
                        cmbatch.DebitTotal  = 0m;
                        cmbatch.CreditTotal = 0m;
                        cmbatch.Description = filter.Description;
                        je.BatchModule.Insert(cmbatch);

                        CurrencyInfo b_info = je.currencyinfo.Select();
                        if (b_info != null)
                        {
                            b_info.CuryID         = hist.CuryID;
                            b_info.CuryEffDate    = hist.CuryEffDate;
                            b_info.CuryRateTypeID = hist.CuryRateTypeID;
                            b_info.CuryRate       = hist.CuryRate;
                            b_info.RecipRate      = hist.RateReciprocal;
                            b_info.CuryMultDiv    = hist.CuryMultDiv;
                            je.currencyinfo.Update(b_info);
                        }
                    }
                    else
                    {
                        if (!je.BatchModule.Cache.ObjectsEqual(je.BatchModule.Current, cmbatch))
                        {
                            je.Clear();
                        }

                        je.BatchModule.Current = je.BatchModule.Search <Batch.batchNbr>(cmbatch.BatchNbr, cmbatch.Module);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = false;
                        tran.AccountID     = hist.AccountID;
                        tran.SubID         = hist.SubID;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (hist.AccountType == AccountType.Asset || hist.AccountType == AccountType.Expense)
                        {
                            tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                            tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                        }
                        else
                        {
                            tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                            tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                        }

                        tran.TranType  = "REV";
                        tran.TranClass = hist.AccountType;
                        tran.RefNbr    = string.Empty;
                        tran.TranDesc  = filter.Description;
                        FinPeriodIDAttribute.SetPeriodsByMaster <GLTran.finPeriodID>(je.GLTranModuleBatNbr.Cache, tran, filter.FinPeriodID);
                        tran.TranDate    = filter.CuryEffDate;
                        tran.CuryInfoID  = null;
                        tran.Released    = true;
                        tran.ReferenceID = null;
                        tran.ProjectID   = PM.ProjectDefaultAttribute.NonProject();

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    foreach (GLTran tran in je.GLTranModuleBatNbr.SearchAll <Asc <GLTran.tranClass> >(new object[] { "G" }))
                    {
                        je.GLTranModuleBatNbr.Delete(tran);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = true;
                        tran.ZeroPost      = false;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (je.BatchModule.Current.DebitTotal > je.BatchModule.Current.CreditTotal)
                        {
                            tran.AccountID = currency.RevalGainAcctID;
                            tran.SubID     = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalGainSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = 0m;
                            tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal);
                        }
                        else
                        {
                            tran.AccountID = currency.RevalLossAcctID;
                            tran.SubID     = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalLossSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = (je.BatchModule.Current.CreditTotal - je.BatchModule.Current.DebitTotal);
                            tran.CreditAmt = 0m;
                        }

                        tran.TranType    = "REV";
                        tran.TranClass   = GLTran.tranClass.UnrealizedAndRevaluationGOL;
                        tran.RefNbr      = string.Empty;
                        tran.TranDesc    = filter.Description;
                        tran.Released    = true;
                        tran.ReferenceID = null;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    {
                        AcctHist accthist = new AcctHist();
                        accthist.BranchID    = hist.BranchID;
                        accthist.LedgerID    = hist.LedgerID;
                        accthist.AccountID   = hist.AccountID;
                        accthist.SubID       = hist.SubID;
                        accthist.FinPeriodID = filter.FinPeriodID;
                        accthist.CuryID      = hist.CuryID;
                        accthist.BalanceType = "A";

                        accthist = (AcctHist)basecache.Insert(accthist);
                        accthist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    PXProcessing <RevaluedGLHistory> .SetProcessed();
                }

                if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                {
                    je.Save.Press();

                    if (created.Find(je.BatchModule.Current) == null)
                    {
                        created.Add(je.BatchModule.Current);
                    }
                }

                ts.Complete();
            }

            CMSetup cmsetup = PXSelect <CMSetup> .Select(je);

            for (int i = 0; i < created.Count; i++)
            {
                if (cmsetup.AutoPostOption == true)
                {
                    pg.Clear();
                    pg.PostBatchProc(created[i]);
                }
            }

            if (hasErrors)
            {
                //Clean current to prevent set exception to the last item
                PXProcessing <RevaluedGLHistory> .SetCurrentItem(null);

                throw new PXException(ErrorMessages.SeveralItemsFailed);
            }

            if (created.Count > 0)
            {
                je.BatchModule.Current = created[created.Count - 1];
                throw new PXRedirectRequiredException(je, "Preview");
            }

            decimal val = 0m;

            foreach (RevaluedGLHistory res in GLAccountList.Cache.Updated)
            {
                if ((bool)res.Selected)
                {
                    decimal sign = AccountRules.IsDEALAccount(res.AccountType) ? 1.0m : -1.0m;
                    val += sign * (decimal)res.FinPtdRevalued;
                }
            }

            if (val == 0)
            {
                throw new PXOperationCompletedWithWarningException(Messages.NoRevaluationEntryWasMade);
            }
        }
Ejemplo n.º 16
0
        public static void Revalue(RevalueFilter filter, List <RevaluedGLHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      cache     = je.Caches[typeof(CuryAcctHist)];
            PXCache      basecache = je.Caches[typeof(AcctHist)];

            je.Views.Caches.Add(typeof(CuryAcctHist));
            je.Views.Caches.Add(typeof(AcctHist));

            string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID;

            if (string.IsNullOrEmpty(extRefNbrNumbering) == false)
            {
                RevaluationRefNbrHelper helper = new RevaluationRefNbrHelper(extRefNbrNumbering);
                je.RowPersisting.AddHandler <GLTran>(helper.OnRowPersisting);
            }

            DocumentList <Batch> created = new DocumentList <Batch>(je);

            Currency currency = PXSelect <Currency, Where <Currency.curyID, Equal <Required <Currency.curyID> > > > .Select(je, filter.CuryID);

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (RevaluedGLHistory hist in list)
                {
                    if (hist.FinPtdRevalued == 0m)
                    {
                        continue;
                    }

                    if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                    {
                        je.Save.Press();

                        if (created.Find(je.BatchModule.Current) == null)
                        {
                            created.Add(je.BatchModule.Current);
                        }
                    }

                    Batch cmbatch = created.Find <Batch.branchID>(hist.BranchID) ?? new Batch();
                    if (cmbatch.BatchNbr == null)
                    {
                        je.Clear();

                        CurrencyInfo info = new CurrencyInfo();
                        info.CuryID      = hist.CuryID;
                        info.CuryEffDate = filter.CuryEffDate;
                        info             = je.currencyinfo.Insert(info) ?? info;

                        cmbatch              = new Batch();
                        cmbatch.BranchID     = hist.BranchID;
                        cmbatch.Module       = "CM";
                        cmbatch.Status       = "U";
                        cmbatch.AutoReverse  = false;
                        cmbatch.Released     = true;
                        cmbatch.Hold         = false;
                        cmbatch.DateEntered  = filter.CuryEffDate;
                        cmbatch.FinPeriodID  = filter.FinPeriodID;
                        cmbatch.TranPeriodID = filter.FinPeriodID;
                        cmbatch.CuryID       = hist.CuryID;
                        cmbatch.CuryInfoID   = info.CuryInfoID;
                        cmbatch.DebitTotal   = 0m;
                        cmbatch.CreditTotal  = 0m;
                        cmbatch.Description  = filter.Description;
                        je.BatchModule.Insert(cmbatch);

                        CurrencyInfo b_info = je.currencyinfo.Select();
                        if (b_info != null)
                        {
                            b_info.CuryID      = hist.CuryID;
                            b_info.CuryEffDate = filter.CuryEffDate;
                            b_info.CuryRate    = 1m;
                            b_info.CuryMultDiv = "M";
                            je.currencyinfo.Update(b_info);
                        }
                    }
                    else
                    {
                        je.BatchModule.Current = je.BatchModule.Search <Batch.batchNbr>(cmbatch.BatchNbr, cmbatch.Module);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = false;
                        tran.AccountID     = hist.AccountID;
                        tran.SubID         = hist.SubID;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (hist.AccountType == AccountType.Asset || hist.AccountType == AccountType.Expense)
                        {
                            tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                            tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                        }
                        else
                        {
                            tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;
                            tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                        }

                        tran.TranType     = "REV";
                        tran.TranClass    = hist.AccountType;
                        tran.RefNbr       = string.Empty;
                        tran.TranDesc     = string.Empty;
                        tran.TranPeriodID = filter.FinPeriodID;
                        tran.FinPeriodID  = filter.FinPeriodID;
                        tran.TranDate     = filter.CuryEffDate;
                        tran.CuryInfoID   = null;
                        tran.Released     = true;
                        tran.ReferenceID  = null;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    foreach (GLTran tran in je.GLTranModuleBatNbr.SearchAll <Asc <GLTran.tranClass> >(new object[] { "G" }))
                    {
                        je.GLTranModuleBatNbr.Delete(tran);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = true;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (je.BatchModule.Current.DebitTotal > je.BatchModule.Current.CreditTotal)
                        {
                            tran.AccountID = currency.RevalGainAcctID;
                            tran.SubID     = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalGainSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = 0m;
                            tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal);
                        }
                        else
                        {
                            tran.AccountID = currency.RevalLossAcctID;
                            tran.SubID     = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalLossSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = (je.BatchModule.Current.CreditTotal - je.BatchModule.Current.DebitTotal);
                            tran.CreditAmt = 0m;
                        }

                        tran.TranType    = "REV";
                        tran.TranClass   = "G";
                        tran.RefNbr      = string.Empty;
                        tran.TranDesc    = string.Empty;
                        tran.Released    = true;
                        tran.ReferenceID = null;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    {
                        AcctHist accthist = new AcctHist();
                        accthist.BranchID    = hist.BranchID;
                        accthist.LedgerID    = hist.LedgerID;
                        accthist.AccountID   = hist.AccountID;
                        accthist.SubID       = hist.SubID;
                        accthist.FinPeriodID = filter.FinPeriodID;
                        accthist.CuryID      = hist.CuryID;
                        accthist.BalanceType = "A";

                        accthist = (AcctHist)basecache.Insert(accthist);
                        accthist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    {
                        CuryAcctHist accthist = new CuryAcctHist();
                        accthist.BranchID    = hist.BranchID;
                        accthist.LedgerID    = hist.LedgerID;
                        accthist.AccountID   = hist.AccountID;
                        accthist.SubID       = hist.SubID;
                        accthist.FinPeriodID = filter.FinPeriodID;
                        accthist.CuryID      = hist.CuryID;
                        accthist.BalanceType = "A";
                        accthist.BaseCuryID  = je.currencyinfo.Current.BaseCuryID;

                        accthist = (CuryAcctHist)cache.Insert(accthist);
                    }
                }

                if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                {
                    je.Save.Press();

                    if (created.Find(je.BatchModule.Current) == null)
                    {
                        created.Add(je.BatchModule.Current);
                    }
                }

                ts.Complete();
            }

            CMSetup cmsetup = PXSelect <CMSetup> .Select(je);

            for (int i = 0; i < created.Count; i++)
            {
                if (cmsetup.AutoPostOption == true)
                {
                    pg.Clear();
                    pg.PostBatchProc(created[i]);
                }
            }

            if (created.Count > 0)
            {
                je.BatchModule.Current = created[created.Count - 1];
                throw new PXRedirectRequiredException(je, "Preview");
            }
        }
        protected virtual void DoTransfer(TransferFilter filter, List <FixedAsset> list)
        {
            DocumentList <FARegister> created = new DocumentList <FARegister>(this);

            foreach (FixedAsset asset in list)
            {
                FADetails det = PXSelect <FADetails, Where <FADetails.assetID, Equal <Current <FixedAsset.assetID> > > > .SelectSingleBound(this, new object[] { asset });

                FALocationHistory location = PXSelect <FALocationHistory, Where <FALocationHistory.assetID, Equal <Current <FADetails.assetID> >, And <FALocationHistory.revisionID, Equal <Current <FADetails.locationRevID> > > > > .SelectSingleBound(this, new object[] { det });

                int?   destClassID  = filter.ClassTo ?? asset.ClassID;
                int?   destBranchID = filter.BranchTo ?? location.LocationID;
                string destDeptID   = string.IsNullOrEmpty(filter.DepartmentTo) ? location.Department : filter.DepartmentTo;

                if (location.LocationID != destBranchID || location.Department != destDeptID || asset.ClassID != destClassID)
                {
                    FADetails         copy_det = (FADetails)Details.Cache.CreateCopy(det);
                    FALocationHistory copy_loc = (FALocationHistory)Lochist.Cache.CreateCopy(location);
                    copy_loc.RevisionID      = ++copy_det.LocationRevID;
                    copy_loc.LocationID      = destBranchID;
                    copy_loc.Department      = destDeptID;
                    copy_loc.PeriodID        = filter.PeriodID;
                    copy_loc.TransactionDate = filter.TransferDate;
                    copy_loc.Reason          = filter.Reason;

                    TransactionEntry.SegregateRegister(this, (int)destBranchID, FARegister.origin.Transfer, null, filter.TransferDate, "", created);

                    Details.Update(copy_det);
                    location = Lochist.Insert(copy_loc);

                    if (asset.ClassID != destClassID)
                    {
                        asset.ClassID = destClassID;
                        AssetSelect.Cache.Update(asset);
                    }

                    FARegister reg = Register.Current;
                    AssetProcess.TransferAsset(this, asset, location, ref reg);
                }
            }
            if (Register.Current != null && created.Find(Register.Current) == null)
            {
                created.Add(Register.Current);
            }
            Actions.PressSave();
            if (fasetup.Current.AutoReleaseTransfer == true)
            {
                SelectTimeStamp();
                PXLongOperation.StartOperation(this, delegate { AssetTranRelease.ReleaseDoc(created, false); });
            }
            else if (created.Count > 0)
            {
                AssetTranRelease graph = CreateInstance <AssetTranRelease>();
                AssetTranRelease.ReleaseFilter fltr = (AssetTranRelease.ReleaseFilter)graph.Filter.Cache.CreateCopy(graph.Filter.Current);
                fltr.Origin = FARegister.origin.Transfer;
                graph.Filter.Update(fltr);
                graph.SelectTimeStamp();

                Dictionary <string, string> parameters = new Dictionary <string, string>();

                for (int i = 0; i < created.Count; ++i)
                {
                    FARegister reg = created[i];
                    reg.Selected = true;
                    graph.FADocumentList.Update(reg);
                    graph.FADocumentList.Cache.SetStatus(reg, PXEntryStatus.Updated);
                    graph.FADocumentList.Cache.IsDirty = false;

                    parameters["FARegister.RefNbr" + i] = reg.RefNbr;
                }

                parameters["PeriodFrom"] = FinPeriodIDFormattingAttribute.FormatForDisplay(filter.PeriodID);
                parameters["PeriodTo"]   = FinPeriodIDFormattingAttribute.FormatForDisplay(filter.PeriodID);
                parameters["Mode"]       = "U";

                PXReportRequiredException reportex = new PXReportRequiredException(parameters, "FA642000", "Preview");
                throw new PXRedirectWithReportException(graph, reportex, "Release FA Transaction");
            }
        }
        public static void Revalue(RevalueFilter filter, List <RevaluedARHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      cache     = je.Caches[typeof(CuryARHist)];
            PXCache      basecache = je.Caches[typeof(ARHist)];

            je.Views.Caches.Add(typeof(CuryARHist));
            je.Views.Caches.Add(typeof(ARHist));

            string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID;

            if (string.IsNullOrEmpty(extRefNbrNumbering) == false)
            {
                RevaluationRefNbrHelper helper = new RevaluationRefNbrHelper(extRefNbrNumbering);
                helper.Subscribe(je);
            }

            DocumentList <Batch> created = new DocumentList <Batch>(je);

            Currency currency = PXSelect <Currency, Where <Currency.curyID, Equal <Required <Currency.curyID> > > > .Select(je, filter.CuryID);

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (RevaluedARHistory hist in list)
                {
                    if (hist.FinPtdRevalued == 0m)
                    {
                        continue;
                    }

                    if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                    {
                        je.Save.Press();

                        if (created.Find(je.BatchModule.Current) == null)
                        {
                            created.Add(je.BatchModule.Current);
                        }
                    }

                    Batch cmbatch = created.Find <Batch.branchID>(hist.BranchID) ?? new Batch();
                    if (cmbatch.BatchNbr == null)
                    {
                        je.Clear();

                        CurrencyInfo info = new CurrencyInfo();
                        info.CuryID      = hist.CuryID;
                        info.CuryEffDate = hist.CuryEffDate;
                        info.BaseCalc    = false;
                        info             = je.currencyinfo.Insert(info) ?? info;

                        cmbatch              = new Batch();
                        cmbatch.BranchID     = hist.BranchID;
                        cmbatch.Module       = "CM";
                        cmbatch.Status       = "U";
                        cmbatch.AutoReverse  = true;
                        cmbatch.Released     = true;
                        cmbatch.Hold         = false;
                        cmbatch.DateEntered  = filter.CuryEffDate;
                        cmbatch.FinPeriodID  = filter.FinPeriodID;
                        cmbatch.TranPeriodID = filter.FinPeriodID;
                        cmbatch.CuryID       = hist.CuryID;
                        cmbatch.CuryInfoID   = info.CuryInfoID;
                        cmbatch.DebitTotal   = 0m;
                        cmbatch.CreditTotal  = 0m;
                        cmbatch.Description  = filter.Description;
                        je.BatchModule.Insert(cmbatch);

                        CurrencyInfo b_info = je.currencyinfo.Select();
                        if (b_info != null)
                        {
                            b_info.CuryID         = hist.CuryID;
                            b_info.CuryEffDate    = hist.CuryEffDate;
                            b_info.CuryRateTypeID = hist.CuryRateTypeID;
                            b_info.CuryRate       = hist.CuryRate;
                            b_info.RecipRate      = hist.RateReciprocal;
                            b_info.CuryMultDiv    = hist.CuryMultDiv;
                            je.currencyinfo.Update(b_info);
                        }
                    }
                    else
                    {
                        if (!je.BatchModule.Cache.ObjectsEqual(je.BatchModule.Current, cmbatch))
                        {
                            je.Clear();
                        }

                        je.BatchModule.Current = je.BatchModule.Search <Batch.batchNbr>(cmbatch.BatchNbr, cmbatch.Module);
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = false;
                        tran.AccountID     = currency.ARProvAcctID ?? hist.AccountID;
                        tran.SubID         = currency.ARProvSubID ?? hist.SubID;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        tran.DebitAmt  = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued;
                        tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m;

                        tran.TranType     = "REV";
                        tran.TranClass    = AccountType.Asset;
                        tran.RefNbr       = string.Empty;
                        tran.TranDesc     = filter.Description;
                        tran.TranPeriodID = filter.FinPeriodID;
                        tran.FinPeriodID  = filter.FinPeriodID;
                        tran.TranDate     = filter.CuryEffDate;
                        tran.CuryInfoID   = null;
                        tran.Released     = true;
                        tran.ReferenceID  = hist.CustomerID;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    CustomerClass custclass = PXSelectReadonly <CustomerClass, Where <CustomerClass.customerClassID, Equal <Required <CustomerClass.customerClassID> > > > .Select(je, hist.CustomerClassID);

                    if (custclass == null)
                    {
                        custclass = new CustomerClass();
                    }

                    if (custclass.UnrealizedGainAcctID == null)
                    {
                        custclass.UnrealizedGainSubID = null;
                    }

                    if (custclass.UnrealizedLossAcctID == null)
                    {
                        custclass.UnrealizedLossSubID = null;
                    }

                    {
                        GLTran tran = new GLTran();
                        tran.SummPost      = true;
                        tran.ZeroPost      = false;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

                        if (je.BatchModule.Current.DebitTotal > je.BatchModule.Current.CreditTotal)
                        {
                            tran.AccountID = custclass.UnrealizedGainAcctID ?? currency.UnrealizedGainAcctID;
                            tran.SubID     = custclass.UnrealizedGainSubID ?? GainLossSubAccountMaskAttribute.GetSubID <Currency.unrealizedGainSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = 0m;
                            tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal);
                        }
                        else
                        {
                            tran.AccountID = custclass.UnrealizedLossAcctID ?? currency.UnrealizedLossAcctID;
                            tran.SubID     = custclass.UnrealizedLossSubID ?? GainLossSubAccountMaskAttribute.GetSubID <Currency.unrealizedLossSubID>(je, hist.BranchID, currency);
                            tran.DebitAmt  = (je.BatchModule.Current.CreditTotal - je.BatchModule.Current.DebitTotal);
                            tran.CreditAmt = 0m;
                        }

                        tran.TranType    = "REV";
                        tran.TranClass   = GLTran.tranClass.UnrealizedAndRevaluationGOL;
                        tran.RefNbr      = string.Empty;
                        tran.TranDesc    = filter.Description;
                        tran.Released    = true;
                        tran.ReferenceID = null;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    {
                        CuryARHist arhist = new CuryARHist();
                        arhist.BranchID    = hist.BranchID;
                        arhist.AccountID   = hist.AccountID;
                        arhist.SubID       = hist.SubID;
                        arhist.FinPeriodID = filter.FinPeriodID;
                        arhist.CustomerID  = hist.CustomerID;
                        arhist.CuryID      = hist.CuryID;

                        arhist = (CuryARHist)cache.Insert(arhist);
                        arhist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    {
                        ARHist arhist = new ARHist();
                        arhist.BranchID    = hist.BranchID;
                        arhist.AccountID   = hist.AccountID;
                        arhist.SubID       = hist.SubID;
                        arhist.FinPeriodID = filter.FinPeriodID;
                        arhist.CustomerID  = hist.CustomerID;

                        arhist = (ARHist)basecache.Insert(arhist);
                        arhist.FinPtdRevalued += hist.FinPtdRevalued;
                    }
                }

                if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted)
                {
                    je.Save.Press();

                    if (created.Find(je.BatchModule.Current) == null)
                    {
                        created.Add(je.BatchModule.Current);
                    }
                }

                ts.Complete();
            }

            CMSetup cmsetup = PXSelect <CMSetup> .Select(je);

            for (int i = 0; i < created.Count; i++)
            {
                if (cmsetup.AutoPostOption == true)
                {
                    pg.Clear();
                    pg.PostBatchProc(created[i]);
                }
            }

            if (created.Count > 0)
            {
                je.BatchModule.Current = created[created.Count - 1];
                throw new PXRedirectRequiredException(je, "Preview");
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Save current document
        /// </summary>
        /// <param name="fallbackTitle"></param>
        /// <returns></returns>
        public async Task SaveCurrentDocument(string fallbackTitle, byte[] img)
        {
            Error = null;
            if (CurrentDocument != null)
            {
                var sum = CurrentSum;
                if (sum != null && sum.PrivateKey == null)
                {
                    DocumentList.Remove(sum);
                    sum = null;
                    CurrentDocument.Id = Guid.NewGuid();
                }

                if (sum == null)
                {
                    string contentSeed = Guid.NewGuid().ToString();
                    string fileSeed    = Guid.NewGuid().ToString();
                    string seedPhrase  = $"{fileSeed}-{salt}";
                    var    key         = SiaSkynetClient.GenerateKeys(seedPhrase);

                    sum = new DocumentSummary()
                    {
                        Id            = CurrentDocument.Id,
                        Title         = CurrentDocument.Title,
                        CreatedDate   = DateTimeOffset.UtcNow,
                        ModifiedDate  = DateTimeOffset.UtcNow,
                        ContentSeed   = contentSeed,
                        PrivateKey    = key.privateKey,
                        PublicKey     = key.publicKey,
                        StorageSource = this.IsDfinityLogin ? StorageSource.Dfinity : StorageSource.Skynet
                    };

                    DocumentList.Add(sum);
                }

                if (sum.PrivateKey == null)
                {
                }


                //Fix title if there is no title
                var title = CurrentDocument.Title;
                if (string.IsNullOrWhiteSpace(title))
                {
                    title = fallbackTitle;
                }
                if (string.IsNullOrWhiteSpace(title))
                {
                    title = "Untitled document " + sum.CreatedDate;
                }

                CurrentDocument.Title = title;
                sum.Title             = title;

                CurrentDocument.ModifiedDate = DateTimeOffset.UtcNow;
                sum.ModifiedDate             = DateTimeOffset.UtcNow;

                //Save image
                string?imgLink = null;
                try
                {
                    imgLink = await SaveDocumentImage(img);

                    sum.PreviewImage             = imgLink;
                    CurrentDocument.PreviewImage = imgLink;
                }
                catch { }

                //Save document
                bool success = await SaveDocument(CurrentDocument, sum);

                if (success)
                {
                    Console.WriteLine("Document saved");

                    //Save updated document list
                    await SaveDocumentList(DocumentList);

                    Console.WriteLine("Document list saved");
                }

                if (!success)
                {
                    Error = "Error saving document. Please try again";
                }
                else
                {
                    CurrentDocument = null;
                }
            }
        }
Ejemplo n.º 20
0
        protected override async Task <bool> OnSave()
        {
            try
            {
                this.Block();
                bool returnType = false;

                if (!this.ValidateEntries())
                {
                    this.ShowToast("Existem campos preenchidos de forma incorreta!");
                    this.Unblock();
                    return(false);
                }

                if (this.CurrentOperation == FormOperation.Editando)
                {
                    DocumentModel updatedDocument = await this.documentService.UpdateDocument(this.CurrentDocument);

                    if (updatedDocument != null)
                    {
                        DocumentModel documentToUpdate = this.DocumentList.Find(document => document.ID == updatedDocument.ID);
                        if (documentToUpdate == null)
                        {
                            await this.GetList();
                        }
                        else
                        {
                            DocumentList.Remove(documentToUpdate);
                            DocumentList.Add(updatedDocument);
                        }
                        this.ShowToast("Documento editado com sucesso!");
                    }
                }
                else
                {
                    var newDocument = await documentService.CreateDocument(CurrentDocument);

                    if (newDocument != null)
                    {
                        this.DocumentList.Add(newDocument);
                        this.ShowToast("Documento inserido com sucesso!");
                        returnType = true;
                    }
                    else
                    {
                        this.CurrentDocument = null;
                        this.ShowToast("Erro ao inserir categoria!");
                    }
                }

                this.CurrentOperation = FormOperation.Nenhum;
                this.SortList();
                this.ResetEntries();
                this.Unblock();
                return(returnType);
            }
            catch (Exception e)
            {
                this.ShowToast(e.Message);
                //this.CurrentOperation = FormOperation.Nenhum;
                //this.ResetEntries();
                this.Unblock();
                return(false);
            }
        }
Ejemplo n.º 21
0
        public virtual void ReleaseLCTrans(IEnumerable <LandedCostTran> aTranSet, DocumentList <INRegister> aINCreated, DocumentList <APInvoice> aAPCreated)
        {
            Dictionary <int, APInvoiceEntry>    apGraphs = new Dictionary <int, APInvoiceEntry>();
            Dictionary <int, INAdjustmentEntry> inGraphs = new Dictionary <int, INAdjustmentEntry>();
            Dictionary <int, int>    combinations        = new Dictionary <int, int>();
            List <APRegister>        forReleaseAP        = new List <APRegister>();
            List <INRegister>        forReleaseIN        = new List <INRegister>();
            DocumentList <APInvoice> apDocuments         = new DocumentList <APInvoice>(this);
            POSetup poSetupR              = this.poSetup.Select();
            bool    autoReleaseIN         = poSetupR.AutoReleaseLCIN.Value;
            bool    autoReleaseAP         = poSetupR.AutoReleaseAP.Value;
            bool    noApplicableItems     = false;
            bool    noApplicableTransfers = false;

            foreach (LandedCostTran iTran in aTranSet)
            {
                LandedCostCode lcCode = PXSelect <LandedCostCode, Where <LandedCostCode.landedCostCodeID, Equal <Required <LandedCostCode.landedCostCodeID> > > > .Select(this, iTran.LandedCostCodeID);

                if ((string.IsNullOrEmpty(iTran.APDocType) || string.IsNullOrEmpty(iTran.APRefNbr)) && iTran.PostponeAP == false)
                {
                    APInvoiceEntry apGraph = null;
                    foreach (KeyValuePair <int, APInvoiceEntry> iGraph in apGraphs)
                    {
                        APInvoice apDoc = iGraph.Value.Document.Current;
                        string    terms = String.IsNullOrEmpty(iTran.TermsID) ? lcCode.TermsID : iTran.TermsID;

                        if (apDoc.VendorID == iTran.VendorID &&
                            apDoc.VendorLocationID == iTran.VendorLocationID &&
                            apDoc.InvoiceNbr == iTran.InvoiceNbr &&
                            apDoc.CuryID == iTran.CuryID &&
                            apDoc.DocDate == iTran.InvoiceDate &&
                            apDoc.TermsID == terms &&
                            (apDoc.DocType == AP.APDocType.Invoice && iTran.CuryLCAmount > Decimal.Zero))
                        {
                            combinations.Add(iTran.LCTranID.Value, iGraph.Key);
                            apGraph = iGraph.Value;
                        }
                    }
                    if (apGraph == null)
                    {
                        apGraph = PXGraph.CreateInstance <APInvoiceEntry>();
                        if (autoReleaseAP)
                        {
                            apGraph.APSetup.Current.RequireControlTotal    = false;
                            apGraph.APSetup.Current.RequireControlTaxTotal = false;
                            apGraph.APSetup.Current.HoldEntry = false;
                        }
                        apGraphs[iTran.LCTranID.Value] = apGraph;
                    }
                    apGraph.InvoiceLandedCost(iTran, null, false);
                    apDocuments.Add(apGraph.Document.Current);
                }

                if (lcCode.AllocationMethod != LandedCostAllocationMethod.None)
                {
                    List <POReceiptLine>       receiptLines = new List <POReceiptLine>();
                    List <LandedCostTranSplit> lcTranSplits = new List <LandedCostTranSplit>();
                    GetReceiptLinesToAllocate(receiptLines, lcTranSplits, iTran);
                    var lch = new LandedCostHelper(this, false);
                    List <LandedCostHelper.POReceiptLineAdjustment> result = lch.AllocateLCOverRCTLines(receiptLines, lcCode, iTran, lcTranSplits);
                    if (result.Count > 0)
                    {
                        if (result.Count == 1 && !result[0].Item1.InventoryID.HasValue)
                        {
                            noApplicableTransfers = !lch.HasApplicableTransfers;
                            noApplicableItems     = true;                          //Skip Cost adjustment creation;
                        }
                        else
                        {
                            INAdjustmentEntry inGraph = PXGraph.CreateInstance <INAdjustmentEntry>();
                            if (autoReleaseIN)
                            {
                                inGraph.insetup.Current.RequireControlTotal = false;
                                inGraph.insetup.Current.HoldEntry           = false;
                            }
                            CreateCostAjustment(inGraph, lcCode, iTran, result);
                            inGraphs[iTran.LCTranID.Value] = inGraph;
                        }
                    }
                }
            }

            using (PXConnectionScope cs = new PXConnectionScope())
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    foreach (LandedCostTran iTran in aTranSet)
                    {
                        bool           needUpdate = false;
                        LandedCostTran tran       = this.landedCostTrans.Select(iTran.LCTranID);

                        if (apGraphs.ContainsKey(tran.LCTranID.Value))
                        {
                            APInvoiceEntry apGraph = apGraphs[iTran.LCTranID.Value];
                            apGraph.Save.Press();
                            tran.APDocType = apGraph.Document.Current.DocType;
                            tran.APRefNbr  = apGraph.Document.Current.RefNbr;
                            if (!tran.APCuryInfoID.HasValue)
                            {
                                tran.APCuryInfoID = apGraph.Document.Current.CuryInfoID;
                            }
                            tran.Processed = true;
                            if (apGraph.Document.Current.Hold != true)
                            {
                                forReleaseAP.Add(apGraph.Document.Current);
                            }
                            if (aAPCreated != null)
                            {
                                aAPCreated.Add(apGraph.Document.Current);
                            }
                            needUpdate = true;
                        }
                        else if (combinations.ContainsKey(tran.LCTranID.Value))
                        {
                            //Its already saved at this point
                            APInvoiceEntry apGraph = apGraphs[combinations[tran.LCTranID.Value]];
                            tran.APDocType = apGraph.Document.Current.DocType;
                            tran.APRefNbr  = apGraph.Document.Current.RefNbr;
                            if (!tran.APCuryInfoID.HasValue)
                            {
                                tran.APCuryInfoID = apGraph.Document.Current.CuryInfoID;
                            }
                            tran.Processed = true;
                            needUpdate     = true;
                        }

                        if (inGraphs.ContainsKey(tran.LCTranID.Value))
                        {
                            INAdjustmentEntry inGraph = inGraphs[iTran.LCTranID.Value];
                            inGraph.Save.Press();
                            tran.INDocType = inGraph.adjustment.Current.DocType;
                            tran.INRefNbr  = inGraph.adjustment.Current.RefNbr;
                            tran.Processed = true;
                            forReleaseIN.Add(inGraph.adjustment.Current);
                            if (aINCreated != null)
                            {
                                aINCreated.Add(inGraph.adjustment.Current);
                            }
                            needUpdate = true;
                        }
                        if (!needUpdate && tran.PostponeAP == true)
                        {
                            LandedCostCode lcCode = PXSelect <LandedCostCode, Where <LandedCostCode.landedCostCodeID, Equal <Required <LandedCostCode.landedCostCodeID> > > > .Select(this, iTran.LandedCostCodeID);

                            if (lcCode.AllocationMethod == LandedCostAllocationMethod.None)
                            {
                                tran.Processed = true;
                                needUpdate     = true;                             //This combination needs no processing here but must be updated
                            }
                        }
                        if (needUpdate)
                        {
                            LandedCostTran copy = (LandedCostTran)this.landedCostTrans.Cache.CreateCopy(tran);
                            tran = this.landedCostTrans.Update(copy);
                        }
                    }
                    this.Actions.PressSave();
                    ts.Complete();
                }
            }
            if (noApplicableTransfers == true)
            {
                throw new NoApplicableSourceException(Messages.LandedCostCannotBeDistributed);
            }
            if (noApplicableItems == true)
            {
                throw new NoApplicableSourceException(Messages.LandedCostAmountRemainderCannotBeDistributedMultyLines);
            }

            if (autoReleaseAP)
            {
                if (forReleaseAP.Count > 0)
                {
                    APDocumentRelease.ReleaseDoc(forReleaseAP, true);
                }
            }

            if (autoReleaseIN)
            {
                if (forReleaseIN.Count > 0)
                {
                    INDocumentRelease.ReleaseDoc(forReleaseIN, false);
                }
            }
        }
Ejemplo n.º 22
0
		public virtual IEnumerable sHipmentlist()
		{
			PXSelectBase<ARTran> cmd = new PXSelect<ARTran, Where<ARTran.sOShipmentNbr, Equal<Current<SOOrderShipment.shipmentNbr>>, And<ARTran.sOShipmentType, Equal<Current<SOOrderShipment.shipmentType>>, And<ARTran.sOOrderType, Equal<Current<SOOrderShipment.orderType>>, And<ARTran.sOOrderNbr, Equal<Current<SOOrderShipment.orderNbr>>>>>>>(this);

			DocumentList<ARInvoice, SOInvoice> list = new DocumentList<ARInvoice, SOInvoice>(this);
			list.Add(Document.Current, SODocument.Select());

			bool newInvoice = Transactions.Select().Count == 0;

			foreach (SOOrderShipment shipment in shipmentlist.Cache.Updated)
			{
				yield return shipment;
			}

			foreach (PXResult<SOOrderShipment, SOOrder, SOShipLine, SOOrderType, SOOrderTypeOperation, ARTran> order in 
			PXSelectJoinGroupBy<SOOrderShipment,
			InnerJoin<SOOrder, On<SOOrder.orderType, Equal<SOOrderShipment.orderType>, And<SOOrder.orderNbr, Equal<SOOrderShipment.orderNbr>>>,
			InnerJoin<SOShipLine, On<SOShipLine.shipmentNbr, Equal<SOOrderShipment.shipmentNbr>, And<SOShipLine.origOrderType, Equal<SOOrderShipment.orderType>, And<SOShipLine.origOrderNbr, Equal<SOOrderShipment.orderNbr>>>>,
			InnerJoin<SOOrderType, On<SOOrderType.orderType, Equal<SOOrderShipment.orderType>>,
			InnerJoin<SOOrderTypeOperation, 
							On<SOOrderTypeOperation.orderType, Equal<SOOrder.orderType>,
							And<SOOrderTypeOperation.operation, Equal<SOOrderShipment.operation>>>,
			LeftJoin<ARTran, On<ARTran.sOShipmentNbr, Equal<SOShipLine.shipmentNbr>, And<ARTran.sOShipmentType, Equal<SOShipLine.shipmentType>, And<ARTran.sOShipmentLineNbr, Equal<SOShipLine.lineNbr>>>>>>>>>,
			Where<SOOrderShipment.customerID, Equal<Current<ARInvoice.customerID>>,
				And<SOOrderShipment.hold, Equal<boolFalse>,
				And<SOOrderShipment.confirmed, Equal<boolTrue>, And<SOOrderShipment.shipmentType, NotEqual<SOShipmentType.dropShip>,
				And<SOOrderType.aRDocType, Equal<Current<ARInvoice.docType>>,
				And<ARTran.refNbr, IsNull>>>>>>,
			Aggregate<GroupBy<SOOrderShipment.shipmentNbr, GroupBy<SOOrderShipment.orderType, GroupBy<SOOrderShipment.orderNbr>>>>>.Select(this))
			{
				if (shipmentlist.Cache.Locate((SOOrderShipment)order) == null && cmd.View.SelectSingleBound(new object[] { (SOOrderShipment)order }) == null)
				{
					if (newInvoice || list.Find<ARInvoice.customerID, SOInvoice.billAddressID, SOInvoice.billContactID, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrder)order).CustomerID, ((SOOrder)order).BillAddressID, ((SOOrder)order).BillContactID, ((SOOrder)order).CuryID, ((SOOrder)order).TermsID, false) != null)
					{
						yield return (SOOrderShipment)order;
					}
				}
			}

			foreach (PXResult<POReceipt, SOOrder, POReceiptLine> order in PXSelectJoinGroupBy<POReceipt,
					CrossJoin<SOOrder,
					InnerJoin<POReceiptLine, On<POReceiptLine.receiptNbr, Equal<POReceipt.receiptNbr>>,
					InnerJoin<SOLine, On<SOLine.pOType, Equal<POReceiptLine.pOType>, And<SOLine.pONbr, Equal<POReceiptLine.pONbr>, And<SOLine.pOLineNbr, Equal<POReceiptLine.pOLineNbr>, And<SOLine.orderType, Equal<SOOrder.orderType>, And<SOLine.orderNbr, Equal<SOOrder.orderNbr>>>>>>,
					LeftJoin<ARTran, On<ARTran.sOShipmentNbr, Equal<POReceiptLine.receiptNbr>, And<ARTran.sOShipmentType, Equal<SOShipmentType.dropShip>, And<ARTran.sOShipmentLineNbr, Equal<POReceiptLine.lineNbr>, And<ARTran.sOOrderType, Equal<SOLine.orderType>, And<ARTran.sOOrderNbr, Equal<SOLine.orderNbr>, And<ARTran.sOOrderLineNbr, Equal<SOLine.lineNbr>>>>>>>,
					InnerJoin<SOOrderType, On<SOOrderType.orderType, Equal<SOLine.orderType>>,
					InnerJoin<SOOrderTypeOperation, 
							On<SOOrderTypeOperation.orderType, Equal<SOLine.orderType>,
							And<SOOrderTypeOperation.operation, Equal<SOLine.operation>>>>>>>>>,
					Where<POReceipt.released, Equal<boolTrue>,
						And2<Where<POReceiptLine.lineType, Equal<POLineType.goodsForDropShip>, Or<POReceiptLine.lineType, Equal<POLineType.nonStockForDropShip>>>,
						And<SOOrder.customerID, Equal<Current<ARInvoice.customerID>>,
						And<SOOrderType.aRDocType, Equal<Current<ARInvoice.docType>>,
						And<ARTran.refNbr, IsNull>>>>>,
					Aggregate<GroupBy<POReceipt.receiptNbr,
						GroupBy<POReceipt.createdByID,
						GroupBy<POReceipt.lastModifiedByID,
						GroupBy<POReceipt.released,
						GroupBy<POReceipt.ownerID,
						GroupBy<POReceipt.hold,
						GroupBy<SOOrder.orderType,
						GroupBy<SOOrder.orderNbr,
						Sum<POReceiptLine.receiptQty,
						Sum<POReceiptLine.extWeight,
						Sum<POReceiptLine.extVolume>>>>>>>>>>>>>.Select(this))
			{
				SOOrderShipment cached;

				if ((cached = (SOOrderShipment)shipmentlist.Cache.Locate((SOOrderShipment)order)) == null && cmd.View.SelectSingleBound(new object[] { (SOOrderShipment)order }) == null)
				{
					if (newInvoice || list.Find<ARInvoice.customerID, SOInvoice.billAddressID, SOInvoice.billContactID, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrder)order).CustomerID, ((SOOrder)order).BillAddressID, ((SOOrder)order).BillContactID, ((SOOrder)order).CuryID, ((SOOrder)order).TermsID, false) != null)
					{
						shipmentlist.Cache.SetStatus((SOOrderShipment)order, PXEntryStatus.Held);
						yield return (SOOrderShipment)order;
					}
				}
				else if (shipmentlist.Cache.GetStatus(cached) == PXEntryStatus.Notchanged || shipmentlist.Cache.GetStatus(cached) == PXEntryStatus.Held)
				{
					yield return (SOOrderShipment)order;
				}
			}
		}
Ejemplo n.º 23
0
		public virtual void InvoiceOrder(DateTime invoiceDate, PXResult<SOOrderShipment, SOOrder, CurrencyInfo, SOAddress, SOContact, SOOrderType> order, PXResultset<SOShipLine, SOLine> details, Customer customer, DocumentList<ARInvoice, SOInvoice> list)
		{
			ARInvoice newdoc;
			SOOrder soOrder = order;
			SOOrderType ordertype = order;

            decimal ApprovedBalance = 0;
            decimal PrevDocBal = 0;

            PXRowUpdated ApprovedBalanceCollector = delegate(PXCache sender, PXRowUpdatedEventArgs e)
            {
                ARInvoice ARDoc = (ARInvoice)e.Row;
                if ((decimal)ARDoc.DocBal > (decimal)ARDoc.ApprovedCreditAmt)
                {
                    if ((bool)((SOOrder)order).ApprovedCredit && (decimal)ARDoc.DocBal > PrevDocBal)
                    {
                        ApprovedBalance += (decimal)ARDoc.DocBal - PrevDocBal;
                        ARDoc.ApprovedCreditAmt = ApprovedBalance;
                    }
                    ARDoc.ApprovedCredit = (ApprovedBalance == (decimal)ARDoc.DocBal ? true : false);
                    PrevDocBal = (decimal)ARDoc.DocBal;
                }
            };

            this.RowUpdated.AddHandler(typeof(ARInvoice), ApprovedBalanceCollector);

			if (list != null)
			{
				bool iscc = false;
				DateTime? orderInvoiceDate = (sosetup.Current.UseShipDateForInvoiceDate == true ? ((SOOrderShipment)order).ShipDate : soOrder.InvoiceDate);

				if (soOrder.BillSeparately == false)
				{
					iscc = PXSelectReadonly<CCProcTran, Where<CCProcTran.origDocType, Equal<Required<CCProcTran.origDocType>>, And<CCProcTran.origRefNbr, Equal<Required<CCProcTran.origRefNbr>>, And<CCProcTran.refNbr, IsNull>>>>.Select(this, soOrder.OrderType, soOrder.OrderNbr).Count > 0;
				}

				if (soOrder.PaymentCntr == 0 && soOrder.BillSeparately == false && iscc == false)
				{
					if(soOrder.PaymentMethodID == null && soOrder.CashAccountID == null)
						newdoc = list.Find<ARInvoice.docType, ARInvoice.docDate, ARInvoice.branchID, ARInvoice.customerID, ARInvoice.customerLocationID, SOInvoice.billAddressID, SOInvoice.billContactID, SOInvoice.extRefNbr, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrderType)order).ARDocType, orderInvoiceDate ?? invoiceDate, soOrder.BranchID, soOrder.CustomerID, soOrder.CustomerLocationID, soOrder.BillAddressID, soOrder.BillContactID, soOrder.ExtRefNbr, soOrder.CuryID, soOrder.TermsID, false) ?? (ARInvoice)new ARInvoice();
					else if (soOrder.CashAccountID == null)
						newdoc = list.Find<ARInvoice.docType, ARInvoice.docDate, ARInvoice.branchID, ARInvoice.customerID, ARInvoice.customerLocationID, SOInvoice.billAddressID, SOInvoice.billContactID, SOInvoice.pMInstanceID, SOInvoice.extRefNbr, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrderType)order).ARDocType, orderInvoiceDate ?? invoiceDate, soOrder.BranchID, soOrder.CustomerID, soOrder.CustomerLocationID, soOrder.BillAddressID, soOrder.BillContactID, soOrder.PMInstanceID, soOrder.ExtRefNbr, soOrder.CuryID, soOrder.TermsID, false) ?? (ARInvoice)new ARInvoice();					
					else
						newdoc = list.Find<ARInvoice.docType, ARInvoice.docDate, ARInvoice.branchID, ARInvoice.customerID, ARInvoice.customerLocationID, SOInvoice.billAddressID, SOInvoice.billContactID, SOInvoice.pMInstanceID, SOInvoice.cashAccountID, SOInvoice.extRefNbr, ARInvoice.curyID, ARInvoice.termsID, ARInvoice.hidden>(((SOOrderType)order).ARDocType, orderInvoiceDate ?? invoiceDate, soOrder.BranchID, soOrder.CustomerID, soOrder.CustomerLocationID, soOrder.BillAddressID, soOrder.BillContactID, soOrder.PMInstanceID, soOrder.CashAccountID, soOrder.ExtRefNbr, soOrder.CuryID, soOrder.TermsID, false) ?? (ARInvoice)new ARInvoice();
				}
				else
				{
					newdoc = list.Find<ARInvoice.hidden, ARInvoice.hiddenOrderType, ARInvoice.hiddenOrderNbr>(true, soOrder.OrderType, soOrder.OrderNbr);
					if (newdoc == null)
					{
						newdoc = new ARInvoice();
						newdoc.HiddenOrderType = soOrder.OrderType;
						newdoc.HiddenOrderNbr = soOrder.OrderNbr;
						newdoc.Hidden = true;
					}
				}

				if (newdoc.RefNbr != null)
				{
					Document.Current = this.Document.Search<ARInvoice.refNbr>(newdoc.RefNbr, newdoc.DocType);
				}
				else
				{
					this.Clear();

					string docType = ((SOOrderType)order).ARDocType;
					if (((SOOrderShipment)order).Operation == ((SOOrderType)order).DefaultOperation)
					{
						newdoc.DocType = docType;
					}
					else
					{
						//for RMA switch document type if previous shipment was not invoiced previously in the current run, i.e. list.Find() returned null
 						newdoc.DocType = 
							docType == ARDocType.Invoice ? ARDocType.CreditMemo :
							docType == ARDocType.DebitMemo ? ARDocType.CreditMemo :
							docType == ARDocType.CreditMemo ? ARDocType.Invoice :
							docType == ARDocType.CashSale ? ARDocType.CashReturn :
							docType == ARDocType.CashReturn ? ARDocType.CashSale :
							null;
					}

					newdoc.DocDate = orderInvoiceDate ?? invoiceDate;

					if (string.IsNullOrEmpty(soOrder.FinPeriodID) == false)
					{
						newdoc.FinPeriodID = soOrder.FinPeriodID;
					}

					if (soOrder.InvoiceNbr != null)
					{
						newdoc.RefNbr = soOrder.InvoiceNbr;
						newdoc.RefNoteID = soOrder.NoteID;
					}

					if (((SOOrderType)order).UserInvoiceNumbering == true && string.IsNullOrEmpty(newdoc.RefNbr))
					{
						throw new PXException(ErrorMessages.FieldIsEmpty, PXUIFieldAttribute.GetDisplayName<SOOrder.invoiceNbr>(soorder.Cache));
					}

					AutoNumberAttribute.SetNumberingId<ARInvoice.refNbr>(Document.Cache, ((SOOrderType)order).ARDocType, ((SOOrderType)order).InvoiceNumberingID);

					newdoc = (ARInvoice)Document.Cache.CreateCopy(this.Document.Insert(newdoc));

					newdoc.BranchID = soOrder.BranchID;
					newdoc.CustomerID = ((SOOrder)order).CustomerID;
					newdoc.CustomerLocationID = ((SOOrder)order).CustomerLocationID;
					newdoc.TermsID = ((SOOrder)order).TermsID;
					newdoc.DiscDate = ((SOOrder)order).DiscDate;
					newdoc.DueDate = ((SOOrder)order).DueDate;
					newdoc.TaxZoneID = ((SOOrder)order).TaxZoneID;
					newdoc.AvalaraCustomerUsageType = ((SOOrder)order).AvalaraCustomerUsageType;
					newdoc.SalesPersonID = ((SOOrder)order).SalesPersonID;
					newdoc.DocDesc = ((SOOrder)order).OrderDesc;
					newdoc.InvoiceNbr = ((SOOrder)order).CustomerOrderNbr;
					newdoc.CuryID = ((SOOrder)order).CuryID;
					newdoc.ProjectID = ((SOOrder)order).ProjectID ?? PM.ProjectDefaultAttribute.NonProject(this);
				    newdoc.Hold = ordertype.InvoiceHoldEntry;

					if (((SOOrderType)order).MarkInvoicePrinted == true)
					{
						newdoc.Printed = true;
					}

					if (((SOOrderType)order).MarkInvoiceEmailed == true)
					{
						newdoc.Emailed = true;
					}

					if (soOrder.PMInstanceID != null || string.IsNullOrEmpty(soOrder.PaymentMethodID) == false)
					{
						newdoc.PMInstanceID = soOrder.PMInstanceID;
						newdoc.PaymentMethodID = soOrder.PaymentMethodID;
						newdoc.CashAccountID = soOrder.CashAccountID;
					}

					newdoc = this.Document.Update(newdoc);


					if (soOrder.PMInstanceID != null || string.IsNullOrEmpty(soOrder.PaymentMethodID) == false)
					{
						SODocument.Current.PMInstanceID = soOrder.PMInstanceID;
						SODocument.Current.PaymentMethodID = soOrder.PaymentMethodID;
						SODocument.Current.CashAccountID = soOrder.CashAccountID;						
						if(SODocument.Current.CashAccountID == null)
							SODocument.Cache.SetDefaultExt<SOInvoice.cashAccountID>(SODocument.Current);
						SODocument.Current.ExtRefNbr = soOrder.ExtRefNbr;
						//clear error in case invoice currency different from default cash account for customer
						SODocument.Cache.RaiseExceptionHandling<SOInvoice.cashAccountID>(SODocument.Current, null, null);
					}

					foreach (CurrencyInfo info in this.currencyinfo.Select())
					{
						if (((SOOrder)order).InvoiceDate != null)
						{
							PXCache<CurrencyInfo>.RestoreCopy(info, (CurrencyInfo)order);
							info.CuryInfoID = newdoc.CuryInfoID;
						}
					}
					AddressAttribute.CopyRecord<ARInvoice.billAddressID>(this.Document.Cache, newdoc, (SOAddress)order, true);
					ContactAttribute.CopyRecord<ARInvoice.billContactID>(this.Document.Cache, newdoc, (SOContact)order, true);					
				}
			}
			else
			{
				newdoc = (ARInvoice)Document.Cache.CreateCopy(Document.Current);

                if (Transactions.SelectSingle() == null)
                {
                    newdoc.CustomerID = ((SOOrder)order).CustomerID;
                    newdoc.ProjectID = ((SOOrder)order).ProjectID;
                    newdoc.CustomerLocationID = ((SOOrder)order).CustomerLocationID;
                    newdoc.SalesPersonID = ((SOOrder)order).SalesPersonID;
                    newdoc.TaxZoneID = ((SOOrder)order).TaxZoneID;
                    newdoc.AvalaraCustomerUsageType = ((SOOrder)order).AvalaraCustomerUsageType;
                    newdoc.DocDesc = ((SOOrder)order).OrderDesc;
                    newdoc.InvoiceNbr = ((SOOrder)order).CustomerOrderNbr;
                    newdoc.TermsID = ((SOOrder)order).TermsID;

					foreach (CurrencyInfo info in this.currencyinfo.Select())
					{
						PXCache<CurrencyInfo>.RestoreCopy(info, (CurrencyInfo)order);
						info.CuryInfoID = newdoc.CuryInfoID;
						newdoc.CuryID = info.CuryID;
					}
                }

                newdoc = this.Document.Update(newdoc);

				

				AddressAttribute.CopyRecord<ARInvoice.billAddressID>(this.Document.Cache, newdoc, (SOAddress)order, true);
				ContactAttribute.CopyRecord<ARInvoice.billContactID>(this.Document.Cache, newdoc, (SOContact)order, true);								
			}

			PXSelectBase<SOInvoiceDiscountDetail> selectInvoiceDiscounts = new PXSelect<SOInvoiceDiscountDetail,
			Where<SOInvoiceDiscountDetail.tranType, Equal<Current<SOInvoice.docType>>,
			And<SOInvoiceDiscountDetail.refNbr, Equal<Current<SOInvoice.refNbr>>,
			And<SOInvoiceDiscountDetail.orderType, Equal<Required<SOInvoiceDiscountDetail.orderType>>,
			And<SOInvoiceDiscountDetail.orderNbr, Equal<Required<SOInvoiceDiscountDetail.orderNbr>>>>>>>(this);

			foreach (SOInvoiceDiscountDetail detail in selectInvoiceDiscounts.Select(((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
			    DiscountDetails.Delete(detail);
			}

			TaxAttribute.SetTaxCalc<ARTran.taxCategoryID>(this.Transactions.Cache, null, TaxCalc.ManualCalc);

			if (details != null)
			{
				foreach (SOShipLine shipline in details)
				{
					this.Caches[typeof(SOShipLine)].Insert(shipline);
				}
			}

			DateTime? origInvoiceDate = null;
			foreach (PXResult<SOShipLine, SOLine, SOOrderTypeOperation, ARTran> res in PXSelectJoin<SOShipLine, InnerJoin<SOLine, On<SOLine.orderType, Equal<SOShipLine.origOrderType>, And<SOLine.orderNbr, Equal<SOShipLine.origOrderNbr>, And<SOLine.lineNbr, Equal<SOShipLine.origLineNbr>>>>, InnerJoin<SOOrderTypeOperation, On<SOOrderTypeOperation.orderType, Equal<SOLine.orderType>, And<SOOrderTypeOperation.operation, Equal<SOLine.operation>>>, LeftJoin<ARTran, On<ARTran.sOShipmentNbr, Equal<SOShipLine.shipmentNbr>, And<ARTran.sOShipmentType, Equal<SOShipLine.shipmentType>, And<ARTran.sOShipmentLineNbr, Equal<SOShipLine.lineNbr>, And<ARTran.sOOrderType, Equal<SOShipLine.origOrderType>, And<ARTran.sOOrderNbr, Equal<SOShipLine.origOrderNbr>, And<ARTran.sOOrderLineNbr, Equal<SOShipLine.origLineNbr>>>>>>>>>>, Where<SOShipLine.shipmentNbr, Equal<Required<SOShipLine.shipmentNbr>>, And<SOShipLine.origOrderType, Equal<Required<SOShipLine.origOrderType>>, And<SOShipLine.origOrderNbr, Equal<Required<SOShipLine.origOrderNbr>>, And<ARTran.refNbr, IsNull>>>>>.Select(this, ((SOOrderShipment)order).ShipmentNbr, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				SOLine orderline = (SOLine)res;
				SOShipLine shipline = (SOShipLine)res;

                if (Math.Abs((decimal)shipline.BaseShippedQty) < 0.0000005m)
                {
                    continue;
                }

				if (origInvoiceDate == null && orderline.InvoiceDate != null)
					origInvoiceDate = orderline.InvoiceDate;

				ARTran newtran = new ARTran();
				newtran.BranchID = orderline.BranchID;
				newtran.AccountID = orderline.SalesAcctID;
				newtran.SubID = orderline.SalesSubID;
				newtran.SOOrderType = shipline.OrigOrderType;
				newtran.SOOrderNbr = shipline.OrigOrderNbr;
				newtran.SOOrderLineNbr = shipline.OrigLineNbr;
				newtran.SOShipmentNbr = shipline.ShipmentNbr;
				newtran.SOShipmentType = shipline.ShipmentType;
				newtran.SOShipmentLineNbr = shipline.LineNbr;

				newtran.LineType = orderline.LineType;
				newtran.InventoryID = shipline.InventoryID;
                newtran.SiteID = orderline.SiteID;
				newtran.UOM = shipline.UOM;

				newtran.Qty = shipline.ShippedQty;
				newtran.BaseQty = shipline.BaseShippedQty;

                newtran.Commissionable = orderline.Commissionable;
                newtran.GroupDiscountRate = orderline.GroupDiscountRate;

				decimal shippedQtyInBaseUnits = INUnitAttribute.ConvertToBase(Transactions.Cache, newtran.InventoryID, shipline.UOM, shipline.ShippedQty.Value, INPrecision.QUANTITY);
				decimal shippedQtyInOrderUnits = INUnitAttribute.ConvertFromBase(Transactions.Cache, newtran.InventoryID, orderline.UOM, shippedQtyInBaseUnits, INPrecision.QUANTITY);

				if (shippedQtyInOrderUnits != orderline.OrderQty || shipline.UOM != orderline.UOM)
				{
					decimal curyUnitPriceInBaseUnits = INUnitAttribute.ConvertFromBase(Transactions.Cache, newtran.InventoryID, orderline.UOM, orderline.CuryUnitPrice.Value, INPrecision.UNITCOST);
					decimal curyUnitPriceInShippedUnits = INUnitAttribute.ConvertToBase(Transactions.Cache, newtran.InventoryID, shipline.UOM, curyUnitPriceInBaseUnits, INPrecision.UNITCOST);

                    if (arsetup.Current.LineDiscountTarget == LineDiscountTargetType.SalesPrice)
					{
						decimal? salesPriceAfterDiscount = curyUnitPriceInShippedUnits * (1m - orderline.DiscPct / 100m);
						newtran.CuryTranAmt = shipline.ShippedQty * PXCurrencyAttribute.Round(Transactions.Cache, newtran, salesPriceAfterDiscount ?? 0, CMPrecision.TRANCURY);
					}
					else
					{
						decimal? curyTranAmt = shipline.ShippedQty * curyUnitPriceInShippedUnits * (1m - orderline.DiscPct / 100m);
						newtran.CuryTranAmt = PXCurrencyAttribute.Round(Transactions.Cache, newtran, curyTranAmt ?? 0, CMPrecision.TRANCURY);
					}

					newtran.CuryUnitPrice = curyUnitPriceInShippedUnits;
					newtran.CuryDiscAmt = (shipline.ShippedQty * curyUnitPriceInShippedUnits) - newtran.CuryTranAmt;
				}
				else
				{
					newtran.CuryUnitPrice = orderline.CuryUnitPrice;
                    newtran.CuryTranAmt = orderline.CuryLineAmt;
					newtran.CuryDiscAmt = orderline.CuryDiscAmt;
				}

				if (newdoc.DocType == ((SOOrderType)order).ARDocType && ((SOOrderType)order).DefaultOperation != ((SOOrderTypeOperation)res).Operation)
				{
					//keep BaseQty positive for PXFormula
					newtran.Qty = -newtran.Qty;
					newtran.CuryDiscAmt = -newtran.CuryDiscAmt;
					newtran.CuryTranAmt = -newtran.CuryTranAmt;
				}

				newtran.ProjectID = orderline.ProjectID;
				newtran.TaskID = orderline.TaskID;
				newtran.TranDesc = orderline.TranDesc;
				newtran.SalesPersonID = orderline.SalesPersonID;
				newtran.TaxCategoryID = orderline.TaxCategoryID;
				newtran.DiscPct = orderline.DiscPct;
				
				newtran.ManualDisc = orderline.ManualDisc == true || orderline.IsFree == true;
				newtran.FreezeManualDisc = true;

                newtran.DiscountID = orderline.DiscountID;
                newtran.DiscountSequenceID = orderline.DiscountSequenceID;

				newtran.DetDiscIDC1 = orderline.DetDiscIDC1;
				newtran.DetDiscIDC2 = orderline.DetDiscIDC2;
				newtran.DetDiscSeqIDC1 = orderline.DetDiscSeqIDC1;
				newtran.DetDiscSeqIDC2 = orderline.DetDiscSeqIDC2;
				newtran.DetDiscApp = orderline.DetDiscApp;
				newtran.DocDiscIDC1 = orderline.DocDiscIDC1;
				newtran.DocDiscIDC2 = orderline.DocDiscIDC2;
				newtran.DocDiscSeqIDC1 = orderline.DocDiscSeqIDC1;
				newtran.DocDiscSeqIDC2 = orderline.DocDiscSeqIDC2;

				foreach (ARTran existing in Transactions.Cache.Inserted)
				{
					if (Transactions.Cache.ObjectsEqual<ARTran.sOShipmentNbr, ARTran.sOShipmentType, ARTran.sOShipmentLineNbr, ARTran.sOOrderType, ARTran.sOOrderNbr, ARTran.sOOrderLineNbr>(newtran, existing))
					{
						Transactions.Cache.RestoreCopy(newtran, existing);
						break;
					}
				}

				if (newtran.LineNbr == null)
				{
					newtran = this.Transactions.Insert(newtran);

					if (((SOOrderType)order).CopyLineNotesToInvoice == true)
					{
						if (((SOOrderType)order).CopyLineNotesToInvoiceOnlyNS == false || orderline.LineType == SOLineType.NonInventory)
						{
							PXNoteAttribute.SetNote(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetNote(Caches[typeof(SOLine)], orderline));
						}
					}

					if (((SOOrderType)order).CopyLineFilesToInvoice == true)
					{
						if (((SOOrderType)order).CopyLineFilesToInvoiceOnlyNS == false || orderline.LineType == SOLineType.NonInventory)
						{
							PXNoteAttribute.SetFileNotes(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetFileNotes(Caches[typeof(SOLine)], orderline));
						}
					}
				}
				else
				{
					newtran = this.Transactions.Update(newtran);
					TaxAttribute.Calculate<ARTran.taxCategoryID>(Transactions.Cache, new PXRowUpdatedEventArgs(newtran, null, true));
				}

			}
			
			PXSelectBase<ARTran> cmd = new PXSelect<ARTran, Where<ARTran.tranType, Equal<Current<ARInvoice.docType>>, And<ARTran.refNbr, Equal<Current<ARInvoice.refNbr>>, And<ARTran.sOOrderType, Equal<Current<SOMiscLine2.orderType>>, And<ARTran.sOOrderNbr, Equal<Current<SOMiscLine2.orderNbr>>, And<ARTran.sOOrderLineNbr, Equal<Current<SOMiscLine2.lineNbr>>>>>>>>(this);

			foreach (SOMiscLine2 orderline in PXSelect<SOMiscLine2, Where<SOMiscLine2.orderType, Equal<Required<SOMiscLine2.orderType>>, And<SOMiscLine2.orderNbr, Equal<Required<SOMiscLine2.orderNbr>>, And<Where<SOMiscLine2.curyUnbilledAmt, Greater<decimal0>, Or<SOMiscLine2.curyLineAmt, LessEqual<decimal0>>>>>>>.Select(this, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				if (cmd.View.SelectSingleBound(new object[] { Document.Current, orderline }) == null)
				{
					ARTran newtran = new ARTran();
					newtran.BranchID = orderline.BranchID;
					newtran.AccountID = orderline.SalesAcctID;
					newtran.SubID = orderline.SalesSubID;
					newtran.SOOrderType = orderline.OrderType;
					newtran.SOOrderNbr = orderline.OrderNbr;
					newtran.SOOrderLineNbr = orderline.LineNbr;
					newtran.SOShipmentNbr = ((SOOrderShipment)order).ShipmentNbr;
					newtran.SOShipmentType = ((SOOrderShipment)order).ShipmentType; 
					newtran.SOShipmentLineNbr = null;

					newtran.LineType = SOLineType.MiscCharge;
					newtran.InventoryID = orderline.InventoryID;
					newtran.TaskID = orderline.TaskID;
					newtran.SalesPersonID = orderline.SalesPersonID;
                    newtran.Commissionable = orderline.Commissionable;
					newtran.UOM = orderline.UOM;
					newtran.Qty = orderline.UnbilledQty;
					newtran.BaseQty = orderline.BaseUnbilledQty;
					newtran.CuryUnitPrice = orderline.CuryUnitPrice;
                    newtran.CuryDiscAmt = orderline.CuryDiscAmt;
					newtran.CuryTranAmt = orderline.CuryUnbilledAmt;
					newtran.TranDesc = orderline.TranDesc;
					newtran.TaxCategoryID = orderline.TaxCategoryID;
                    newtran.DiscPct = orderline.DiscPct;
					newtran.ManualDisc = orderline.ManualDisc == true || orderline.IsFree == true;
					newtran.FreezeManualDisc = true;

                    newtran.DiscountID = orderline.DiscountID;
                    newtran.DiscountSequenceID = orderline.DiscountSequenceID;

					newtran.DetDiscIDC1 = orderline.DetDiscIDC1;
					newtran.DetDiscIDC2 = orderline.DetDiscIDC2;
					newtran.DetDiscSeqIDC1 = orderline.DetDiscSeqIDC1;
					newtran.DetDiscSeqIDC2 = orderline.DetDiscSeqIDC2;
					newtran.DetDiscApp = orderline.DetDiscApp;
					newtran.DocDiscIDC1 = orderline.DocDiscIDC1;
					newtran.DocDiscIDC2 = orderline.DocDiscIDC2;
					newtran.DocDiscSeqIDC1 = orderline.DocDiscSeqIDC1;
					newtran.DocDiscSeqIDC2 = orderline.DocDiscSeqIDC2;

					newtran = this.Transactions.Insert(newtran);

					if (((SOOrderType)order).CopyLineNotesToInvoice == true)
					{
						PXNoteAttribute.SetNote(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetNote(Caches[typeof(SOMiscLine2)], orderline));
					}

					if (((SOOrderType)order).CopyLineFilesToInvoice == true)
					{
						PXNoteAttribute.SetFileNotes(Caches[typeof(ARTran)], newtran, PXNoteAttribute.GetFileNotes(Caches[typeof(SOMiscLine2)], orderline));
					}
				}
			}

			SODocument.Current = (SOInvoice)SODocument.Select() ?? (SOInvoice)SODocument.Cache.Insert();
			SODocument.Current.BillAddressID = soOrder.BillAddressID;
			SODocument.Current.BillContactID = soOrder.BillContactID;
			SODocument.Current.ShipAddressID = soOrder.ShipAddressID;
			SODocument.Current.ShipContactID = soOrder.ShipContactID;
			SODocument.Current.IsCCCaptured = soOrder.IsCCCaptured;
			SODocument.Current.IsCCCaptureFailed = soOrder.IsCCCaptureFailed;
			SODocument.Current.PaymentProjectID = PM.ProjectDefaultAttribute.NonProject(this);
			
			if (soOrder.IsCCCaptured == true)
			{
				SODocument.Current.CuryCCCapturedAmt = soOrder.CuryCCCapturedAmt;
				SODocument.Current.CCCapturedAmt = soOrder.CCCapturedAmt;
			}

			SODocument.Current.RefTranExtNbr = soOrder.RefTranExtNbr;

			SOOrderShipment shipment = PXCache<SOOrderShipment>.CreateCopy((SOOrderShipment)order);
			shipment.InvoiceType = SODocument.Current.DocType;
			shipment.InvoiceNbr = SODocument.Current.RefNbr;
			shipmentlist.Cache.Update(shipment);

			FillFreightDetails((SOOrder)order, shipment);

            /*In case Discounts were not recalculated add prorated Doc discounts */
            if (ordertype.RecalculateDiscOnPartialShipment != true)
            {
                //add prorated document discount details from invoice:
                PXSelectBase<SOOrderDiscountDetail> selectOrderDocGroupDiscounts = new PXSelect<SOOrderDiscountDetail,
                Where<SOOrderDiscountDetail.orderType, Equal<Required<SOOrderDiscountDetail.orderType>>,
                And<SOOrderDiscountDetail.orderNbr, Equal<Required<SOOrderDiscountDetail.orderNbr>>>>>(this);

                decimal? rate = 1m;
                if (soOrder.LineTotal > 0m)
                    rate = shipment.LineTotal / soOrder.LineTotal;

                foreach (SOOrderDiscountDetail docGroupDisc in selectOrderDocGroupDiscounts.Select(((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
                {
                        SOInvoiceDiscountDetail dd = new SOInvoiceDiscountDetail();
                        dd.Type = docGroupDisc.Type;
                        dd.DiscountID = docGroupDisc.DiscountID;
                        dd.DiscountSequenceID = docGroupDisc.DiscountSequenceID;
                        dd.OrderType = docGroupDisc.OrderType;
                        dd.OrderNbr = docGroupDisc.OrderNbr;
                        dd.TranType = newdoc.DocType;
                        dd.RefNbr = newdoc.RefNbr;
                        dd.DiscountPct = docGroupDisc.DiscountPct;
                        dd.FreeItemID = docGroupDisc.FreeItemID;
                        dd.FreeItemQty = docGroupDisc.FreeItemQty;

                        if (docGroupDisc.Type == DiscountType.Group)
                        {
                            SOOrderEntry soOrderQ = (SOOrderEntry)PXGraph.CreateInstance(typeof(SOOrderEntry));
                            soOrderQ.Document.Current = order;

                            Dictionary<DiscountSequenceKey, DiscountEngine<SOLine>.DiscountDetailToLineCorrelation<SOOrderDiscountDetail>> grLinesOrderCorrelation = DiscountEngine<SOLine>.CollectGroupDiscountToLineCorrelation(soOrderQ.Transactions.Cache, soOrderQ.Transactions, soOrderQ.DiscountDetails, soOrder.CustomerLocationID, (DateTime)soOrder.OrderDate, false);

                            foreach (KeyValuePair<DiscountSequenceKey, DiscountEngine<SOLine>.DiscountDetailToLineCorrelation<SOOrderDiscountDetail>> dsGroup in grLinesOrderCorrelation)
                            {
                                if (dsGroup.Key.DiscountID == docGroupDisc.DiscountID && dsGroup.Key.DiscountSequenceID == docGroupDisc.DiscountSequenceID)
                                {
                                    decimal invoicedGroupAmt = 0m;
                                    foreach (SOLine soLine in dsGroup.Value.listOfApplicableLines)
                                    {
                                        foreach (ARTran tran in Transactions.Select())
                                        {
                                            if (soLine.LineNbr == tran.SOOrderLineNbr)
                                                invoicedGroupAmt += (tran.CuryLineAmt ?? 0m);
                                        }
                                    }
                                    rate = (invoicedGroupAmt / (decimal)dsGroup.Value.discountDetailLine.CuryDiscountableAmt);
                                }
                            }
                        }

                        SOInvoiceDiscountDetail located = DiscountDetails.Locate(dd);
                        if (located != null)
                        {
                            located.DiscountAmt += docGroupDisc.DiscountAmt * rate;
                            located.CuryDiscountAmt += docGroupDisc.CuryDiscountAmt * rate;
                            located.DiscountableAmt += docGroupDisc.DiscountableAmt * rate;
                            located.CuryDiscountableAmt += docGroupDisc.CuryDiscountableAmt * rate;
                            located.DiscountableQty += docGroupDisc.DiscountableQty * rate;

                            DiscountDetails.Update(located);
                        }
                        else
                        {
                            dd.DiscountAmt = docGroupDisc.DiscountAmt * rate;
                            dd.CuryDiscountAmt = docGroupDisc.CuryDiscountAmt * rate;
                            dd.DiscountableAmt = docGroupDisc.DiscountableAmt * rate;
                            dd.CuryDiscountableAmt = docGroupDisc.CuryDiscountableAmt * rate;
                            dd.DiscountableQty = docGroupDisc.DiscountableQty * rate;

                            DiscountDetails.Insert(dd);
                        }

                    }
                }
            else
            {
                //Recalculate all discounts
                foreach (ARTran tran in Transactions.Select())
                {
                    RecalculateDiscounts(this.Transactions.Cache, tran);
                }
            }
			RecalculateTotalDiscount();

			foreach (PXResult<SOTaxTran, Tax> res in PXSelectJoin<SOTaxTran,
				InnerJoin<Tax, On<SOTaxTran.taxID, Equal<Tax.taxID>>>,
				Where<SOTaxTran.orderType, Equal<Required<SOTaxTran.orderType>>, And<SOTaxTran.orderNbr, Equal<Required<SOTaxTran.orderNbr>>>>>.Select(this, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				SOTaxTran tax = (SOTaxTran)res;
				ARTaxTran newtax = new ARTaxTran();
				newtax.Module = BatchModule.AR;
                Taxes.Cache.SetDefaultExt<ARTaxTran.origTranType>(newtax);
                Taxes.Cache.SetDefaultExt<ARTaxTran.origRefNbr>(newtax);
				Taxes.Cache.SetDefaultExt<ARTaxTran.lineRefNbr>(newtax);
				newtax.TranType = Document.Current.DocType;
				newtax.RefNbr = Document.Current.RefNbr;
				newtax.TaxID = tax.TaxID;
				newtax.TaxRate = 0m;

				this.Taxes.Delete(newtax);

				newtax = this.Taxes.Insert(newtax);
			}

			decimal? CuryApplAmt = 0m;
			bool Calculated = false;

			

			foreach (SOAdjust soadj in PXSelectJoin<SOAdjust, InnerJoin<AR.ARPayment, On<AR.ARPayment.docType, Equal<SOAdjust.adjgDocType>, And<AR.ARPayment.refNbr, Equal<SOAdjust.adjgRefNbr>>>>, Where<SOAdjust.adjdOrderType, Equal<Required<SOAdjust.adjdOrderType>>, And<SOAdjust.adjdOrderNbr, Equal<Required<SOAdjust.adjdOrderNbr>>, And<AR.ARPayment.openDoc, Equal<True>>>>>.Select(this, ((SOOrderShipment)order).OrderType, ((SOOrderShipment)order).OrderNbr))
			{
				ARAdjust prev_adj = null;
				bool found = false;

				foreach (ARAdjust adj in Adjustments.Select())
				{
					if (Calculated)
					{
						CuryApplAmt -= adj.CuryAdjdAmt;
					}

					if (string.Equals(adj.AdjgDocType, soadj.AdjgDocType) && string.Equals(adj.AdjgRefNbr, soadj.AdjgRefNbr))
					{
						if (soadj.CuryAdjdAmt > 0m)
						{
							ARAdjust copy = PXCache<ARAdjust>.CreateCopy(adj);
							copy.CuryAdjdAmt += (soadj.CuryAdjdAmt > adj.CuryDocBal) ? adj.CuryDocBal : soadj.CuryAdjdAmt;
							copy.AdjdOrderType = soadj.AdjdOrderType;
							copy.AdjdOrderNbr = soadj.AdjdOrderNbr;
							prev_adj = Adjustments.Update(copy);
						}

						found = true;

						if (Calculated)
						{
							CuryApplAmt += adj.CuryAdjdAmt;
							break;
						}
					}

					CuryApplAmt += adj.CuryAdjdAmt;
				}

				//if soadjust is not available in adjustments mark as billed
				if (!found)
				{
				/*
					soadj.Billed = true;
					soadjustments.Cache.SetStatus(soadj, PXEntryStatus.Updated);
				*/
				}

				Calculated = true;

				if (!IsExternalTax)
				{
					if (CuryApplAmt > Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt && prev_adj != null)
					{
						prev_adj = PXCache<ARAdjust>.CreateCopy(prev_adj);

						if (prev_adj.CuryAdjdAmt > (CuryApplAmt - (Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt)))
						{
							prev_adj.CuryAdjdAmt -= (CuryApplAmt - (Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt));
							CuryApplAmt = Document.Current.CuryDocBal - Document.Current.CuryOrigDiscAmt;
						}
						else
						{
							CuryApplAmt -= prev_adj.CuryAdjdAmt;
							prev_adj.CuryAdjdAmt = 0m;
						}

						prev_adj = Adjustments.Update(prev_adj);
					}
				}
			}

			newdoc = (ARInvoice)Document.Cache.CreateCopy(Document.Current);
			newdoc.OrigDocDate = origInvoiceDate;
			SOInvoice socopy = (SOInvoice)SODocument.Cache.CreateCopy(SODocument.Current);

			PXFormulaAttribute.CalcAggregate<ARAdjust.curyAdjdAmt>(Adjustments.Cache, SODocument.Current, false);
			Document.Cache.RaiseFieldUpdated<SOInvoice.curyPaymentTotal>(SODocument.Current, null);
			PXDBCurrencyAttribute.CalcBaseValues<SOInvoice.curyPaymentTotal>(SODocument.Cache, SODocument.Current);

			SODocument.Cache.RaiseRowUpdated(SODocument.Current, socopy);

			List<string> ordersdistinct = new List<string>();
			foreach (SOOrderShipment shipments in PXSelect<SOOrderShipment, Where<SOOrderShipment.invoiceType, Equal<Current<ARInvoice.docType>>, And<SOOrderShipment.invoiceNbr, Equal<Current<ARInvoice.refNbr>>>>>.Select(this))
			{
				string key = string.Format("{0}|{1}", shipments.OrderType, shipments.OrderNbr);
				if (!ordersdistinct.Contains(key))
				{
					ordersdistinct.Add(key);
				}

				if (ordersdistinct.Count > 1)
				{
					newdoc.InvoiceNbr = null;
					newdoc.SalesPersonID = null;
					newdoc.DocDesc = null;
					break;
				}

				#region Update FreeItemQty for DiscountDetails based on shipments
				
				PXSelectBase<SOShipmentDiscountDetail> selectShipmentDiscounts = new PXSelect<SOShipmentDiscountDetail,
						Where<SOShipmentDiscountDetail.orderType, Equal<Required<SOShipmentDiscountDetail.orderType>>,
						And<SOShipmentDiscountDetail.orderNbr, Equal<Required<SOShipmentDiscountDetail.orderNbr>>,
						And<SOShipmentDiscountDetail.shipmentNbr, Equal<Required<SOShipmentDiscountDetail.shipmentNbr>>>>>>(this);

				foreach (SOShipmentDiscountDetail sdd in selectShipmentDiscounts.Select(shipments.OrderType, shipments.OrderNbr, shipments.ShipmentNbr))
				{
					SOInvoiceDiscountDetail idd = PXSelect<SOInvoiceDiscountDetail,
						Where<SOInvoiceDiscountDetail.tranType, Equal<Current<ARInvoice.docType>>,
						And<SOInvoiceDiscountDetail.refNbr, Equal<Current<ARInvoice.refNbr>>,
						And<SOInvoiceDiscountDetail.orderType, Equal<Required<SOInvoiceDiscountDetail.orderType>>,
						And<SOInvoiceDiscountDetail.orderNbr, Equal<Required<SOInvoiceDiscountDetail.orderNbr>>,
						And<SOInvoiceDiscountDetail.discountID, Equal<Required<SOInvoiceDiscountDetail.discountID>>,
						And<SOInvoiceDiscountDetail.discountSequenceID, Equal<Required<SOInvoiceDiscountDetail.discountSequenceID>>>>>>>>>.Select(this, shipments.OrderType, shipments.OrderNbr, sdd.DiscountID, sdd.DiscountSequenceID);

					if (idd != null)
					{
						if (idd.FreeItemID == null)
						{
							idd.FreeItemID = sdd.FreeItemID;
							idd.FreeItemQty = sdd.FreeItemQty;
						}
						else
							idd.FreeItemQty = sdd.FreeItemQty;

						DiscountDetails.Update(idd);
					}
					else
					{
						idd = new SOInvoiceDiscountDetail();
						idd.Type = DiscountType.Line;
						idd.TranType = newdoc.DocType;
						idd.RefNbr = newdoc.RefNbr;
						idd.OrderType = sdd.OrderType;
						idd.OrderNbr = sdd.OrderNbr;
						idd.DiscountID = sdd.DiscountID;
						idd.DiscountSequenceID = sdd.DiscountSequenceID;
						idd.FreeItemID = sdd.FreeItemID;
						idd.FreeItemQty = sdd.FreeItemQty;

						DiscountDetails.Insert(idd);
					}
				} 

				#endregion
			}

            this.Document.Update(newdoc);

			if (list != null)
			{
				if (Transactions.Search<ARTran.sOOrderType, ARTran.sOOrderNbr, ARTran.sOShipmentType, ARTran.sOShipmentNbr>(shipment.OrderType, shipment.OrderNbr, shipment.ShipmentType, shipment.ShipmentNbr).Count > 0)
				{
					try
					{
						this.Document.Current.ApplyPaymentWhenTaxAvailable = true;
						this.Save.Press();
					}
					finally
					{
						this.Document.Current.ApplyPaymentWhenTaxAvailable = false;
					}
					

					if (list.Find(this.Document.Current) == null)
					{
						list.Add(this.Document.Current, this.SODocument.Current);
					}
				}
				else
				{
					this.Clear();
				}
			}
            this.RowUpdated.RemoveHandler(typeof(ARInvoice), ApprovedBalanceCollector);
		}
Ejemplo n.º 24
0
        //Modify Existing Code on Main App
        //207 Lines of Code
        private void Search(string query)
        {
            int  docCount = 1;
            bool truncate = false;

            Log.Info("Search()", String.Format("Search Begins" + ""));
            searchFragmentActivity = new SearchFragmentActivity();
            // RadioButton radio = FindViewById<RadioButton>(Resource.Id.viewAllRadio);
            using (var conn = new SQLite.SQLiteConnection(dbPath))
            {
                var      cmd = new SQLite.SQLiteCommand(conn); var searchStr = new SQLite.SQLiteCommand(conn);
                bool     proofs = true, answers = true, searchAll = false, viewDocs = false;
                CheckBox answerCheck = FindViewById <CheckBox>(Resource.Id.AnswerBox), proofCheck = FindViewById <CheckBox>(Resource.Id.proofBox),
                         searchCheck = FindViewById <CheckBox>(Resource.Id.searchAllCheckBox);
                RadioButton viewRadio = FindViewById <RadioButton>(Resource.Id.viewAllRadio);
                Spinner     spinner = FindViewById <Spinner>(Resource.Id.spinner1), spinner2 = FindViewById <Spinner>(Resource.Id.spinner2);
                spinner.ItemSelected  += new EventHandler <AdapterView.ItemSelectedEventArgs>(Spinner1_ItemSelected);
                spinner2.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(Spinner2_ItemSelected);

                string fileString = "", accessString = "";
                accessString = TableAccess("");
                if (searchCheck.Checked)
                {
                    searchAll = true;
                }
                else
                {
                    searchAll = false; accessString = TableAccess(string.Format(" where documentname = '{0}' ", fileName));
                }
                //Data filters
                if (allOpen)
                {
                    if (searchAll)
                    {
                        fileString = TableAccess("");//"select * from Documenttitlelist";
                    }
                    else
                    {
                        fileString = TableAccess(string.Format("Where Documentname='{0}'", fileName));//String.Format("select * from DocumentTableList where DocumentName='{0}'", fileName);
                    }
                }
                if (catechismOpen)
                {
                    if (searchAll)
                    {
                        fileString = TableAccess("Where documentTypeName='CATECHISM'"); //"and DocumentTypeName='CATECHISM'");
                    }
                    else
                    {
                        fileString = TableAccess(String.Format("where DocumentTypeName='CATECHISM' and DocumentName='{0}' ", fileName));
                    }
                }
                if (confessionOpen)
                {
                    if (searchAll)
                    {
                        fileString = TableAccess("where DocumentTypeName='CONFESSION' ");
                    }
                    else
                    {
                        fileString = TableAccess(String.Format("where DocumentTypeName='CONFESSION' and DocumentName='{0}'  ", fileName));
                    }
                }
                if (creedOpen)
                {
                    if (searchAll)
                    {
                        fileString = TableAccess("where DocumentTypeName='CREED' ");
                    }
                    else
                    {
                        fileString = TableAccess(string.Format("where DocumentTypeName='CREED' and DocumentName='{0}' ", fileName));
                    }
                }
                //Proofs enabled
                if (proofCheck.Checked)
                {
                    proofs = true;
                }
                else
                {
                    proofs = false;
                }
                //Read Document
                if (viewRadio.Checked)
                {
                    viewDocs = true;
                }
                else
                {
                    viewDocs = false;
                }
                cmd.CommandText       = fileString;
                searchStr.CommandText = accessString;
                var r = cmd.ExecuteQuery <DocumentTitle>();
                var searchFields = searchStr.ExecuteQuery <Document>();
                documentList = new DocumentList();
                //Add Entries to DocumentList
                for (int x = 0; x < searchFields.Count; x++)
                {
                    DocumentTitle docTitle = new DocumentTitle();
                    docTitle.DocumentID = searchFields[x].DocumentID;
                    for (int y = 0; y < r.Count; y++)
                    {
                        if (!r[y].DocumentID.Equals(docTitle.DocumentID))
                        {
                            foreach (DocumentTitle doc in r)
                            {
                                if (doc.DocumentID == docTitle.DocumentID)
                                {
                                    docTitle.Title = doc.Title;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            docTitle.Title = r[y].CompareIDs(docTitle.DocumentID);
                        }
                    }
                    searchFields[x].DocumentName = docTitle.Title;
                    Document document = new Document();
                    document.ChName       = searchFields[x].ChName;
                    document.DocDetailID  = searchFields[x].DocDetailID;
                    document.DocumentText = Formatter(searchFields[x].DocumentText);
                    document.DocumentName = searchFields[x].DocumentName;
                    document.ChNumber     = searchFields[x].ChNumber;
                    document.ChProofs     = Formatter(searchFields[x].ChProofs);
                    document.Tags         = searchFields[x].Tags;
                    documentList.Add(document);
                }
                if (FindViewById <CheckBox>(Resource.Id.truncateCheck).Checked)
                {
                    truncate = true;
                }
                if (viewRadio.Checked != true && query != "" && FindViewById <RadioButton>(Resource.Id.topicRadio).Checked)
                {
                    if (FindViewById <RadioButton>(Resource.Id.topicRadio).Checked)
                    {
                        stopwatch.Start();
                        FilterResults(documentList, truncate, true, proofs, searchAll, query);
                        documentList.Reverse();
                        stopwatch.Stop();
                    }
                }
                else if (FindViewById <RadioButton>(Resource.Id.chapterRadio).Checked & query != "")
                {
                    int searchInt = Int32.Parse(query);
                    FilterResults(this.documentList, truncate, answers, proofs, searchAll, searchInt);
                }
                else if (viewDocs)
                {
                    if (!FindViewById <CheckBox>(Resource.Id.searchAllCheckBox).Checked)
                    {
                        query = "Results for All";
                    }
                    else
                    {
                        query = "View All";
                    }
                }
                if (documentList.Count > 1)
                {
                    SetContentView(Resource.Layout.search_results);
                    ViewPager     viewPager = FindViewById <ViewPager>(Resource.Id.viewpager);
                    SearchAdapter adapter   = new SearchAdapter(SupportFragmentManager, documentList, query, truncate);
                    searchFragmentActivity.DisplayResults(documentList, viewPager, adapter, query, 0, truncate);
                }
                else
                {
                    stopwatch.Stop();
                    if (this.documentList.Count == 0)
                    {
                        #region Error Logging
                        Log.Info("Search()", String.Format("No Results were found for {0}", query));
                        Toast.MakeText(this, String.Format("No results were found for  {0}", query), ToastLength.Long).Show();
                        #endregion
                        #region Variable Declaration and Assignment

                        SetContentView(Resource.Layout.errorLayout);
                        TextView errorMsg = FindViewById <TextView>(Resource.Id.errorTV);
                        errorMsg.Text = String.Format("No Search Results were found for {0}\r\n\r\n" +
                                                      "Go back to home page to search for another topic", query);


                        #endregion
                        #region Dialog Box
                        Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
                        alert.SetTitle("No Results Found");
                        alert.SetMessage(String.Format("No Results were found for {0}.\r\n\r\n" +
                                                       "Do you want to go back and search for another topic?", query));
                        alert.SetPositiveButton("Yes", (senderAlert, args) =>
                        {
                            intent = new Intent(this, Class);
                            searchFragmentActivity = null;
                            this.OnStop();
                            this.Finish();
                            StartActivity(intent);
                        });
                        alert.SetNegativeButton("No", (senderAlert, args) => { alert.Dispose(); });

                        Dialog dialog = alert.Create();
                        dialog.Show();
                        #endregion
                    }
                    else
                    {
                        //SetTitle();
                        Document document = this.documentList[this.documentList.Count - 1];
                        SetContentView(Resource.Layout.confession_results);
                        TextView chapterBox  = FindViewById <TextView>(Resource.Id.chapterText);
                        TextView proofBox    = FindViewById <TextView>(Resource.Id.proofText);
                        TextView chNumbBox   = FindViewById <TextView>(Resource.Id.confessionChLabel);
                        TextView docTitleBox = FindViewById <TextView>(Resource.Id.documentTitleLabel);

                        chapterBox.Text  = document.DocumentText;
                        chNumbBox.Text   = String.Format("Chapter {0} : {1}", document.ChNumber.ToString(), document.ChName);
                        proofBox.Text    = document.ChProofs;
                        docTitleBox.Text = document.DocumentName;
                        TextView proofView = FindViewById <TextView>(Resource.Id.proofLabel);
                        ChangeColor(true, Android.Graphics.Color.Black, chapterBox, proofBox, chNumbBox, docTitleBox);
                        ChangeColor(proofView, false, Android.Graphics.Color.Black);
                        shareList = docTitleBox.Text + newLine + chNumbBox.Text + newLine + chapterBox.Text + newLine + "Proofs" + newLine + proofBox.Text;
                        FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.shareActionButton);
                        ChangeColor(fab, Android.Graphics.Color.Black);

                        fab.Click += ShareContent;
                    }
                }
            }
        }
        //TODO:refactor
        public static void SOCreateProc(List <SOFixedDemand> list, DateTime?PurchDate)
        {
            SOOrderEntry           docgraph = PXGraph.CreateInstance <SOOrderEntry>();
            SOSetup                sosetup  = docgraph.sosetup.Current;
            DocumentList <SOOrder> created  = new DocumentList <SOOrder>(docgraph);

            docgraph.ExceptionHandling.AddHandler <SOLineSplit.qty>((cache, e) => { e.Cancel = true; });
            docgraph.ExceptionHandling.AddHandler <SOLineSplit.isAllocated>((cache, e) => { ((SOLineSplit)e.Row).IsAllocated = true; e.Cancel = true; });

            foreach (SOFixedDemand demand in list)
            {
                string OrderType =
                    sosetup.TransferOrderType ?? SOOrderTypeConstants.TransferOrder;

                string demandPlanType = demand.PlanType;

                try
                {
                    if (demand.SourceSiteID == null)
                    {
                        PXProcessing <SOFixedDemand> .SetWarning(list.IndexOf(demand), Messages.MissingSourceSite);

                        continue;
                    }

                    SOOrder      order;
                    SOLineSplit2 sosplit = PXSelect <SOLineSplit2, Where <SOLineSplit2.planID, Equal <Required <SOLineSplit2.planID> > > > .Select(docgraph, demand.PlanID);

                    if (sosplit != null)
                    {
                        order = created.Find <SOOrder.orderType, SOOrder.destinationSiteID, SOOrder.defaultSiteID>(OrderType, sosplit.ToSiteID, sosplit.SiteID);
                    }
                    else
                    {
                        if (demand.SourceSiteID == demand.SiteID)
                        {
                            PXProcessing <SOFixedDemand> .SetWarning(list.IndexOf(demand), Messages.EqualSourceDestinationSite);

                            continue;
                        }

                        order = created.Find <SOOrder.orderType, SOOrder.destinationSiteID, SOOrder.defaultSiteID>(OrderType, demand.SiteID, demand.SourceSiteID);
                    }

                    if (order == null)
                    {
                        order = new SOOrder();
                    }

                    if (order.OrderNbr == null)
                    {
                        docgraph.Clear();

                        if (sosplit != null)
                        {
                            INSite sourceSite = PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(docgraph, sosplit.SiteID);

                            order.BranchID  = sourceSite.BranchID;
                            order.OrderType = OrderType;
                            order           = PXCache <SOOrder> .CreateCopy(docgraph.Document.Insert(order));

                            order.DefaultSiteID     = sosplit.SiteID;
                            order.DestinationSiteID = sosplit.ToSiteID;
                            order.OrderDate         = PurchDate;

                            docgraph.Document.Update(order);
                        }
                        else
                        {
                            INSite sourceSite = PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(docgraph, demand.SourceSiteID);

                            order.BranchID  = sourceSite.BranchID;
                            order.OrderType = OrderType;
                            order           = PXCache <SOOrder> .CreateCopy(docgraph.Document.Insert(order));

                            order.DefaultSiteID     = demand.SourceSiteID;
                            order.DestinationSiteID = demand.SiteID;
                            order.OrderDate         = PurchDate;

                            docgraph.Document.Update(order);
                        }
                    }
                    else if (docgraph.Document.Cache.ObjectsEqual(docgraph.Document.Current, order) == false)
                    {
                        docgraph.Document.Current = docgraph.Document.Search <SOOrder.orderNbr>(order.OrderNbr, order.OrderType);
                    }

                    SOLine      newline;
                    SOLineSplit newsplit;
                    PXCache     cache = docgraph.Caches[typeof(INItemPlan)];
                    INItemPlan  rp;

                    if (sosplit != null)
                    {
                        docgraph.Transactions.Current = newline = docgraph.Transactions.Search <SOLine.inventoryID, SOLine.subItemID, SOLine.siteID, SOLine.pOCreate>(demand.InventoryID, demand.SubItemID, demand.SiteID, false);
                        if (newline == null)
                        {
                            newline = PXCache <SOLine> .CreateCopy(docgraph.Transactions.Insert());

                            newline.InventoryID = demand.InventoryID;
                            newline.SubItemID   = demand.SubItemID;
                            newline.SiteID      = demand.SiteID;
                            newline.UOM         = demand.UOM;
                            newline.OrderQty    = 0m;

                            newline = docgraph.Transactions.Update(newline);
                        }

                        newsplit = new SOLineSplit();
                        newsplit.LotSerialNbr = sosplit.LotSerialNbr;
                        newsplit.IsAllocated  = true;
                        newsplit.IsMergeable  = false;
                        newsplit.SiteID       = demand.SiteID; //SiteID should be explicitly set because of PXFormula
                        newsplit.Qty          = demand.OrderQty;
                        newsplit.RefNoteID    = demand.RefNoteID;

                        //we have to delete previous allocation and reinsert it after the newsplit for transfer-order allocation to work properly
                        rp = PXCache <INItemPlan> .CreateCopy(demand);

                        cache.RaiseRowDeleted(demand);

                        newsplit = docgraph.splits.Insert(newsplit);

                        sosplit.SOOrderType    = newsplit.OrderType;
                        sosplit.SOOrderNbr     = newsplit.OrderNbr;
                        sosplit.SOLineNbr      = newsplit.LineNbr;
                        sosplit.SOSplitLineNbr = newsplit.SplitLineNbr;
                        docgraph.sodemand.Update(sosplit);

                        rp.SiteID       = sosplit.ToSiteID;
                        rp.PlanType     = INPlanConstants.Plan93;
                        rp.FixedSource  = null;
                        rp.SupplyPlanID = newsplit.PlanID;
                        cache.RaiseRowInserted(rp);
                        cache.SetStatus(rp, PXEntryStatus.Updated);
                    }
                    else
                    {
                        docgraph.Transactions.Current = newline = docgraph.Transactions.Search <SOLine.inventoryID, SOLine.subItemID, SOLine.siteID, SOLine.pOCreate>(demand.InventoryID, demand.SubItemID, demand.SourceSiteID, demand.VendorID != null);
                        if (newline == null)
                        {
                            newline = PXCache <SOLine> .CreateCopy(docgraph.Transactions.Insert());

                            newline.InventoryID = demand.InventoryID;
                            newline.SubItemID   = demand.SubItemID;
                            newline.SiteID      = demand.SourceSiteID;
                            newline.UOM         = demand.UOM;
                            newline.OrderQty    = 0m;
                            //newline.POCreate = (demand.VendorID != null);
                            newline.POCreate = (demand.FixedSource == INReplenishmentSource.TransferToPurchase);
                            newline.VendorID = demand.VendorID;
                            //newline.VendorLocationID = demand.VendorLocationID;

                            newline = docgraph.Transactions.Update(newline);
                        }

                        newsplit             = new SOLineSplit();
                        newsplit.IsAllocated = false;
                        newsplit.Qty         = demand.OrderQty;
                        //newsplit.POCreate = (demand.VendorID != null);
                        newsplit.POCreate = (demand.FixedSource == INReplenishmentSource.TransferToPurchase);
                        newsplit.VendorID = demand.VendorID;
                        //newsplit.VendorLocationID = demand.VendorLocationID;
                        newsplit = docgraph.splits.Insert(newsplit) ?? docgraph.splits.Current;

                        rp = PXCache <INItemPlan> .CreateCopy(demand);

                        cache.RaiseRowDeleted(demand);
                        rp.SiteID       = demand.SiteID;
                        rp.PlanType     = INPlanConstants.Plan94;
                        rp.FixedSource  = null;
                        rp.SupplyPlanID = newsplit.PlanID;
                        cache.RaiseRowInserted(rp);
                        cache.SetStatus(rp, PXEntryStatus.Updated);
                    }

                    if (newsplit.PlanID == null)
                    {
                        throw new PXRowPersistedException(typeof(SOLine).Name, newline, RQ.Messages.UnableToCreateSOOrders);
                    }

                    if (docgraph.Transactions.Cache.IsInsertedUpdatedDeleted)
                    {
                        using (PXTransactionScope scope = new PXTransactionScope())
                        {
                            docgraph.Save.Press();
                            if (demandPlanType == INPlanConstants.Plan90)
                            {
                                docgraph.Replenihment.Current = docgraph.Replenihment.Search <INReplenishmentOrder.noteID>(demand.RefNoteID);
                                if (docgraph.Replenihment.Current != null)
                                {
                                    INReplenishmentLine rLine =
                                        PXCache <INReplenishmentLine> .CreateCopy(docgraph.ReplenishmentLines.Insert(new INReplenishmentLine()));

                                    rLine.InventoryID       = newsplit.InventoryID;
                                    rLine.SubItemID         = newsplit.SubItemID;
                                    rLine.UOM               = newsplit.UOM;
                                    rLine.Qty               = newsplit.Qty;
                                    rLine.SOType            = newsplit.OrderType;
                                    rLine.SONbr             = docgraph.Document.Current.OrderNbr;
                                    rLine.SOLineNbr         = newsplit.LineNbr;
                                    rLine.SOSplitLineNbr    = newsplit.SplitLineNbr;
                                    rLine.SiteID            = demand.SourceSiteID;
                                    rLine.DestinationSiteID = demand.SiteID;
                                    rLine.PlanID            = demand.PlanID;
                                    docgraph.ReplenishmentLines.Update(rLine);
                                    INItemPlan plan = PXSelect <INItemPlan,
                                                                Where <INItemPlan.planID, Equal <Required <INItemPlan.planID> > > > .SelectWindowed(docgraph, 0, 1,
                                                                                                                                                    demand.SupplyPlanID);

                                    if (plan != null)
                                    {
                                        //plan.SupplyPlanID = rp.PlanID;
                                        rp.SupplyPlanID = plan.PlanID;
                                        cache.SetStatus(rp, PXEntryStatus.Updated);
                                    }

                                    docgraph.Save.Press();
                                }
                            }
                            scope.Complete();
                        }

                        PXProcessing <SOFixedDemand> .SetInfo(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA(Messages.TransferOrderCreated, docgraph.Document.Current.OrderNbr));

                        if (created.Find(docgraph.Document.Current) == null)
                        {
                            created.Add(docgraph.Document.Current);
                        }
                    }
                }
                catch (Exception e)
                {
                    PXProcessing <SOFixedDemand> .SetError(list.IndexOf(demand), e);
                }
            }
            if (created.Count == 1)
            {
                using (new PXTimeStampScope(null))
                {
                    docgraph.Clear();
                    docgraph.Document.Current = docgraph.Document.Search <POOrder.orderNbr>(created[0].OrderNbr, created[0].OrderType);
                    throw new PXRedirectRequiredException(docgraph, Messages.SOOrder);
                }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Save current document
        /// </summary>
        /// <param name="fallbackTitle"></param>
        /// <returns></returns>
        public async Task SaveCurrentDocument(string fallbackTitle, byte[] img)
        {
            Error = null;
            if (CurrentDocument != null)
            {
                var existing = DocumentList.Where(x => x.Id == CurrentDocument.Id).FirstOrDefault();
                if (existing != null)
                {
                    DocumentList.Remove(existing);
                }

                var created = existing?.CreatedDate ?? DateTimeOffset.UtcNow;

                //Fix title if there is no title
                var title = CurrentDocument.Title;
                if (string.IsNullOrWhiteSpace(title))
                {
                    title = fallbackTitle;
                }
                if (string.IsNullOrWhiteSpace(title))
                {
                    title = "Untitled document " + created;
                }

                CurrentDocument.Title = title;

                DocumentSummary sum = new DocumentSummary()
                {
                    Id           = CurrentDocument.Id,
                    Title        = CurrentDocument.Title,
                    CreatedDate  = created,
                    ModifiedDate = DateTimeOffset.UtcNow
                };
                DocumentList.Add(sum);

                string?imgLink = null;
                if (img != null)
                {
                    using (Stream stream = new MemoryStream(img))
                    {
                        //Save preview image to Skynet file
                        var response = await client.UploadFileAsync("document.jpg", stream);

                        imgLink = response.Skylink;
                    }
                }
                sum.PreviewImage = imgLink;

                bool success = await SaveDocument(CurrentDocument);

                if (success)
                {
                    CurrentDocument = null;
                }
                else
                {
                    Error = "Unable to save document to Skynet. Please try again.";
                }

                //Save updated document list
                await SaveDocumentList(DocumentList);
            }
        }
Ejemplo n.º 27
0
        public static PXRedirectRequiredException CreatePOOrders2(
            System.Collections.Generic.List <POFixedDemand> list,
            DateTime?PurchDate,
            bool extSort)
        {
            POOrderEntry docgraph = PXGraph.CreateInstance <POOrderEntry>();

            docgraph.Views.Caches.Add(typeof(POOrderEntry.SOLineSplit3));
            POSetup current = docgraph.POSetup.Current;
            DocumentList <POOrder> documentList1 = new DocumentList <POOrder>((PXGraph)docgraph);
            Dictionary <string, DocumentList <POLine> > dictionary = new Dictionary <string, DocumentList <POLine> >();

            list.Sort((Comparison <POFixedDemand>)((a, b) =>
            {
                string empty1 = string.Empty;
                string empty2 = string.Empty;
                string str;
                if (a.PlanType == "90")
                {
                    PX.Objects.IN.InventoryItem inventoryItem = PX.Objects.IN.InventoryItem.PK.Find((PXGraph)docgraph, a.InventoryID);
                    str = string.Format("ZZ.{0}", inventoryItem == null ? (object)string.Empty : (object)inventoryItem.InventoryCD);
                }
                else
                {
                    POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3)PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)a.PlanID);
                    str = soLineSplit3 == null ? string.Empty : string.Format("{0}.{1}.{2:D7}", (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.SortOrder.GetValueOrDefault());
                }
                string strB;
                if (b.PlanType == "90")
                {
                    PX.Objects.IN.InventoryItem inventoryItem = PX.Objects.IN.InventoryItem.PK.Find((PXGraph)docgraph, b.InventoryID);
                    strB = string.Format("ZZ.{0}", inventoryItem == null ? (object)string.Empty : (object)inventoryItem.InventoryCD);
                }
                else
                {
                    POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3)PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)b.PlanID);
                    strB = soLineSplit3 == null ? string.Empty : string.Format("{0}.{1}.{2:D7}", (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.SortOrder.GetValueOrDefault());
                }
                return(str.CompareTo(strB));
            }));
            POOrder poOrder1 = (POOrder)null;
            bool    flag1    = false;

            foreach (POFixedDemand demand in list)
            {
                if (!(demand.FixedSource != "P"))
                {
                    string OrderType = demand.PlanType == "6D" ? "DP" : (demand.PlanType == "6E" ? "DP" : "RO");
                    string str1      = (string)null;
                    int?   nullable1 = demand.VendorID;
                    int    num1;
                    if (nullable1.HasValue)
                    {
                        nullable1 = demand.VendorLocationID;
                        num1      = !nullable1.HasValue ? 1 : 0;
                    }
                    else
                    {
                        num1 = 1;
                    }
                    if (num1 != 0)
                    {
                        PXProcessing <POFixedDemand> .SetWarning(list.IndexOf(demand), "Vendor and vendor location should be defined.");
                    }
                    else
                    {
                        PXErrorLevel pxErrorLevel = PXErrorLevel.RowInfo;
                        string       empty        = string.Empty;
                        try
                        {
                            PX.Objects.SO.SOOrder soOrder = (PX.Objects.SO.SOOrder) PXSelectBase <PX.Objects.SO.SOOrder, PXSelect <PX.Objects.SO.SOOrder, Where <PX.Objects.SO.SOOrder.noteID, Equal <Required <PX.Objects.SO.SOOrder.noteID> > > > .Config> .Select((PXGraph)docgraph, (object)demand.RefNoteID);

                            POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3) PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)demand.PlanID);

                            string str2 = (string)null;
                            string str3 = (string)null;
                            if (demand.PlanType == "6B" || demand.PlanType == "6E")
                            {
                                str2 = soLineSplit3.POType;
                                str3 = soLineSplit3.PONbr;
                            }
                            System.Collections.Generic.List <FieldLookup> fieldLookupList1 = new System.Collections.Generic.List <FieldLookup>()
                            {
                                (FieldLookup) new FieldLookup <POOrder.orderType>((object)OrderType),
                                (FieldLookup) new FieldLookup <POOrder.vendorID>((object)demand.VendorID),
                                (FieldLookup) new FieldLookup <POOrder.vendorLocationID>((object)demand.VendorLocationID),
                                (FieldLookup) new FieldLookup <POOrder.bLOrderNbr>((object)str3)
                            };
                            if (OrderType == "RO")
                            {
                                bool?projectPerDocument = docgraph.apsetup.Current.RequireSingleProjectPerDocument;
                                bool flag2 = true;
                                if (projectPerDocument.GetValueOrDefault() == flag2 & projectPerDocument.HasValue)
                                {
                                    nullable1 = demand.ProjectID;
                                    int?nullable2 = nullable1.HasValue ? nullable1 : ProjectDefaultAttribute.NonProject();
                                    fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.projectID>((object)nullable2));
                                }
                                int num2;
                                if (poOrder1 != null && poOrder1.ShipDestType == "L")
                                {
                                    nullable1 = poOrder1.SiteID;
                                    num2      = !nullable1.HasValue ? 1 : 0;
                                }
                                else
                                {
                                    num2 = 0;
                                }
                                if (num2 == 0)
                                {
                                    fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.siteID>((object)demand.POSiteID));
                                }
                            }
                            else if (OrderType == "DP")
                            {
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.sOOrderType>((object)soLineSplit3.OrderType));
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.sOOrderNbr>((object)soLineSplit3.OrderNbr));
                            }
                            else
                            {
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.shipToBAccountID>((object)soOrder.CustomerID));
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.shipToLocationID>((object)soOrder.CustomerLocationID));
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.siteID>((object)demand.POSiteID));
                            }
                            poOrder1 = documentList1.Find(fieldLookupList1.ToArray()) ?? new POOrder();
                            if (poOrder1.OrderNbr == null)
                            {
                                docgraph.Clear();
                                poOrder1.OrderType = OrderType;
                                poOrder1           = PXCache <POOrder> .CreateCopy(docgraph.Document.Insert(poOrder1));

                                poOrder1.VendorID         = demand.VendorID;
                                poOrder1.VendorLocationID = demand.VendorLocationID;
                                poOrder1.SiteID           = demand.POSiteID;
                                nullable1 = demand.ProjectID;
                                if (nullable1.HasValue)
                                {
                                    poOrder1.ProjectID = demand.ProjectID;
                                }
                                poOrder1.OrderDate  = PurchDate;
                                poOrder1.BLType     = str2;
                                poOrder1.BLOrderNbr = str3;
                                if (OrderType == "DP" | extSort)
                                {
                                    poOrder1.SOOrderType = soLineSplit3.OrderType;
                                    poOrder1.SOOrderNbr  = soLineSplit3.OrderNbr;
                                }
                                if (!string.IsNullOrEmpty(poOrder1.BLOrderNbr))
                                {
                                    POOrder poOrder2 = (POOrder)PXSelectBase <POOrder, PXSelect <POOrder, Where <POOrder.orderType, Equal <Current <POOrder.bLType> >, And <POOrder.orderNbr, Equal <Current <POOrder.bLOrderNbr> > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1]
                                    {
                                        (object)poOrder1
                                    });

                                    if (poOrder2 != null)
                                    {
                                        poOrder1.VendorRefNbr = poOrder2.VendorRefNbr;
                                    }
                                }
                                if (OrderType == "DP")
                                {
                                    poOrder1.ShipDestType     = "C";
                                    poOrder1.ShipToBAccountID = soOrder.CustomerID;
                                    poOrder1.ShipToLocationID = soOrder.CustomerLocationID;
                                }
                                else if (current.ShipDestType == "S")
                                {
                                    poOrder1.ShipDestType = "S";
                                    poOrder1.SiteID       = demand.POSiteID;
                                }
                                if (PXAccess.FeatureInstalled <PX.Objects.CS.FeaturesSet.multicurrency>())
                                {
                                    docgraph.currencyinfo.Current.CuryID = (string)null;
                                }
                                poOrder1 = docgraph.Document.Update(poOrder1);
                                if (OrderType == "DP")
                                {
                                    SOAddress soAddress = (SOAddress)PXSelectBase <SOAddress, PXSelect <SOAddress, Where <SOAddress.addressID, Equal <Required <PX.Objects.SO.SOOrder.shipAddressID> > > > .Config> .Select((PXGraph)docgraph, (object)soOrder.ShipAddressID);

                                    bool?isDefaultAddress = soAddress.IsDefaultAddress;
                                    bool flag2            = false;
                                    if (isDefaultAddress.GetValueOrDefault() == flag2 & isDefaultAddress.HasValue)
                                    {
                                        SharedRecordAttribute.CopyRecord <POOrder.shipAddressID>(docgraph.Document.Cache, (object)poOrder1, (object)soAddress, true);
                                    }
                                    SOContact soContact = (SOContact)PXSelectBase <SOContact, PXSelect <SOContact, Where <SOContact.contactID, Equal <Required <PX.Objects.SO.SOOrder.shipContactID> > > > .Config> .Select((PXGraph)docgraph, (object)soOrder.ShipContactID);

                                    bool?isDefaultContact = soContact.IsDefaultContact;
                                    bool flag3            = false;
                                    if (isDefaultContact.GetValueOrDefault() == flag3 & isDefaultContact.HasValue)
                                    {
                                        SharedRecordAttribute.CopyRecord <POOrder.shipContactID>(docgraph.Document.Cache, (object)poOrder1, (object)soContact, true);
                                    }
                                    DateTime?expectedDate = poOrder1.ExpectedDate;
                                    DateTime?requestDate  = soOrder.RequestDate;
                                    if (expectedDate.HasValue & requestDate.HasValue && expectedDate.GetValueOrDefault() < requestDate.GetValueOrDefault())
                                    {
                                        poOrder1 = PXCache <POOrder> .CreateCopy(poOrder1);

                                        poOrder1.ExpectedDate = soOrder.RequestDate;
                                        poOrder1 = docgraph.Document.Update(poOrder1);
                                    }
                                }
                            }
                            else if (!docgraph.Document.Cache.ObjectsEqual((object)docgraph.Document.Current, (object)poOrder1))
                            {
                                docgraph.Document.Current = (POOrder)docgraph.Document.Search <POOrder.orderNbr>((object)poOrder1.OrderNbr, (object)poOrder1.OrderType);
                            }
                            poOrder1.UpdateVendorCost = new bool?(false);
                            POLine poLine1 = (POLine)null;
                            DocumentList <POLine> documentList2;
                            if (!dictionary.TryGetValue(demand.PlanType, out documentList2))
                            {
                                documentList2 = dictionary[demand.PlanType] = new DocumentList <POLine>((PXGraph)docgraph);
                            }
                            if (OrderType == "RO" && demand.PlanType != "6B")
                            {
                                System.Collections.Generic.List <FieldLookup> fieldLookupList2 = new System.Collections.Generic.List <FieldLookup>();
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.vendorID>((object)demand.VendorID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.vendorLocationID>((object)demand.VendorLocationID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.siteID>((object)demand.POSiteID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.inventoryID>((object)demand.InventoryID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.subItemID>((object)demand.SubItemID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.requestedDate>((object)(DateTime?)soLineSplit3?.ShipDate));
                                int?nullable2;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable2 = nullable1;
                                }
                                else
                                {
                                    nullable2 = soLineSplit3.ProjectID;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.projectID>((object)nullable2));
                                int?nullable3;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable3 = nullable1;
                                }
                                else
                                {
                                    nullable3 = soLineSplit3.TaskID;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.taskID>((object)nullable3));
                                int?nullable4;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable4 = nullable1;
                                }
                                else
                                {
                                    nullable4 = soLineSplit3.CostCodeID;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.costCodeID>((object)nullable4));
                                int?nullable5;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable5 = nullable1;
                                }
                                else
                                {
                                    nullable5 = soLineSplit3.LineNbr;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.lineNbr>((object)nullable5));
                                System.Collections.Generic.List <FieldLookup> fieldLookupList3 = fieldLookupList2;
                                bool?nullable6 = current.CopyLineDescrSO;
                                bool flag2     = true;
                                if (nullable6.GetValueOrDefault() == flag2 & nullable6.HasValue && soLineSplit3 != null)
                                {
                                    fieldLookupList3.Add((FieldLookup) new FieldLookup <POLine.tranDesc>((object)soLineSplit3.TranDesc));
                                    poLine1 = documentList2.Find(fieldLookupList3.ToArray());
                                    int num2;
                                    if (poLine1 != null)
                                    {
                                        nullable6 = current.CopyLineNoteSO;
                                        bool flag3 = true;
                                        if (nullable6.GetValueOrDefault() == flag3 & nullable6.HasValue)
                                        {
                                            num2 = PXNoteAttribute.GetNote(docgraph.Caches[typeof(POLine)], (object)poLine1) != null ? 1 : (PXNoteAttribute.GetNote(docgraph.Caches[typeof(POOrderEntry.SOLineSplit3)], (object)soLineSplit3) != null ? 1 : 0);
                                            goto label_67;
                                        }
                                    }
                                    num2 = 0;
label_67:
                                    if (num2 != 0)
                                    {
                                        poLine1 = (POLine)null;
                                    }
                                }
                                else
                                {
                                    poLine1 = documentList2.Find(fieldLookupList3.ToArray());
                                }
                            }
                            POLine dest = poLine1 ?? new POLine();
                            POLine copy1;
                            if (dest.OrderNbr == null)
                            {
                                docgraph.FillPOLineFromDemand(dest, demand, OrderType, soLineSplit3);
                                POLine line           = docgraph.Transactions.Insert(dest);
                                bool?  copyLineNoteSo = current.CopyLineNoteSO;
                                bool   flag2          = true;
                                if (copyLineNoteSo.GetValueOrDefault() == flag2 & copyLineNoteSo.HasValue && soLineSplit3 != null)
                                {
                                    PXNoteAttribute.SetNote(docgraph.Transactions.Cache, (object)line, PXNoteAttribute.GetNote(docgraph.Caches[typeof(POOrderEntry.SOLineSplit3)], (object)soLineSplit3));
                                }
                                if (docgraph.onCopyPOLineFields != null)
                                {
                                    docgraph.onCopyPOLineFields(demand, line);
                                }
                                copy1 = PXCache <POLine> .CreateCopy(line);

                                documentList2.Add(copy1);
                            }
                            else
                            {
                                copy1 = PXCache <POLine> .CreateCopy((POLine)PXSelectBase <POLine, PXSelect <POLine, Where <POLine.orderType, Equal <Current <POOrder.orderType> >, And <POLine.orderNbr, Equal <Current <POOrder.orderNbr> >, And <POLine.lineNbr, Equal <Current <POLine.lineNbr> > > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1]
                                {
                                    (object)dest
                                }));

                                POLine  poLine2   = copy1;
                                Decimal?orderQty1 = poLine2.OrderQty;
                                Decimal?orderQty2 = demand.OrderQty;
                                poLine2.OrderQty = orderQty1.HasValue & orderQty2.HasValue ? new Decimal?(orderQty1.GetValueOrDefault() + orderQty2.GetValueOrDefault()) : new Decimal?();
                            }
                            if (demand.PlanType == "6B" || demand.PlanType == "6E")
                            {
                                str1 = demand.PlanType == "6B" ? "66" : "6D";
                                demand.FixedSource = "P";
                                copy1.POType       = soLineSplit3.POType;
                                copy1.PONbr        = soLineSplit3.PONbr;
                                copy1.POLineNbr    = soLineSplit3.POLineNbr;
                                POLine poLine2 = (POLine)PXSelectBase <POLine, PXSelect <POLine, Where <POLine.orderType, Equal <Current <POLine.pOType> >, And <POLine.orderNbr, Equal <Current <POLine.pONbr> >, And <POLine.lineNbr, Equal <Current <POLine.pOLineNbr> > > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1]
                                {
                                    (object)copy1
                                });

                                if (poLine2 != null)
                                {
                                    Decimal?nullable2   = demand.PlanQty;
                                    Decimal?baseOpenQty = poLine2.BaseOpenQty;
                                    if (nullable2.GetValueOrDefault() > baseOpenQty.GetValueOrDefault() & (nullable2.HasValue & baseOpenQty.HasValue))
                                    {
                                        POLine  poLine3  = copy1;
                                        Decimal?orderQty = poLine3.OrderQty;
                                        nullable2        = demand.OrderQty;
                                        poLine3.OrderQty = orderQty.HasValue & nullable2.HasValue ? new Decimal?(orderQty.GetValueOrDefault() - nullable2.GetValueOrDefault()) : new Decimal?();
                                        if (string.Equals(copy1.UOM, poLine2.UOM))
                                        {
                                            POLine poLine4 = copy1;
                                            nullable2 = poLine4.OrderQty;
                                            Decimal?openQty = poLine2.OpenQty;
                                            poLine4.OrderQty = nullable2.HasValue & openQty.HasValue ? new Decimal?(nullable2.GetValueOrDefault() + openQty.GetValueOrDefault()) : new Decimal?();
                                        }
                                        else
                                        {
                                            PXDBQuantityAttribute.CalcBaseQty <POLine.orderQty>(docgraph.Transactions.Cache, (object)copy1);
                                            POLine  poLine4      = copy1;
                                            Decimal?baseOrderQty = poLine4.BaseOrderQty;
                                            nullable2            = poLine2.BaseOpenQty;
                                            poLine4.BaseOrderQty = baseOrderQty.HasValue & nullable2.HasValue ? new Decimal?(baseOrderQty.GetValueOrDefault() + nullable2.GetValueOrDefault()) : new Decimal?();
                                            PXDBQuantityAttribute.CalcTranQty <POLine.orderQty>(docgraph.Transactions.Cache, (object)copy1);
                                        }
                                        pxErrorLevel = PXErrorLevel.RowWarning;
                                        empty       += PXMessages.LocalizeFormatNoPrefixNLA("Order Quantity reduced to Blanket Order: '{0}' Open Qty. for this item", (object)copy1.PONbr);
                                    }
                                    copy1.CuryUnitCost = poLine2.CuryUnitCost;
                                    copy1.UnitCost     = poLine2.UnitCost;
                                }
                            }
                            copy1.SiteID = POCreate_Extension.GetWasrehouseByBranch((PXGraph)docgraph, copy1.BranchID);
                            short?       vleadTime = docgraph.location.Current.VLeadTime;
                            POLine       poLine5   = copy1;
                            DateTime     dateTime  = soLineSplit3.ShipDate.Value;
                            ref DateTime local     = ref dateTime;
                            short?       nullable7 = vleadTime;
                            nullable1 = nullable7.HasValue ? new int?((int)nullable7.GetValueOrDefault()) : new int?();
                            int      num3      = 0;
                            double   num4      = nullable1.GetValueOrDefault() > num3 & nullable1.HasValue ? (double)-vleadTime.Value : -14.0;
                            DateTime?nullable8 = new DateTime?(local.AddDays(num4));
                            poLine5.RequestedDate = nullable8;
                            POLine  poLine6 = docgraph.Transactions.Update(copy1);
                            PXCache cach    = docgraph.Caches[typeof(INItemPlan)];
                            POCreate_Extension.CreateSplitDemand2(cach, demand);
                            cach.SetStatus((object)demand, PXEntryStatus.Updated);
                            demand.SupplyPlanID = poLine6.PlanID;
                            if (str1 != null)
                            {
                                cach.RaiseRowDeleted((object)demand);
                                demand.PlanType = str1;
                                cach.RaiseRowInserted((object)demand);
                            }
                            if (soLineSplit3 != null)
                            {
                                int num2;
                                if (demand.AlternateID != null)
                                {
                                    nullable1 = demand.InventoryID;
                                    num2      = nullable1.HasValue ? 1 : 0;
                                }
                                else
                                {
                                    num2 = 0;
                                }
                                if (num2 != 0)
                                {
                                    PXSelectBase <INItemXRef> pxSelectBase = (PXSelectBase <INItemXRef>) new PXSelect <INItemXRef, Where <INItemXRef.inventoryID, Equal <Required <INItemXRef.inventoryID> >, And <INItemXRef.alternateID, Equal <Required <INItemXRef.alternateID> > > > >((PXGraph)docgraph);
                                    INItemXRef inItemXref1 = (INItemXRef)pxSelectBase.Select((object)demand.InventoryID, (object)demand.AlternateID);
                                    if (inItemXref1 != null && inItemXref1.AlternateType == "GLBL")
                                    {
                                        int num5;
                                        if (poLine6.AlternateID != null)
                                        {
                                            nullable1 = poLine6.InventoryID;
                                            num5      = nullable1.HasValue ? 1 : 0;
                                        }
                                        else
                                        {
                                            num5 = 0;
                                        }
                                        if (num5 != 0)
                                        {
                                            INItemXRef inItemXref2 = (INItemXRef)pxSelectBase.Select((object)poLine6.InventoryID, (object)poLine6.AlternateID);
                                            if (inItemXref2 != null && inItemXref2.AlternateType == "GLBL")
                                            {
                                                poLine6.AlternateID = demand.AlternateID;
                                            }
                                        }
                                        else
                                        {
                                            poLine6.AlternateID = demand.AlternateID;
                                        }
                                    }
                                }
                                soLineSplit3.POType    = poLine6.OrderType;
                                soLineSplit3.PONbr     = poLine6.OrderNbr;
                                soLineSplit3.POLineNbr = poLine6.LineNbr;
                                soLineSplit3.RefNoteID = docgraph.Document.Current.NoteID;
                                PX.Objects.SO.SOLine soLine = SelectFrom <PX.Objects.SO.SOLine> .Where <PX.Objects.SO.SOLine.orderType.IsEqual <P.AsString>
                                                                                                        .And <PX.Objects.SO.SOLine.orderNbr.IsEqual <P.AsString>
                                                                                                              .And <PX.Objects.SO.SOLine.lineNbr.IsEqual <P.AsInt> > > > .View.ReadOnly.Select((PXGraph)docgraph, (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.LineNbr);

                                POLineExt extension1 = poLine6.GetExtension <POLineExt>();
                                SOLineExt extension2 = soLine.GetExtension <SOLineExt>();
                                extension1.UsrEndCustomerID = extension2.UsrEndCustomerID;
                                extension1.UsrNonStockItem  = extension2.UsrNonStockItem;
                                extension1.UsrProjectNbr    = extension2.UsrProjectNbr;
                                if (!string.IsNullOrEmpty(extension2.UsrProjectNbr))
                                {
                                    FLXProject flxProject = SelectFrom <FLXProject> .Where <FLXProject.projectNbr.IsEqual <P.AsString> > .View.ReadOnly.Select((PXGraph)docgraph, (object)extension2.UsrProjectNbr);

                                    extension1.UsrCust2Factory = flxProject.Cust2Factory;
                                    extension1.UsrFactoryPN    = flxProject.FactoryPN;
                                }
                                docgraph.GetExtension <POOrderEntry_Extension>().UpdateSOLine(soLineSplit3, docgraph.Document.Current.VendorID, true);
                                docgraph.FixedDemand.Cache.SetStatus((object)soLineSplit3, PXEntryStatus.Updated);
                            }
                            if (docgraph.Transactions.Cache.IsInsertedUpdatedDeleted)
                            {
                                using (PXTransactionScope transactionScope = new PXTransactionScope())
                                {
                                    docgraph.Save.Press();
                                    if (demand.PlanType == "90")
                                    {
                                        docgraph.Replenihment.Current = (INReplenishmentOrder)docgraph.Replenihment.Search <INReplenishmentOrder.noteID>((object)demand.RefNoteID);
                                        if (docgraph.Replenihment.Current != null)
                                        {
                                            INReplenishmentLine copy2 = PXCache <INReplenishmentLine> .CreateCopy(docgraph.ReplenishmentLines.Insert(new INReplenishmentLine()));

                                            copy2.InventoryID      = poLine6.InventoryID;
                                            copy2.SubItemID        = poLine6.SubItemID;
                                            copy2.UOM              = poLine6.UOM;
                                            copy2.VendorID         = poLine6.VendorID;
                                            copy2.VendorLocationID = poLine6.VendorLocationID;
                                            copy2.Qty              = poLine6.OrderQty;
                                            copy2.POType           = poLine6.OrderType;
                                            copy2.PONbr            = docgraph.Document.Current.OrderNbr;
                                            copy2.POLineNbr        = poLine6.LineNbr;
                                            copy2.SiteID           = demand.POSiteID;
                                            copy2.PlanID           = demand.PlanID;
                                            docgraph.ReplenishmentLines.Update(copy2);
                                            docgraph.Caches[typeof(INItemPlan)].Delete((object)demand);
                                            docgraph.Save.Press();
                                        }
                                    }
                                    transactionScope.Complete();
                                }
                                if (pxErrorLevel == PXErrorLevel.RowInfo)
                                {
                                    PXProcessing <POFixedDemand> .SetInfo(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA("Purchase Order '{0}' created.", (object)docgraph.Document.Current.OrderNbr) + "\r\n" + empty);
                                }
                                else
                                {
                                    PXProcessing <POFixedDemand> .SetWarning(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA("Purchase Order '{0}' created.", (object)docgraph.Document.Current.OrderNbr) + "\r\n" + empty);
                                }
                                if (documentList1.Find((object)docgraph.Document.Current) == null)
                                {
                                    documentList1.Add(docgraph.Document.Current);
                                }
                            }
                        }
Ejemplo n.º 28
0
        public static void SOCreateProc(List <SOFixedDemand> list, DateTime?PurchDate)
        {
            SOOrderEntry           docgraph = PXGraph.CreateInstance <SOOrderEntry>();
            SOSetup                sosetup  = docgraph.sosetup.Current;
            DocumentList <SOOrder> created  = new DocumentList <SOOrder>(docgraph);

            foreach (SOFixedDemand demand in list)
            {
                string OrderType =
                    sosetup.TransferOrderType ?? SOOrderTypeConstants.TransferOrder;

                string ErrorText = string.Empty;

                try
                {
                    if (demand.ReplenishmentSourceSiteID == null)
                    {
                        PXProcessing <SOFixedDemand> .SetWarning(list.IndexOf(demand), Messages.MissingSourceSite);

                        continue;
                    }

                    if (demand.ReplenishmentSourceSiteID == demand.SiteID)
                    {
                        PXProcessing <SOFixedDemand> .SetWarning(list.IndexOf(demand), Messages.EqualSourceDestinationSite);

                        continue;
                    }
                    SOOrder order;
                    POLine  poline = PXSelect <POLine, Where <POLine.planID, Equal <Required <POLine.planID> > > > .Select(docgraph, demand.PlanID);

                    if (poline != null)
                    {
                        order =
                            created.Find <SOOrder.orderType, SOOrder.destinationSiteID, SOOrder.defaultSiteID, SOOrder.origPOType, SOOrder.origPONbr>(
                                OrderType, demand.SiteID, demand.ReplenishmentSourceSiteID, poline.OrderType, poline.OrderNbr);
                    }
                    else
                    {
                        order = created.Find <SOOrder.orderType, SOOrder.destinationSiteID, SOOrder.defaultSiteID>(OrderType, demand.SiteID, demand.ReplenishmentSourceSiteID);
                    }

                    if (order == null)
                    {
                        order = new SOOrder();
                    }

                    if (order.OrderNbr == null)
                    {
                        docgraph.Clear();

                        INSite sourceSite = PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(docgraph, demand.ReplenishmentSourceSiteID);

                        order.BranchID  = sourceSite.BranchID;
                        order.OrderType = OrderType;
                        order           = PXCache <SOOrder> .CreateCopy(docgraph.Document.Insert(order));

                        order.DefaultSiteID     = demand.ReplenishmentSourceSiteID;
                        order.DestinationSiteID = demand.SiteID;
                        order.Status            = SOOrderStatus.Open;
                        order.OrderDate         = PurchDate;
                        if (poline != null)
                        {
                            order.OrigPOType = poline.OrderType;
                            order.OrigPONbr  = poline.OrderNbr;
                        }
                        docgraph.Document.Update(order);
                    }
                    else if (docgraph.Document.Cache.ObjectsEqual(docgraph.Document.Current, order) == false)
                    {
                        docgraph.Document.Current = docgraph.Document.Search <SOOrder.orderNbr>(order.OrderNbr, order.OrderType);
                    }
                    SOLine line = new SOLine();
                    line = PXCache <SOLine> .CreateCopy(docgraph.Transactions.Insert(line));

                    line.InventoryID = demand.InventoryID;
                    line.SubItemID   = demand.SubItemID;
                    line.SiteID      = demand.ReplenishmentSourceSiteID;
                    line.UOM         = demand.UOM;
                    line.OrderQty    = demand.OrderQty;
                    if (poline != null)
                    {
                        line.OrigPOType    = poline.OrderType;
                        line.OrigPONbr     = poline.OrderNbr;
                        line.OrigPOLineNbr = poline.LineNbr;
                    }

                    line = docgraph.Transactions.Update(line);

                    if (line.PlanID == null)
                    {
                        throw new PXRowPersistedException(typeof(SOLine).Name, line, RQ.Messages.UnableToCreateSOOrders);
                    }

                    PXCache cache          = docgraph.Caches[typeof(INItemPlan)];
                    string  demandPlanType = demand.PlanType;
                    //cache.SetStatus(demand, PXEntryStatus.Updated);
                    //demand.SupplyPlanID = line.PlanID;
                    INItemPlan rp = PXCache <INItemPlan> .CreateCopy(demand);

                    cache.RaiseRowDeleted(demand);
                    rp.PlanType     = INPlanConstants.Plan94;
                    rp.FixedSource  = null;
                    rp.SupplyPlanID = line.PlanID;
                    cache.RaiseRowInserted(rp);
                    cache.SetStatus(rp, PXEntryStatus.Updated);

                    if (docgraph.Transactions.Cache.IsInsertedUpdatedDeleted)
                    {
                        using (PXTransactionScope scope = new PXTransactionScope())
                        {
                            docgraph.Save.Press();
                            if (demandPlanType == INPlanConstants.Plan90)
                            {
                                docgraph.Replenihment.Current = docgraph.Replenihment.Search <INReplenishmentOrder.noteID>(demand.RefNoteID);
                                if (docgraph.Replenihment.Current != null)
                                {
                                    INReplenishmentLine rLine =
                                        PXCache <INReplenishmentLine> .CreateCopy(docgraph.ReplenishmentLines.Insert(new INReplenishmentLine()));

                                    rLine.InventoryID       = line.InventoryID;
                                    rLine.SubItemID         = line.SubItemID;
                                    rLine.UOM               = line.UOM;
                                    rLine.Qty               = line.OrderQty;
                                    rLine.SOType            = line.OrderType;
                                    rLine.SONbr             = docgraph.Document.Current.OrderNbr;
                                    rLine.SOLineNbr         = line.LineNbr;
                                    rLine.SiteID            = demand.ReplenishmentSourceSiteID;
                                    rLine.DestinationSiteID = demand.SiteID;
                                    rLine.PlanID            = demand.PlanID;
                                    docgraph.ReplenishmentLines.Update(rLine);
                                    INItemPlan plan = PXSelect <INItemPlan,
                                                                Where <INItemPlan.planID, Equal <Required <INItemPlan.planID> > > > .SelectWindowed(docgraph, 0, 1,
                                                                                                                                                    demand.SupplyPlanID);

                                    if (plan != null)
                                    {
                                        //plan.SupplyPlanID = rp.PlanID;
                                        rp.SupplyPlanID = plan.PlanID;
                                        cache.SetStatus(rp, PXEntryStatus.Updated);
                                    }

                                    docgraph.Save.Press();
                                }
                            }
                            scope.Complete();
                        }

                        PXProcessing <SOFixedDemand> .SetInfo(list.IndexOf(demand), string.Format(Messages.TransferOrderCreated, docgraph.Document.Current.OrderNbr) + "\r\n" + ErrorText);


                        if (created.Find(docgraph.Document.Current) == null)
                        {
                            created.Add(docgraph.Document.Current);
                        }
                    }
                }
                catch (Exception e)
                {
                    PXProcessing <SOFixedDemand> .SetError(list.IndexOf(demand), e);
                }
            }
        }