Ejemplo n.º 1
0
        private void DokumentPrzyjecie_Load(object sender, EventArgs e)
        {
            DocumentList faktura = new DocumentList();
            Document fakturaData = faktura.ShowItem(documentId, DokType.FA);

            //label2.Text = fakturaData.Type + "/" + fakturaData.Year + "/" + fakturaData.Series;
            label2.Text = fakturaData.GIDNumer;
            label4.Text = fakturaData.Date.ToString();

            _source.Clear();
            for (int j = 0; j < fakturaData.Elements._towarList.Count; j++)
            {
                Towar temp = new Towar(
                    fakturaData.Elements._towarList[j].Nazwa,
                    fakturaData.Elements._towarList[j].Cena,
                    fakturaData.Elements._towarList[j].Vat,
                    fakturaData.Elements._towarList[j].Jm,
                    fakturaData.Elements._towarList[j].Nr_kat,
                    fakturaData.Elements._towarList[j].Stan,
                    fakturaData.Elements._towarList[j].Id
                    );
                _source.Add(temp);
            }

            dataGridView1.DataSource = _source;
        }
Ejemplo n.º 2
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.º 3
0
        public void Child_FetchTest()
        {
            var retriever = new DocumentList();
            var item = new DocumentList();

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

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

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

            Mock.Assert(DocumentList.GetDocumentList(Arg.IsAny<IEnumerable<SectionViewDocumentDto>>()));
        }
		public DocumentsWorkspaceModel(IUnityContainer container, IEventAggregator eventAggregator)
		{
			OpenDocumentCommand = new DelegateCommand<Document>(OpenDocument);
			DeleteSelectedDocumentCommand = new DelegateCommand<object>(DeleteSelectedDocument, CanDeleteSelectedDocument);				
			CreateNewDocumentCommand = new DelegateCommand<object>(CreateNewDocument);

			this.EventAggregator = eventAggregator;
			view = new DocumentsWorkspace(this);			
			documentController = container.Resolve<IDocumentController>(Controllers.DocumentController);

			Documents = new DocumentList();
			LoadAllDocuments();
		}
Ejemplo n.º 5
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.º 6
0
        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);
                    }

                    foreach (GLTran tran in je.GLTranModuleBatNbr.SearchAll <Asc <GLTran.tranClass> >(new object[] { GLTran.tranClass.UnrealizedAndRevaluationGOL }))
                    {
                        je.GLTranModuleBatNbr.Delete(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.º 7
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.º 8
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;
                    }
                }
            }
        }
Ejemplo n.º 9
0
		public OpenDocumentListVM(bool syntaxHighlight, IClassificationFormatMap classificationFormatMap, ITextElementProvider textElementProvider, DocumentListService documentListService, Func<string, string> askUser) {
			SyntaxHighlight = syntaxHighlight;
			ClassificationFormatMap = classificationFormatMap;
			TextElementProvider = textElementProvider;
			this.documentListService = documentListService;
			this.askUser = askUser;
			documentListColl = new ObservableCollection<DocumentListVM>();
			collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(documentListColl);
			collectionView.CustomSort = new DocumentListVM_Comparer();
			selectedItems = Array.Empty<DocumentListVM>();
			removedDocumentLists = new HashSet<DocumentListVM>();
			addedDocumentLists = new List<DocumentListVM>();
			cancellationTokenSource = new CancellationTokenSource();
			cancellationToken = cancellationTokenSource.Token;
			searchingForDefaultLists = true;

			var hash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (var documentList in documentListService.DocumentLists) {
				hash.Add(documentList.Name);
				documentListColl.Add(new DocumentListVM(this, documentList, true, true));
			}
			Refilter();

			Task.Factory.StartNew(() => new DefaultDocumentListFinder(cancellationToken).Find(), cancellationToken)
			.ContinueWith(t => {
				var ex = t.Exception;
				SearchingForDefaultLists = false;
				if (!t.IsCanceled && !t.IsFaulted) {
					foreach (var defaultList in t.Result) {
						if (hash.Contains(defaultList.Name))
							continue;
						var documentList = new DocumentList(defaultList);
						documentListColl.Add(new DocumentListVM(this, documentList, false, false));
					}
					Refilter();
				}
			}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
		}
        public ControlSetSummary GetControlSetSummary(long matterId, long dataSetId, long projectId)
        {
            var result = new ControlSetSummary();
            if (mockDocuments != null)
            {
                var controlSetMockDocuments = new DocumentList();

                controlSetMockDocuments.Documents = mockDocuments.Documents.Where(d => d.Fields[ControlDocumentIndex].Value == "1").ToList();
                result.TotalDocuments = controlSetMockDocuments.Documents.Count;
                controlSetMockDocuments.Documents.ForEach(d =>
                {
                    var reviewerCategoryValue = d.Fields.Find(f => (f.DisplayName == "Reviewer Category")).Value;
                    if (reviewerCategoryValue == Relevant)
                    {
                        result.NumberOfRelevantDocuments++;
                    }
                    else if (reviewerCategoryValue == NotRelevant)
                    {
                        result.NumberOfNotRelevantDocuments++;
                    }
                    else if (reviewerCategoryValue == NotCoded)
                    {
                        result.NumberOfNotCodedDocuments++;
                    }
                    else
                    {
                        result.NumberOfSkippedDocuments++;
                    }
                });
                result.PercentageOfTotalPopulation = result.NumberOfRelevantDocuments/(float)result.TotalDocuments;
                result.EstimatedTotalDocuments = (long)(result.PercentageOfTotalPopulation * mockDocuments.Documents.Count);
                result.PercentageOfTotalPopulation *= 100;
            }
            else
            {
                var resourceName = string.Format(CultureInfo.InvariantCulture, "{0}.matter_{1}-dataset_{2}-project_{3}-controlset-summary.json",
                      MockDataNameSpace, matterId, dataSetId, projectId);

                var mockData = GetEmbeddedResource(resourceName);

                result = JsonConvert.DeserializeObject<ControlSetSummary>(mockData);

            }
            return result;
        }
Ejemplo n.º 11
0
        private bool RunCQ(Application app, WorkflowEventArgs args, string strBusinessUnit, string strAGMeetingMonth, string strAGMeetingYear, string strAGAddendum, string strDocType, string strLicenseType, string strApplicationNumber, long lngDocHandle, string strCameraReady, string lngMstrDocHandle, bool bOkayToProcessWithoutError)

        {
            const long CIU_APPLICATION_MSTR_DTID              = 773;
            const long CIU_CRIMINAL_RESULTS_MSTR_DTID         = 771;
            const long CIU_SUPPORTING_DOCS_MSTR_DTID          = 770;
            const long CIU_CORRESPONDENCE_MSTR_DTID           = 772;
            const long CIU_CR_CAMERA_READY_DOCUMENT_MSTR_DTID = 2343;

            //String to hold output information
            string output = string.Empty;

            WriteLog(app, string.Format("[{0}][{1}][{2}][{3}][{4}][{5}][{6}][{7}]", strBusinessUnit, strAGMeetingYear, strAGMeetingMonth, strAGAddendum, strDocType, strLicenseType, strApplicationNumber, lngDocHandle.ToString(), strCameraReady));

            long gDocTypeID;
            long lngCurrentMSTRDTID;

            switch (strDocType)
            {
            case "CAMERA READY DOCUMENT":
            {
                gDocTypeID         = PCIU_CR_CAMERA_READY_DOCUMENT_DTID;
                lngCurrentMSTRDTID = CIU_CR_CAMERA_READY_DOCUMENT_MSTR_DTID;
                break;
            }

            case "APPLICATION":
            {
                gDocTypeID         = PCIU_APPLICATIONS_CR_DTID;
                lngCurrentMSTRDTID = CIU_APPLICATION_MSTR_DTID;
                break;
            }

            case "CRIMINAL RESULTS":
            {
                gDocTypeID         = PCIU_CRIMINAL_RESULTS_CR_DTID;
                lngCurrentMSTRDTID = CIU_CRIMINAL_RESULTS_MSTR_DTID;
                break;
            }

            case "SUPPORTING DOCS":
            {
                gDocTypeID         = PCIU_SUPPORTING_DOCS_CR_DTID;
                lngCurrentMSTRDTID = CIU_SUPPORTING_DOCS_MSTR_DTID;
                break;
            }

            case "CORRESPONDENCE":
            {
                gDocTypeID         = PCIU_CORRESPONDENCE_CR_DTID;
                lngCurrentMSTRDTID = CIU_CORRESPONDENCE_MSTR_DTID;
                break;
            }

            default:
            {
                gDocTypeID         = 0;
                lngCurrentMSTRDTID = 0;
                break;
            }
            }


            // Create document query
            WriteLog(app, string.Format("Setting up Document Query [{0} - {1}]", strDocType, gDocTypeID.ToString()));
            DocumentQuery documentQuery = app.Core.CreateDocumentQuery();

            // Ensure custom query was found
            if (documentQuery == null)
            {
                throw new Exception("Unable to create document query");
            }

            // Add custom query to document query
            DocumentType docType = app.Core.DocumentTypes.Find(gDocTypeID);

            if (docType == null)
            {
                throw new Exception(string.Format("Could not find document type with ID: {0}", gDocTypeID.ToString()));
            }
            documentQuery.AddDocumentType(docType);

            KeywordType kwdType = app.Core.KeywordTypes.Find(PAPPNUMBERKWID);

            if (kwdType == null)
            {
                throw new Exception(string.Format("Could not find keyword type with ID: {0}", PAPPNUMBERKWID.ToString()));
            }
            documentQuery.AddKeyword(kwdType.Name, Convert.ToInt64(strApplicationNumber));

            kwdType = app.Core.KeywordTypes.Find(PLICTYPEKWID);
            if (kwdType == null)
            {
                throw new Exception(string.Format("Could not find keyword type with ID: {0}", PLICTYPEKWID.ToString()));
            }
            documentQuery.AddKeyword(kwdType.Name, strLicenseType);

            kwdType = app.Core.KeywordTypes.Find(PDOCNUMBERCONSTKWID);
            if (kwdType == null)
            {
                throw new Exception(string.Format("Could not find keyword type with ID: {0}", PDOCNUMBERCONSTKWID.ToString()));
            }
            documentQuery.AddKeyword(kwdType.Name, Convert.ToInt64(lngMstrDocHandle));

            documentQuery.AddSort(DocumentQuery.SortAttribute.DocumentID, true);

            WriteLog(app, string.Format("Running Document Query - Search KW [{0} = {1}]", PAPPNUMBERKWID.ToString(), strApplicationNumber));
            WriteLog(app, string.Format("Running Document Query - Search KW [{0} = {1}]", KNLICTYPE, strLicenseType));
            WriteLog(app, string.Format("Running Document Query - Search KW [{0} = {1}]", KNDOCNUMBERCONSTKWID, lngMstrDocHandle.ToString()));

            // Execute query
            const int    MAX_DOCUMENTS = 1000;
            DocumentList documentList  = documentQuery.Execute(MAX_DOCUMENTS);

            if (documentList.Count == 0)
            {
                if (!bOkayToProcessWithoutError)
                {
                    WriteLog(app, "  ");
                    WriteLog(app, "*************** ERROR: NO DOCUMENTS FOUND IN SEARCH **************");
                    WriteLog(app, "  ");
                    strProcessingErrors = string.Format("{0}{1}  Failed to locate any documents of type - {2}.  AN: {3} - LT: {4}", strProcessingErrors, DateTime.Now, strDocType, strApplicationNumber, strLicenseType);

                    return(false);
                }
                else
                {
                    WriteLog(app, "  ");
                    WriteLog(app, "*************** ERROR BYPASSED: USER STATED TO PROCESS WITH MISSING DOCUMENTS **************");
                    WriteLog(app, "  ");
                    WriteLog(app, "TEST CAMERA READY");
                    WriteLog(app, "  ");
                    return(true);
                }
            }
            // Line 298 from VB script.
            // Iterate through documents returned from query
            bool   bIsFirstDocument = true;
            string ProcessedDocIDs  = "";
            //string ProcessedDoc = "";
            //string strDocID = "";
            string laststrPrimaryDocID = "0";

            //int intNumDocsProcessed = 0;
            //int gDocCount = 0;

            foreach (Document document in documentList)
            {
                if (bIsFirstDocument)
                {
                    DocumentType objDocType = document.DocumentType;
                    WriteLog(app, "  ");
                    WriteLog(app, "*************** SETTING DOCUMENT TYPE TO IT MASTER EQUIVALENT **************");
                    WriteLog(app, "  ");
                    WriteLog(app, String.Format("*************** CURRENT DOCUMENT TYPE : {0} **************", objDocType.Name.ToString().Trim()));
                    WriteLog(app, String.Format("*************** CURRENT DOCUMENT TYPE : {0} **************", objDocType.ID.ToString().Trim()));

                    DocumentType newdoctype = app.Core.DocumentTypes.Find(lngCurrentMSTRDTID);

                    if (newdoctype == null)
                    {
                        throw new ApplicationException(string.Format("Document Type {0} does not exist", lngCurrentMSTRDTID));
                    }
                    Storage           storage           = app.Core.Storage;
                    ReindexProperties reindexProperties = storage.CreateReindexProperties(document, newdoctype);
                    Document          newDocument       = storage.ReindexDocument(reindexProperties);

                    WriteLog(app, String.Format("*************** UPDATED DOCUMENT TYPE : {0} **************", newdoctype.Name));
                    WriteLog(app, String.Format("*************** UPDATED DOCUMENT TYPE ID (Should be: {0} : {1} **************", lngCurrentMSTRDTID.ToString(), document.ID.ToString()));

                    // Update the document AutoName
                    //WriteLog(app,"*************** UPDATED DOCUMENT AUTO NAME: " & Trim(CStr(objDoc.Name)) & " **************")
                    //objDoc.AutoName
                }
                app.Diagnostics.Write(string.Format("Document ID: {0} Document Name: {1}{2}", document.ID, document.Name, Environment.NewLine));
                //Line 349
                //int x = 1;
                // If there are multiple instances of a KW value on a document, we do not want to output the same doc again
                // as the result set will contain an document entry for each unique KW value of the same type.
                if (ProcessedDocIDs.Contains(document.ID.ToString().Trim()) || (document.ID.ToString() == laststrPrimaryDocID.Trim()))
                {
                    app.Diagnostics.Write("Made it into odd logic fork");
                }
                else
                {
                    //intNumDocsProcessed++;
                    ProcessedDocIDs = string.Format("{0}{1}", ProcessedDocIDs, document.ID.ToString().Trim());
                    //gDocCount++;
                    string fileTypeExt = "";

                    long      fileTypeID       = 2;
                    Rendition objFormRendition = document.DefaultRenditionOfLatestRevision;
                    fileTypeID = objFormRendition.FileType.ID;

                    switch (fileTypeID)
                    {
                    case 1:
                        fileTypeExt = "txt";
                        break;

                    case 2:
                        fileTypeExt = "tif";
                        break;

                    case 16:
                        fileTypeExt = "pdf";
                        break;

                    case 17:
                        fileTypeExt = "htm";
                        break;

                    case 13:
                        fileTypeExt = "xls";
                        break;

                    case 12:
                        fileTypeExt = "doc";
                        break;

                    case 14:
                        fileTypeExt = "ppt";
                        break;

                    case 15:
                        fileTypeExt = "rtf";
                        break;

                    case 24:
                        fileTypeExt = "htm";
                        break;

                    case 32:
                        fileTypeExt = "xml";
                        break;

                    default:
                        fileTypeExt = "unknown";
                        break;
                    }

                    KeywordType kwtDocConversionStatus = null;
                    Keyword     kwdDocConversionStatus = null;
                    if (fileTypeExt == "tif")
                    {
                        kwtDocConversionStatus = app.Core.KeywordTypes.Find(DOCUMENTCONVERSIONSTATUS);
                        if (kwtDocConversionStatus == null)
                        {
                            throw new Exception(String.Format("Keyword Type '{0}' not found", DOCUMENTCONVERSIONSTATUS));
                        }
                        kwdDocConversionStatus = CreateKeywordHelper(kwtDocConversionStatus, "CONV OK");
                        WriteLog(app, "Document file format is TIFF");
                    }
                    else
                    {
                        kwtDocConversionStatus = app.Core.KeywordTypes.Find(DOCUMENTCONVERSIONSTATUS);
                        if (kwtDocConversionStatus == null)
                        {
                            throw new Exception(String.Format("Keyword Type '{0}' not found", DOCUMENTCONVERSIONSTATUS));
                        }
                        kwdDocConversionStatus = CreateKeywordHelper(kwtDocConversionStatus, "NOT IMAGE FORMAT");
                        WriteLog(app, "Document file format is NOT TIFF - need to add logic to convert to TIFF");
                        strProcessingErrors = string.Format("{0}{1}{2}   " +
                                                            "Document is not Image File Format - {3}.  AN: {4} - LT: {5}", strProcessingErrors, Environment.NewLine, DateTime.Now.ToString(DateTimeFormat), strDocType, strApplicationNumber, strLicenseType);
                    }

                    using (DocumentLock documentLock = document.LockDocument())
                    {
                        // Ensure lock was obtained
                        if (documentLock.Status != DocumentLockStatus.LockObtained)
                        {
                            throw new Exception("Document lock not obtained");
                        }
                        // Create keyword modifier object to hold keyword changes
                        KeywordModifier keyModifier = document.CreateKeywordModifier();

                        //Add update keyword call to keyword modifier object
                        //Note Overloads available for use
                        //(I.E.): keyModifier.AddKeyword(keywordTypeName,keywordValue)
                        keyModifier.AddKeyword(kwdDocConversionStatus);

                        // Apply keyword change to the document
                        keyModifier.ApplyChanges();

                        WriteLog(app, string.Format("Keyword: '{0}' added to Document .", DOCUMENTCONVERSIONSTATUS));
                    }
                    if (fileTypeExt != "tif")
                    {
                        return(false);
                    }

                    WriteLog(app, string.Format("  Processing DocID [{0}]", document.ID.ToString()));
                    // Set property bag for use by OnBase DocDataProvider object
                    args.PropertyBag.Set("docID", document.ID.ToString());

                    sourceDocHandle = document.ID;

                    // If the source file format is not image, we need to save it out and append to the current document.
                    // Otherwise, we need to append the current image file in the diskgroup
                    // If currentDocumentFileFormatIsImage Then
                    if (bIsFirstDocument)
                    {
                        app.Diagnostics.Write("in first doc logic");
                        destinationDocHandle = sourceDocHandle;
                        bIsFirstDocument     = false;
                    }
                    else
                    {
                        app.Diagnostics.Write("Made it in");
                        AppendToDocument(app, args, sourceDocHandle, destinationDocHandle);
                    }
                }
                laststrPrimaryDocID = document.ID.ToString();
            }
            return(true);
        }
Ejemplo n.º 12
0
		public virtual void InvoiceOrder(DateTime invoiceDate, PXResult<SOOrderShipment, SOOrder, CurrencyInfo, SOAddress, SOContact, SOOrderType> order, Customer customer, DocumentList<ARInvoice, SOInvoice> list)
		{
			InvoiceOrder(invoiceDate, order, null, customer, list);
		}
        private static DocumentList FilterDocumentList(DocumentList docList, DocumentQueryContext queryContext)
        {
            if (queryContext != null)
            { 
                if (queryContext.KeyWord.Length > 0)
                {
                    docList.Documents = docList.Documents.Where(d => d.Fields[ReviewerCategoryIndex].Value.Contains(queryContext.KeyWord)).ToList();
                    docList.Total = docList.Documents.Count;
                }

                if (queryContext.Filters.Count > 0)
                {
                    docList.Documents = docList.Documents.Where(d => d.Fields[ReviewerCategoryIndex].Value == queryContext.Filters[0].Value).ToList();
                    docList.Total = docList.Documents.Count;

                    docList=UpdatePredictedCategoryValue(docList, queryContext);
                 
                }

                if (queryContext.Sort.Count > 0 && docList.Documents.Count > 0)
                {
                    var index = docList.Documents[0].Fields.FindIndex(f => f.Name == queryContext.Sort[0].Name);
                    if (queryContext.Sort[0].Order == SortOrder.Ascending)
                    {
                        docList.Documents = docList.Documents.Where(d => d.Fields[index].Name == queryContext.Sort[0].Name).OrderBy(o => o.Fields[index].Value).ToList();
                    }
                    if (queryContext.Sort[0].Order == SortOrder.Descending)
                    {
                        docList.Documents = docList.Documents.Where(d => d.Fields[index].Name == queryContext.Sort[0].Name).OrderByDescending(o => o.Fields[index].Value).ToList();
                    }
                }
                
            }

            return docList;
        }
Ejemplo n.º 14
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.º 15
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.º 16
0
        public static void ReleaseDoc(List <POReceipt> list, bool aIsMassProcess)
        {
            POReceiptEntry            docgraph        = PXGraph.CreateInstance <POReceiptEntry>();
            DocumentList <INRegister> created         = new DocumentList <INRegister>(docgraph);
            DocumentList <APInvoice>  invoicesCreated = new DocumentList <APInvoice>(docgraph);
            INReceiptEntry            iRe             = null;
            INIssueEntry      iIe = null;
            INAdjustmentEntry iAe = null;

            AP.APInvoiceEntry apInvoiceGraph = docgraph.CreateAPInvoiceEntry();
            int  iRow   = 0;
            bool failed = false;

            foreach (POReceipt order in list)
            {
                try
                {
                    switch (order.ReceiptType)
                    {
                    case POReceiptType.POReceipt:
                    case POReceiptType.TransferReceipt:
                        if (iRe == null)
                        {
                            iRe = docgraph.CreateReceiptEntry();
                        }
                        docgraph.ReleaseReceipt(iRe, apInvoiceGraph, order, created, invoicesCreated, aIsMassProcess);
                        break;

                    case POReceiptType.POReturn:
                        if (order.ReturnOrigCost == true)
                        {
                            if (iAe == null)
                            {
                                iAe = docgraph.CreateAdjustmentEntry();
                            }
                            docgraph.ReleaseReturnViaAdjustment(iAe, apInvoiceGraph, order, created, invoicesCreated, aIsMassProcess);
                        }
                        else
                        {
                            if (iIe == null)
                            {
                                iIe = docgraph.CreateIssueEntry();
                            }
                            docgraph.ReleaseReturnViaIssue(iIe, apInvoiceGraph, order, created, invoicesCreated, aIsMassProcess);
                        }
                        break;
                    }
                    PXProcessing <POReceipt> .SetInfo(iRow, ActionsMessages.RecordProcessed);
                }
                catch (Exception e)
                {
                    if (aIsMassProcess)
                    {
                        PXProcessing <POReceipt> .SetError(iRow, e);

                        failed = true;
                    }
                    else
                    {
                        throw;
                    }
                }
                iRow++;
            }
            if (failed)
            {
                throw new PXException(Messages.ReleaseOfOneOrMoreReceiptsHasFailed);
            }
        }
Ejemplo n.º 17
0
        public void Revalue(RevalueFilter filter, List <RevaluedAPHistory> list)
        {
            JournalEntry je        = PXGraph.CreateInstance <JournalEntry>();
            PostGraph    pg        = PXGraph.CreateInstance <PostGraph>();
            PXCache      cache     = je.Caches[typeof(CuryAPHist)];
            PXCache      basecache = je.Caches[typeof(APHist)];

            je.Views.Caches.Add(typeof(CuryAPHist));
            je.Views.Caches.Add(typeof(APHist));

            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 (RevaluedAPHistory hist in list)
                {
                    PXProcessing <RevaluedAPHistory> .SetCurrentItem(hist);

                    if (hist.FinPtdRevalued == 0m)
                    {
                        PXProcessing <RevaluedAPHistory> .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 = true;
                        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     = currency.APProvAcctID ?? hist.AccountID;
                        tran.SubID         = currency.APProvSubID ?? hist.SubID;
                        tran.CuryDebitAmt  = 0m;
                        tran.CuryCreditAmt = 0m;

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

                        tran.TranType  = "REV";
                        tran.TranClass = AccountType.Liability;
                        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 = hist.VendorID;

                        je.GLTranModuleBatNbr.Insert(tran);
                    }

                    VendorClass vendclass = PXSelectReadonly <VendorClass, Where <VendorClass.vendorClassID, Equal <Required <VendorClass.vendorClassID> > > > .Select(je, hist.VendorClassID);

                    if (vendclass == null)
                    {
                        vendclass = new VendorClass();
                    }

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

                    if (vendclass.UnrealizedLossAcctID == null)
                    {
                        vendclass.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 = vendclass.UnrealizedGainAcctID ?? currency.UnrealizedGainAcctID;
                            tran.SubID     = vendclass.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 = vendclass.UnrealizedLossAcctID ?? currency.UnrealizedLossAcctID;
                            tran.SubID     = vendclass.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);
                    }

                    {
                        CuryAPHist aphist = new CuryAPHist();
                        aphist.BranchID    = hist.BranchID;
                        aphist.AccountID   = hist.AccountID;
                        aphist.SubID       = hist.SubID;
                        aphist.FinPeriodID = filter.FinPeriodID;
                        aphist.VendorID    = hist.VendorID;
                        aphist.CuryID      = hist.CuryID;

                        aphist = (CuryAPHist)cache.Insert(aphist);
                        aphist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    {
                        APHist aphist = new APHist();
                        aphist.BranchID    = hist.BranchID;
                        aphist.AccountID   = hist.AccountID;
                        aphist.SubID       = hist.SubID;
                        aphist.FinPeriodID = filter.FinPeriodID;
                        aphist.VendorID    = hist.VendorID;

                        aphist = (APHist)basecache.Insert(aphist);
                        aphist.FinPtdRevalued += hist.FinPtdRevalued;
                    }

                    PXProcessing <RevaluedAPHistory> .SetProcessed();
                }

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

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

                ts.Complete();
            }

            //Clean current to prevent set exception to the last item
            PXProcessing <RevaluedAPHistory> .SetCurrentItem(null);

            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)
            {
                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 (RevaluedAPHistory res in APAccountList.Cache.Updated)
            {
                if ((bool)res.Selected)
                {
                    val += (decimal)res.FinPtdRevalued;
                }
            }

            if (val == 0)
            {
                throw new PXOperationCompletedWithWarningException(Messages.NoRevaluationEntryWasMade);
            }
        }
Ejemplo n.º 18
0
 public DocListAdapter(Activity context, DocumentList documents) : base()
 {
     this.context   = context;
     this.documents = documents;
 }
Ejemplo n.º 19
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.º 20
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);
		}
        /// <summary>
        /// Deletes the analytic project.
        /// </summary>
        /// <param name="matterId">The matter identifier.</param>
        /// <param name="dataSetId">The data set identifier.</param>
        /// <param name="projectId">The project identifier.</param>
        public void DeleteAnalyticProject(long matterId, long dataSetId, long projectId)
        {
            mockDocuments = null;
            analysisSets = null;
            currentAnalyticSetName = "Training Set 001";
            trainingSetCount = 0;
            resultTrainingSetSummary = new TrainingSetSummary();

            MockWorkflowState.Initialize();
        }
Ejemplo n.º 22
0
		public virtual void PostInvoice(INIssueEntry docgraph, ARInvoice invoice, DocumentList<INRegister> list)
		{
			SOOrderEntry oe = null;
			SOShipmentEntry se = null;

			foreach (PXResult<SOOrderShipment, SOOrder> res in PXSelectJoin<SOOrderShipment, InnerJoin<SOOrder, On<SOOrder.orderType, Equal<SOOrderShipment.orderType>, And<SOOrder.orderNbr, Equal<SOOrderShipment.orderNbr>>>>, Where<SOOrderShipment.invoiceType, Equal<Current<ARInvoice.docType>>, And<SOOrderShipment.invoiceNbr, Equal<Current<ARInvoice.refNbr>>>>>.SelectMultiBound(this, new object[] { invoice }))
			{
				if (((SOOrderShipment)res).ShipmentType == SOShipmentType.DropShip)
				{
					if (se == null)
					{
						se = PXGraph.CreateInstance<SOShipmentEntry>();
					}
					else
					{
						se.Clear();
					}
					se.PostReceipt(docgraph, res, list);
				}
				else if (string.Equals(((SOOrderShipment)res).ShipmentNbr, Constants.NoShipmentNbr))
				{
					if (oe == null)
					{
						oe = PXGraph.CreateInstance<SOOrderEntry>();
					}
					else
					{
						oe.Clear();
					}
					oe.PostOrder(docgraph, (SOOrder)res, list);
				}
				else
				{
					if (se == null)
					{
						se = PXGraph.CreateInstance<SOShipmentEntry>();

						se.Caches[typeof(SiteStatus)] = docgraph.Caches[typeof(SiteStatus)];
						se.Caches[typeof(LocationStatus)] = docgraph.Caches[typeof(LocationStatus)];
						se.Caches[typeof(LotSerialStatus)] = docgraph.Caches[typeof(LotSerialStatus)];
						se.Caches[typeof(ItemLotSerial)] = docgraph.Caches[typeof(ItemLotSerial)];

						se.Views.Caches.Remove(typeof(SiteStatus));
						se.Views.Caches.Remove(typeof(LocationStatus));
						se.Views.Caches.Remove(typeof(LotSerialStatus));
						se.Views.Caches.Remove(typeof(ItemLotSerial));
					}
					else
					{
						se.Clear();
					}
					se.PostShipment(docgraph, res, list);
				}
			}		
		}
        /// <summary>
        /// Gets document list for a page.
        /// </summary>
        /// <param name="docList">The sorted or filtered document list.</param>
        /// <param name="queryContext">The query context.</param>
        /// <returns>The page documents list</returns>
        private static DocumentList PageNavigationDocumentList(DocumentList docList, DocumentQueryContext queryContext)
        {
            if (queryContext != null)
            {
                var start = ((queryContext.PageIndex - 1) * queryContext.PageSize);
                var end = start + queryContext.PageSize;
                var count = queryContext.PageSize;


                if (end > docList.Total)
                {
                    count = docList.Total - start;
                }

                docList.Documents = docList.Documents.GetRange(start, count);
                docList.Total = docList.Documents.Count;
            }

            return docList;
        }        
Ejemplo n.º 24
0
		protected virtual IEnumerable Post(PXAdapter adapter)
		{
			List<ARRegister> list = new List<ARRegister>();
			foreach (ARInvoice order in adapter.Get<ARInvoice>())
			{
				list.Add(order);
			}

			Save.Press();

			PXLongOperation.StartOperation(this, delegate()
			{
				SOInvoiceEntry ie = PXGraph.CreateInstance<SOInvoiceEntry>();
				INIssueEntry ingraph = PXGraph.CreateInstance<INIssueEntry>();
				ingraph.FieldVerifying.AddHandler<INTran.inventoryID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
				ingraph.FieldVerifying.AddHandler<INTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
				ingraph.FieldVerifying.AddHandler<INTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
				DocumentList<INRegister> inlist = new DocumentList<INRegister>(ingraph);

				bool failed = false;

				foreach (ARInvoice ardoc in list)
				{
					try
					{
						ie.PostInvoice(ingraph, ardoc, inlist);

						if (adapter.MassProcess)
						{
							PXProcessing<ARInvoice>.SetInfo(list.IndexOf(ardoc), ActionsMessages.RecordProcessed);
						}
					}
					catch (Exception ex)
					{
						if (!adapter.MassProcess)
						{
							throw;
						}
						PXProcessing<ARInvoice>.SetError(list.IndexOf(ardoc), ex);
						failed = true;
					} 
				}

				if (ie.sosetup.Current.AutoReleaseIN == true && inlist.Count > 0 && inlist[0].Hold == false)
				{
					INDocumentRelease.ReleaseDoc(inlist, false);
				}

				if (failed)
				{
					throw new PXOperationCompletedException(ErrorMessages.SeveralItemsFailed);
				}
			});

			return adapter.Get();
		}
        public AnalysisSetDocumentInfo GetUncodedDocument(long orgId, long matterId, long dataSetId,
            long projectId, string documentRefId, DocumentQueryContext searchContext)
        {
            var result = new AnalysisSetDocumentInfo();
            var docList = new DocumentList();
            if(searchContext.AnalysisSet.Type == AnalysisSetType.ControlSet)
            {
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[ControlDocumentIndex].Value == "1").ToList();
                docList.Total = docList.Documents.Count;
            }
            if (searchContext.AnalysisSet.Type == AnalysisSetType.TrainingSet)
            {
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[TrainingDocumentIndex].Name == searchContext.AnalysisSet.Name).ToList();
                docList.Total = docList.Documents.Count;
            }
            if (searchContext.AnalysisSet.Type == AnalysisSetType.QcSet)
            {
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[QualityDocumentIndex].Name == searchContext.AnalysisSet.Name).ToList();
                docList.Total = docList.Documents.Count;
            }
            result.TotalDocumentCount = docList.Documents.Count;

            var doc =
                docList.Documents.Find(
                    d => d.Fields.Exists(f => (f.DisplayName == "Reviewer Category" && f.Value == NotCoded)));

            if (doc != null)
            {
                result.DocumentReferenceId = doc.ReferenceId;
                result.ProjectName = "Predictive Coding Project";
                result.DocumentText = "Mock Document " + doc.Id + " - Concordance® Evolution feeds your need for speed during document review. Litigation support professionals and document reviewers told us what they need most in an e-discovery review engine: outstanding speed, capacity and ease of use. Get it all with LexisNexis® Concordance® Evolution. Concordance® puts you in the driver’s seat, maintaining control and accelerating the review process to enhance client service and improve efficiency.";
                result.DocumentIndexId = Convert.ToInt32(doc.Id);
                result.ReviewerCategory = NotCoded;
                var dcnField = doc.Fields.Find(f => (f.DisplayName == "DCN"));
                if (dcnField != null)
                {
                    result.DocumentDcn = dcnField.Value;
                }
            }

            var reviewStatus = doc != null ? Status.Inprogress : Status.Completed;
            MockWorkflowState.SetReviewStatus(searchContext.AnalysisSet.Type, reviewStatus);

            return result;
        }
        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);
                }
            }
        }
        public virtual IEnumerable Action(
            PXAdapter adapter,
            [PXInt]
            [PXIntList(new int[] { 1, 2, 3, 4, 5 }, new string[] { "Create Shipment", "Apply Assignment Rules", "Create Invoice", "Post Invoice to IN", "Create Purchase Order" })]
            int?actionID,
            [PXDate]
            DateTime?shipDate,
            [PXSelector(typeof(INSite.siteCD))]
            string siteCD,
            [SOOperation.List]
            string operation,
            [PXString()]
            string ActionName,
            Func <PXAdapter, int?, DateTime?, string, string, string, IEnumerable> baseMtd)
        {
            switch (actionID)
            {
            case 1:
            {
                if (!string.IsNullOrEmpty(ActionName))
                {
                    PXAction action = Base.Actions[ActionName];

                    if (action != null)
                    {
                        Base.Save.Press();
                        List <object> result = new List <object>();
                        foreach (object data in action.Press(adapter))
                        {
                            result.Add(data);
                        }
                        return(result);
                    }
                }

                List <SOOrder> list = new List <SOOrder>();
                foreach (SOOrder order in adapter.Get <SOOrder>())
                {
                    list.Add(order);
                }

                if (shipDate != null)
                {
                    Base.soparamfilter.Current.ShipDate = shipDate;
                }

                if (Base.soparamfilter.Current.ShipDate == null)
                {
                    Base.soparamfilter.Current.ShipDate = Base.Accessinfo.BusinessDate;
                }

                if (siteCD != null)
                {
                    Base.soparamfilter.Cache.SetValueExt <SOParamFilter.siteID>(Base.soparamfilter.Current, siteCD);
                }

                if (!adapter.MassProcess)
                {
                    if (Base.soparamfilter.Current.SiteID == null)
                    {
                        Base.soparamfilter.Current.SiteID = GetPreferedSiteID();
                    }
                    if (adapter.ExternalCall)
                    {
                        Base.soparamfilter.AskExt(true);
                    }
                }
                if (Base.soparamfilter.Current.SiteID != null || adapter.MassProcess)
                {
                    try
                    {
                        Base.RecalculateExternalTaxesSync = true;
                        Base.Save.Press();
                    }
                    finally
                    {
                        Base.RecalculateExternalTaxesSync = false;
                    }
                    PXAutomation.RemovePersisted(Base, typeof(SOOrder), new List <object>(list));

                    SOParamFilter filter = Base.soparamfilter.Current;
                    PXLongOperation.StartOperation(Base, delegate()
                        {
                            bool anyfailed                    = false;
                            SOShipmentEntry docgraph          = PXGraph.CreateInstance <SOShipmentEntry>();
                            SOOrderEntry ordgraph             = PXGraph.CreateInstance <SOOrderEntry>();
                            DocumentList <SOShipment> created = new DocumentList <SOShipment>(docgraph);

                            //address AC-92776
                            for (int i = 0; i < list.Count; i++)
                            {
                                SOOrder order = list[i];
                                if (adapter.MassProcess)
                                {
                                    PXProcessing <SOOrder> .SetCurrentItem(order);
                                }

                                SOOrder ordercopy = (SOOrder)Base.Caches[typeof(SOOrder)].CreateCopy(order);
                                try
                                {
                                    if (operation == SOOperation.Issue)
                                    {
                                        ReviewWarehouseAvailability(ordgraph, order);
                                    }
                                }
                                catch (SOShipmentException ex)
                                {
                                    Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                    if (!adapter.MassProcess)
                                    {
                                        throw;
                                    }

                                    order.LastShipDate = filter.ShipDate;
                                    order.Status       = SOOrderStatus.Shipping; //Automation will set the order to back order since no shipments were created

                                    docgraph.Clear();

                                    var ordergraph = PXGraph.CreateInstance <SOOrderEntry>();
                                    ordergraph.Clear();

                                    ordergraph.Document.Cache.MarkUpdated(order);
                                    PXAutomation.CompleteSimple(ordergraph.Document.View);
                                    try
                                    {
                                        ordergraph.Save.Press();
                                        PXAutomation.RemovePersisted(ordergraph, order);

                                        PXTrace.WriteInformation(ex);
                                        PXProcessing <SOOrder> .SetWarning(ex);
                                    }
                                    catch (Exception inner)
                                    {
                                        Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                        PXProcessing <SOOrder> .SetError(inner);
                                        anyfailed = true;
                                    }
                                    continue;     //Stop there for this order
                                }
                                catch (Exception ex)
                                {
                                    if (!adapter.MassProcess)
                                    {
                                        throw;
                                    }
                                    PXProcessing <SOOrder> .SetError(ex);
                                    anyfailed = true;
                                    continue;
                                }

                                List <int?> sites = new List <int?>();

                                if (filter.SiteID != null)
                                {
                                    sites.Add(filter.SiteID);
                                }
                                else
                                {
                                    foreach (SOShipmentPlan plan in PXSelectGroupBy <SOShipmentPlan, Where <SOShipmentPlan.orderType, Equal <Current <SOOrder.orderType> >, And <SOShipmentPlan.orderNbr, Equal <Current <SOOrder.orderNbr> > > >, Aggregate <GroupBy <SOShipmentPlan.siteID> >, OrderBy <Asc <SOShipmentPlan.siteID> > > .SelectMultiBound(docgraph, new object[] { order }))
                                    {
                                        sites.Add(plan.SiteID);
                                    }
                                }

                                foreach (int?SiteID in sites)
                                {
                                    ordercopy = (SOOrder)Base.Caches[typeof(SOOrder)].CreateCopy(order);
                                    try
                                    {
                                        using (var ts = new PXTransactionScope())
                                        {
                                            PXTimeStampScope.SetRecordComesFirst(typeof(SOOrder), true);
                                            docgraph.CreateShipment(order, SiteID, filter.ShipDate, adapter.MassProcess, operation, created, adapter.QuickProcessFlow);
                                            ts.Complete();
                                        }

                                        if (adapter.MassProcess)
                                        {
                                            PXProcessing <SOOrder> .SetProcessed();
                                        }
                                    }
                                    catch (SOShipmentException ex)
                                    {
                                        Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                        if (!adapter.MassProcess)
                                        {
                                            throw;
                                        }
                                        order.LastSiteID   = SiteID;
                                        order.LastShipDate = filter.ShipDate;
                                        order.Status       = SOOrderStatus.Shipping;

                                        docgraph.Clear();

                                        var ordergraph = PXGraph.CreateInstance <SOOrderEntry>();
                                        ordergraph.Clear();

                                        ordergraph.Document.Cache.MarkUpdated(order);
                                        PXAutomation.CompleteSimple(ordergraph.Document.View);
                                        try
                                        {
                                            ordergraph.Save.Press();
                                            PXAutomation.RemovePersisted(ordergraph, order);

                                            PXTrace.WriteInformation(ex);
                                            PXProcessing <SOOrder> .SetWarning(ex);
                                        }
                                        catch (Exception inner)
                                        {
                                            Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                            PXProcessing <SOOrder> .SetError(inner);
                                            anyfailed = true;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Base.Caches[typeof(SOOrder)].RestoreCopy(order, ordercopy);
                                        docgraph.Clear();

                                        if (!adapter.MassProcess)
                                        {
                                            throw;
                                        }
                                        PXProcessing <SOOrder> .SetError(ex);
                                        anyfailed = true;
                                    }
                                }
                            }

                            if (adapter.AllowRedirect && !adapter.MassProcess && created.Count > 0)
                            {
                                using (new PXTimeStampScope(null))
                                {
                                    docgraph.Clear();
                                    docgraph.Document.Current = docgraph.Document.Search <SOShipment.shipmentNbr>(created[0].ShipmentNbr);
                                    throw new PXRedirectRequiredException(docgraph, "Shipment");
                                }
                            }

                            if (anyfailed)
                            {
                                throw new PXOperationCompletedWithErrorException(ErrorMessages.SeveralItemsFailed);
                            }
                        });
                }
                return(list);
            }

            default:
                return(baseMtd(adapter, actionID, shipDate, siteCD, operation, ActionName));
            }
        }
Ejemplo n.º 28
0
        //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.º 29
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);
                }
            }
        }
Ejemplo n.º 30
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.º 31
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.º 32
0
        private void bindData()
        {
            int   leadID  = 0;
            int   claimID = 0;
            Leads lead    = null;
            Claim claim   = null;
            List <LeadsDocument> leadDocuments  = null;
            List <ClaimDocument> claimDocuments = null;
            List <DocumentList>  allDocuments   = new List <DocumentList>();

            int.TryParse(Core.SecurityManager.DecryptQueryString(Request.Params["q"].ToString()), out claimID);

            if (claimID > 0)
            {
                claim = ClaimsManager.Get(claimID);
                if (claim != null)
                {
                    lead = claim.LeadPolicy.Leads;

                    lblName.Text = lead.insuredName;

                    // lead documents
                    leadDocuments = LeadsUploadManager.getLeadsDocumentForExportByLeadID(leadID);
                    if (leadDocuments != null && leadDocuments.Count > 0)
                    {
                        foreach (LeadsDocument leadDocument in leadDocuments)
                        {
                            DocumentList doc = new DocumentList();
                            doc.DocumentName = leadDocument.DocumentName;
                            doc.Description  = leadDocument.Description;

                            doc.DocumentPath = string.Format("/LeadsDocument/{0}/{1}/{2}",
                                                             leadDocument.LeadId,
                                                             leadDocument.LeadDocumentId,                                               // document id
                                                             leadDocument.DocumentName);                                                // document file name

                            allDocuments.Add(doc);
                        }
                    }

                    // claim documents
                    claimDocuments = ClaimDocumentManager.GetAll(claimID);
                    if (claimDocuments != null && claimDocuments.Count > 0)
                    {
                        foreach (ClaimDocument claimDocument in claimDocuments)
                        {
                            DocumentList doc = new DocumentList();
                            doc.DocumentName = claimDocument.DocumentName;
                            doc.Description  = claimDocument.Description;

                            doc.DocumentPath = string.Format("/ClaimDocuments/{0}/{1}/{2}",
                                                             claimDocument.ClaimID,
                                                             claimDocument.ClaimDocumentID,                                             // document id
                                                             claimDocument.DocumentName);                                               // document file name
                            allDocuments.Add(doc);
                        }
                    }

                    gvDocument.DataSource = allDocuments;
                    gvDocument.DataBind();
                }
            }
        }
        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");
            }
        }
 /// <summary>
 /// Add additional documents to analysis set
 /// </summary>
 /// <param name="orgId">orgId</param>
 /// <param name="matterId">matterId</param>
 /// <param name="dataSetId">dataSetId</param>
 /// <param name="projectId">projectId</param>
 /// <param name="analysisset">analysisset</param>
 /// <returns>number of documents added</returns>
 public int AddDocumentsToAnalysisSet(long orgId, long matterId, long dataSetId,
     long projectId, string analysisset)
 {
     var currentTrianingRoundSummary = UpdateTrainingSetSummary(this.GetAllAnalysisSets(matterId, dataSetId, projectId), "current");
     if(currentTrianingRoundSummary.NumberOfRelevantDocuments == 0 || currentTrianingRoundSummary.NumberOfNotRelevantDocuments == 0 )
     {
         if(mockTrainingSetAdditionalDocuments == null)
         {
             var resourceName = string.Format(CultureInfo.InvariantCulture,
             "{0}.matter_{1}-dataset_{2}-project_{3}-additionaltrainingsetdocuments.json",
             MockDataNameSpace, matterId, dataSetId, projectId);
             var mockData = GetEmbeddedResource(resourceName);
             mockTrainingSetAdditionalDocuments = JsonConvert.DeserializeObject<DocumentList>(mockData);
         }
         for (int i = addTrainingDocumentIndex; i < addTrainingDocumentIndex + 2; i++)
         {
             mockDocuments.Documents.Add(mockTrainingSetAdditionalDocuments.Documents[i]);
         }
         addTrainingDocumentIndex += 2;
         mockDocuments.Total = mockDocuments.Total + 2 ;
     return 50;
 }
     return 0;
 }
        public TransactionEntry()
        {
            FASetup setup = fasetup.Current;

            _created = new DocumentList <FARegister>(this);
        }
Ejemplo n.º 36
0
        public List <TheGraphShare> ExistingShares()
        {
            var existing = DocumentList.Select(x => x.ShareOrigin);

            return(Shares.Where(x => existing.Contains(x.Id) || x.Sender == null).OrderByDescending(x => x.BlockNumber).ToList());
        }
        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.º 38
0
		public void Add(DocumentList documentList) {
			if (documentsList.Contains(documentList))
				return;
			documentsList.Add(documentList);
		}
Ejemplo n.º 39
0
		public bool Load(DocumentList documentList, IDsDocumentLoader documentLoader) {
			const bool isReload = false;
			if (documentLoader == null)
				documentLoader = new DefaultDsDocumentLoader(documentTabService.DocumentTreeView.DocumentService);
			if (!CanLoad)
				return false;
			if (!CheckCanLoad(isReload))
				return false;
			if (documentList != documentListService.SelectedDocumentList)
				SaveCurrentDocumentsToList();

			NotifyBeforeLoad(isReload);
			using (DisableSaveToList()) {
				documentTabService.CloseAll();
				documentTabService.DocumentTreeView.DocumentService.Clear();
				documentLoader.Load(documentList.Documents.Select(a => new DocumentToLoad(a)));
			}
			NotifyAfterLoad(isReload);

			Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => {
				GC.Collect();
				GC.WaitForPendingFinalizers();
			}));
			return true;
		}
Ejemplo n.º 40
0
		void CreateDefaultList() {
			var fl = new DocumentList(DocumentList.DEFAULT_NAME);
			fl.AddDefaultDocuments();
			documentsList.Add(fl);
		}
        public List<AnalyticsWorkflowState> UpdateAnalyticWorkflowState(long matterId, long datasetId, long projectId, string binderId, List<AnalyticsWorkflowState> workflowState)
        {
            if(workflowState.Count > 1)
            {
                mockDocuments = null;
                mockAnalyticsProjectInfo = null;
                mockQcSts = null;
                mockTrainingSetAdditionalDocuments = null;
                analysisSets = null;                
                addTrainingDocumentIndex = 0;
                trainingSetCount = 0;
                mockPredictAllSummaryInfo = null;
                resultTrainingSetSummary = new TrainingSetSummary();
                resultTrainingSetSummary.CompletedRoundsSummary = new AnalysisSet();
                resultTrainingSetSummary.CompletedRoundDetails = new List<AnalysisSet>();
                resultTrainingSetSummary.CurrentRoundProgress = new AnalysisSet();
                MockWorkflowState.Initialize();
                MockWorkflowState.ChangeToState = new AnalyticsWorkflowState();
                //Ensure data is initialized as expected for the updated workflow state

                var random = new Random();

                //ControlSet
                AnalyticsWorkflowState state = workflowState.Find(p => p.Name == State.ControlSet);
                if (state.ReviewStatus == Status.Inprogress)
                {
                    var controlSetDocs = this.GetDocuments(matterId, datasetId, projectId, "controlset", null);

                    //ReviewStatus inprogress means some controlset documents should be coded
                    if (controlSetDocs.Documents.Find(d => d.Fields[ReviewerCategoryIndex].Value == NotCoded) != null)
                    {
                        foreach (var doc in controlSetDocs.Documents)
                        {
                            doc.Fields[ReviewerCategoryIndex].Value = (random.Next(2) == 0) ? Relevant : NotCoded;
                        }
                    }
                    UpdateControlSetSummary(this.GetAllAnalysisSets(matterId, datasetId, projectId));
                }

                if (state.ReviewStatus == Status.Completed)
                {
                    var controlSetDocs = this.GetDocuments(matterId, datasetId, projectId, "controlset", null);

                    //ReviewStatus Completed means all controlset documents should be coded
                    if (controlSetDocs.Documents.Find(d => d.Fields[ReviewerCategoryIndex].Value == NotCoded) != null)
                    {
                        foreach (var doc in controlSetDocs.Documents)
                        {
                            doc.Fields[ReviewerCategoryIndex].Value = (random.Next(2) == 0)? NotRelevant : Relevant;
                        }
                    }
                    
                    UpdateControlSetSummary(this.GetAllAnalysisSets(matterId, datasetId, projectId));
                }

                //TrainingSet
                state = workflowState.Find(p => p.Name == State.TrainingSet);
                if (state.CreateStatus == Status.Completed)
                {
                    this.CreateTrainingset(matterId.ToString(CultureInfo.InvariantCulture), datasetId.ToString(CultureInfo.InvariantCulture), projectId.ToString(CultureInfo.InvariantCulture));

                    //MockWorkflowState.ChangeToState = workflowState.Find(p => p.Name == State.ControlSet);
                    //resultTrainingSetSummary.CompletedRoundsSummary = new AnalysisSet();
                    //resultTrainingSetSummary.CompletedRoundDetails = new List<AnalysisSet>();
                    //resultTrainingSetSummary.CompletedRoundsSummary.Type = AnalysisSetType.TrainingSet;
                    //resultTrainingSetSummary.RoundsCompleted = 0;
                    //resultTrainingSetSummary.CurrentRound = 1;
                }
                if (state.ReviewStatus == Status.Inprogress)
                {
                    var trainingSetDocs = this.GetDocuments(matterId, datasetId, projectId, "trainingset", CreateQueryContext(AnalysisSetType.TrainingSet, "Training Set 001"));
                    trainingSetDocs.Documents[0].Fields[ReviewerCategoryIndex].Value = Relevant;
                    trainingSetDocs.Documents[1].Fields[ReviewerCategoryIndex].Value = NotRelevant;
                    trainingSetDocs.Documents[2].Fields[ReviewerCategoryIndex].Value = Skipped;
                    UpdateTrainingSetSummary(this.GetAllAnalysisSets(matterId, datasetId, projectId), "current");
                    resultTrainingSetSummary.CompletedRoundsSummary = new AnalysisSet();
                    resultTrainingSetSummary.RoundsCompleted = 0;
                    resultTrainingSetSummary.CurrentRound = 1;

                }
                if (state.ReviewStatus == Status.Completed)
                {
                    var queryContext = CreateQueryContext(AnalysisSetType.TrainingSet, "Training Set 001");
                    var trainingSetDocs = this.GetDocuments(matterId, datasetId, projectId, "trainingset",queryContext);
                    foreach (var doc in trainingSetDocs.Documents)
                    {
                        doc.Fields[ReviewerCategoryIndex].Value = (random.Next(2) == 0) ? NotRelevant : Relevant;
                    }
                    this.CreateTrainingset(matterId.ToString(CultureInfo.InvariantCulture), datasetId.ToString(CultureInfo.InvariantCulture), projectId.ToString(CultureInfo.InvariantCulture));
                    queryContext.AnalysisSet.Name = "Training Set 002";
                    trainingSetDocs = this.GetDocuments(matterId, datasetId, projectId, "trainingset", queryContext);
                    foreach (var doc in trainingSetDocs.Documents)
                    {
                        doc.Fields[ReviewerCategoryIndex].Value = (random.Next(2) == 0) ? NotRelevant : Relevant;
                    }

                    this.CreateTrainingset(matterId.ToString(CultureInfo.InvariantCulture), datasetId.ToString(CultureInfo.InvariantCulture), projectId.ToString(CultureInfo.InvariantCulture));
                }

                //QcSet
                state = workflowState.Find(p => p.Name == State.QcSet);
                if (state.CreateStatus == Status.Completed)
                {
                    this.CreateQcSet(matterId, datasetId, projectId, new QcSet());                    
                }
                if (state.ReviewStatus == Status.Inprogress)
                {
                    var queryContext = CreateQueryContext(AnalysisSetType.QcSet, "QCSet01");
                    var qcSetDocs = this.GetDocuments(matterId, datasetId, projectId, "qcset", queryContext);
                    foreach (var doc in qcSetDocs.Documents)
                    {
                        doc.Fields[ReviewerCategoryIndex].Value = (random.Next(2) == 0) ? Relevant : NotCoded;
                    }
                }

                if (state.ReviewStatus == Status.Completed)
                {
                    var queryContext = CreateQueryContext(AnalysisSetType.QcSet, "QCSet01");
                    var qcSetDocs = this.GetDocuments(matterId, datasetId, projectId, "qcset", queryContext);
                    foreach (var doc in qcSetDocs.Documents)
                    {
                        doc.Fields[ReviewerCategoryIndex].Value = (random.Next(2) == 0) ? NotRelevant : Relevant;
                    }
                }
                //PredictSet
                state = workflowState.Find(p => p.Name == State.PredictSet);
                if (state.ReviewStatus == Status.Completed)
                {
                    if (mockDocuments != null)
                    {
                        foreach (var doc in mockDocuments.Documents)
                        {
                            doc.Fields[PredictedCategoryIndex].Value = doc.Fields[PredictedCategoryIndex].Value == NotCoded ? Relevant : doc.Fields[PredictedCategoryIndex].Value;
                        }
                        
                    }

                }
            }
            
            return MockWorkflowState.UpdateStates(workflowState);
        }
Ejemplo n.º 42
0
		public bool Remove(DocumentList documentList) {
			if (documentList == SelectedDocumentList)
				return false;
			var selected = SelectedDocumentList;
			documentsList.Remove(documentList);
			selectedIndex = documentsList.IndexOf(selected);
			Debug.Assert(selectedIndex >= 0);
			Debug.Assert(SelectedDocumentList == selected);
			return true;
		}
        /// <summary>
        /// Gets the documents.
        /// </summary>
        /// <param name="matterId">The matter identifier.</param>
        /// <param name="dataSetId">The data set identifier.</param>
        /// <param name="projectId">The project identifier.</param>
        /// <param name="analysisSet">The analysis set.</param>
        /// <param name="queryContext">The query context.</param>
        /// <returns></returns>
        public DocumentList GetDocuments(long matterId, long dataSetId, long projectId, string analysisSet, DocumentQueryContext queryContext)
        {

            var docList = new DocumentList();
           
            if(mockDocuments == null )
            {
                var resourceName = string.Format(CultureInfo.InvariantCulture, "{0}.matter_{1}-dataset_{2}-project_{3}-documents.json",
                             MockDataNameSpace, matterId, dataSetId, projectId);

                var mockData = GetEmbeddedResource(resourceName);
                mockDocuments = JsonConvert.DeserializeObject<DocumentList>(mockData);
             
            }
            if(analysisSet == "controlset")
            {
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[ControlDocumentIndex].Value == "1").ToList();
                docList.Total = docList.Documents.Count;
            }
            if(analysisSet ==  "trainingset")
            {
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[TrainingDocumentIndex].Name == queryContext.AnalysisSet.Name).ToList();
                docList.Total = docList.Documents.Count;
            }
            if (analysisSet == "qcset")
            {
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[QualityDocumentIndex].Name == queryContext.AnalysisSet.Name).ToList();
                docList.Total = docList.Documents.Count;
            }
            if (analysisSet == "alldocuments")
            {
                docList.Documents = mockDocuments.Documents;
                docList.Total = docList.Documents.Count;
            }
            
            docList = FilterDocumentList(docList, queryContext);

            var pageDocuments = PageNavigationDocumentList(docList, queryContext);
            return pageDocuments;           
          
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Associate documents from selected document set to selected client
        /// </summary>
        /// <param name="clientUID"></param>
        /// <param name="clientDocumentSetUID"></param>
        /// <param name="documentSetUID"></param>
        public static void AssociateDocumentsToClient(
            ClientDocumentSet clientDocumentSet,
            int documentSetUID,
            HeaderInfo headerInfo)
        {
            // It is a new client document set
            // It maybe a new client, the client document set MUST be new or empty
            // 1) Instantiate a TREE for the Client Document Set document
            // 2) Instantiate a second tree for the documents related to that document set
            // 3) Now the old copy all starts, all the nodes from the second tree are moved to the new tree
            //    following current process
            // 4) Save happens as per usual
            //

            TreeView tvFileList           = new TreeView();               // This is the list of documents for a client, it should be EMPTY
            TreeView tvDocumentsAvailable = new TreeView();               // This is the list of documents for a client, it should be EMPTY
            string   folderOnly           = clientDocumentSet.FolderOnly; // Contains the folder location of the file

            // Add root folder
            //
            ClientDocument clientDocument = new ClientDocument();

            clientDocument.AddRootFolder(clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID, clientDocumentSet.FolderOnly);

            // List client document list !!!!!!! Important because the ROOT folder is loaded ;-)

            var documentSetList = new ClientDocument();

            documentSetList.List(clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID);

            tvFileList.Nodes.Clear();
            documentSetList.ListInTree(tvFileList, "CLIENT");
            if (tvFileList.Nodes.Count > 0)
            {
                tvFileList.Nodes[0].Expand();
            }

            // Load available documents
            //
            tvDocumentsAvailable.Nodes.Clear();

            // Get document list for a given document set
            //
            DocumentSet documentSet = new DocumentSet();

            documentSet.UID = documentSetUID;
            documentSet.Read(IncludeDocuments: 'Y');

            // Load document in the treeview
            //
            Document.Document root = new Document.Document();
            root.GetRoot(headerInfo);

            DocumentList.ListInTree(tvDocumentsAvailable, documentSet.documentList, root);

            while (tvDocumentsAvailable.Nodes[0].Nodes.Count > 0)
            {
                TreeNode tn = tvDocumentsAvailable.Nodes[0].Nodes[0];
                tn.Remove();

                tvFileList.Nodes[0].Nodes.Add(tn);
            }

            tvFileList.SelectedNode = tvFileList.Nodes[0];

            // -------------------------------------------------------------------
            // The documents have been moved from the available to client's tree
            // Now it is time to save the documents
            // -------------------------------------------------------------------
            Save(clientDocumentSet, documentSetUID, tvFileList);

            ClientDocumentLink cloneLinks = new ClientDocumentLink();

            cloneLinks.ReplicateDocSetDocLinkToClient(clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID, documentSetUID);
        }
        private static DocumentList UpdatePredictedCategoryValue(DocumentList docList, DocumentQueryContext queryContext)
        {
            if (queryContext.Filters.Count == 2 && docList.Total > 0)
            {
                var totalDocs = docList.Total;
                var count = queryContext.Filters[0].Value == Relevant ? queryContext.Filters[1].Value == Relevant ? mockDiscrepancies[0][0] : mockDiscrepancies[0][1] : queryContext.Filters[1].Value == Relevant ? mockDiscrepancies[1][0] : mockDiscrepancies[1][1];
                if (count > totalDocs)
                    count = totalDocs;
                docList.Documents = docList.Documents.GetRange(0, count);
                docList.Total = docList.Documents.Count;
                foreach (var doc in docList.Documents)
                {
                    doc.Fields[PredictedCategoryIndex].Value = queryContext.Filters[1].Value;
                }

            }

            return docList;
        }
Ejemplo n.º 46
0
        public async Task <IActionResult> Post([FromBody] DocumentList documentList)
        {
            var response = await _sentimentService.SendToAzure(documentList);

            return(Ok(response));
        }
        private static AnalysisSet UpdateTrainingSetSummary(List<AnalysisSet> analysisSets, string roundStatus)
        {
                AnalysisSet roundSummary = new AnalysisSet();           
                roundSummary.Name = currentAnalyticSetName;
                roundSummary.Type = AnalysisSetType.TrainingSet;
                roundSummary.BinderId = analysisSets.FirstOrDefault(s => s.Name == currentAnalyticSetName).BinderId;
                var docList = new DocumentList();
                docList.Documents = mockDocuments.Documents.Where(d => d.Fields[1].Name == currentAnalyticSetName).ToList();

                if (roundStatus == "completed")
                {
                    roundSummary = resultTrainingSetSummary.CompletedRoundsSummary;
                }               
                roundSummary.TotalDocuments = roundSummary.TotalDocuments + docList.Documents.Count;
                roundSummary.NumberOfRelevantDocuments = roundSummary.NumberOfRelevantDocuments + docList.Documents.Where(d => d.Fields[ReviewerCategoryIndex].Value == Relevant).ToList().Count;
                roundSummary.NumberOfNotRelevantDocuments = roundSummary.NumberOfNotRelevantDocuments + docList.Documents.Where(d => d.Fields[ReviewerCategoryIndex].Value == NotRelevant).ToList().Count;
                roundSummary.NumberOfNotCodedDocuments = roundSummary.NumberOfNotCodedDocuments + docList.Documents.Where(d => d.Fields[ReviewerCategoryIndex].Value == NotCoded).ToList().Count;
                roundSummary.NumberOfSkippedDocuments = roundSummary.NumberOfSkippedDocuments + docList.Documents.Where(d => d.Fields[ReviewerCategoryIndex].Value == Skipped).ToList().Count;
                return roundSummary;           
        }
Ejemplo n.º 48
0
        protected void Page_Load(object sender, EventArgs e)
        {
            LabelMain.Text = GetContent("Body");

            LabelRightSideBarArea.Text = "<span class=\"subtitle\">By Month</span><br />";


            TagList         pageTagList  = null;
            List <Document> SideBarList  = null;
            List <Document> DocumentList = null;


            if (null == Session["EditjudekGallery"])
            {
                DocumentList = Cache.Get("cache.judek.MultimediaFiles") as List <Document>;
                SideBarList  = Cache.Get("cache.judek.MultimediaSideBar") as List <Document>;
                pageTagList  = Cache.Get("cache.judek.MultimediaTagList") as TagList;
            }


            if ((null == DocumentList) ||
                (null == SideBarList) ||
                (null == pageTagList))
            {//Means that there is no cache read everything from disk
                #region ReadLoop

                DocumentList = new List <Document>();
                SideBarList  = new List <Document>();
                pageTagList  = new TagList();


                DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(Document.MULTIMEDIA_FOLDER));

                List <FileInfo> multimediaFileList = new List <FileInfo>();

                multimediaFileList.AddRange(directoryInfo.GetFiles("*.mp3"));
                multimediaFileList.AddRange(directoryInfo.GetFiles("*.wma"));
                multimediaFileList.AddRange(directoryInfo.GetFiles("*.aac"));
                multimediaFileList.AddRange(directoryInfo.GetFiles("*.ac3"));
                multimediaFileList.AddRange(directoryInfo.GetFiles("*.mp4"));
                multimediaFileList.AddRange(directoryInfo.GetFiles("*.wmv"));
                multimediaFileList.AddRange(directoryInfo.GetFiles("*.mpg"));

                Document doc;
                System.Collections.Hashtable ht2 = new System.Collections.Hashtable();


                foreach (FileInfo file in multimediaFileList)
                {
                    try
                    {
                        if ((file.Extension.ToLower() == ".mp4") || (file.Extension.ToLower() == ".wmv") || (file.Extension.ToLower() == ".mpg"))
                        {
                            doc = new VideoFile(this, file.Name);
                        }
                        else
                        {
                            doc = new AudioFile(this, file.Name);
                        }


                        foreach (Tag t in doc.Tags)
                        {
                            pageTagList.Add(t);
                        }

                        //doc.Link = Document.MULTIMEDIA_FOLDER + "/" + doc.Name;
                        doc.Link = doc.Name;
                    }
                    catch { continue; }


                    DocumentList.Add(doc);



                    #region Fill RightSideBar



                    if (null == SideBarList.Find(delegate(Document st) { return((st.Dated.Year == doc.Dated.Year) && (st.Dated.Month == doc.Dated.Month)); }))
                    {
                        SideBarList.Add(doc);
                    }


                    #endregion
                }
                #endregion

                #region Sort
                //Sort by date - sort should always be done after all filters for performance
                DocumentList.Sort(delegate(Document f1, Document f2)
                {
                    return(DateTime.Compare(f2.Dated, f1.Dated));
                });


                //Do the same for right side bar
                SideBarList.Sort(delegate(Document f1, Document f2)
                {
                    return(DateTime.Compare(f2.Dated, f1.Dated));
                });

                //And left
                pageTagList.Sort(delegate(ListedTag t1, ListedTag t2)
                {
                    return(t1.Name.CompareTo(t2.Name));
                });

                #endregion

                #region Insert Cache
                //Fill the cache with newly read info.

                Cache.Insert("cache.judek.MultimediaFiles", DocumentList);
                Cache.Insert("cache.judek.MultimediaSideBar", SideBarList);
                Cache.Insert("cache.judek.MultimediaTagList", pageTagList);

                #endregion
            }


            #region Filter
            try
            {
                //Try and do all filters here at once for performance
                if (Request.QueryString["perma"] != null)
                {
                    string permaFilter = Request.QueryString["perma"];
                    DocumentList = DocumentList.FindAll(delegate(Document d)
                    {
                        return((d.Name.ToLower() == permaFilter.ToLower()));
                    });
                }


                else if (Request.QueryString["MonthFilter"] != null)
                {
                    string MonthFilter = Request.QueryString["MonthFilter"];
                    if (MonthFilter.Length == 6)
                    {
                        int nYearFilter  = Int32.Parse(MonthFilter.Substring(0, 4));
                        int nMonthFilter = Int32.Parse(MonthFilter.Substring(4, 2));

                        DocumentList = DocumentList.FindAll(delegate(Document d)
                        {
                            return((d.Dated.Month == nMonthFilter) && (d.Dated.Year == nYearFilter));
                        });
                    }
                }
                else if (Request.QueryString["Tags"] != null)
                {
                    string sTag = Request.QueryString["Tags"];

                    DocumentList = DocumentList.FindAll(delegate(Document d)
                    {
                        return(d.Tags.HasTag(sTag));
                    });
                }
                else
                {
                    ;//no filter
                }
            }
            catch { }
            #endregion



            #region Body Write Loop
            //Show just 25 entries maximum
            for (int i = 0; ((i < 25) && (i < DocumentList.Count)); i++)
            {
                MultimediaFile d = DocumentList[i] as MultimediaFile;

                if (null == d)
                {
                    continue;
                }


                LabelMultiMediaFiles.Text += "<br><span class=\"subtitle\" >";

                string slink;

                if (d.MultimediaType == MultimediaType.audio)
                {
                    slink = "<br><a href=Play.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=380&H=50" + "&plugins=spectrumvisualizer-1" + " onclick=\"window.open(this.href,'newWindow','width=400,height=400', 'modal');return false\">";
                }
                else if (d.MultimediaType == MultimediaType.video)
                {
                    slink = "<br><a href=Play.aspx?FL=" + Document.MULTIMEDIA_FOLDER + "&F=" + d.Link + "&T=" + d.MultimediaType + "&W=640&H=388" + " onclick=\"window.open(this.href,'newWindow','width=652,height=700', 'modal');return false\">";
                }
                else
                {
                    slink = "";
                }



                slink += d.Title + "</a></span>";

                LabelMultiMediaFiles.Text += slink;
                LabelMultiMediaFiles.Text += " <br /><span class=\"footer\" >[" + d.Dated.ToLongDateString() + "] <a href=\"Multimedia.aspx?perma=" + d.Name + "\">PermaLink</a></span>";

                if (d.Attachments.Count > 0)
                {
                    LabelMultiMediaFiles.Text += "<br /><span class=\"footer\" >Attachements:</span>";
                }


                foreach (Attachement att in d.Attachments)
                {
                    LabelMultiMediaFiles.Text += "&nbsp;<span class=\"footer\" >(<a href=GetFile.aspx?SF=" + Document.ATTACHMENT_FOLDER + "/" + att.AttachmentInfo.Name + "&TF=" + att.Title + ">" + att.Title + "</a>)</span>";
                }
                LabelMultiMediaFiles.Text += "<br />" + d.HTMLDescription + "";
            }
            #endregion

            #region SideBar Write Loop


            foreach (Document SideBarDoc in SideBarList)
            {
                string sYearMonth = SideBarDoc.Dated.ToString("yyyy") + SideBarDoc.Dated.ToString("MM");

                LabelRightSideBarArea.Text += string.Format("<a href=\"{2}\">{0}-{1}</a><br />",
                                                            SideBarDoc.Dated.ToString("MMMM"), SideBarDoc.Dated.ToString("yyyy"),
                                                            "Multimedia.aspx?MonthFilter=" + sYearMonth);
            }


            #endregion


            //LabelTagCloud.Text = "Categories <i>(Click any link below)</i><br />";
            foreach (Tag tag in pageTagList)
            {
                LabelTagCloud.Text += string.Format(" | <a href=\"Multimedia.aspx?Tags={0}\">{1}</a> ",
                                                    tag.Signature, tag.Name);
            }
        }
        public ControlSet CreateControlset(string matterId, string dataSetId, string projectId, ControlSet project)
        {
            var resourceName = string.Format(CultureInfo.InvariantCulture, "{0}.matter_{1}-dataset_{2}-analytic-project_{3}-create-controlset.json",
                MockDataNameSpace, matterId, dataSetId, projectId);

            var mockData = GetEmbeddedResource(resourceName);

            var result = JsonConvert.DeserializeObject<ControlSet>(mockData);

            //Reset Mock Documents
            mockDocuments = null;

            MockWorkflowState.UpdateState(name: State.ControlSet, createStatus: Status.Completed, reviewStatus: Status.NotStarted, isCurrent: true);

            return result;
        }
Ejemplo n.º 50
0
		public DocumentListVM(OpenDocumentListVM owner, DocumentList documentList, bool isExistingList, bool isUserList) {
			this.owner = owner;
			DocumentList = documentList;
			IsExistingList = isExistingList;
			IsUserList = isUserList;
		}
Ejemplo n.º 51
0
        private void CreateDocument()
        {
            Document.LineSpacing = 1;

            var titleparagraph = new Paragraph();
            titleparagraph.StyleName = string.Format("Heading{0}", 1);

            if (ShowImage)
            {
                CreateNodeIcon(RootMap, ref titleparagraph);
            }

            var titlespan = new Span(RootMap.Name);// {FontSize = 22, ForeColor = Colors.DarkSlateBlue};
            titleparagraph.Inlines.Add(titlespan);
            Section.Blocks.Add(titleparagraph);

            var documentList = new DocumentList(DefaultListStyles.Bulleted, Document);
            documentList.Style.Levels[8].LevelText = "";

            foreach (var node in RootMap.ChildNodes.OrderBy(q => q.YPosition).ThenBy(q => q.XPosition))
            {
                AddNodeToDocument(node, documentList.ID);
            }

            foreach (var map in Maps)
            {
                if (map.Id != RootMap.Id)
                {
                    var subMapDocumentList = new DocumentList(DefaultListStyles.Bulleted, Document);
                    subMapDocumentList.Style.Levels[8].LevelText = "";

                    AddSubTitle(map, map.Id.ToLongString());
                    foreach (var node in map.ChildNodes.OrderBy(q => q.YPosition).ThenBy(q => q.XPosition))
                    {
                        AddNodeToDocument(node, subMapDocumentList.ID);
                    }
                }
            }

            Document.Sections.Add(Section);
            if (ShowPages)
            {
                AddPageFooter();
            }
        }
 protected DxDockPanelViewModel()
 {
     DocumentContainer = new DocumentList();
 }