Exemplo n.º 1
0
        private void SendCopyMessageToInside(PXGraph graph, EMailAccount account, EPActivity message, IEnumerable <Mailbox> email)
        {
            var cache = graph.Caches[message.GetType()];
            var copy  = (EPActivity)cache.CreateCopy(message);

            copy.TaskID       = null;
            copy.IsIncome     = false;
            copy.ParentTaskID = message.TaskID;
            copy.MailTo       = ConcatAddresses(email);       //TODO: need add address description
            copy.MailCc       = null;
            copy.MailBcc      = null;
            copy.MPStatus     = MailStatusListAttribute.PreProcess;
            copy.ClassID      = CRActivityClass.EmailRouting;
            new AddInfoEmailProcessor().Process(new EmailProcessEventArgs(graph, account, copy));
            copy.RefNoteID       = null;
            copy.ParentRefNoteID = null;
            var imcUid = Guid.NewGuid();

            copy.ImcUID    = imcUid;
            copy.MessageId = GetType().Name + "_" + imcUid.ToString().Replace("-", string.Empty);
            copy.Owner     = message.Owner;
            copy.IsPrivate = message.IsPrivate;
            cache.Insert(copy);
            var noteFiles = PXNoteAttribute.GetFileNotes(cache, message);

            if (noteFiles != null)
            {
                PXNoteAttribute.SetFileNotes(cache, copy, noteFiles);
            }
        }
Exemplo n.º 2
0
        protected virtual void InsertARTran(ARInvoiceEntry arGraph, EPExpenseClaimDetails row, bool copyNotes, bool copyFiles)
        {
            ARTran tran = (ARTran)arGraph.Transactions.Cache.CreateInstance();

            tran.InventoryID = row.InventoryID;
            tran.TranDesc    = row.TranDesc;
            tran.TranCost    = row.ExtCost;
            tran.Qty         = row.Qty;
            tran.UOM         = row.UOM;
            tran.CuryTranAmt = row.CuryTranAmt;
            tran.AccountID   = row.SalesAccountID;
            tran.SubID       = row.SalesSubID;
            tran.Date        = row.ExpenseDate;
            tran             = arGraph.Transactions.Insert(tran);

            if (copyNotes)
            {
                string note = PXNoteAttribute.GetNote(Caches[typeof(EPExpenseClaimDetails)], row);
                if (note != null)
                {
                    PXNoteAttribute.SetNote(arGraph.Transactions.Cache, tran, note);
                }
            }
            if (copyFiles)
            {
                Guid[] files = PXNoteAttribute.GetFileNotes(Caches[typeof(EPExpenseClaimDetails)], row);
                if (files != null && files.Length > 0)
                {
                    PXNoteAttribute.SetFileNotes(arGraph.Transactions.Cache, tran, files);
                }
            }
        }
        protected virtual CRSMEmail CreateMessage()
        {
            var activityCache = Graph.Caches[typeof(CRSMEmail)];
            var act           = (CRSMEmail)activityCache.Insert();

            //CRActivity
            act.ClassID      = CRActivityClass.Email;
            act.Type         = null;
            act.OwnerID      = Owner;
            act.StartDate    = PXTimeZoneInfo.Now;
            act.BAccountID   = BAccountID;
            act.RefNoteID    = RefNoteID;
            act.ParentNoteID = ParentNoteID;

            //SMEmail
            var accountId = MailAccountId ?? MailAccountManager.DefaultMailAccountID;

            act.MailAccountID = accountId;

            act.MailFrom = accountId.
                           With(_ => (EMailAccount)PXSelect <EMailAccount,
                                                             Where <EMailAccount.emailAccountID, Equal <Required <EMailAccount.emailAccountID> > > > .
                                Select(_graph, _.Value)).
                           With(_ => _.Address);

            act.MailTo    = MergeAddressList(act, To, act.MailTo);
            act.MailCc    = MergeAddressList(act, Cc, act.MailCc);
            act.MailBcc   = MergeAddressList(act, Bcc, act.MailBcc);
            act.MailReply = string.IsNullOrEmpty(Reply) ? act.MailFrom : Reply;
            act.IsIncome  = false;
            act.MPStatus  = MailStatusListAttribute.PreProcess;
            act.Format    = BodyFormat ?? EmailFormatListAttribute.Html;

            act.Subject = Subject;
            act.Body    = BodyFormat == null || BodyFormat == EmailFormatListAttribute.Html
                ? CreateHtmlBody(Body)
                : CreateTextBody(Body);

            if (AttachmentsID != null)
            {
                foreach (NoteDoc doc in
                         PXSelect <NoteDoc, Where <NoteDoc.noteID, Equal <Required <NoteDoc.noteID> > > > .Select(Graph, AttachmentsID))
                {
                    if (doc.FileID != null && !_attachments.Contains(doc.FileID.Value))
                    {
                        _attachments.Add(doc.FileID.Value);
                    }
                }
            }

            if (_attachments.Count > 0)
            {
                PXNoteAttribute.SetFileNotes(activityCache, act, _attachments.ToArray());
            }

            act = (CRSMEmail)activityCache.Update(act);

            return(act);
        }
Exemplo n.º 4
0
        protected void SendCopyMessageToInside(PXGraph graph, EMailAccount account, CRSMEmail message, IEnumerable <MailAddress> addresses)
        {
            var cache = graph.Caches[message.GetType()];
            var copy  = (CRSMEmail)cache.CreateCopy(message);

            copy.NoteID       = null;
            copy.EmailNoteID  = null;
            copy.IsIncome     = false;
            copy.ParentNoteID = message.NoteID;
            MailAddress address = null;

            copy.MailFrom = EmailParser.TryParse(message.MailFrom, out address)
                                ? new MailAddress(account.Address, address.DisplayName).ToString()
                                : account.Address;
            copy.MailTo    = PXDBEmailAttribute.ToString(addresses);          //TODO: need add address description
            copy.MailCc    = null;
            copy.MailBcc   = null;
            copy.MailReply = copy.MailFrom;
            copy.MPStatus  = MailStatusListAttribute.PreProcess;
            copy.ClassID   = CRActivityClass.EmailRouting;
            new AddInfoEmailProcessor().Process(new EmailProcessEventArgs(graph, account, copy));
            copy.RefNoteID  = null;
            copy.BAccountID = null;
            copy.ContactID  = null;
            copy.Pop3UID    = null;
            copy.ImapUID    = null;
            var imcUid = Guid.NewGuid();

            copy.ImcUID      = imcUid;
            copy.MessageId   = this.GetType().Name + "_" + imcUid.ToString().Replace("-", string.Empty);
            copy.OwnerID     = null;
            copy.WorkgroupID = null;

            copy = (CRSMEmail)cache.CreateCopy(cache.Insert(copy));

            //Update owner and reset owner if employee not found
            copy.OwnerID = message.OwnerID;
            try
            {
                cache.Update(copy);
            }
            catch (PXSetPropertyException)
            {
                copy.OwnerID = null;
                copy         = (CRSMEmail)cache.CreateCopy(cache.Update(copy));
            }

            copy.IsPrivate   = message.IsPrivate;
            copy.WorkgroupID = message.WorkgroupID;

            var noteFiles = PXNoteAttribute.GetFileNotes(cache, message);

            if (noteFiles != null)
            {
                PXNoteAttribute.SetFileNotes(cache, copy, noteFiles);
            }
        }
Exemplo n.º 5
0
        protected virtual void InsertPMTran(RegisterEntry pmGraph, EPExpenseClaimDetails row, EPExpenseClaim doc, bool copyNotes, bool copyFiles)
        {
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(pmGraph, row.ContractID);

            Account account = PXSelect <Account, Where <Account.accountID, Equal <Required <Account.accountID> > > > .Select(this, row.ExpenseAccountID);

            if (account.AccountGroupID == null && project.BaseType == PMProject.ProjectBaseType.Project)
            {
                throw new PXException(Messages.AccountGroupIsNotAssignedForAccount, account.AccountCD);
            }

            PMTran tran = (PMTran)pmGraph.Transactions.Cache.Insert();

            tran.AccountGroupID = account.AccountGroupID;
            tran.BAccountID     = row.CustomerID;
            tran.LocationID     = row.CustomerLocationID;
            tran.ProjectID      = row.ContractID;
            tran.TaskID         = row.TaskID;
            tran.InventoryID    = row.InventoryID;
            tran.Qty            = row.Qty;
            tran.Billable       = true;
            tran.BillableQty    = row.Qty;
            tran.UOM            = row.UOM;
            tran.UnitRate       = row.UnitCost;
            tran.Amount         = row.TranAmt;
            tran.AccountID      = row.ExpenseAccountID;
            tran.SubID          = row.ExpenseSubID;
            tran.StartDate      = row.ExpenseDate;
            tran.EndDate        = row.ExpenseDate;
            tran.Date           = row.ExpenseDate;
            tran.ResourceID     = doc.EmployeeID;
            tran.Released       = project.BaseType == PMProject.ContractBaseType.Contract;      //contract trans are created as released

            pmGraph.Transactions.Update(tran);

            pmGraph.Document.Current.Released = project.BaseType == PMProject.ContractBaseType.Contract;

            if (copyNotes)
            {
                string note = PXNoteAttribute.GetNote(Caches[typeof(EPExpenseClaimDetails)], row);
                if (note != null)
                {
                    PXNoteAttribute.SetNote(pmGraph.Transactions.Cache, tran, note);
                }
            }
            if (copyFiles)
            {
                Guid[] files = PXNoteAttribute.GetFileNotes(Caches[typeof(EPExpenseClaimDetails)], row);
                if (files != null && files.Length > 0)
                {
                    PXNoteAttribute.SetFileNotes(pmGraph.Transactions.Cache, tran, files);
                }
            }
        }
        private void SendCopyMessage(PXGraph graph, EMailAccount account, CRSMEmail message, string email)
        {
            var cache = graph.Caches[message.GetType()];
            var copy  = (CRSMEmail)cache.CreateCopy(message);

            copy.NoteID       = null;
            copy.EmailNoteID  = null;
            copy.IsIncome     = false;
            copy.ParentNoteID = message.NoteID;
            copy.MailTo       = email;       //TODO: need add address description
            copy.MailCc       = null;
            copy.MailBcc      = null;
            copy.MPStatus     = MailStatusListAttribute.PreProcess;
            copy.ClassID      = CRActivityClass.EmailRouting;
            new AddInfoEmailProcessor().Process(new EmailProcessEventArgs(graph, account, copy));
            copy.RefNoteID  = null;
            copy.BAccountID = null;
            copy.ContactID  = null;
            copy.Pop3UID    = null;
            copy.ImapUID    = null;
            var imcUid = Guid.NewGuid();

            copy.ImcUID      = imcUid;
            copy.MessageId   = this.GetType().Name + "_" + imcUid.ToString().Replace("-", string.Empty);
            copy.OwnerID     = null;
            copy.WorkgroupID = null;

            copy = (CRSMEmail)cache.CreateCopy(cache.Insert(copy));

            //Update owner and reset owner if employee not found
            copy.OwnerID = message.OwnerID;
            try
            {
                cache.Update(copy);
            }
            catch (PXSetPropertyException)
            {
                copy.OwnerID = null;
                copy         = (CRSMEmail)cache.CreateCopy(cache.Update(copy));
            }

            copy.WorkgroupID = message.WorkgroupID;

            var noteFiles = PXNoteAttribute.GetFileNotes(cache, message);

            if (noteFiles != null)
            {
                PXNoteAttribute.SetFileNotes(cache, copy, noteFiles);
            }
            graph.EnsureCachePersistence(copy.GetType());
        }
Exemplo n.º 7
0
        private void SendCopyMessageToOutside(PXGraph graph, EMailAccount account, CRSMEmail message, IEnumerable <Mailbox> email)
        {
            var cache = graph.Caches[message.GetType()];
            var copy  = (CRSMEmail)cache.CreateCopy(message);

            copy.NoteID       = null;
            copy.EmailNoteID  = null;
            copy.IsIncome     = false;
            copy.ParentNoteID = message.NoteID;
            Mailbox mailFrom;

            copy.MailFrom = Mailbox.TryParse(message.MailFrom, out mailFrom)
                ? new Mailbox(mailFrom.DisplayName, account.Address).ToString()
                : account.Address;
            copy.MailTo   = ConcatAddresses(email); //TODO: need add address description
            copy.MailCc   = null;
            copy.MailBcc  = null;
            copy.MPStatus = MailStatusListAttribute.PreProcess;
            copy.ClassID  = CRActivityClass.Email;
            var imcUid = Guid.NewGuid();

            copy.ImcUID       = imcUid;
            copy.MessageId    = GetType().Name + "_" + imcUid.ToString().Replace("-", string.Empty);
            copy.IsPrivate    = message.IsPrivate;
            copy.OwnerID      = null;
            copy.ParentNoteID = null;

            copy = (CRSMEmail)cache.CreateCopy(cache.Insert(copy));

            //Update owner and reset owner if employee not found
            copy.OwnerID = message.OwnerID;
            try
            {
                copy = (CRSMEmail)cache.Update(copy);
            }
            catch (PXSetPropertyException)
            {
                copy.OwnerID = null;
                copy         = (CRSMEmail)cache.Update(copy);
            }

            copy.ParentNoteID = message.NoteID;

            var noteFiles = PXNoteAttribute.GetFileNotes(cache, message);

            if (noteFiles != null)
            {
                PXNoteAttribute.SetFileNotes(cache, copy, noteFiles);
            }
        }
Exemplo n.º 8
0
        private void PrepareCertificationData(CarrierPlugin cp)
        {
            ICarrierService plugin = CreateCarrierService(this, cp);

            if (plugin != null)
            {
                UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>();
                CarrierResult <IList <CarrierCertificationData> > result = plugin.GetCertificationData();

                if (result != null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Message message in result.Messages)
                    {
                        sb.AppendFormat("{0}:{1} ", message.Code, message.Description);
                    }

                    if (result.IsSuccess)
                    {
                        CarrierPlugin copy = (CarrierPlugin)Plugin.Cache.CreateCopy(cp);

                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                        {
                            ZipArchive zip = new ZipArchive(ms, false);

                            foreach (CarrierCertificationData d in result.Result)
                            {
                                using (System.IO.Stream zipStream = zip.OpenWrite(string.Format("{0}.{1}", d.Description, d.Format)))
                                {
                                    zipStream.Write(d.File, 0, d.File.Length);
                                }
                            }

                            FileInfo file = new FileInfo("CertificationData.zip", null, ms.ToArray());
                            upload.SaveFile(file, FileExistsAction.CreateVersion);
                            PXNoteAttribute.SetFileNotes(Plugin.Cache, copy, file.UID.Value);
                        }

                        Plugin.Update(copy);

                        this.Save.Press();
                    }
                    else
                    {
                        throw new PXException(SO.Messages.CarrierServiceError, sb.ToString());
                    }
                }
            }
        }
Exemplo n.º 9
0
        protected virtual IEnumerable LumGenerate3PLUKFile(PXAdapter adapter)
        {
            try
            {
                SOShipment soShipment = adapter.Get <SOShipment>()?.FirstOrDefault();
                // Get Csv String Builder
                var result = CombineCSV(soShipment, "P3PL");
                // Upload Graph
                UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>();
                // Create SM.FileInfo
                var      fileName = $"{result.OrderNbr}.csv";
                var      data     = new UTF8Encoding(true).GetBytes(result.csvText.ToString());
                FileInfo fi       = new FileInfo(fileName, null, data);
                // Upload file to FTP
                #region 3PL UK FTP
                var configYusen = SelectFrom <LUM3PLUKSetup> .View.Select(Base).RowCast <LUM3PLUKSetup>().FirstOrDefault();

                FTP_Config config = new FTP_Config()
                {
                    FtpHost = configYusen.FtpHost,
                    FtpUser = configYusen.FtpUser,
                    FtpPass = configYusen.FtpPass,
                    FtpPort = configYusen.FtpPort,
                    FtpPath = configYusen.FtpPath
                };

                var ftpResult = UploadFileByFTP(config, fileName, data);
                //var ftpResult = true;
                if (!ftpResult)
                {
                    throw new Exception("Ftp Upload Fail!!");
                }
                #endregion

                // Upload file to Attachment
                upload.SaveFile(fi);
                PXNoteAttribute.SetFileNotes(Base.Document.Cache, Base.Document.Current, fi.UID.Value);
                Base.Document.Current.GetExtension <SOShipmentExt>().UsrSendToWareHouse = true;
                Base.Document.UpdateCurrent();
                Base.Save.Press();
            }
            catch (Exception ex)
            {
                PXProcessing.SetError(ex.Message);
            }

            return(adapter.Get());
        }
Exemplo n.º 10
0
        protected virtual EPActivity CreateMessage()
        {
            var activityCache = Graph.Caches[typeof(EPActivity)];
            var act           = PXCache <EPActivity> .CreateCopy((EPActivity)activityCache.Insert());

            act.ClassID = CRActivityClass.Email;
            act.Type    = null;
            var accountId = MailAccountId ?? MailAccountManager.DefaultMailAccountID;

            act.MailAccountID = accountId;
            act.MailFrom      = accountId.
                                With(_ => (EMailAccount)PXSelect <EMailAccount,
                                                                  Where <EMailAccount.emailAccountID, Equal <Required <EMailAccount.emailAccountID> > > > .
                                     Select(_graph, _.Value)).
                                With(_ => _.Address);
            act.MailTo          = To;
            act.MailCc          = UpdateMailTo(act, Cc);
            act.MailBcc         = UpdateMailTo(act, Bcc);
            act.MailReply       = string.IsNullOrEmpty(Reply) ? act.MailFrom : Reply;
            act.Subject         = Subject;
            act.IsIncome        = false;
            act.MPStatus        = MailStatusListAttribute.PreProcess;
            act.Format          = BodyFormat ?? EmailFormatListAttribute.Html;
            act.RefNoteID       = RefNoteID;
            act.ParentRefNoteID = ParentRefNoteID;
            act.ParentTaskID    = ParentTaskID;
            act.Owner           = Owner;
            act.IsBillable      = false;

            act.StartDate = PXTimeZoneInfo.Now;
            act.Subject   = Subject;
            act.Body      = BodyFormat == null || BodyFormat == EmailFormatListAttribute.Html
                                                ? CreateHtmlBody(Body)
                                                : CreateTextBody(Body);

            act.IsSystem = IsSystem;
            if (_attachments.Count > 0)
            {
                PXNoteAttribute.SetFileNotes(activityCache, act, _attachments.ToArray());
            }

            act = (EPActivity)activityCache.Update(act);

            return(act);
        }
Exemplo n.º 11
0
        private void SendCopyMessageToOutside(PXGraph graph, EPActivity message, IEnumerable <Mailbox> email)
        {
            var cache = graph.Caches[message.GetType()];
            var copy  = (EPActivity)cache.CreateCopy(message);

            copy.TaskID       = null;
            copy.IsIncome     = false;
            copy.ParentTaskID = message.TaskID;
            copy.MailTo       = ConcatAddresses(email);       //TODO: need add address description
            copy.MailCc       = null;
            copy.MailBcc      = null;
            copy.MPStatus     = MailStatusListAttribute.PreProcess;
            copy.ClassID      = CRActivityClass.Email;
            var imcUid = Guid.NewGuid();

            copy.ImcUID    = imcUid;
            copy.MessageId = GetType().Name + "_" + imcUid.ToString().Replace("-", string.Empty);
            copy.IsPrivate = message.IsPrivate;
            copy.Owner     = null;
            copy           = (EPActivity)cache.CreateCopy(cache.Insert(copy));
            //Update owner and reset owner if employee not found
            copy.Owner = message.Owner;
            try
            {
                cache.Update(copy);
            }
            catch (PXSetPropertyException)
            {
                copy.Owner = null;
                cache.Update(copy);
            }

            var noteFiles = PXNoteAttribute.GetFileNotes(cache, message);

            if (noteFiles != null)
            {
                PXNoteAttribute.SetFileNotes(cache, copy, noteFiles);
            }
        }
Exemplo n.º 12
0
        public virtual bool Bill(int?projectID, DateTime?invoiceDate)
        {
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, projectID);

            ContractBillingSchedule schedule = PXSelect <ContractBillingSchedule> .Search <ContractBillingSchedule.contractID>(this, project.ContractID);

            DateTime billingDate;

            if (invoiceDate == null)
            {
                if (schedule.Type == BillingType.OnDemand)
                {
                    billingDate = Accessinfo.BusinessDate ?? DateTime.Now;
                }
                else
                {
                    billingDate = schedule.NextDate.Value;
                }
            }
            else
            {
                billingDate = invoiceDate.Value;
            }

            Customer customer = null;

            if (project.CustomerID != null)
            {
                customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(this, project.CustomerID);
            }

            if (customer == null)
            {
                throw new PXException(Messages.NoCustomer);
            }

            List <BillingData> list          = new List <BillingData>();
            List <PMTran>      reversalTrans = new List <PMTran>();

            PXSelectBase <PMTask> selectTasks = new PXSelect <PMTask,
                                                              Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                                     And <PMTask.billingID, IsNotNull,
                                                                          And <PMTask.isActive, Equal <True> > > > >(this);

            foreach (PMTask task in selectTasks.Select(project.ContractID))
            {
                if ((task.BillingOption == PMBillingOption.OnTaskCompletion && task.IsCompleted == true) ||
                    (task.BillingOption == PMBillingOption.OnProjectCompetion && project.IsCompleted == true) ||
                    task.BillingOption == PMBillingOption.OnBilling)
                {
                    list.AddRange(BillTask(task, billingDate));
                    reversalTrans.AddRange(ReverseWipTask(task, billingDate));
                }
            }

            //Regroup by Invoices:
            Dictionary <string, List <BillingData> > invoices = new Dictionary <string, List <BillingData> >();
            string emptyInvoiceDescriptionKey = "!@#$%^&";

            foreach (BillingData data in list)
            {
                if (string.IsNullOrEmpty(data.Rule.InvoiceDescription))
                {
                    if (invoices.ContainsKey(emptyInvoiceDescriptionKey))
                    {
                        invoices[emptyInvoiceDescriptionKey].Add(data);
                    }
                    else
                    {
                        invoices.Add(emptyInvoiceDescriptionKey, new List <BillingData>(new BillingData[] { data }));
                    }
                }
                else
                {
                    if (invoices.ContainsKey(data.Rule.InvoiceDescription))
                    {
                        invoices[data.Rule.InvoiceDescription].Add(data);
                    }
                    else
                    {
                        invoices.Add(data.Rule.InvoiceDescription, new List <BillingData>(new BillingData[] { data }));
                    }
                }

                //Reverse On Billing:

                if (data.PMTran != null)
                {
                    bool reverseOnBilling = false;

                    if (data.PMTran.Reverse == PMReverse.OnBilling)
                    {
                        reverseOnBilling = true;
                    }
                    else if (data.PMTran.Reverse != PMReverse.Never && IsNonGL(data.PMTran))
                    {
                        reverseOnBilling = true;
                    }

                    if (reverseOnBilling)
                    {
                        reversalTrans.AddRange(ReverseTran(data.PMTran));
                    }
                }
            }


            //Schedule update:
            schedule.NextDate = GetNextBillingDate(this, schedule, schedule.NextDate);
            schedule.LastDate = this.Accessinfo.BusinessDate;
            BillingSchedule.Update(schedule);


            //ContractDetail update:
            PXSelectBase <ContractDetailExt> cis = new PXSelect <ContractDetailExt, Where <ContractDetailExt.contractID, Equal <Required <ContractDetailExt.contractID> >,
                                                                                           And <ContractDetailExt.resetUsage, Equal <ResetUsageOption.onBilling> > > >(this);

            foreach (ContractDetailExt ci in cis.Select(project.ContractID))
            {
                ci.Used = 0;
                ContractDetail.Update(ci);
            }

            List <ARRegister> doclist     = new List <ARRegister>();
            PMRegister        reversalDoc = null;

            if (invoices.Count > 0)
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    ARInvoiceEntry invoiceEntry = PXGraph.CreateInstance <ARInvoiceEntry>();
                    invoiceEntry.FieldVerifying.AddHandler <ARInvoice.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                    invoiceEntry.FieldVerifying.AddHandler <ARTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                    invoiceEntry.FieldVerifying.AddHandler <ARTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });

                    foreach (KeyValuePair <string, List <BillingData> > kv in invoices)
                    {
                        invoiceEntry.Clear(PXClearOption.ClearAll);

                        string    description = kv.Key == emptyInvoiceDescriptionKey ? null : kv.Key;
                        string    docDesc     = description ?? string.Format(PXMessages.LocalizeNoPrefix(CT.Messages.BillingFor), project.ContractCD, project.Description);
                        ARInvoice invoice     = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].CreateInstance();
                        invoice.DocType = GetDocType(kv.Value);
                        int mult = 1;
                        if (invoice.DocType == ARDocType.CreditMemo)
                        {
                            mult = -1;
                        }

                        invoice = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].Insert(invoice);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValueExt <ARInvoice.customerID>(invoice, customer.AcctCD);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.customerLocationID>(invoice, project.LocationID);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValueExt <ARInvoice.docDate>(invoice, billingDate);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.docDesc>(invoice, docDesc);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.projectID>(invoice, project.ContractID);

                        CurrencyInfo curyinfo = (CurrencyInfo)invoiceEntry.Caches[typeof(CurrencyInfo)].Current;
                        foreach (BillingData data in kv.Value)
                        {
                            data.Tran.ExtPrice = data.Tran.ExtPrice.GetValueOrDefault() * mult;
                            data.Tran.Qty      = data.Tran.Qty.GetValueOrDefault() * mult;
                            data.Tran.TranAmt  = data.Tran.TranAmt.GetValueOrDefault() * mult;

                            decimal curyamount;
                            PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, data.Tran.UnitPrice.GetValueOrDefault(), out curyamount);
                            data.Tran.CuryUnitPrice = curyamount;
                            PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, data.Tran.ExtPrice.GetValueOrDefault(), out curyamount);
                            data.Tran.CuryExtPrice     = curyamount;
                            data.Tran.CuryTranAmt      = data.Tran.CuryExtPrice;
                            data.Tran.FreezeManualDisc = true;
                            data.Tran.CuryInfoID       = curyinfo.CuryInfoID;
                            ARTran newTran = (ARTran)invoiceEntry.Caches[typeof(ARTran)].Insert(data.Tran);

                            if (data.Tran.TranAmt > newTran.TranAmt)
                            {
                                newTran.PMDeltaOption = ARTran.pMDeltaOption.CompleteLine;                                //autocomplete when currency descrepency exists.
                            }

                            if (data.Tran.AccountID != null)
                            {
                                ARTran copy = (ARTran)invoiceEntry.Caches[typeof(ARTran)].CreateCopy(newTran);
                                copy.AccountID = data.Tran.AccountID;

                                copy = (ARTran)invoiceEntry.Caches[typeof(ARTran)].Update(copy);

                                if (data.SubCD != null)
                                {
                                    invoiceEntry.Caches[typeof(ARTran)].SetValueExt <ARTran.subID>(copy, data.SubCD);
                                }
                            }

                            if (data.Note != null)
                            {
                                PXNoteAttribute.SetNote(invoiceEntry.Caches[typeof(ARTran)], newTran, data.Note);
                            }
                            if (data.Files != null && data.Files.Length > 0)
                            {
                                PXNoteAttribute.SetFileNotes(invoiceEntry.Caches[typeof(ARTran)], newTran, data.Files);
                            }


                            //item.RefLineNbr = newTran.LineNbr;
                        }

                        ARInvoice oldInvoice = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].CreateCopy(invoice);

                        invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                        invoiceEntry.Caches[typeof(ARInvoice)].RaiseRowUpdated(invoice, oldInvoice);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.curyOrigDocAmt>(invoice, invoice.CuryDocBal);

                        if (project.AutomaticReleaseAR == true)
                        {
                            invoiceEntry.Caches[typeof(ARInvoice)].SetValueExt <ARInvoice.hold>(invoice, false);
                        }

                        doclist.Add((ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].Current);
                        invoiceEntry.Save.Press();
                    }

                    Actions.PressSave();

                    if (reversalTrans.Count > 0)
                    {
                        RegisterEntry pmEntry = PXGraph.CreateInstance <RegisterEntry>();
                        pmEntry.FieldVerifying.AddHandler <PMTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });                    //Project can be completed.
                        pmEntry.FieldVerifying.AddHandler <PMTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });                       //Task can be completed.
                        pmEntry.FieldVerifying.AddHandler <PMTran.inventoryID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                        reversalDoc              = (PMRegister)pmEntry.Document.Cache.Insert();
                        reversalDoc.OrigDocType  = PMOrigDocType.AllocationReversal;
                        reversalDoc.Description  = "Allocation Reversal on Billing";
                        pmEntry.Document.Current = reversalDoc;

                        foreach (PMTran tran in reversalTrans)
                        {
                            pmEntry.Transactions.Insert(tran);
                        }
                        pmEntry.Save.Press();
                    }

                    ts.Complete();
                }
            }
            else
            {
                this.Persist(typeof(ContractBillingSchedule), PXDBOperation.Update);
                this.Persist(typeof(Contract), PXDBOperation.Update);
            }

            if (project.AutomaticReleaseAR == true)
            {
                try
                {
                    ARDocumentRelease.ReleaseDoc(doclist, false);
                }
                catch (Exception ex)
                {
                    throw new PXException(Messages.AutoReleaseARFailed, ex);
                }

                if (reversalDoc != null)
                {
                    try
                    {
                        RegisterRelease.Release(reversalDoc);
                    }
                    catch (Exception ex)
                    {
                        throw new PXException(Messages.AutoReleaseOfReversalFailed, ex);
                    }
                }
            }

            return(doclist.Count > 0);
        }
Exemplo n.º 13
0
        public virtual void GenerateProc(Schedule s, short Times, DateTime runDate)
        {
            string             LastBatchNbr = "0000000000";
            Int64              LastInfoID   = -1;
            List <ScheduleDet> sd           = MakeSchedule(s, Times, runDate);

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (ScheduleDet d in sd)
                {
                    foreach (BatchNew b in PXSelect <BatchNew, Where <BatchNew.scheduleID, Equal <Optional <Schedule.scheduleID> >, And <BatchNew.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID))
                    {
                        BatchNew copy = PXCache <BatchNew> .CreateCopy(b);

                        copy.OrigBatchNbr = copy.BatchNbr;
                        copy.OrigModule   = copy.Module;
                        copy.CuryInfoID   = null;
                        copy.NumberCode   = "GLREC";
                        copy.NoteID       = null;

                        CurrencyInfo info = (CurrencyInfo)PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(this, b.CuryInfoID);

                        if (info != null)
                        {
                            CurrencyInfo infocopy = PXCache <CurrencyInfo> .CreateCopy(info);

                            infocopy.CuryInfoID = LastInfoID;
                            copy.CuryInfoID     = LastInfoID;
                            CuryInfo_Created.Cache.Insert(infocopy);
                        }

                        copy.Posted    = false;
                        copy.Released  = false;
                        copy.Status    = "B";
                        copy.Scheduled = false;

                        copy.DateEntered  = d.ScheduledDate;
                        copy.FinPeriodID  = d.ScheduledPeriod;
                        copy.TranPeriodID = null;

                        copy.BatchNbr    = LastBatchNbr;
                        copy.RefBatchNbr = LastBatchNbr;
                        LastBatchNbr     = AutoNumberAttribute.NextNumber(LastBatchNbr);
                        LastInfoID--;

                        copy = (BatchNew)Batch_Created.Cache.Insert(copy);

                        CurrencyInfoAttribute.SetEffectiveDate <Batch.dateEntered>(Batch_Created.Cache, new PXFieldUpdatedEventArgs(copy, null, false));
                        PXNoteAttribute.SetNote(Batch_Created.Cache, copy, PXNoteAttribute.GetNote(Caches[typeof(BatchNew)], b));
                        PXNoteAttribute.SetFileNotes(Batch_Created.Cache, copy, PXNoteAttribute.GetFileNotes(Caches[typeof(BatchNew)], b));

                        foreach (GLTranNew tran in PXSelect <GLTranNew, Where <GLTranNew.module, Equal <Required <GLTranNew.module> >, And <GLTranNew.batchNbr, Equal <Required <GLTranNew.batchNbr> > > > > .Select(this, b.Module, b.BatchNbr))
                        {
                            GLTranNew trancopy = PXCache <GLTranNew> .CreateCopy(tran);

                            trancopy.OrigBatchNbr = trancopy.BatchNbr;
                            trancopy.OrigModule   = trancopy.Module;
                            trancopy.BatchNbr     = copy.BatchNbr;
                            trancopy.RefBatchNbr  = copy.RefBatchNbr;
                            trancopy.CuryInfoID   = copy.CuryInfoID;
                            trancopy.CATranID     = null;

                            trancopy.TranDate     = d.ScheduledDate;
                            trancopy.FinPeriodID  = d.ScheduledPeriod;
                            trancopy.TranPeriodID = d.ScheduledPeriod;
                            Tran_Created.Cache.Insert(trancopy);
                        }
                    }

                    s.LastRunDate = d.ScheduledDate;
                    Running_Schedule.Cache.Update(s);
                }
                Running_Schedule.Cache.Persist(PXDBOperation.Update);

                Batch_Created.Cache.Persist(PXDBOperation.Insert);
                Batch_Created.Cache.Persist(PXDBOperation.Update);

                foreach (GLTranNew tran in Tran_Created.Cache.Inserted)
                {
                    foreach (BatchNew batch in Batch_Created.Cache.Cached)
                    {
                        if (object.Equals(batch.RefBatchNbr, tran.RefBatchNbr))
                        {
                            tran.BatchNbr   = batch.BatchNbr;
                            tran.CuryInfoID = batch.CuryInfoID;
                            if (!string.IsNullOrEmpty(batch.RefNbr))
                            {
                                tran.RefNbr = batch.RefNbr;
                            }
                            break;
                        }
                    }
                }
                Tran_Created.Cache.Normalize();

                Tran_Created.Cache.Persist(PXDBOperation.Insert);
                Tran_Created.Cache.Persist(PXDBOperation.Update);
                Caches[typeof(CA.CADailySummary)].Persist(PXDBOperation.Insert);

                ts.Complete(this);
            }
            Running_Schedule.Cache.Persisted(false);
            Batch_Created.Cache.Persisted(false);
            Tran_Created.Cache.Persisted(false);
            Caches[typeof(CA.CADailySummary)].Persisted(false);
        }
Exemplo n.º 14
0
        public virtual void GenerateProc(Schedule s, short Times, DateTime runDate)
        {
            List <ScheduleDet> sd = GL.ScheduleProcess.MakeSchedule(this, s, Times, runDate);

            APInvoiceEntry docgraph = CreateGraph();

            foreach (ScheduleDet sdet in sd)
            {
                foreach (PXResult <APInvoice, Vendor, CurrencyInfo> res in PXSelectJoin <APInvoice, InnerJoin <Vendor, On <Vendor.bAccountID, Equal <APInvoice.vendorID> >, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <APInvoice.curyInfoID> > > >, Where <APInvoice.scheduleID, Equal <Required <APInvoice.scheduleID> >, And <APInvoice.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID))
                {
                    docgraph.Clear();
                    docgraph.vendor.Current = (Vendor)res;
                    APInvoice    apdoc = (APInvoice)res;
                    CurrencyInfo info  = (CurrencyInfo)res;

                    CurrencyInfo new_info = PXCache <CurrencyInfo> .CreateCopy(info);

                    new_info.CuryInfoID = null;
                    new_info            = docgraph.currencyinfo.Insert(new_info);

                    APInvoice new_apdoc = PXCache <APInvoice> .CreateCopy(apdoc);

                    new_apdoc.CuryInfoID          = new_info.CuryInfoID;
                    new_apdoc.DocDate             = sdet.ScheduledDate;
                    new_apdoc.FinPeriodID         = sdet.ScheduledPeriod;
                    new_apdoc.TranPeriodID        = null;
                    new_apdoc.DueDate             = null;
                    new_apdoc.DiscDate            = null;
                    new_apdoc.PayDate             = null;
                    new_apdoc.CuryOrigDiscAmt     = null;
                    new_apdoc.OrigDiscAmt         = null;
                    new_apdoc.RefNbr              = null;
                    new_apdoc.Scheduled           = false;
                    new_apdoc.CuryLineTotal       = 0m;
                    new_apdoc.CuryVatTaxableTotal = 0m;
                    new_apdoc.CuryVatExemptTotal  = 0m;
                    new_apdoc.NoteID              = null;
                    new_apdoc = docgraph.Document.Insert(new_apdoc);

                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    PXNoteAttribute.SetNote(docgraph.Document.Cache, new_apdoc, PXNoteAttribute.GetNote(Caches[typeof(APInvoice)], apdoc));
                    PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, new_apdoc, PXNoteAttribute.GetFileNotes(Caches[typeof(APInvoice)], apdoc));

                    foreach (APTran aptran in PXSelect <APTran, Where <APTran.tranType, Equal <Required <APTran.tranType> >, And <APTran.refNbr, Equal <Required <APTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        APTran new_aptran = PXCache <APTran> .CreateCopy(aptran);

                        new_aptran.RefNbr     = null;
                        new_aptran.CuryInfoID = null;
                        docgraph.Transactions.Insert(new_aptran);
                    }

                    foreach (APTaxTran tax in PXSelect <APTaxTran, Where <APTaxTran.tranType, Equal <Required <APTaxTran.tranType> >, And <APTaxTran.refNbr, Equal <Required <APTaxTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        APTaxTran new_aptax = new APTaxTran();
                        new_aptax.TaxID = tax.TaxID;

                        new_aptax = docgraph.Taxes.Insert(new_aptax);

                        if (new_aptax != null)
                        {
                            new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                            new_aptax.TaxRate        = tax.TaxRate;
                            new_aptax.CuryTaxableAmt = tax.CuryTaxableAmt;
                            new_aptax.CuryTaxAmt     = tax.CuryTaxAmt;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                    }
                    docgraph.Save.Press();
                }
                s.LastRunDate = sdet.ScheduledDate;
                Running_Schedule.Cache.Update(s);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }
            Running_Schedule.Cache.Persisted(false);
        }
Exemplo n.º 15
0
        protected virtual IEnumerable PrintFedexLabel(PXAdapter adapter)
        {
            var shiporder = Base.Document.Current;
            var carrier   = Carrier.PK.Find(Base, shiporder.ShipVia);

            if (!UseCarrierService(shiporder, carrier))
            {
                return(adapter.Get());
            }

            if (shiporder.ShippedViaCarrier != true)
            {
                // Build Fedex Request object
                ICarrierService cs            = CarrierMaint.CreateCarrierService(Base, shiporder.ShipVia);
                CarrierRequest  cr            = Base.CarrierRatesExt.BuildRequest(shiporder);
                var             warehouseInfo = SelectFrom <INSite> .Where <INSite.siteID.IsEqual <P.AsInt> > .View
                                                .Select(Base, shiporder.SiteID).RowCast <INSite>().FirstOrDefault();

                // Replace ShipTo Info to DCL warehouse
                Address warehouseAddress = PXSelect <Address, Where <Address.addressID, Equal <Required <Address.addressID> > > > .Select(Base, warehouseInfo?.AddressID);

                Contact warehouseContact = PXSelect <Contact, Where <Contact.contactID, Equal <Required <Contact.contactID> > > > .Select(Base, warehouseInfo?.ContactID);

                cr.Destination        = warehouseAddress;
                cr.DestinationContact = warehouseContact;

                if (cr.Packages.Count > 0)
                {
                    // Get Fedex web service data
                    CarrierResult <ShipResult> result = cs.Ship(cr);

                    if (result != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (Message message in result.Messages)
                        {
                            sb.AppendFormat("{0}:{1} ", message.Code, message.Description);
                        }

                        if (result.IsSuccess)
                        {
                            using (PXTransactionScope ts = new PXTransactionScope())
                            {
                                UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>();

                                foreach (PackageData pd in result.Result.Data)
                                {
                                    if (pd.Image != null)
                                    {
                                        string   fileName = string.Format("Label #{0}.{1}", pd.TrackingNumber, pd.Format);
                                        FileInfo file     = new FileInfo(fileName, null, pd.Image);
                                        try
                                        {
                                            upload.SaveFile(file);
                                        }
                                        catch (PXNotSupportedFileTypeException exc)
                                        {
                                            throw new PXException(exc, Messages.NotSupportedFileTypeFromCarrier, pd.Format);
                                        }
                                        PXNoteAttribute.SetFileNotes(Base.Document.Cache, Base.Document.Current, file.UID.Value);
                                    }
                                    Base.Document.UpdateCurrent();
                                }

                                Base.Save.Press();
                                ts.Complete();
                            }
                            //show warnings:
                            if (result.Messages.Count > 0)
                            {
                                Base.Document.Cache.RaiseExceptionHandling <SOShipment.curyFreightCost>(shiporder, shiporder.CuryFreightCost,
                                                                                                        new PXSetPropertyException(sb.ToString(), PXErrorLevel.Warning));
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(result.RequestData))
                            {
                                PXTrace.WriteError(result.RequestData);
                            }

                            Base.Document.Cache.RaiseExceptionHandling <SOShipment.curyFreightCost>(shiporder, shiporder.CuryFreightCost,
                                                                                                    new PXSetPropertyException(Messages.CarrierServiceError, PXErrorLevel.Error, sb.ToString()));

                            throw new PXException(Messages.CarrierServiceError, sb.ToString());
                        }
                    }
                }
            }

            return(adapter.Get());
        }
Exemplo n.º 16
0
        public static void ReleaseDoc(EPExpenseClaim claim)
        {
            APInvoiceEntry    docgraph     = PXGraph.CreateInstance <APInvoiceEntry>();
            ExpenseClaimEntry expenseclaim = PXGraph.CreateInstance <ExpenseClaimEntry>();

            if (claim.FinPeriodID == null)
            {
                throw new PXException(Messages.ReleaseClaimWithoutFinPeriod);
            }
            //docgraph.FieldVerifying.AddHandler<APInvoice.vendorLocationID>(APInterceptor);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            docgraph.vendor.Current   = employee;
            docgraph.location.Current = emplocation;

            CurrencyInfo infoOriginal = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

            CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy(infoOriginal);

            info.CuryInfoID = null;
            info            = docgraph.currencyinfo.Insert(info);
            APInvoice invoice = new APInvoice();

            invoice.CuryInfoID = info.CuryInfoID;

            invoice.Hold     = true;
            invoice.Released = false;
            invoice.Printed  = false;
            invoice.OpenDoc  = true;

            invoice.DocDate          = claim.DocDate;
            invoice.InvoiceNbr       = claim.RefNbr;
            invoice.DocDesc          = claim.DocDesc;
            invoice.VendorID         = claim.EmployeeID;
            invoice.CuryID           = info.CuryID;
            invoice.VendorLocationID = claim.LocationID;
            invoice.APAccountID      = emplocation != null ? emplocation.APAccountID : null;
            invoice.APSubID          = emplocation != null ? emplocation.APSubID : null;
            invoice.TaxZoneID        = claim.TaxZoneID;
            invoice = docgraph.Document.Insert(invoice);

            PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
            PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

            if (epsetup.CopyNotesAP == true)
            {
                string note = PXNoteAttribute.GetNote(claimcache, claim);
                if (note != null)
                {
                    PXNoteAttribute.SetNote(docgraph.Document.Cache, invoice, note);
                }
            }
            if (epsetup.CopyFilesAP == true)
            {
                Guid[] files = PXNoteAttribute.GetFileNotes(claimcache, claim);
                if (files != null && files.Length > 0)
                {
                    PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, invoice, files);
                }
            }

            using (PXConnectionScope cs = new PXConnectionScope())
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);

                    foreach (PXResult <EPExpenseClaimDetails, Contract> res in PXSelectJoin <EPExpenseClaimDetails,
                                                                                             LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID> > >,
                                                                                             Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                    {
                        EPExpenseClaimDetails claimdetail = (EPExpenseClaimDetails)res;
                        Contract contract = (Contract)res;

                        if (claimdetail.TaskID != null)
                        {
                            PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseclaim, claimdetail.TaskID);

                            if (task != null && !(bool)task.VisibleInAP)
                            {
                                throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                            }
                        }

                        APTran tran = new APTran();
                        tran.InventoryID  = claimdetail.InventoryID;
                        tran.TranDesc     = claimdetail.TranDesc;
                        tran.CuryUnitCost = claimdetail.CuryUnitCost;
                        tran.Qty          = claimdetail.Qty;
                        tran.UOM          = claimdetail.UOM;
                        tran.NonBillable  = claimdetail.Billable != true;
                        tran.CuryLineAmt  = claimdetail.CuryTranAmt;
                        tran.Date         = claimdetail.ExpenseDate;

                        if (contract.BaseType == PM.PMProject.ProjectBaseType.Project)
                        {
                            tran.ProjectID = claimdetail.ContractID;
                        }
                        else
                        {
                            tran.ProjectID = PM.ProjectDefaultAttribute.NonProject(docgraph);
                        }

                        tran.TaskID        = claimdetail.TaskID;
                        tran.AccountID     = claimdetail.ExpenseAccountID;
                        tran.SubID         = claimdetail.ExpenseSubID;
                        tran.TaxCategoryID = claimdetail.TaxCategoryID;
                        tran = docgraph.Transactions.Insert(tran);
                        if (epsetup.CopyNotesAP == true)
                        {
                            string note = PXNoteAttribute.GetNote(claimdetailcache, claimdetail);
                            if (note != null)
                            {
                                PXNoteAttribute.SetNote(docgraph.Transactions.Cache, tran, note);
                            }
                        }
                        if (epsetup.CopyFilesAP == true)
                        {
                            Guid[] files = PXNoteAttribute.GetFileNotes(claimdetailcache, claimdetail);
                            if (files != null && files.Length > 0)
                            {
                                PXNoteAttribute.SetFileNotes(docgraph.Transactions.Cache, tran, files);
                            }
                        }
                        claimdetail.Released = true;
                        expenseclaim.ExpenseClaimDetails.Update(claimdetail);
                    }

                    foreach (EPTaxTran tax in PXSelect <EPTaxTran, Where <EPTaxTran.refNbr, Equal <Required <EPTaxTran.refNbr> > > > .Select(docgraph, claim.RefNbr))
                    {
                        APTaxTran new_aptax = new APTaxTran();
                        new_aptax.TaxID = tax.TaxID;

                        new_aptax = docgraph.Taxes.Insert(new_aptax);

                        if (new_aptax != null)
                        {
                            new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                            new_aptax.TaxRate        = tax.TaxRate;
                            new_aptax.CuryTaxableAmt = tax.CuryTaxableAmt;
                            new_aptax.CuryTaxAmt     = tax.CuryTaxAmt;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                    }

                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    invoice.Hold           = false;
                    docgraph.Document.Update(invoice);
                    docgraph.Save.Press();
                    claim.Status    = EPClaimStatus.Released;
                    claim.Released  = true;
                    claim.APRefNbr  = invoice.RefNbr;
                    claim.APDocType = invoice.DocType;
                    expenseclaim.ExpenseClaim.Update(claim);

                    #region EP History Update
                    EPHistory hist = new EPHistory();
                    hist.EmployeeID  = invoice.VendorID;
                    hist.FinPeriodID = invoice.FinPeriodID;
                    hist             = (EPHistory)expenseclaim.Caches[typeof(EPHistory)].Insert(hist);

                    hist.FinPtdClaimed += invoice.DocBal;
                    hist.FinYtdClaimed += invoice.DocBal;
                    if (invoice.FinPeriodID == invoice.TranPeriodID)
                    {
                        hist.TranPtdClaimed += invoice.DocBal;
                        hist.TranYtdClaimed += invoice.DocBal;
                    }
                    else
                    {
                        EPHistory tranhist = new EPHistory();
                        tranhist.EmployeeID      = invoice.VendorID;
                        tranhist.FinPeriodID     = invoice.TranPeriodID;
                        tranhist                 = (EPHistory)expenseclaim.Caches[typeof(EPHistory)].Insert(tranhist);
                        tranhist.TranPtdClaimed += invoice.DocBal;
                        tranhist.TranYtdClaimed += invoice.DocBal;
                    }
                    expenseclaim.Views.Caches.Add(typeof(EPHistory));
                    #endregion

                    expenseclaim.Save.Press();

                    ts.Complete();
                }
            }
            if ((bool)epsetup.AutomaticReleaseAP == true)
            {
                List <APRegister> doclist = new List <APRegister>();
                doclist.Add(docgraph.Document.Current);
                APDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Exemplo n.º 17
0
        public override void Persist()
        {
            // Current Data
            var _currData = (LumItemsCOC)_viewLine.Cache.Current;
            // Create Upload Image Graph
            UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>();
            // Html to Image and Upload to Server
            Action <string, string> htmlToImage = (_html, _fileName) =>
            {
                HtmlDocument _doc = new HtmlDocument();
                _doc.LoadHtml(_html);
                if (string.IsNullOrEmpty(_doc.DocumentNode.InnerText))
                {
                    return;
                }
                var      htmlNode = _doc.DocumentNode.SelectSingleNode("//html");
                HtmlNode newNode  = HtmlNode.CreateNode(@"<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />");
                htmlNode.InsertBefore(newNode, htmlNode.ChildNodes[0]);
                var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter();
                var jpegBytes       = htmlToImageConv.GenerateImage(_doc.DocumentNode.OuterHtml, NReco.ImageGenerator.ImageFormat.Jpeg);

                FileInfo file = new FileInfo($"{_fileName}.jpeg", null, jpegBytes);
                upload.SaveFile(file, FileExistsAction.CreateVersion);

                //To Attach file to Entity
                PXNoteAttribute.SetFileNotes(_viewLine.Cache, _viewLine.Cache.Current, file.UID.Value);
            };

            // Process All Tab


            #region MaterialProductDesc

            if (!CheckInnerTextIsEmpty(_currData.MaterialProductDesc))
            {
                htmlToImage(_currData.MaterialProductDesc, $"COC_{_currData.InventoryID}_MaterialProductDesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.materialProductDesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            #region MaterialProductDesc2
            if (!CheckInnerTextIsEmpty(_currData.MaterialProductDesc2))
            {
                htmlToImage(_currData.MaterialProductDesc2, $"COC_{_currData.InventoryID}_MaterialProductDesc2");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.materialProductDesc2>(_viewLine.Cache.Current, null);
            }
            #endregion ;

            #region COCProductDesc
            if (!CheckInnerTextIsEmpty(_currData.COCProductDesc))
            {
                htmlToImage(_currData.COCProductDesc, $"COC_{_currData.InventoryID}_COCProductDesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.cOCProductDesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            #region TESTProductDesc

            if (!CheckInnerTextIsEmpty(_currData.TESTProductDesc))
            {
                htmlToImage(_currData.TESTProductDesc, $"COC_{_currData.InventoryID}_TESTProductDesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.tESTProductDesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            #region REROHSProductDesc

            if (!CheckInnerTextIsEmpty(_currData.REROHSProductDesc))
            {
                htmlToImage(_currData.REROHSProductDesc, $"COC_{_currData.InventoryID}_REROHSProductDesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.rEROHSProductDesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            #region REACHProductDesc
            if (!CheckInnerTextIsEmpty(_currData.REACHProductDesc))
            {
                htmlToImage(_currData.REACHProductDesc, $"COC_{_currData.InventoryID}_REACHProductDesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.rEACHProductDesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            #region REACHProductDesc2
            if (!CheckInnerTextIsEmpty(_currData.REACHProductDesc2))
            {
                htmlToImage(_currData.REACHProductDesc2, $"COC_{_currData.InventoryID}_REACHProductDesc2");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.rEACHProductDesc2>(_viewLine.Cache.Current, null);
            }

            #endregion

            #region Compliantproductdesc
            if (!CheckInnerTextIsEmpty(_currData.Compliantproductdesc))
            {
                htmlToImage(_currData.Compliantproductdesc, $"COC_{_currData.InventoryID}_Compliantproductdesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.compliantproductdesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            #region QCProductDesc
            if (!CheckInnerTextIsEmpty(_currData.QCProductDesc))
            {
                htmlToImage(_currData.QCProductDesc, $"COC_{_currData.InventoryID}_QCProductDesc");
            }
            else
            {
                _viewLine.Cache.SetValue <LumItemsCOC.qCProductDesc>(_viewLine.Cache.Current, null);
            }
            #endregion

            base.Persist();
        }
Exemplo n.º 18
0
        protected CRSMEmail CreateMessage(bool isTemplate)
        {
            var activityCache = Graph.Caches[typeof(CRSMEmail)];
            var act           = (CRSMEmail)activityCache.Insert();

            //CRActivity
            act.ClassID    = CRActivityClass.Email;
            act.Type       = null;
            act.OwnerID    = Owner;
            act.StartDate  = PXTimeZoneInfo.Now;
            act.BAccountID = BAccountID;
            if (act.ContactID == null)
            {
                act.ContactID = ContactID;
            }
            act.RefNoteID      = RefNoteID;
            act.DocumentNoteID = DocumentNoteID;
            act.ParentNoteID   = ParentNoteID;

            //SMEmail
            var accountId = MailAccountId ?? MailAccountManager.DefaultMailAccountID;

            act.MailAccountID = accountId;

            var account = (EMailAccount)PXSelect <EMailAccount,
                                                  Where <EMailAccount.emailAccountID, Equal <Required <EMailAccount.emailAccountID> > > > .
                          Select(_graph, accountId);

            if (account != null)
            {
                if (account.SenderDisplayNameSource == SenderDisplayNameSourceAttribute.Account)
                {
                    act.MailFrom = string.IsNullOrEmpty(account.AccountDisplayName)
                                                ? account.Address
                                                : new MailAddress(account.Address, account.AccountDisplayName).ToString();
                }
                else
                {
                    act.MailFrom = $"{TextUtils.QuoteString(account.Description)} <{account.Address}>";
                }
            }

            if (!isTemplate)
            {
                act.MailTo    = MergeAddressList(act, To, act.MailTo);
                act.MailCc    = MergeAddressList(act, Cc, act.MailCc);
                act.MailBcc   = MergeAddressList(act, Bcc, act.MailBcc);
                act.MailReply = string.IsNullOrEmpty(Reply) ? act.MailFrom : Reply;
                act.Subject   = Subject;
                act.Body      = BodyFormat == null || BodyFormat == EmailFormatListAttribute.Html
                ? CreateHtmlBody(Body)
                : CreateTextBody(Body);
            }

            act.IsIncome = false;
            act.MPStatus = MailStatusListAttribute.PreProcess;
            act.Format   = BodyFormat ?? EmailFormatListAttribute.Html;

            if (AttachmentsID != null)
            {
                foreach (NoteDoc doc in
                         PXSelect <NoteDoc, Where <NoteDoc.noteID, Equal <Required <NoteDoc.noteID> > > > .Select(Graph, AttachmentsID))
                {
                    if (doc.FileID != null && !_attachmentLinks.Contains(doc.FileID.Value))
                    {
                        _attachmentLinks.Add(doc.FileID.Value);
                    }
                }
            }

            if (_attachmentLinks.Count > 0)
            {
                PXNoteAttribute.SetFileNotes(activityCache, act, _attachmentLinks.ToArray());
            }

            act = (CRSMEmail)activityCache.Update(act);

            return(act);
        }
Exemplo n.º 19
0
        public virtual void GenerateProc(Schedule s, short Times, DateTime runDate)
        {
            List <ScheduleDet> sd = GL.ScheduleProcess.MakeSchedule(this, s, Times, runDate);

            ARInvoiceEntry docgraph = CreateGraph();

            foreach (ScheduleDet sdet in sd)
            {
                foreach (PXResult <ARInvoice, Customer, CurrencyInfo> res in PXSelectJoin <ARInvoice, InnerJoin <Customer, On <Customer.bAccountID, Equal <ARInvoice.customerID> >, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <ARInvoice.curyInfoID> > > >, Where <ARInvoice.scheduleID, Equal <Required <ARInvoice.scheduleID> >, And <ARInvoice.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID))
                {
                    docgraph.Clear();
                    docgraph.customer.Current = (Customer)res;
                    ARInvoice    apdoc = (ARInvoice)res;
                    CurrencyInfo info  = (CurrencyInfo)res;

                    CurrencyInfo new_info = PXCache <CurrencyInfo> .CreateCopy(info);

                    new_info.CuryInfoID = null;
                    new_info            = docgraph.currencyinfo.Insert(new_info);

                    ARInvoice new_ardoc = PXCache <ARInvoice> .CreateCopy(apdoc);

                    new_ardoc.CuryInfoID          = new_info.CuryInfoID;
                    new_ardoc.DocDate             = sdet.ScheduledDate;
                    new_ardoc.FinPeriodID         = sdet.ScheduledPeriod;
                    new_ardoc.TranPeriodID        = null;
                    new_ardoc.DueDate             = null;
                    new_ardoc.DiscDate            = null;
                    new_ardoc.CuryOrigDiscAmt     = null;
                    new_ardoc.OrigDiscAmt         = null;
                    new_ardoc.RefNbr              = null;
                    new_ardoc.Scheduled           = false;
                    new_ardoc.CuryLineTotal       = 0m;
                    new_ardoc.CuryVatTaxableTotal = 0m;
                    new_ardoc.CuryVatExemptTotal  = 0m;
                    new_ardoc.NoteID              = null;
                    bool forceClear = false;
                    bool clearPM    = false;
                    if (new_ardoc.PMInstanceID.HasValue)
                    {
                        PXResult <CustomerPaymentMethod, CA.PaymentMethod> pmiResult = (PXResult <CustomerPaymentMethod, CA.PaymentMethod>) PXSelectJoin <CustomerPaymentMethod, InnerJoin <CA.PaymentMethod, On <CA.PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >, Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .Select(docgraph, new_ardoc.PMInstanceID);

                        if (pmiResult != null)
                        {
                            CustomerPaymentMethod pmInstance    = pmiResult;
                            CA.PaymentMethod      paymentMethod = pmiResult;
                            if (pmInstance == null || pmInstance.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                            {
                                clearPM    = true;
                                forceClear = true;
                            }
                        }
                        else
                        {
                            clearPM    = true;
                            forceClear = true;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(new_ardoc.PaymentMethodID) == false)
                        {
                            CA.PaymentMethod pm = PXSelect <CA.PaymentMethod, Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > > .Select(docgraph, new_ardoc.PaymentMethodID);

                            if (pm == null || pm.IsActive != true || pm.UseForAR != true)
                            {
                                clearPM    = true;
                                forceClear = true;
                            }
                        }
                    }

                    if (clearPM)
                    {
                        new_ardoc.PMInstanceID    = null;
                        new_ardoc.PaymentMethodID = null;
                        new_ardoc.CashAccountID   = null;
                    }

                    new_ardoc = docgraph.Document.Insert(new_ardoc);

                    //force creditrule back
                    docgraph.customer.Current = (Customer)res;

                    if (forceClear == true)
                    {
                        ARInvoice copy = PXCache <ARInvoice> .CreateCopy(new_ardoc);

                        copy.PMInstanceID    = null;
                        copy.PaymentMethodID = null;
                        copy.CashAccountID   = null;
                        new_ardoc            = docgraph.Document.Update(copy);
                    }
                    AddressAttribute.CopyRecord <ARInvoice.billAddressID>(docgraph.Document.Cache, new_ardoc, apdoc, false);
                    ContactAttribute.CopyRecord <ARInvoice.billContactID>(docgraph.Document.Cache, new_ardoc, apdoc, false);

                    TaxAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    PXNoteAttribute.SetNote(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetNote(Caches[typeof(ARInvoice)], apdoc));
                    PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetFileNotes(Caches[typeof(ARInvoice)], apdoc));

                    foreach (ARTran aptran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >, And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        ARTran new_aptran = PXCache <ARTran> .CreateCopy(aptran);

                        new_aptran.RefNbr     = null;
                        new_aptran.CuryInfoID = null;
                        docgraph.Transactions.Insert(new_aptran);
                    }

                    foreach (ARTaxTran tax in PXSelect <ARTaxTran, Where <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >, And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        ARTaxTran new_artax = new ARTaxTran();
                        new_artax.TaxID = tax.TaxID;

                        new_artax = docgraph.Taxes.Insert(new_artax);

                        if (new_artax != null)
                        {
                            new_artax = PXCache <ARTaxTran> .CreateCopy(new_artax);

                            new_artax.TaxRate        = tax.TaxRate;
                            new_artax.CuryTaxableAmt = tax.CuryTaxableAmt;
                            new_artax.CuryTaxAmt     = tax.CuryTaxAmt;
                            new_artax = docgraph.Taxes.Update(new_artax);
                        }
                    }

                    docgraph.Save.Press();
                }
                s.LastRunDate = sdet.ScheduledDate;
                Running_Schedule.Cache.Update(s);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }
            Running_Schedule.Cache.Persisted(false);
        }
Exemplo n.º 20
0
        protected virtual IEnumerable LumGenerate3PLUKFile(PXAdapter adapter, [PXDate] DateTime?shipDate, [PXInt] int?siteID, [SOOperation.List] string operation)
        {
            try
            {
                // Create SOShipment Graph
                var graph   = PXGraph.CreateInstance <SOShipmentEntry>();
                var soOrder = adapter.Get <SOOrder>().FirstOrDefault();
                using (PXTransactionScope sc = new PXTransactionScope())
                {
                    // FBM wont create Shipment, only upload file to FTP
                    if (soOrder.OrderType == "FM")
                    {
                        // Combine csv data
                        var result = graph.GetExtension <SOShipmentEntryExt>().CombineCSVForFBM(soOrder, "P3PL");
                        // Upload Graph
                        UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>();
                        // Create SM.FileInfo
                        var      fileName = $"{soOrder.OrderNbr}.csv";
                        var      data     = new UTF8Encoding(true).GetBytes(result.csvText.ToString());
                        FileInfo fi       = new FileInfo(fileName, null, data);

                        // upload file to FTP
                        #region 3PL UK FTP
                        var configYusen = SelectFrom <LUM3PLUKSetup> .View.Select(Base).RowCast <LUM3PLUKSetup>().FirstOrDefault();

                        FTP_Config config = new FTP_Config()
                        {
                            FtpHost = configYusen.FtpHost,
                            FtpUser = configYusen.FtpUser,
                            FtpPass = configYusen.FtpPass,
                            FtpPort = configYusen.FtpPort,
                            FtpPath = configYusen.FtpPath
                        };

                        var ftpResult = graph.GetExtension <SOShipmentEntryExt>().UploadFileByFTP(config, fileName, data);
                        //var ftpResult = true;
                        if (!ftpResult)
                        {
                            throw new Exception("Ftp Upload Fail!!");
                        }
                        #endregion

                        // upload file to Attachment
                        upload.SaveFile(fi);
                        PXNoteAttribute.SetFileNotes(Base.Document.Cache, Base.Document.Current, fi.UID.Value);
                        Base.Save.Press();
                        PXProcessing.SetProcessed();
                    }
                    else
                    {
                        // Create Shipment
                        Base.CreateShipmentIssue(adapter, shipDate, siteID);
                        if (PXProcessing <SOOrder> .GetItemMessage().ErrorLevel != PXErrorLevel.RowInfo)
                        {
                            return(null);
                        }

                        // Find SOShipment
                        var _soOrderShipment =
                            FbqlSelect <SelectFromBase <SOOrderShipment, TypeArrayOf <IFbqlJoin> .Empty> .Where <BqlChainableConditionBase <TypeArrayOf <IBqlBinary> .FilledWith <And <Compare <SOOrderShipment.orderType, Equal <P.AsString> > > > > .And <BqlOperand <SOOrderShipment.orderNbr, IBqlString> .IsEqual <P.AsString> > >, SOOrderShipment> .View.Select(Base, soOrder.OrderType, soOrder.OrderNbr)
                            .RowCast <SOOrderShipment>().FirstOrDefault();

                        // Create new Adapter
                        var newAdapter = new PXAdapter(graph.Document)
                        {
                            Searches = new Object[] { _soOrderShipment.ShipmentNbr }
                        };
                        // Generate UK csv file and upload to FTP
                        graph.GetExtension <SOShipmentEntryExt>().lumGenerate3PLUKFile.PressButton(newAdapter);
                        // Remove Hold
                        graph.releaseFromHold.PressButton(newAdapter);
                    }
                    if (PXProcessing <SOOrder> .GetItemMessage().ErrorLevel == PXErrorLevel.RowInfo)
                    {
                        sc.Complete();
                    }
                }
            }
            catch (Exception ex)
            {
                PXProcessing.SetError <SOOrder>(ex.Message);
            }
            return(adapter.Get());
        }