public void CopyPOLineFields(POFixedDemand demand, POLine line)
        {
            PXResult <FSSODetSplit, FSSODet> fsSODetSplitDetRow =
                (PXResult <FSSODetSplit, FSSODet>) PXSelectJoin <FSSODetSplit,
                                                                 InnerJoin <FSSODet,
                                                                            On <FSSODet.lineNbr, Equal <FSSODetSplit.lineNbr>,
                                                                                And <FSSODet.srvOrdType, Equal <FSSODetSplit.srvOrdType>,
                                                                                     And <FSSODet.refNbr, Equal <FSSODetSplit.refNbr> > > > >,
                                                                 Where <FSSODetSplit.planID, Equal <Required <FSSODetSplit.planID> > > >
                .Select(Base, demand.PlanID);

            if (fsSODetSplitDetRow != null)
            {
                FSSODet fsSODetRow = (FSSODet)fsSODetSplitDetRow;

                if (POSetupRecord.Current != null)
                {
                    if (POSetupRecord.Current.CopyLineNotesFromServiceOrder == true ||
                        POSetupRecord.Current.CopyLineAttachmentsFromServiceOrder == true)
                    {
                        var fsSODetCache = new PXCache <FSSODet>(Base);
                        fsSODetCache.Update(fsSODetRow);

                        PXNoteAttribute.CopyNoteAndFiles(fsSODetCache,
                                                         fsSODetRow,
                                                         Base.Transactions.Cache,
                                                         line,
                                                         POSetupRecord.Current.CopyLineNotesFromServiceOrder == true,
                                                         POSetupRecord.Current.CopyLineAttachmentsFromServiceOrder == true);
                    }
                }

                line.TranDesc = fsSODetRow.TranDesc;
            }
        }
Esempio n. 2
0
        protected virtual void InsertARTran(ARInvoiceEntry arGraph, EPExpenseClaimDetails row, decimal signOperation)
        {
            CurrencyInfo curyInfo = PXSelect <CurrencyInfo> .Search <CurrencyInfo.curyInfoID>(arGraph, row.CuryInfoID);

            decimal curyamount;

            if (arGraph.currencyinfo.Current != null && curyInfo != null && arGraph.currencyinfo.Current.CuryID == curyInfo.CuryID)
            {
                curyamount = row.CuryTranAmt.GetValueOrDefault(0);
            }
            else
            {
                CM.PXCurrencyAttribute.CuryConvCury(arGraph.Document.Cache, arGraph.currencyinfo, row.TranAmt.GetValueOrDefault(), out curyamount);
            }

            ARTran tran = arGraph.Transactions.Insert();

            tran.InventoryID   = row.InventoryID;
            tran.TranDesc      = row.TranDesc;
            tran.Qty           = row.Qty * signOperation;
            tran.UOM           = row.UOM;
            tran.AccountID     = row.SalesAccountID;
            tran.SubID         = row.SalesSubID;
            tran.Date          = row.ExpenseDate;
            tran.CuryTranAmt   = curyamount * signOperation;
            tran.CuryUnitPrice = (curyamount / (row.Qty.GetValueOrDefault(1m) != 0m ? row.Qty.GetValueOrDefault(1m) : 1m)) * signOperation;
            tran.CuryExtPrice  = curyamount * signOperation;
            tran = arGraph.Transactions.Update(tran);

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], row, arGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.ar>());
        }
Esempio n. 3
0
        public virtual IEnumerable createAP(PXAdapter adapter)
        {
            UploadFileRevision file = PXSelectJoin <UploadFileRevision,
                                                    InnerJoin <UploadFile,
                                                               On <UploadFileRevision.fileID, Equal <UploadFile.fileID>,
                                                                   And <UploadFileRevision.fileRevisionID, Equal <UploadFile.lastRevisionID> > >,
                                                               InnerJoin <NoteDoc,
                                                                          On <NoteDoc.fileID, Equal <UploadFile.fileID> > > >,
                                                    Where <NoteDoc.noteID, Equal <Required <CRSMEmail.noteID> >,
                                                           And <UploadFile.name, Like <pdfExtension> > >,
                                                    OrderBy <Desc <UploadFileRevision.createdDateTime> > > .Select(Base, Base.Emails.Current.NoteID);

            string url = null;

            if (file != null)
            {
                string rooturl;

                if (HttpContext.Current == null)
                {
                    rooturl = string.Empty;
                }

                var applicationpath = string.IsNullOrEmpty(HttpContext.Current.Request.ApplicationPath)
                                        ? string.Empty
                                        : HttpContext.Current.Request.ApplicationPath + "/";
                rooturl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + applicationpath;

                url = string.Concat(rooturl != null ? rooturl : string.Empty, HandlerURL, file.FileID.GetValueOrDefault(Guid.Empty).ToString("D"));

                CRSMEmail email = Base.Emails.Current;

                APInvoiceEntryPXInhExt graph = PXGraph.CreateInstance <APInvoiceEntryPXInhExt>();
                graph.Clear();
                APInvoice doc = (APInvoice)graph.Document.Cache.CreateInstance();
                doc.GetExtension <APInvoiceExt>().UsrFileURL = url;
                doc.LineCntr = 0;
                TryFillValuesFromPDF(graph.Document.Cache, doc, Base.Emails.Cache, email);
                doc = graph.Document.Insert(doc);

                (email).Selected = false;
                CRSMEmail copy = PXCache <CRSMEmail> .CreateCopy(email);

                CRActivity newActivity = (CRActivity)graph.Caches[typeof(CRActivity)].Insert();

                copy.BAccountID = newActivity.BAccountID;
                copy.ContactID  = newActivity.ContactID;
                copy.RefNoteID  = newActivity.RefNoteID;
                copy.MPStatus   = MailStatusListAttribute.Processed;
                copy.Exception  = null;
                PXRefNoteSelectorAttribute.EnsureNotePersistence(Base, Base.entityFilter.Current.Type, Base.entityFilter.Current.RefNoteID);
                copy = Base.Emails.Update(copy);
                Base.Save.Press();

                PXNoteAttribute.CopyNoteAndFiles(Base.Emails.Cache, Base.Emails.Current, graph.Document.Cache, doc);
                PXRedirectHelper.TryRedirect(graph, PXRedirectHelper.WindowMode.NewWindow);
            }
            return(adapter.Get());
        }
        protected virtual PMTran InsertPMTran(RegisterEntry pmGraph, PXResult <EPExpenseClaimDetails, Contract, Account> res)
        {
            EPExpenseClaimDetails detail = res;
            Contract contract            = res;
            Account  account             = res;

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

            bool released = contract.BaseType == CTPRType.Contract;             //contract trans are created as released

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

            tran.AccountGroupID   = account.AccountGroupID;
            tran.BAccountID       = detail.CustomerID;
            tran.LocationID       = detail.CustomerLocationID;
            tran.ProjectID        = detail.ContractID;
            tran.TaskID           = detail.TaskID;
            tran.CostCodeID       = detail.CostCodeID;
            tran.InventoryID      = detail.InventoryID;
            tran.Qty              = detail.Qty;
            tran.Billable         = true;
            tran.BillableQty      = detail.Qty;
            tran.UOM              = detail.UOM;
            tran.TranCuryID       = detail.CuryID;
            tran.BaseCuryInfoID   = detail.CuryInfoID;
            tran.TranCuryAmount   = detail.ClaimCuryTranAmt;
            tran.Amount           = detail.ClaimTranAmt;
            tran.TranCuryUnitRate = detail.CuryUnitCost;
            tran.UnitRate         = detail.UnitCost;

            //TODO: Review the following code (exists only to support MA302 case when UnitCost is not entered):
            if (detail.CuryUnitCost == 0m && detail.Qty != 0)
            {
                tran.TranCuryUnitRate = detail.ClaimCuryTranAmt / detail.Qty;
                tran.UnitRate         = detail.ClaimTranAmt / detail.Qty;
            }
            tran.AccountID  = detail.ExpenseAccountID;
            tran.SubID      = detail.ExpenseSubID;
            tran.StartDate  = detail.ExpenseDate;
            tran.EndDate    = detail.ExpenseDate;
            tran.Date       = detail.ExpenseDate;
            tran.ResourceID = detail.EmployeeID;
            tran.Released   = released;

            tran = pmGraph.Transactions.Update(tran);

            pmGraph.Document.Current.Released = released;
            if (released)
            {
                pmGraph.Document.Current.Status = PMRegister.status.Released;
            }

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], detail, pmGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.pm>());

            return(tran);
        }
Esempio n. 5
0
        protected virtual PMTran InsertPMTran(RegisterEntry pmGraph, PXResult <EPExpenseClaimDetails, Contract, Account> res)
        {
            EPExpenseClaimDetails detail = res;
            Contract contract            = res;
            Account  account             = res;

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

            bool released = contract.BaseType == Contract.ContractBaseType.Contract;             //contract trans are created as released

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

            tran.AccountGroupID = account.AccountGroupID;
            tran.BAccountID     = detail.CustomerID;
            tran.LocationID     = detail.CustomerLocationID;
            tran.ProjectID      = detail.ContractID;
            tran.TaskID         = detail.TaskID;
            tran.InventoryID    = detail.InventoryID;
            tran.Qty            = detail.Qty;
            tran.Billable       = true;
            tran.BillableQty    = detail.Qty;
            tran.UOM            = detail.UOM;
            if (detail.CuryInfoID == detail.ClaimCuryInfoID && detail.EmployeePart == 0m)
            {
                tran.UnitRate = detail.UnitCost;
            }
            else
            {
                tran.UnitRate = detail.ClaimTranAmt / detail.Qty;
            }
            tran.Amount     = detail.ClaimTranAmt;
            tran.AccountID  = detail.ExpenseAccountID;
            tran.SubID      = detail.ExpenseSubID;
            tran.StartDate  = detail.ExpenseDate;
            tran.EndDate    = detail.ExpenseDate;
            tran.Date       = detail.ExpenseDate;
            tran.ResourceID = detail.EmployeeID;
            tran.Released   = released;

            tran = pmGraph.Transactions.Update(tran);

            pmGraph.Document.Current.Released = released;

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], detail, pmGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.pm>());

            return(tran);
        }
        private void CloneServices(AppointmentEntry sourceAppointmentGraph, AppointmentEntry newAppointmentGraph, FSAppointment newAppointmentRow)
        {
            foreach (FSAppointmentDetService sourceRow in sourceAppointmentGraph.AppointmentDetServices.Select())
            {
                FSSODet fsSODetRow = ServiceOrderCore.GetSODetFromAppointmentDet(sourceAppointmentGraph, sourceRow);

                if (fsSODetRow != null &&
                    (fsSODetRow.Status == ID.Status_AppointmentDet.CANCELED ||
                     fsSODetRow.Status == ID.Status_AppointmentDet.COMPLETED))
                {
                    continue;
                }

                FSAppointmentDetService newRow = PXCache <FSAppointmentDetService> .CreateCopy(sourceRow);

                newRow.ActualDuration      = 0;
                newRow.ActualDateTimeBegin = null;
                newRow.ActualDateTimeEnd   = null;
                newRow.Qty = 0;

                newRow = AppointmentEntry.InsertServicePartLine <FSAppointmentDetService, FSAppointmentDetService>(
                    newAppointmentGraph.AppointmentDetServices.Cache,
                    newRow,
                    sourceAppointmentGraph.AppointmentDetServices.Cache,
                    sourceRow,
                    null,
                    sourceRow.SODetID,
                    copyTranDate: false,
                    tranDate: sourceRow.TranDate,
                    SetValuesAfterAssigningSODetID: true,
                    copyingFromQuote: false);

                PXNoteAttribute.CopyNoteAndFiles(
                    sourceAppointmentGraph.AppointmentDetServices.Cache,
                    sourceRow,
                    newAppointmentGraph.AppointmentDetServices.Cache,
                    newRow,
                    copyNotes: true,
                    copyFiles: false);


                newAppointmentGraph.AppointmentDetServices.SetValueExt <FSAppointmentDetService.acctID>(newRow, sourceRow.AcctID);
                newAppointmentGraph.AppointmentDetServices.SetValueExt <FSAppointmentDetService.subID>(newRow, sourceRow.SubID);

                AppointmentCore.UpdateAppointmentsInfoInServiceOrder(newAppointmentGraph.AppointmentDetServices.Cache, newRow, ServiceOrderRelated);
            }
        }
        protected virtual void InsertDetails(ARInvoiceEntry invoiceEntry, ARInvoice scheduledInvoice, ARInvoice newInvoice)
        {
            foreach (ARTran originalLine in PXSelect <
                         ARTran,
                         Where <
                             ARTran.tranType, Equal <Required <ARTran.tranType> >,
                             And <ARTran.refNbr, Equal <Required <ARTran.refNbr> >,
                                  And <Where <
                                           ARTran.lineType, IsNull,
                                           Or <ARTran.lineType, NotEqual <SOLineType.discount> > > > > > >
                     .Select(invoiceEntry, scheduledInvoice.DocType, scheduledInvoice.RefNbr))
            {
                ARTran newLine = PXCache <ARTran> .CreateCopy(originalLine);

                newLine.FinPeriodID  = null;
                newLine.TranPeriodID = null;
                newLine.RefNbr       = null;
                newLine.CuryInfoID   = null;
                newLine.ManualPrice  = true;
                newLine.ManualDisc   = true;
                newLine.NoteID       = null;

                newLine = invoiceEntry.Transactions.Insert(newLine);

                PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(ARTran)], originalLine, invoiceEntry.Transactions.Cache, newLine);
            }

            foreach (ARInvoiceDiscountDetail originalDiscountDetail in PXSelect <
                         ARInvoiceDiscountDetail,
                         Where <
                             ARInvoiceDiscountDetail.docType, Equal <Required <ARInvoiceDiscountDetail.docType> >,
                             And <ARInvoiceDiscountDetail.refNbr, Equal <Required <ARInvoiceDiscountDetail.refNbr> > > > >
                     .Select(invoiceEntry, scheduledInvoice.DocType, scheduledInvoice.RefNbr))
            {
                ARInvoiceDiscountDetail newDiscountDetail =
                    PXCache <ARInvoiceDiscountDetail> .CreateCopy(originalDiscountDetail);

                newDiscountDetail.RefNbr     = null;
                newDiscountDetail.CuryInfoID = null;
                newDiscountDetail.IsManual   = true;

                DiscountEngineProvider.GetEngineFor <ARTran, ARInvoiceDiscountDetail>().InsertDiscountDetail(invoiceEntry.ARDiscountDetails.Cache, invoiceEntry.ARDiscountDetails, newDiscountDetail);
            }
        }
        private void CloneAttendees(AppointmentEntry graphOriginalAppointment, AppointmentEntry graphNewAppointment, FSAppointment newFSAppointmentRow)
        {
            foreach (FSAppointmentAttendee originalAppointmentAttendee in graphOriginalAppointment.AppointmentAttendees.Select())
            {
                FSAppointmentAttendee fsAppointmentAttendeeRow = PXCache <FSAppointmentAttendee> .CreateCopy(originalAppointmentAttendee);

                fsAppointmentAttendeeRow.AppointmentID = newFSAppointmentRow.AppointmentID;
                fsAppointmentAttendeeRow.RefNbr        = null;
                fsAppointmentAttendeeRow.NoteID        = null;
                fsAppointmentAttendeeRow = graphNewAppointment.AppointmentAttendees.Insert(fsAppointmentAttendeeRow);

                PXNoteAttribute.CopyNoteAndFiles(
                    graphOriginalAppointment.AppointmentAttendees.Cache,
                    originalAppointmentAttendee,
                    graphNewAppointment.AppointmentAttendees.Cache,
                    fsAppointmentAttendeeRow,
                    copyNotes: true,
                    copyFiles: false);
            }
        }
Esempio n. 9
0
        public virtual void CloneServices(AppointmentEntry gOriginalAppt, AppointmentEntry gNewAppt, FSAppointment newAppointmentRow, FSAppointmentDet sourceRow, Dictionary <string, string> itemLineRef)
        {
            if (sourceRow == null || sourceRow.Status == ID.Status_AppointmentDet.CANCELED)
            {
                return;
            }

            // Creates a copy to not edit the original row.
            FSAppointmentDet sourceRowCopy = PXCache <FSAppointmentDet> .CreateCopy(sourceRow);

            ClearSourceLineBeforeCopy(sourceRowCopy);

            FSAppointmentDet newRow = new FSAppointmentDet();

            newRow = AppointmentEntry.InsertDetailLine <FSAppointmentDet, FSAppointmentDet>(
                gNewAppt.AppointmentDetails.Cache,
                newRow,
                gOriginalAppt.AppointmentDetails.Cache,
                sourceRowCopy,
                null,
                sourceRowCopy.SODetID,
                copyTranDate: false,
                tranDate: sourceRowCopy.TranDate,
                SetValuesAfterAssigningSODetID: true,
                copyingFromQuote: false);

            PXNoteAttribute.CopyNoteAndFiles(
                gOriginalAppt.AppointmentDetails.Cache,
                sourceRow,
                gNewAppt.AppointmentDetails.Cache,
                newRow,
                copyNotes: true,
                copyFiles: false);


            gNewAppt.AppointmentDetails.SetValueExt <FSAppointmentDet.acctID>(newRow, sourceRowCopy.AcctID);
            gNewAppt.AppointmentDetails.SetValueExt <FSAppointmentDet.subID>(newRow, sourceRowCopy.SubID);

            itemLineRef.Add(sourceRow.LineRef, newRow.LineRef);
        }
        /// <summary>
        /// Create a Service Order from a TimeSlot.
        /// </summary>
        protected void CreateServiceOrder(TimeSlot timeSlotServiceOrder, bool createAppointmentFlag = false, bool appointmentsBelongToRoute = false)
        {
            // This action allows to avoid errors related to cache
            if (graphServiceOrderEntry != null)
            {
                graphServiceOrderEntry.Clear(PXClearOption.ClearAll);
            }
            else
            {
                graphServiceOrderEntry = PXGraph.CreateInstance <ServiceOrderEntry>();
                graphServiceOrderEntry.DisableServiceOrderUnboundFieldCalc = true;
            }

            FSSchedule        fsScheduleRow        = ScheduleSelected.Select(timeSlotServiceOrder.ScheduleID);
            FSServiceContract fsServiceContractRow = ServiceContractSelected.Select(fsScheduleRow.EntityID);

            bool isPrepaidContract = fsServiceContractRow.BillingType == ID.Contract_BillingType.STANDARDIZED_BILLINGS;

            //Services from the Schedule
            var fsScheduleDetSet = ScheduleLinesSelected.Select(timeSlotServiceOrder.ScheduleID);

            //Templates from the Schedule
            var fsScheduleDetTemplateSet = ScheduleTemplatesSelected.Select(timeSlotServiceOrder.ScheduleID);

            FSServiceOrder fsServiceOrderRow = new FSServiceOrder();

            fsServiceOrderRow.SrvOrdType = fsScheduleRow.SrvOrdType;
            graphServiceOrderEntry.ServiceOrderRecords.Insert(fsServiceOrderRow);

            fsServiceOrderRow = graphServiceOrderEntry.ServiceOrderRecords.Cache.CreateCopy(graphServiceOrderEntry.ServiceOrderRecords.Current) as FSServiceOrder;

            fsServiceOrderRow.BranchID         = fsScheduleRow.BranchID;
            fsServiceOrderRow.BranchLocationID = fsScheduleRow.BranchLocationID;
            fsServiceOrderRow.OrderDate        = timeSlotServiceOrder.DateTimeBegin.Date;
            fsServiceOrderRow.CustomerID       = fsServiceContractRow.CustomerID;
            fsServiceOrderRow.LocationID       = fsScheduleRow.CustomerLocationID;

            graphServiceOrderEntry.ServiceOrderRecords.Update(fsServiceOrderRow);
            fsServiceOrderRow = graphServiceOrderEntry.ServiceOrderRecords.Cache.CreateCopy(graphServiceOrderEntry.ServiceOrderRecords.Current) as FSServiceOrder;

            // Currently Service-Management's contracts DO NOT support multi-currency specification
            // therefore their ServiceOrders MUST be created in customer base currency
            if (PXAccess.FeatureInstalled <FeaturesSet.multicurrency>())
            {
                string curyID = null;

                Customer customer = (Customer)PXSelect <Customer,
                                                        Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > >
                                    .Select(this, fsServiceContractRow.CustomerID);

                if (customer != null)
                {
                    curyID = customer.CuryID;
                }

                if (string.IsNullOrEmpty(curyID) == true)
                {
                    curyID = this.Accessinfo.BaseCuryID ?? new PXSetup <PX.Objects.GL.Company>(this).Current?.BaseCuryID;
                }

                fsServiceOrderRow.CuryID = curyID;
            }

            fsServiceOrderRow.DocDesc           = timeSlotServiceOrder.Descr;
            fsServiceOrderRow.BillCustomerID    = fsServiceContractRow.BillCustomerID;
            fsServiceOrderRow.BillLocationID    = fsServiceContractRow.BillLocationID;
            fsServiceOrderRow.ServiceContractID = fsServiceContractRow.ServiceContractID;
            fsServiceOrderRow.ProjectID         = fsServiceContractRow.ProjectID;
            fsServiceOrderRow.DfltProjectTaskID = fsServiceContractRow.DfltProjectTaskID;

            if (isPrepaidContract == true &&
                graphServiceOrderEntry.BillingCycleRelated.Current != null &&
                graphServiceOrderEntry.BillingCycleRelated.Current.BillingBy == ID.Billing_By.SERVICE_ORDER)
            {
                fsServiceOrderRow.BillServiceContractID = fsServiceContractRow.ServiceContractID;
            }

            fsServiceOrderRow.ScheduleID        = timeSlotServiceOrder.ScheduleID;
            fsServiceOrderRow.ServiceContractID = fsServiceContractRow.ServiceContractID;
            fsServiceOrderRow.GenerationID      = timeSlotServiceOrder.GenerationID;

            fsServiceOrderRow.SalesPersonID  = fsServiceContractRow.SalesPersonID;
            fsServiceOrderRow.Commissionable = fsServiceContractRow.Commissionable;

            fsServiceOrderRow = graphServiceOrderEntry.ServiceOrderRecords.Update(fsServiceOrderRow);

            if (fsServiceOrderRow.SalesPersonID == null)
            {
                object salesPersonID;
                graphServiceOrderEntry.ServiceOrderRecords.Cache.RaiseFieldDefaulting <FSServiceOrder.salesPersonID>(fsServiceOrderRow, out salesPersonID);
                fsServiceOrderRow.SalesPersonID = (int?)salesPersonID;

                object commissionable;
                graphServiceOrderEntry.ServiceOrderRecords.Cache.RaiseFieldDefaulting <FSServiceOrder.commissionable>(fsServiceOrderRow, out commissionable);
                fsServiceOrderRow.Commissionable = (bool?)commissionable;
            }

            graphServiceOrderEntry.Answers.CopyAllAttributes(fsServiceOrderRow, fsScheduleRow);

            #region Setting Service Order Details
            foreach (FSScheduleDet fsScheduleDetRow in fsScheduleDetSet)
            {
                if (fsScheduleDetRow.LineType == ID.LineType_ServiceContract.SERVICE_TEMPLATE)
                {
                    foreach (FSScheduleDet fsScheduleDetLocalRow in fsScheduleDetTemplateSet.Where(x => ((FSScheduleDet)x).ServiceTemplateID == fsScheduleDetRow.ServiceTemplateID))
                    {
                        var fsServiceTemplateDetSet_Service = ServiceTemplateSelected.Select(fsScheduleDetRow.ServiceTemplateID);

                        foreach (FSServiceTemplateDet fsServiceTemplateDetRow_Service in fsServiceTemplateDetSet_Service)
                        {
                            FSSODet fsSODetRow = new FSSODet();

                            // Insert the new row with key fields
                            fsSODetRow.ScheduleID    = fsScheduleDetLocalRow.ScheduleID;
                            fsSODetRow.ScheduleDetID = fsScheduleDetLocalRow.ScheduleDetID;
                            fsSODetRow.LineType      = fsServiceTemplateDetRow_Service.LineType;

                            fsSODetRow = graphServiceOrderEntry.ServiceOrderDetails.Insert(fsSODetRow);

                            fsSODetRow.InventoryID = fsServiceTemplateDetRow_Service.InventoryID;

                            fsSODetRow = graphServiceOrderEntry.ServiceOrderDetails.Update(fsSODetRow);

                            PXNoteAttribute.CopyNoteAndFiles(ScheduleLinesSelected.Cache,
                                                             fsScheduleDetLocalRow,
                                                             graphServiceOrderEntry.ServiceOrderDetails.Cache,
                                                             fsSODetRow,
                                                             copyNotes: true,
                                                             copyFiles: true);

                            // Create a copy to update the other fields
                            fsSODetRow = (FSSODet)graphServiceOrderEntry.ServiceOrderDetails.Cache.CreateCopy(fsSODetRow);

                            fsSODetRow.TranDesc = fsServiceTemplateDetRow_Service.TranDesc;

                            InventoryItem inventoryItemRow = SharedFunctions.GetInventoryItemRow(this, fsServiceTemplateDetRow_Service.InventoryID);

                            if (inventoryItemRow != null)
                            {
                                FSxService fsxServiceRow = PXCache <InventoryItem> .GetExtension <FSxService>(inventoryItemRow);

                                if (fsxServiceRow != null && fsxServiceRow.BillingRule == ID.BillingRule.TIME)
                                {
                                    int?estimatedDuration = CalculateEstimatedDuration(fsSODetRow, fsServiceTemplateDetRow_Service.Qty);
                                    fsSODetRow.EstimatedDuration = estimatedDuration;
                                }
                                else
                                {
                                    fsSODetRow.EstimatedQty = fsServiceTemplateDetRow_Service.Qty;
                                }
                            }

                            if (fsServiceContractRow.SourcePrice == ID.SourcePrice.CONTRACT)
                            {
                                fsSODetRow.ManualPrice = true;
                                // TODO: Check where is assigned the contract price?
                            }

                            if (createAppointmentFlag)
                            {
                                fsSODetRow.Scheduled = true;
                                fsSODetRow.Status    = ID.Status_SODet.SCHEDULED;
                            }

                            fsSODetRow.EquipmentAction  = fsScheduleDetRow.EquipmentAction;
                            fsSODetRow.SMEquipmentID    = fsScheduleDetRow.SMEquipmentID;
                            fsSODetRow.ComponentID      = fsScheduleDetRow.ComponentID;
                            fsSODetRow.EquipmentLineRef = fsScheduleDetRow.EquipmentLineRef;
                            fsSODetRow.ProjectTaskID    = fsScheduleDetRow.ProjectTaskID;
                            fsSODetRow.CostCodeID       = fsScheduleDetRow.CostCodeID;

                            if (fsSODetRow.InventoryID != null)
                            {
                                fsSODetRow.ProjectTaskID = fsScheduleDetRow.ProjectTaskID;
                                fsSODetRow.CostCodeID    = fsScheduleDetRow.CostCodeID;
                            }

                            graphServiceOrderEntry.ServiceOrderDetails.Update(fsSODetRow);
                        }
                    }
                }
                else
                {
                    FSSODet fsSODetRow = new FSSODet();

                    // Insert the new row with key fields
                    fsSODetRow.ScheduleID    = fsScheduleDetRow.ScheduleID;
                    fsSODetRow.ScheduleDetID = fsScheduleDetRow.ScheduleDetID;
                    fsSODetRow.LineType      = fsScheduleDetRow.LineType;

                    fsSODetRow = graphServiceOrderEntry.ServiceOrderDetails.Insert(fsSODetRow);

                    fsSODetRow.InventoryID = fsScheduleDetRow.InventoryID;

                    fsSODetRow = graphServiceOrderEntry.ServiceOrderDetails.Update(fsSODetRow);

                    PXNoteAttribute.CopyNoteAndFiles(ScheduleLinesSelected.Cache,
                                                     fsScheduleDetRow,
                                                     graphServiceOrderEntry.ServiceOrderDetails.Cache,
                                                     fsSODetRow,
                                                     copyNotes: true,
                                                     copyFiles: true);

                    // Create a copy to update the other fields
                    fsSODetRow = (FSSODet)graphServiceOrderEntry.ServiceOrderDetails.Cache.CreateCopy(fsSODetRow);

                    fsSODetRow.TranDesc    = fsScheduleDetRow.TranDesc;
                    fsSODetRow.BillingRule = fsScheduleDetRow.BillingRule;

                    if (fsSODetRow.BillingRule == ID.BillingRule.TIME)
                    {
                        int?estimatedDuration = CalculateEstimatedDuration(fsSODetRow, fsScheduleDetRow?.Qty);
                        fsSODetRow.EstimatedDuration = estimatedDuration;
                    }
                    else
                    {
                        fsSODetRow.EstimatedQty = fsScheduleDetRow.Qty;
                    }

                    if (fsServiceContractRow.SourcePrice == ID.SourcePrice.CONTRACT)
                    {
                        fsSODetRow.ManualPrice = true;
                        // TODO: AC-142850 Check where is assigned the contract price?
                    }

                    if (createAppointmentFlag)
                    {
                        fsSODetRow.Scheduled = true;
                        fsSODetRow.Status    = ID.Status_SODet.SCHEDULED;
                    }

                    fsSODetRow.EquipmentAction  = fsScheduleDetRow.EquipmentAction;
                    fsSODetRow.SMEquipmentID    = fsScheduleDetRow.SMEquipmentID;
                    fsSODetRow.ComponentID      = fsScheduleDetRow.ComponentID;
                    fsSODetRow.EquipmentLineRef = fsScheduleDetRow.EquipmentLineRef;
                    fsSODetRow.ProjectTaskID    = fsScheduleDetRow.ProjectTaskID;
                    fsSODetRow.CostCodeID       = fsScheduleDetRow.CostCodeID;

                    if (fsSODetRow.InventoryID != null)
                    {
                        fsSODetRow.ProjectTaskID = fsScheduleDetRow.ProjectTaskID;
                        fsSODetRow.CostCodeID    = fsScheduleDetRow.CostCodeID;
                    }

                    graphServiceOrderEntry.ServiceOrderDetails.Update(fsSODetRow);
                }
            }

            if (fsScheduleRow.VendorID != null)
            {
                FSSOEmployee fsSOEmployeeRow = new FSSOEmployee();
                fsSOEmployeeRow.EmployeeID = fsScheduleRow.VendorID;
                graphServiceOrderEntry.ServiceOrderEmployees.Insert(fsSOEmployeeRow);
            }

            #endregion

            graphServiceOrderEntry.Save.Press();

            if (createAppointmentFlag)
            {
                string origStatus = graphServiceOrderEntry.ServiceOrderRecords.Current.Status;

                if (origStatus != ID.Status_ServiceOrder.OPEN)
                {
                    //Due to FSAppointment.sORefNbr selector, Service Order status must be OPEN to allow the SetValueExt<SORefNbr> inside createAppointment() work properly.
                    //PXUpdate is used to avoid raising any ServiceOrderEntry event.
                    PXUpdate <
                        Set <FSServiceOrder.status, FSServiceOrder.status.Open>,
                        FSServiceOrder,
                        Where <
                            FSServiceOrder.sOID, Equal <Required <FSServiceOrder.sOID> > > >
                    .Update(this, graphServiceOrderEntry.ServiceOrderRecords.Current.SOID);
                }

                CreateAppointment(graphServiceOrderEntry.ServiceOrderRecords.Current, timeSlotServiceOrder, fsScheduleRow, true, appointmentsBelongToRoute, isPrepaidContract);

                if (origStatus != ID.Status_ServiceOrder.OPEN)
                {
                    PXUpdate <
                        Set <FSServiceOrder.status, Required <FSServiceOrder.status> >,
                        FSServiceOrder,
                        Where <
                            FSServiceOrder.sOID, Equal <Required <FSServiceOrder.sOID> > > >
                    .Update(this, origStatus, graphServiceOrderEntry.ServiceOrderRecords.Current.SOID);
                }
            }
        }
Esempio n. 11
0
        protected virtual ARInvoice InsertDocument(
            ARInvoiceEntry invoiceEntry,
            ScheduleDet occurrence,
            Customer customer,
            ARInvoice scheduledInvoice,
            CurrencyInfo scheduledInvoiceCurrencyInfo)
        {
            if (scheduledInvoice.Released == true)
            {
                throw new PXException(Messages.ScheduledDocumentAlreadyReleased);
            }

            // Cloning currency info is required because we want to preserve
            // (and not default) the currency rate type of the template document.
            // -
            CurrencyInfo newCurrencyInfo = PXCache <CurrencyInfo> .CreateCopy(scheduledInvoiceCurrencyInfo);

            newCurrencyInfo.CuryInfoID  = null;
            newCurrencyInfo.CuryRate    = null;
            newCurrencyInfo.CuryEffDate = occurrence.ScheduledDate;

            newCurrencyInfo = invoiceEntry.currencyinfo.Insert(newCurrencyInfo);

            ARInvoice newInvoice = PXCache <ARInvoice> .CreateCopy(scheduledInvoice);

            newInvoice.CuryInfoID = newCurrencyInfo.CuryInfoID;
            newInvoice.DocDate    = occurrence.ScheduledDate;

            FinPeriod finPeriod =
                FinPeriodRepository.GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(newInvoice.BranchID), occurrence.ScheduledPeriod)
                .GetValueOrRaiseError();

            newInvoice.FinPeriodID = finPeriod.FinPeriodID;

            newInvoice.TranPeriodID        = null;
            newInvoice.DueDate             = null;
            newInvoice.DiscDate            = null;
            newInvoice.CuryOrigDiscAmt     = null;
            newInvoice.OrigDiscAmt         = null;
            newInvoice.RefNbr              = null;
            newInvoice.Scheduled           = false;
            newInvoice.CuryLineTotal       = 0m;
            newInvoice.CuryVatTaxableTotal = 0m;
            newInvoice.CuryVatExemptTotal  = 0m;
            newInvoice.NoteID              = null;
            newInvoice.IsTaxValid          = false;
            newInvoice.IsTaxPosted         = false;
            newInvoice.IsTaxSaved          = false;
            newInvoice.OrigDocType         = scheduledInvoice.DocType;
            newInvoice.OrigRefNbr          = scheduledInvoice.RefNbr;

            invoiceEntry.Document.Cache.SetDefaultExt <ARInvoice.printed>(newInvoice);
            invoiceEntry.Document.Cache.SetDefaultExt <ARInvoice.emailed>(newInvoice);

            bool forceClear         = false;
            bool clearPaymentMethod = false;

            if (newInvoice.PMInstanceID.HasValue)
            {
                PXResult <CustomerPaymentMethod, PaymentMethod> paymentMethodResult = (PXResult <CustomerPaymentMethod, PaymentMethod>)
                                                                                      PXSelectJoin <
                    CustomerPaymentMethod,
                    InnerJoin <PaymentMethod,
                               On <PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >,
                    Where <
                        CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > >
                                                                                      .Select(invoiceEntry, newInvoice.PMInstanceID);

                if (paymentMethodResult != null)
                {
                    CustomerPaymentMethod customerPaymentMethod = paymentMethodResult;
                    PaymentMethod         paymentMethod         = paymentMethodResult;
                    if (customerPaymentMethod == null || customerPaymentMethod.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                    {
                        clearPaymentMethod = true;
                        forceClear         = true;
                    }
                }
                else
                {
                    clearPaymentMethod = true;
                    forceClear         = true;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(newInvoice.PaymentMethodID))
                {
                    PaymentMethod paymentMethod = PXSelect <
                        PaymentMethod,
                        Where <PaymentMethod.paymentMethodID, Equal <Required <PaymentMethod.paymentMethodID> > > >
                                                  .Select(invoiceEntry, newInvoice.PaymentMethodID);

                    if (paymentMethod == null || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                    {
                        clearPaymentMethod = true;
                        forceClear         = true;
                    }
                }
            }

            if (clearPaymentMethod)
            {
                newInvoice.PMInstanceID    = null;
                newInvoice.PaymentMethodID = null;
                newInvoice.CashAccountID   = null;
            }

            invoiceEntry.ClearRetainageSummary(newInvoice);

            newInvoice = invoiceEntry.Document.Insert(newInvoice);

            if (newInvoice.DontApprove != true)
            {
                // We always generate documents on hold
                // if approval process is enabled in AP.
                // -
                newInvoice.Hold = true;
            }

            newInvoice = invoiceEntry.Document.Update(newInvoice);

            // Force credit rule back
            // -
            invoiceEntry.customer.Current = customer;

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

                copy.PMInstanceID    = null;
                copy.PaymentMethodID = null;
                copy.CashAccountID   = null;
                newInvoice           = invoiceEntry.Document.Update(copy);
            }

            AddressAttribute.CopyRecord <ARInvoice.billAddressID>(invoiceEntry.Document.Cache, newInvoice, scheduledInvoice, false);
            ContactAttribute.CopyRecord <ARInvoice.billContactID>(invoiceEntry.Document.Cache, newInvoice, scheduledInvoice, false);

            CurrencyInfoAttribute.SetEffectiveDate <ARInvoice.docDate>(
                invoiceEntry.Document.Cache,
                new PXFieldUpdatedEventArgs(newInvoice, null, false));

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(ARInvoice)], scheduledInvoice, invoiceEntry.Document.Cache, newInvoice);

            return(newInvoice);
        }
        protected override BAccount CreateMaster(BusinessAccountMaint graph, AccountConversionOptions config)
        {
            var param      = AccountInfo.Current;
            var document   = Documents.Current;
            var docContact = Contacts.Current ?? Contacts.SelectSingle();
            var docAddress = Addresses.Current ?? Addresses.SelectSingle();

            object cd = param.BAccountID;

            graph.BAccount.Cache.RaiseFieldUpdating <BAccount.acctCD>(null, ref cd);

            BAccount account = graph.BAccount.Insert(new BAccount
            {
                AcctCD           = (string)cd,
                AcctName         = param.AccountName,
                Type             = BAccountType.ProspectType,
                ParentBAccountID = document.ParentBAccountID,
                CampaignSourceID = document.CampaignID,
            });

            account.ClassID = param.AccountClass;             // In case of (param.AccountClass == null) constructor fills ClassID with default value, so we have to set this directly.

            CRCustomerClass ocls = PXSelect <
                CRCustomerClass,
                Where <
                    CRCustomerClass.cRCustomerClassID, Equal <Required <CRCustomerClass.cRCustomerClassID> > > >
                                   .SelectSingleBound(graph, null, account.ClassID);

            if (ocls?.DefaultOwner == CRDefaultOwnerAttribute.Source)
            {
                account.WorkgroupID = document.WorkgroupID;
                account.OwnerID     = document.OwnerID;
            }

            account = graph.BAccount.Update(account);

            if (param.LinkContactToAccount == true)
            {
                // in case of opportunity
                Contact contact = PXSelect <Contact, Where <Contact.contactID, Equal <Required <CROpportunity.contactID> > > > .Select(graph, document.RefContactID);

                if (contact != null)
                {
                    graph.Answers.CopyAttributes(account, contact);
                    contact.BAccountID = account.BAccountID;
                    graph.Contacts.Update(contact);
                }
            }


            var defContact = graph.DefContact.SelectSingle()
                             ?? throw new InvalidOperationException("Cannot get Contact for Business Account.");    // just to ensure

            MapContact(docContact, account, ref defContact);
            MapConsentable(docContact, defContact);
            defContact = graph.DefContact.Update(defContact);

            var defAddress = graph.AddressCurrent.SelectSingle()
                             ?? throw new InvalidOperationException("Cannot get Address for Business Account.");    // just to ensure

            MapAddress(docAddress, account, ref defAddress);
            defAddress = graph.AddressCurrent.Update(defAddress);

            CR.Location location = graph.DefLocation.Select();
            location.DefAddressID = defAddress.AddressID;
            location.CTaxZoneID   = document.TaxZoneID;           // Saving tax zone before ReverseDocumentUpdate() removes it
            graph.DefLocation.Update(location);

            ReverseDocumentUpdate(graph, account);

            FillRelations(graph.Relations, account);

            FillAttributes(graph.Answers, account);

            TransferActivities(graph, account);

            // Copy Note text and Files references
            CRSetup setup = PXSetupOptional <CRSetup> .Select(graph);

            PXNoteAttribute.CopyNoteAndFiles(graph.Caches <TMain>(), GetMain(document), graph.CurrentBAccount.Cache, account, setup);

            return(account);
        }
        protected override Contact CreateMaster(ContactMaint graph, ContactConversionOptions _)
        {
            var entity           = Documents.Current;
            var param            = ContactInfo.Current;
            var docContact       = Contacts.Current ?? Contacts.SelectSingle();
            var docContactMethod = ContactMethod.Current ?? ContactMethod.SelectSingle();
            var docAddress       = Addresses.Current ?? Addresses.SelectSingle();

            Contact contact = new Contact
            {
                ContactType      = ContactTypesAttribute.Person,
                ParentBAccountID = entity.ParentBAccountID
            };

            MapContact(docContact, contact);
            MapConsentable(docContact, contact);

            contact.FirstName        = param.FirstName;
            contact.LastName         = param.LastName;
            contact.Salutation       = param.Salutation;
            contact.Phone1           = param.Phone1;
            contact.Phone1Type       = param.Phone1Type;
            contact.EMail            = param.Email;
            contact.ContactType      = ContactTypesAttribute.Person;
            contact.ParentBAccountID = entity.ParentBAccountID;
            contact.BAccountID       = entity.BAccountID;
            contact.Source           = entity.Source;

            MapContactMethod(docContactMethod, contact);

            var address = (Address)graph.AddressCurrent.Cache.CreateInstance();

            address = graph.AddressCurrent.Insert(address);

            contact = graph.Contact.Insert(contact);

            contact.ClassID = param.ContactClass;

            CRContactClass cls = PXSelect <
                CRContactClass,
                Where <
                    CRContactClass.classID, Equal <Required <CRContactClass.classID> > > >
                                 .SelectSingleBound(graph, null, contact.ClassID);

            if (cls?.DefaultOwner == CRDefaultOwnerAttribute.Source)
            {
                contact.WorkgroupID = entity.WorkgroupID;
                contact.OwnerID     = entity.OwnerID;
            }

            MapAddress(docAddress, address);

            address = (Address)graph.AddressCurrent.Cache.Update(address);

            contact.DefAddressID = address.AddressID;

            contact = graph.Contact.Update(contact);

            ReverseDocumentUpdate(graph, contact);

            FillRelations(graph.Relations, contact);

            FillAttributes(graph.Answers, contact);

            TransferActivities(graph, contact);

            // Copy Note text and Files references
            CRSetup setup = PXSetupOptional <CRSetup> .Select(graph);

            PXNoteAttribute.CopyNoteAndFiles(graph.Caches <TMain>(), Documents.Cache.GetMain(entity), graph.Contact.Cache, contact, setup);

            return(graph.Contact.Update(contact));
        }
        public virtual void GenerateProc(Schedule schedule, short times, DateTime runDate)
        {
            IEnumerable <ScheduleDet> occurrences = new Scheduler(this).MakeSchedule(schedule, times, runDate);

            APInvoiceEntry invoiceEntry = CreateGraph();

            using (PXTransactionScope transactionScope = new PXTransactionScope())
            {
                foreach (ScheduleDet occurrence in occurrences)
                {
                    foreach (PXResult <APInvoice, Vendor, CurrencyInfo> scheduledInvoiceResult 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, schedule.ScheduleID))
                    {
                        invoiceEntry.Clear();

                        invoiceEntry.vendor.Current = (Vendor)scheduledInvoiceResult;
                        APInvoice    scheduledInvoice             = (APInvoice)scheduledInvoiceResult;
                        CurrencyInfo scheduledInvoiceCurrencyInfo = (CurrencyInfo)scheduledInvoiceResult;

                        if (scheduledInvoice.Released == true)
                        {
                            throw new PXException(AR.Messages.ScheduledDocumentAlreadyReleased);
                        }

                        // Cloning currency info is required because we want to preserve
                        // (and not default) the currency rate type of the template document.
                        // -
                        CurrencyInfo newCurrencyInfo = PXCache <CurrencyInfo> .CreateCopy(scheduledInvoiceCurrencyInfo);

                        newCurrencyInfo.CuryInfoID  = null;
                        newCurrencyInfo.CuryRate    = null;
                        newCurrencyInfo.CuryEffDate = occurrence.ScheduledDate;

                        newCurrencyInfo = invoiceEntry.currencyinfo.Insert(newCurrencyInfo);

                        APInvoice newInvoice = PXCache <APInvoice> .CreateCopy(scheduledInvoice);

                        newInvoice.CuryInfoID          = newCurrencyInfo.CuryInfoID;
                        newInvoice.DocDate             = occurrence.ScheduledDate;
                        newInvoice.FinPeriodID         = occurrence.ScheduledPeriod;
                        newInvoice.TranPeriodID        = null;
                        newInvoice.DueDate             = null;
                        newInvoice.DiscDate            = null;
                        newInvoice.PayDate             = null;
                        newInvoice.CuryOrigDiscAmt     = null;
                        newInvoice.OrigDiscAmt         = null;
                        newInvoice.RefNbr              = null;
                        newInvoice.Scheduled           = false;
                        newInvoice.CuryLineTotal       = 0m;
                        newInvoice.CuryVatTaxableTotal = 0m;
                        newInvoice.CuryVatExemptTotal  = 0m;
                        newInvoice.NoteID              = null;
                        newInvoice.PaySel              = false;
                        newInvoice.IsTaxValid          = false;
                        newInvoice.IsTaxPosted         = false;
                        newInvoice.IsTaxSaved          = false;
                        newInvoice.OrigDocType         = scheduledInvoice.DocType;
                        newInvoice.OrigRefNbr          = scheduledInvoice.RefNbr;

                        newInvoice = invoiceEntry.Document.Insert(newInvoice);                         //we insert an item here because we need DontApprove field to be set in RowSelected
                        if (newInvoice.DontApprove != true)
                        {
                            // We always generate documents on hold
                            // if approval process is enabled in AP.
                            // -
                            newInvoice.Hold = true;
                        }

                        newInvoice = invoiceEntry.Document.Update(newInvoice);

                        CurrencyInfoAttribute.SetEffectiveDate <APInvoice.docDate>(
                            invoiceEntry.Document.Cache,
                            new PXFieldUpdatedEventArgs(newInvoice, null, false));

                        PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(APInvoice)], scheduledInvoice, invoiceEntry.Document.Cache, newInvoice);

                        foreach (APTran originalLine in PXSelect <
                                     APTran,
                                     Where <
                                         APTran.tranType, Equal <Required <APTran.tranType> >,
                                         And <APTran.refNbr, Equal <Required <APTran.refNbr> >,
                                              And <Where <
                                                       APTran.lineType, IsNull,
                                                       Or <APTran.lineType, NotEqual <SOLineType.discount> > > > > > >
                                 .Select(invoiceEntry, scheduledInvoice.DocType, scheduledInvoice.RefNbr))
                        {
                            APTran newLine = PXCache <APTran> .CreateCopy(originalLine);

                            newLine.RefNbr      = null;
                            newLine.CuryInfoID  = null;
                            newLine.ManualPrice = true;
                            newLine.ManualDisc  = true;
                            newLine.NoteID      = null;
                            newLine             = invoiceEntry.Transactions.Insert(newLine);

                            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(APTran)], originalLine, invoiceEntry.Transactions.Cache, newLine);
                        }

                        foreach (APInvoiceDiscountDetail originalDiscountDetail in PXSelect <
                                     APInvoiceDiscountDetail,
                                     Where <
                                         APInvoiceDiscountDetail.docType, Equal <Required <APInvoiceDiscountDetail.docType> >,
                                         And <APInvoiceDiscountDetail.refNbr, Equal <Required <APInvoiceDiscountDetail.refNbr> > > > >
                                 .Select(invoiceEntry, scheduledInvoice.DocType, scheduledInvoice.RefNbr))
                        {
                            APInvoiceDiscountDetail newDiscountDetail =
                                PXCache <APInvoiceDiscountDetail> .CreateCopy(originalDiscountDetail);

                            newDiscountDetail.RefNbr     = null;
                            newDiscountDetail.CuryInfoID = null;
                            newDiscountDetail.IsManual   = true;

                            DiscountEngineProvider.GetEngineFor <APTran, APInvoiceDiscountDetail>().InsertDiscountDetail(invoiceEntry.DiscountDetails.Cache, invoiceEntry.DiscountDetails, newDiscountDetail);
                        }

                        BalanceCalculation.ForceDocumentControlTotals(invoiceEntry, newInvoice);

                        try
                        {
                            invoiceEntry.Save.Press();
                        }
                        catch
                        {
                            if (invoiceEntry.Document.Cache.IsInsertedUpdatedDeleted)
                            {
                                throw;
                            }
                        }
                    }

                    schedule.LastRunDate = occurrence.ScheduledDate;
                    Running_Schedule.Cache.Update(schedule);
                }

                transactionScope.Complete(this);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }

            Running_Schedule.Cache.Persisted(false);
        }
Esempio n. 15
0
        public virtual List <APRegister> ReleaseClaimDetails
        <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>
            (ExpenseClaimEntry expenseClaimGraph, EPExpenseClaim claim, IEnumerable <EPExpenseClaimDetails> receipts, string receiptGroupPaidWithType)
            where TGraph : PXGraph, new()
            where TAPDocument : InvoiceBase, new()
            where TInvoiceMapping : IBqlMapping
            where TAPDocumentGraphExtension : PX.Objects.Common.GraphExtensions.Abstract.InvoiceBaseGraphExtension <TGraph, TAPDocument, TInvoiceMapping>
        {
            #region prepare required variable

            var docgraph = PXGraph.CreateInstance <TGraph>();

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

            TAPDocumentGraphExtension apDocumentGraphExtension = docgraph.FindImplementation <TAPDocumentGraphExtension>();

            List <List <EPExpenseClaimDetails> > receiptsForDocument = new List <List <EPExpenseClaimDetails> >();

            if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
            {
                receiptsForDocument = receipts.GroupBy(item => new { item.TaxZoneID, item.TaxCalcMode })
                                      .Select(group => group.ToList())
                                      .ToList();
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
            {
                if (epsetup.PostSummarizedCorpCardExpenseReceipts == true)
                {
                    receiptsForDocument = receipts.GroupBy(item =>
                                                           new
                    {
                        item.TaxZoneID,
                        item.TaxCalcMode,
                        item.CorpCardID,
                        item.ExpenseDate,
                        item.ExpenseRefNbr
                    })
                                          .Select(group => group.ToList())
                                          .ToList();
                }
                else
                {
                    receiptsForDocument = receipts.Select(receipt => receipt.SingleToList()).ToList();
                }
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
            {
                receiptsForDocument = new List <List <EPExpenseClaimDetails> >()
                {
                    receipts.ToList()
                };
            }
            else
            {
                throw new NotImplementedException();
            }

            if (!receiptsForDocument.Any())
            {
                receiptsForDocument.Add(new List <EPExpenseClaimDetails>());
            }

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

            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);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();


            if (claim.FinPeriodID != null)
            {
                FinPeriodUtils.ValidateFinPeriod(claim.SingleToArray());
            }
            #endregion

            foreach (var receiptGroup in receiptsForDocument)
            {
                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count > 1)
                {
                    EPExpenseClaimDetails[] matchedReceipts = receiptGroup.Where(receipt => receipt.BankTranDate != null).Take(11).ToArray();

                    if (matchedReceipts.Any())
                    {
                        PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran>[] rows =
                            PXSelectJoin <EPExpenseClaimDetails,
                                          InnerJoin <CABankTranMatch,
                                                     On <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                                         And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                              And <CABankTranMatch.docRefNbr, Equal <EPExpenseClaimDetails.claimDetailCD> > > >,
                                                     InnerJoin <CABankTran,
                                                                On <CABankTran.tranID, Equal <CABankTranMatch.tranID> > > >,
                                          Where <EPExpenseClaimDetails.claimDetailCD, In <Required <EPExpenseClaimDetails.claimDetailCD> > > >
                            .Select(expenseClaimGraph, matchedReceipts.Select(receipt => receipt.ClaimDetailCD).ToArray())
                            .Cast <PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran> >()
                            .ToArray();

                        throw new PXException(Messages.ExpenseReceiptCannotBeSummarized,
                                              rows.Select(row => String.Concat(PXMessages.LocalizeNoPrefix(Messages.Receipt),
                                                                               " ",
                                                                               ((EPExpenseClaimDetails)row).ClaimDetailCD,
                                                                               " - ",
                                                                               ((CABankTran)row).GetFriendlyKeyImage(Caches[typeof(CABankTran)])))
                                              .ToArray()
                                              .JoinIntoStringForMessageNoQuotes(maxCount: 10));
                    }
                }

                docgraph.Clear(PXClearOption.ClearAll);
                docgraph.SelectTimeStamp();
                apDocumentGraphExtension.Contragent.Current = apDocumentGraphExtension.Contragent.Cache.GetExtension <Contragent>(employee);
                apDocumentGraphExtension.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            = apDocumentGraphExtension.CurrencyInfo.Insert(info);

                #region CreateInvoiceHeader

                var invoice = new TAPDocument();

                CABankTranMatch bankTranMatch = null;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
                {
                    invoice.DocType = receiptGroup.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0
                        ? APInvoiceType.DebitAdj
                        : APInvoiceType.Invoice;
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
                {
                    EPExpenseClaimDetails receipt = receiptGroup.First();

                    invoice.DocType = APDocType.QuickCheck;

                    CACorpCard card = CACorpCard.PKID.Find(this, receipt.CorpCardID);

                    PaymentMethodAccount paymentMethodAccount = PXSelect <PaymentMethodAccount,
                                                                          Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> > > >
                                                                .Select(this, card.CashAccountID);

                    invoice.CashAccountID   = card.CashAccountID;
                    invoice.PaymentMethodID = paymentMethodAccount.PaymentMethodID;
                    invoice.ExtRefNbr       = receipt.ExpenseRefNbr;

                    if (receiptGroup.Count == 1)
                    {
                        bankTranMatch =
                            PXSelect <CABankTranMatch,
                                      Where <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                             And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                  And <CABankTranMatch.docRefNbr, Equal <Required <CABankTranMatch.docRefNbr> > > > > >
                            .Select(expenseClaimGraph, receipt.ClaimDetailCD);

                        if (bankTranMatch != null)
                        {
                            CABankTran bankTran = CABankTran.PK.Find(expenseClaimGraph, bankTranMatch.TranID);

                            invoice.ClearDate = bankTran.ClearDate;
                            invoice.Cleared   = true;
                        }
                    }
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.DocType = APDocType.DebitAdj;
                }
                else
                {
                    throw new NotImplementedException();
                }

                invoice.CuryInfoID = info.CuryInfoID;

                invoice.Hold     = true;
                invoice.Released = false;
                invoice.Printed  = invoice.DocType == APDocType.QuickCheck;
                invoice.OpenDoc  = true;

                invoice.HeaderDocDate        = claim.DocDate;
                invoice.FinPeriodID          = claim.FinPeriodID;
                invoice.InvoiceNbr           = claim.RefNbr;
                invoice.DocDesc              = claim.DocDesc;
                invoice.ContragentID         = claim.EmployeeID;
                invoice.CuryID               = info.CuryID;
                invoice.ContragentLocationID = claim.LocationID;
                invoice.ModuleAccountID      = emplocation != null ? emplocation.APAccountID : null;
                invoice.ModuleSubID          = emplocation != null ? emplocation.APSubID : null;
                invoice.TaxCalcMode          = receiptGroup.Any() ? receiptGroup.First().TaxCalcMode: claim.TaxCalcMode;
                invoice.BranchID             = claim.BranchID;
                invoice.OrigModule           = BatchModule.EP;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1)
                {
                    invoice.OrigDocType = EPExpenseClaimDetails.DocType;
                    invoice.OrigRefNbr  = receiptGroup.Single().ClaimDetailCD;
                }
                else
                {
                    invoice.OrigDocType = EPExpenseClaim.DocType;
                    invoice.OrigRefNbr  = claim.RefNbr;
                }

                bool reversedDocument = invoice.DocType == APInvoiceType.DebitAdj && receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount;

                decimal signOperation = reversedDocument ? -1 : 1;

                invoice = apDocumentGraphExtension.Documents.Insert(invoice);
                (apDocumentGraphExtension.Documents.Cache as PXModelExtension <TAPDocument>)?.UpdateExtensionMapping(invoice, MappingSyncDirection.BaseToExtension);

                invoice.TaxZoneID = receiptGroup.Any() ? receiptGroup.First().TaxZoneID : claim.TaxZoneID;

                invoice = apDocumentGraphExtension.Documents.Update(invoice);

                PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                info.CuryInfoID = invoice.CuryInfoID;

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

                PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, apDocumentGraphExtension.Documents.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                #endregion

                TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.ManualCalc);

                decimal?claimCuryTaxRoundDiff = 0m;
                decimal?claimTaxRoundDiff     = 0m;
                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    #region AddDetails

                    decimal tipQty;
                    if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                    {
                        tipQty = 1;
                    }
                    else
                    {
                        tipQty = -1;
                    }
                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

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

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

                    InvoiceTran tran = new InvoiceTran();
                    tran.InventoryID = claimdetail.InventoryID;
                    tran.TranDesc    = claimdetail.TranDesc;
                    decimal unitCost;
                    decimal amount;
                    decimal taxableAmt;
                    decimal taxAmt;
                    if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                    {
                        unitCost   = claimdetail.CuryUnitCost ?? 0m;
                        amount     = claimdetail.CuryTaxableAmt ?? 0m;
                        taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                        taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                    }
                    else
                    {
                        if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                        {
                            unitCost = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                        }
                        if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                        {
                            amount = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                        }
                        if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                        {
                            taxableAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                        }
                        if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                        {
                            taxAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                        }
                    }

                    tran.ManualPrice       = true;
                    tran.CuryUnitCost      = unitCost;
                    tran.Qty               = claimdetail.Qty * signOperation;
                    tran.UOM               = claimdetail.UOM;
                    tran.NonBillable       = claimdetail.Billable != true;
                    claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                    claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                    tran.Date              = claimdetail.ExpenseDate;

                    if (contract.BaseType == CT.CTPRType.Project)
                    {
                        tran.ProjectID = claimdetail.ContractID;
                    }
                    else
                    {
                        tran.ProjectID = ProjectDefaultAttribute.NonProject();
                    }

                    tran.TaskID     = claimdetail.TaskID;
                    tran.CostCodeID = claimdetail.CostCodeID;

                    if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        CACorpCard  card        = CACorpCard.PKID.Find(this, claimdetail.CorpCardID);
                        CashAccount cashAccount = CashAccount.PK.Find(this, card.CashAccountID);

                        tran.AccountID = cashAccount.AccountID;
                        tran.SubID     = cashAccount.SubID;
                    }
                    else
                    {
                        tran.AccountID = claimdetail.ExpenseAccountID;
                        tran.SubID     = claimdetail.ExpenseSubID;
                    }

                    tran.BranchID = claimdetail.BranchID;


                    tran = InsertInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });

                    if (claimdetail.PaidWith == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        claimdetail.APLineNbr = tran.LineNbr;
                    }

                    tran.CuryLineAmt    = amount * signOperation;
                    tran.CuryTaxAmt     = 0;
                    tran.CuryTaxableAmt = taxableAmt * signOperation;
                    tran.CuryTaxAmt     = taxAmt * signOperation;
                    tran.TaxCategoryID  = claimdetail.TaxCategoryID;


                    tran = UpdateInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });


                    if ((claimdetail.CuryTipAmt ?? 0) != 0)
                    {
                        InvoiceTran tranTip = new InvoiceTran();
                        if (epsetup.NonTaxableTipItem == null)
                        {
                            throw new PXException(Messages.TipItemIsNotDefined);
                        }
                        IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                             Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                        if (tipItem == null)
                        {
                            string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                            throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                        }
                        tranTip.InventoryID = epsetup.NonTaxableTipItem;
                        tranTip.TranDesc    = tipItem.Descr;
                        if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                            tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                        }
                        else
                        {
                            decimal tipAmt;
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                            tranTip.CuryUnitCost = Math.Abs(tipAmt);
                            tranTip.CuryTranAmt  = tipAmt * signOperation;
                        }
                        tranTip.Qty         = tipQty;
                        tranTip.UOM         = tipItem.BaseUnit;
                        tranTip.NonBillable = claimdetail.Billable != true;
                        tranTip.Date        = claimdetail.ExpenseDate;

                        tranTip.BranchID = claimdetail.BranchID;

                        tranTip = InsertInvoiceTipTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                              new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });


                        if (epsetup.UseReceiptAccountForTips == true)
                        {
                            tranTip.AccountID = claimdetail.ExpenseAccountID;
                            tranTip.SubID     = claimdetail.ExpenseSubID;
                        }
                        else
                        {
                            tranTip.AccountID = tipItem.COGSAcctID;
                            Location companyloc = (Location)PXSelectJoin <Location,
                                                                          InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                    And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                     InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                          Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                            PMTask task = PXSelect <PMTask,
                                                    Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                           And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                            Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                            int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                            int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                            int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                            int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                            int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                            int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                            object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                    new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                    new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                            docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                            tranTip.SubID = (int?)value;
                        }

                        tranTip = UpdateInvoiceTipTransactionAccounts(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                      new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });

                        tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                        tranTip.ProjectID     = tran.ProjectID;
                        tranTip.TaskID        = tran.TaskID;
                        tranTip = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tranTip, true);


                        tranTip = UpdateInvoiceTipTransactionTaxesAndProject(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                             new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });
                    }

                    PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, apDocumentGraphExtension.InvoiceTrans.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    claimdetail.Released = true;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    #endregion

                    if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        tran = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tran, false);
                    }
                }

                #region legacy taxes
                foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                 Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                {
                    #region Add taxes
                    GenericTaxTran new_aptax = apDocumentGraphExtension.TaxTrans.Search <GenericTaxTran.taxID>(tax.TaxID);

                    if (new_aptax == null)
                    {
                        new_aptax       = new GenericTaxTran();
                        new_aptax.TaxID = tax.TaxID;
                        new_aptax       = apDocumentGraphExtension.TaxTrans.Insert(new_aptax);
                        if (new_aptax != null)
                        {
                            new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                            new_aptax.CuryTaxableAmt = 0m;
                            new_aptax.CuryTaxAmt     = 0m;
                            new_aptax.CuryExpenseAmt = 0m;
                            new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                        }
                    }

                    if (new_aptax != null)
                    {
                        new_aptax                = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                        new_aptax.TaxRate        = tax.TaxRate;
                        new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                        new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                        new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                        new_aptax                = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                    }
                    #endregion
                }
                #endregion

                invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                invoice.Hold           = false;
                apDocumentGraphExtension.SuppressApproval();
                apDocumentGraphExtension.Documents.Update(invoice);

                if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (InvoiceTran line in apDocumentGraphExtension.InvoiceTrans.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }
                }

                invoice = apDocumentGraphExtension.Documents.Update(invoice);
                docgraph.Actions.PressSave();

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1 &&
                    bankTranMatch != null)
                {
                    CABankTransactionsMaint.RematchFromExpenseReceipt(this, bankTranMatch, invoice.CATranID, invoice.ContragentID, receiptGroup.Single());
                }

                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    claimdetail.APDocType = invoice.DocType;
                    claimdetail.APRefNbr  = invoice.RefNbr;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                }

                claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                claim.Released = true;

                expenseClaimGraph.ExpenseClaim.Update(claim);


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

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

                expenseClaimGraph.Save.Press();

                Actions.PressSave();

                doclist.Add((APRegister)apDocumentGraphExtension.Documents.Current.Base);
            }

            return(doclist);
        }
        protected virtual void InsertARTran(ARInvoiceEntry arGraph, EPExpenseClaimDetails row, decimal signOperation, decimal tipQty = 1m, bool isTipTransaction = false)
        {
            CurrencyInfo curyInfo = PXSelect <CurrencyInfo> .Search <CurrencyInfo.curyInfoID>(arGraph, row.CuryInfoID);

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


            ARTran tran = arGraph.Transactions.Insert();

            if (isTipTransaction)
            {
                IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                     Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(arGraph, epsetup.NonTaxableTipItem);

                tran.InventoryID = epsetup.NonTaxableTipItem;
                tran.Qty         = tipQty;
                tran.UOM         = tipItem.BaseUnit;
                tran.TranDesc    = tipItem.Descr;

                SetAmount(arGraph, row.CuryTipAmt, row.TipAmt, tipQty, signOperation, curyInfo, tran);
                tran = arGraph.Transactions.Update(tran);

                if (epsetup.UseReceiptAccountForTips == true)
                {
                    tran.AccountID = row.SalesAccountID;
                    tran.SubID     = row.SalesSubID;
                }
                else
                {
                    Location companyloc = (Location)PXSelectJoin <Location,
                                                                  InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                            And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                             InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                  Where <GL.Branch.branchID, Equal <Current <ARTran.branchID> > > > .Select(arGraph);

                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <Contract.contractID> > > > .Select(this, row.ContractID);

                    PMTask task = PXSelect <PMTask,
                                            Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                   And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(arGraph, row.ContractID, row.TaskID);

                    EPEmployee employee = (EPEmployee)PXSelect <EPEmployee> .Search <EPEmployee.bAccountID>(this, row != null?row.EmployeeID : null);

                    Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(arGraph.Caches[typeof(EPExpenseClaimDetails)], row);

                    int?employee_SubID = (int?)arGraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.salesSubID>(employee);
                    int?item_SubID     = (int?)arGraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.salesSubID>(tipItem);
                    int?company_SubID  = (int?)arGraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(companyloc);
                    int?project_SubID  = (int?)arGraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                    int?task_SubID     = (int?)arGraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                    int?location_SubID = (int?)arGraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                    object value = SubAccountMaskAttribute.MakeSub <EPSetup.salesSubMask>(arGraph, epsetup.SalesSubMask,
                                                                                          new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                          new Type[] { typeof(EPEmployee.salesSubID), typeof(IN.InventoryItem.salesSubID), typeof(Location.cSalesSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                    arGraph.Caches[typeof(ARTran)].RaiseFieldUpdating <ARTran.subID>(tran, ref value);
                    tran.SubID = (int?)value;
                }
            }
            else
            {
                tran.InventoryID = row.InventoryID;
                tran.Qty         = row.Qty * signOperation;
                tran.UOM         = row.UOM;
                tran             = arGraph.Transactions.Update(tran);
                tran.AccountID   = row.SalesAccountID;
                tran.SubID       = row.SalesSubID;
                tran.TranDesc    = row.TranDesc;

                //For gross taxes we can't put tranAmt. So we should use taxable amount
                EPTaxTran firstLevelTaxTran = null;
                foreach (EPTaxTran taxRow in PXSelect <EPTaxTran,
                                                       Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> >,
                                                              And <EPTaxTran.isTipTax, Equal <False> > > > .Select(this, row.ClaimDetailID))
                {
                    if (firstLevelTaxTran == null || Math.Abs(firstLevelTaxTran.CuryTaxableAmt ?? 0m) > Math.Abs(taxRow.CuryTaxableAmt ?? 0m))
                    {
                        firstLevelTaxTran = taxRow;
                    }
                }
                decimal?curyAmt = firstLevelTaxTran?.CuryTaxableAmt ?? row.CuryTaxableAmt;
                decimal?amt     = firstLevelTaxTran?.TaxableAmt ?? row.TaxableAmt;
                SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran);
                tran = arGraph.Transactions.Update(tran);
                if (tran.CuryTaxableAmt != 0 && tran.CuryTaxableAmt != curyAmt)                 // indicates that we have gross/ iclusive taxes. In this case recalculation is required
                {
                    curyAmt = row.CuryTaxableAmt;
                    amt     = row.TaxableAmt;
                    SetAmount(arGraph, curyAmt, amt, row.Qty, signOperation, curyInfo, tran);
                }
            }
            tran.Date        = row.ExpenseDate;
            tran.ManualPrice = true;
            tran             = arGraph.Transactions.Update(tran);
            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], row, arGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.ar>());
        }
        public virtual IEnumerable ConvertToOpportunity(PXAdapter adapter)
        {
            Save.Press();
            bool           isOpportunityAutoNumberOn = this.IsNumberingAutonumbered(Setup.Current.OpportunityNumberingID);
            List <Contact> contacts = new List <Contact>(adapter.Get().Cast <Contact>());

            foreach (Contact l in contacts)
            {
                OpportunityMaint opportunityMaint = CreateInstance <OpportunityMaint>();
                CROpportunity    opportunity      = (CROpportunity)opportunityMaint.Opportunity.Cache.Insert();

                if (!isOpportunityAutoNumberOn)
                {
                    if (OpportunityInfo.AskExt() != WebDialogResult.OK || !OpportunityInfo.VerifyRequired())
                    {
                        return(contacts);
                    }
                    CROpportunity existing = PXSelect <CROpportunity, Where <CROpportunity.opportunityID, Equal <Required <CROpportunity.opportunityID> > > > .SelectSingleBound(this, null, OpportunityInfo.Current.OpportunityID);

                    if (existing != null)
                    {
                        OpportunityInfo.Cache.RaiseExceptionHandling <OpportunityFilter.opportunityID>(OpportunityInfo.Current, OpportunityInfo.Current.OpportunityID, new PXSetPropertyException(Messages.OpportunityAlreadyExists, OpportunityInfo.Current.OpportunityID));
                        return(contacts);
                    }

                    object cd = OpportunityInfo.Current.OpportunityID;
                    opportunityMaint.Opportunity.Cache.RaiseFieldUpdating <CROpportunity.opportunityID>(null, ref cd);
                    opportunity.OpportunityID = (string)cd;
                }
                Contact lead = l;
                PXLongOperation.StartOperation(this, delegate()
                {
                    CRContactClass cls = PXSelect <CRContactClass, Where <CRContactClass.classID, Equal <Current <Contact.classID> > > > .SelectSingleBound(this, new object[] { lead });
                    if (cls != null && cls.OwnerToOpportunity == true)
                    {
                        opportunity.WorkgroupID = lead.WorkgroupID;
                        opportunity.OwnerID     = lead.OwnerID;
                    }
                    if (cls != null && cls.TargetOpportunityClassID != null)
                    {
                        opportunity.CROpportunityClassID = cls.TargetOpportunityClassID;
                    }

                    if (lead.BAccountID != null)
                    {
                        opportunity.BAccountID = lead.BAccountID;
                    }

                    if (lead.ParentBAccountID != null)
                    {
                        opportunity.ParentBAccountID = lead.ParentBAccountID;
                    }

                    if (lead.CampaignID != null)
                    {
                        opportunity.CampaignSourceID = lead.CampaignID;
                    }
                    opportunity.ContactID       = lead.ContactID;
                    opportunity.ConvertedLeadID = lead.ContactID;
                    opportunity.OpportunityName = string.IsNullOrEmpty(lead.FullName) ? lead.DisplayName : lead.FullName;
                    opportunity = (CROpportunity)opportunityMaint.Opportunity.Cache.Update(opportunity);

                    ContactMaint contactGraph = CreateInstance <ContactMaint>();
                    lead.ContactType          = ContactTypesAttribute.Person;
                    lead.QualificationDate    = PXTimeZoneInfo.Now;
                    lead.ConvertedBy          = Accessinfo.UserID;
                    lead = contactGraph.Contact.Update(lead);

                    opportunityMaint.Opportunity.Search <CROpportunity.opportunityID>(opportunity.OpportunityID);
                    lead = opportunityMaint.Leads.Update(lead);

                    // Copy Note text and Files references
                    CRSetup setup = PXSetupOptional <CRSetup> .Select(opportunityMaint);
                    PXNoteAttribute.CopyNoteAndFiles(opportunityMaint.Leads.Cache, lead, opportunityMaint.OpportunityCurrent.Cache, opportunity, setup);

                    throw new PXRedirectRequiredException(opportunityMaint, "Opportunity", true);
                });
            }
            return(contacts);
        }
        protected virtual void CloneAppointment(AppointmentEntry graphOriginalAppointment, AppointmentEntry graphNewAppointment)
        {
            if (AppointmentSelected.Current == null)
            {
                return;
            }

            graphNewAppointment.Clear(PXClearOption.ClearAll);
            graphNewAppointment.clearLocalServiceOrder();

            FSAppointment fsAppointmentRow = PXCache <FSAppointment> .CreateCopy(AppointmentSelected.Current);

            //Clear key and special fields
            fsAppointmentRow.RefNbr                     = null;
            fsAppointmentRow.AppointmentID              = null;
            fsAppointmentRow.NoteID                     = null;
            fsAppointmentRow.CuryInfoID                 = null;
            fsAppointmentRow.AgreementSignature         = false;
            fsAppointmentRow.FullNameSignature          = null;
            fsAppointmentRow.customerSignaturePath      = null;
            fsAppointmentRow.BillServiceContractID      = null;
            fsAppointmentRow.HandleManuallyActualTime   = null;
            fsAppointmentRow.HandleManuallyScheduleTime = null;

            fsAppointmentRow.OriginalAppointmentID = AppointmentSelected.Current.AppointmentID;

            fsAppointmentRow.ScheduledDateTimeBegin = AppointmentCore.GetDateTimeEnd(
                Filter.Current.ScheduledDate, Filter.Current.ScheduledStartTime);

            fsAppointmentRow.ScheduledDateTimeEnd =
                AppointmentCore.GetDateTimeEnd(
                    Filter.Current.ScheduledDate, Filter.Current.ScheduledEndTime);

            fsAppointmentRow.ExecutionDate = fsAppointmentRow.ScheduledDateTimeBegin.Value.Date;

            fsAppointmentRow.CutOffDate
                = ServiceOrderCore.GetCutOffDate(graphNewAppointment, graphOriginalAppointment.ServiceOrderRelated.Current.CBID, fsAppointmentRow.ExecutionDate);

            fsAppointmentRow.Status = ID.Status_Appointment.MANUAL_SCHEDULED;
            fsAppointmentRow.Hold   = false;

            fsAppointmentRow.AdditionalCommentsCustomer = null;
            fsAppointmentRow.AdditionalCommentsStaff    = null;

            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //Clean total fields
            fsAppointmentRow.EstimatedDurationTotal = 0;
            fsAppointmentRow.ActualDurationTotal    = 0;

            fsAppointmentRow.CuryEstimatedLineTotal = 0;
            fsAppointmentRow.CuryLineTotal          = 0;
            fsAppointmentRow.CuryBillableLineTotal  = 0;
            fsAppointmentRow.CuryCostTotal          = 0;

            fsAppointmentRow.EstimatedLineTotal = 0;
            fsAppointmentRow.LineTotal          = 0;
            fsAppointmentRow.BillableLineTotal  = 0;
            fsAppointmentRow.CostTotal          = 0;
            //----------------------------------------------------------------------

            graphNewAppointment.IsCloningAppointment = true;
            fsAppointmentRow = graphNewAppointment.AppointmentRecords.Insert(fsAppointmentRow);

            graphNewAppointment.AttributeListRecords.Current = graphNewAppointment.AttributeListRecords.Select();
            graphNewAppointment.Answers.Current = graphNewAppointment.Answers.Select();
            graphNewAppointment.Answers.CopyAllAttributes(graphNewAppointment.AppointmentRecords.Current, AppointmentSelected.Current);

            PXNoteAttribute.CopyNoteAndFiles(
                AppointmentSelected.Cache,
                AppointmentSelected.Current,
                graphNewAppointment.AppointmentSelected.Cache,
                fsAppointmentRow,
                copyNotes: true,
                copyFiles: false);


            this.CloneParts(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow);
            this.CloneServices(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow);
            this.CloneEmployees(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow);
            this.CloneAttendees(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow);
            this.CloneResources(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow);

            if (graphNewAppointment.AppointmentRecords.Current.ScheduledDateTimeEnd != Filter.Current.ScheduledEndTime)
            {
                graphNewAppointment.AppointmentRecords.Cache.SetValueExt <FSAppointment.handleManuallyScheduleTime>(fsAppointmentRow, true);
                graphNewAppointment.AppointmentRecords.Cache.SetValueExt <FSAppointment.scheduledDateTimeEnd>(fsAppointmentRow, Filter.Current.ScheduledEndTime);
            }

            graphNewAppointment.AppointmentRecords.Cache.SetDefaultExt <FSAppointment.billContractPeriodID>(fsAppointmentRow);
            graphNewAppointment.Save.Press();
        }
        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();
            decimal   signOperation;

            if (claim.CuryDocBal < 0)
            {
                invoice.DocType = APInvoiceType.DebitAdj;
                signOperation   = -1;
            }
            else
            {
                invoice.DocType = APInvoiceType.Invoice;
                signOperation   = 1;
            }

            invoice.CuryInfoID = info.CuryInfoID;

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

            invoice.DocDate          = claim.DocDate;
            invoice.FinPeriodID      = claim.FinPeriodID;
            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.TaxCalcMode      = AP.VendorClass.taxCalcMode.TaxSetting;
            invoice.BranchID         = claim.BranchID;
            invoice = docgraph.Document.Insert(invoice);

            PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

            info.CuryInfoID = invoice.CuryInfoID;

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

            PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, docgraph.Document.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());

            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;
                        if (claimdetail.CuryInfoID == claimdetail.ClaimCuryInfoID)
                        {
                            tran.CuryUnitCost = claimdetail.CuryUnitCost * signOperation;
                        }
                        else if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                        {
                            tran.CuryUnitCost = 0m;
                        }
                        else
                        {
                            decimal newValue;
                            CM.PXCurrencyAttribute.CuryConvCury(docgraph.Document.Cache, info, (decimal)claimdetail.UnitCost, out newValue);
                            tran.CuryUnitCost = newValue * signOperation;
                        }
                        tran.Qty         = claimdetail.Qty * signOperation;
                        tran.UOM         = claimdetail.UOM;
                        tran.NonBillable = claimdetail.Billable != true;
                        tran.CuryLineAmt = claimdetail.ClaimCuryTranAmt * signOperation;
                        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.BranchID      = claimdetail.BranchID;
                        tran = docgraph.Transactions.Insert(tran);

                        PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, docgraph.Transactions.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());

                        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 * signOperation;
                            new_aptax.CuryTaxAmt     = tax.CuryTaxAmt * signOperation;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                    }

                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                    invoice.Hold           = false;
                    docgraph.Document.Update(invoice);
                    docgraph.Save.Press();
                    claim.Status    = EPExpenseClaimStatus.ReleasedStatus;
                    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);
            }
        }
Esempio n. 20
0
        private static void CreateMemo(ARInvoiceEntry graph, ARRegister doc, RUTROT rutrot, string docType, bool OnRelease = false)
        {
            DuplicateFilter filter = PXCache <DuplicateFilter> .CreateCopy(graph.duplicatefilter.Current);

            foreach (PXResult <ARInvoice, CurrencyInfo, Terms, Customer> res in ARInvoice_CurrencyInfo_Terms_Customer.Select(graph, (object)doc.DocType, doc.RefNbr, doc.CustomerID))
            {
                CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy((CurrencyInfo)res);

                info.CuryInfoID = null;
                info.IsReadOnly = false;
                info            = PXCache <CurrencyInfo> .CreateCopy(graph.currencyinfo.Insert(info));

                ARInvoice invoice = (ARInvoice)graph.Document.Cache.CreateInstance();

                if (docType == ARDocType.CreditMemo)
                {
                    invoice.DueDate     = null;
                    invoice.DiscDate    = null;
                    invoice.CustomerID  = doc.CustomerID;
                    invoice.ARAccountID = doc.ARAccountID;
                    invoice.ARSubID     = doc.ARSubID;
                }

                if (docType == ARInvoiceType.DebitMemo)
                {
                    invoice.DueDate  = ((ARInvoice)res).DueDate;
                    invoice.DiscDate = ((ARInvoice)res).DiscDate;

                    BranchRUTROT branchRUTROT = GetBranchRUTROT(graph);

                    invoice.CustomerID  = branchRUTROT.TaxAgencyAccountID;
                    invoice.ARAccountID = null;
                    invoice.ARSubID     = null;
                }

                ARInvoiceRUTROT invoiceRUTROT = RUTROTHelper.GetExtensionNullable <ARInvoice, ARInvoiceRUTROT>(invoice);
                invoiceRUTROT.IsRUTROTDeductible = false;

                invoice.CuryInfoID = info.CuryInfoID;
                invoice.DocType    = docType;
                invoice.OrigModule = GL.BatchModule.AR;
                invoice.RefNbr     = null;
                invoice.OrigModule = GL.BatchModule.AR;
                invoice.DocDesc    = PXLocalizer.LocalizeFormat(RUTROTMessages.MemoDescription, doc.RefNbr);

                invoice.OpenDoc    = true;
                invoice.Released   = false;
                invoice.Hold       = false;
                invoice.Printed    = false;
                invoice.Emailed    = false;
                invoice.BatchNbr   = null;
                invoice.ScheduleID = null;
                invoice.Scheduled  = false;
                invoice.NoteID     = null;
                invoice.RefNoteID  = null;

                invoice.TermsID             = null;
                invoice.InstallmentCntr     = null;
                invoice.InstallmentNbr      = null;
                invoice.CuryOrigDiscAmt     = 0m;
                invoice.FinPeriodID         = doc.FinPeriodID;
                invoice.OrigDocDate         = invoice.DocDate;
                invoice.CuryLineTotal       = 0m;
                invoice.IsTaxPosted         = false;
                invoice.IsTaxValid          = false;
                invoice.CuryVatTaxableTotal = 0m;
                invoice.CuryVatExemptTotal  = 0m;
                invoice.StatementDate       = null;
                invoice.PendingPPD          = false;
                invoice.CustomerLocationID  = null;

                if (!string.IsNullOrEmpty(invoice.PaymentMethodID))
                {
                    CA.PaymentMethod pm = null;

                    if (invoice.CashAccountID.HasValue)
                    {
                        CA.PaymentMethodAccount pmAccount = null;
                        PXResult <CA.PaymentMethod, CA.PaymentMethodAccount> pmResult = (PXResult <CA.PaymentMethod, CA.PaymentMethodAccount>)
                                                                                        PXSelectJoin <CA.PaymentMethod,
                                                                                                      LeftJoin <
                                                                                                          CA.PaymentMethodAccount, On <CA.PaymentMethod.paymentMethodID, Equal <CA.PaymentMethodAccount.paymentMethodID> > >,
                                                                                                      Where <
                                                                                                          CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> >,
                                                                                                          And <CA.PaymentMethodAccount.cashAccountID, Equal <Required <CA.PaymentMethodAccount.cashAccountID> > > > > .
                                                                                        Select(graph, invoice.PaymentMethodID, invoice.CashAccountID);

                        pm        = pmResult;
                        pmAccount = pmResult;

                        if (pm == null || pm.UseForAR == false || pm.IsActive == false)
                        {
                            invoice.PaymentMethodID = null;
                            invoice.CashAccountID   = null;
                        }
                        else if (pmAccount == null || pmAccount.CashAccountID == null || pmAccount.UseForAR != true)
                        {
                            invoice.CashAccountID = null;
                        }
                    }
                    else
                    {
                        pm = PXSelect <CA.PaymentMethod,
                                       Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > >
                             .Select(graph, invoice.PaymentMethodID);

                        if (pm == null || pm.UseForAR == false || pm.IsActive == false)
                        {
                            invoice.PaymentMethodID = null;
                            invoice.CashAccountID   = null;
                            invoice.PMInstanceID    = null;
                        }
                    }

                    if (invoice.PMInstanceID.HasValue)
                    {
                        CustomerPaymentMethod cpm = PXSelect <CustomerPaymentMethod,
                                                              Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .
                                                    Select(graph, invoice.PMInstanceID);

                        if (string.IsNullOrEmpty(invoice.PaymentMethodID) || cpm == null || cpm.IsActive == false || cpm.PaymentMethodID != invoice.PaymentMethodID)
                        {
                            invoice.PMInstanceID = null;
                        }
                    }
                }
                else
                {
                    invoice.CashAccountID = null;
                    invoice.PMInstanceID  = null;
                }

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARInvoice.salesPersonID>(graph.Document.Cache, invoice);

                if (sp == null || sp.IsActive == false)
                {
                    invoice.SalesPersonID = null;
                }

                invoice = graph.Document.Insert(invoice);
            }

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

            graph.FieldDefaulting.AddHandler <ARTran.salesPersonID>((sender, e) =>
            {
                e.NewValue = null;
                e.Cancel   = true;
            });

            decimal roundedTotalDistributedLinesAmt = 0m;

            foreach (ARTran srcTran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >,
                                                                And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr))
            {
                ARTran tran = PXCache <ARTran> .CreateCopy(srcTran);

                ARTranRUTROT tranRR = RUTROTHelper.GetExtensionNullable <ARTran, ARTranRUTROT>(tran);

                if (tranRR.IsRUTROTDeductible != true)
                {
                    continue;
                }

                tran.TranType = graph.Document.Current.DocType;
                tran.RefNbr   = graph.Document.Current.RefNbr;
                string origDrCr = tran.DrCr;
                tran.DrCr                        = null;
                tran.Released                    = null;
                tran.CuryInfoID                  = null;
                tran.SOOrderNbr                  = null;
                tran.SOShipmentNbr               = null;
                tran.OrigInvoiceDate             = tran.TranDate;
                tran.NoteID                      = null;
                tran.ManualPrice                 = true;
                tran.CuryTranAmt                 = Math.Floor(tranRR.CuryRUTROTAvailableAmt ?? 0m);
                roundedTotalDistributedLinesAmt += tran.CuryTranAmt ?? 0m;
                tranRR.IsRUTROTDeductible        = false;

                if (!string.IsNullOrEmpty(tran.DeferredCode))
                {
                    DRSchedule schedule = PXSelect <DRSchedule,
                                                    Where <DRSchedule.module, Equal <BQLConstants.moduleAR>,
                                                           And <DRSchedule.docType, Equal <Required <DRSchedule.docType> >,
                                                                And <DRSchedule.refNbr, Equal <Required <DRSchedule.refNbr> >,
                                                                     And <DRSchedule.lineNbr, Equal <Required <DRSchedule.lineNbr> > > > > > > .
                                          Select(graph, doc.DocType, doc.RefNbr, tran.LineNbr);

                    if (schedule != null)
                    {
                        tran.DefScheduleID = schedule.ScheduleID;
                    }
                }

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARTran.salesPersonID>(graph.Transactions.Cache, tran);

                if (sp == null || sp.IsActive == false)
                {
                    tran.SalesPersonID = null;
                }

                ARTran insertedTran = graph.Transactions.Insert(tran);
                PXNoteAttribute.CopyNoteAndFiles(graph.Transactions.Cache, srcTran, graph.Transactions.Cache, insertedTran);

                insertedTran.ManualDisc = true;

                insertedTran.TaxCategoryID = null;
                graph.Transactions.Update(insertedTran);
            }

            decimal distributedFee = (rutrot.CuryDistributedAmt ?? 0m) - roundedTotalDistributedLinesAmt;

            if (distributedFee != 0m)
            {
                foreach (ARTran artran in graph.Transactions.Cache.Inserted)
                {
                    if (Math.Round(distributedFee) == 0m)
                    {
                        break;
                    }
                    if (artran.CuryTranAmt != 0m)
                    {
                        artran.CuryTranAmt += Math.Sign(distributedFee);
                        distributedFee     -= Math.Sign(distributedFee);
                    }

                    graph.Transactions.Update(artran);
                }
            }

            graph.Document.Current.CuryOrigDocAmt = graph.Document.Current.CuryDocBal;
            graph.Document.Cache.Update(graph.Document.Current);

            graph.RowInserting.AddHandler <ARSalesPerTran>((sender, e) => { e.Cancel = true; });

            foreach (ARSalesPerTran salespertran in PXSelect <ARSalesPerTran, Where <ARSalesPerTran.docType, Equal <Required <ARSalesPerTran.docType> >,
                                                                                     And <ARSalesPerTran.refNbr, Equal <Required <ARSalesPerTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr))
            {
                ARSalesPerTran newtran = PXCache <ARSalesPerTran> .CreateCopy(salespertran);

                newtran.DocType         = graph.Document.Current.DocType;
                newtran.RefNbr          = graph.Document.Current.RefNbr;
                newtran.Released        = false;
                newtran.CuryInfoID      = null;
                newtran.CuryCommnblAmt *= -1m;
                newtran.CuryCommnAmt   *= -1m;

                SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARSalesPerTran.salespersonID>(graph.salesPerTrans.Cache, newtran);

                if (!(sp == null || sp.IsActive == false))
                {
                    graph.salesPerTrans.Update(newtran);
                }
            }

            var discountDetailsSet = PXSelect <ARInvoiceDiscountDetail,
                                               Where <ARInvoiceDiscountDetail.docType, Equal <Required <ARInvoice.docType> >,
                                                      And <ARInvoiceDiscountDetail.refNbr, Equal <Required <ARInvoice.refNbr> > > >,
                                               OrderBy <Asc <ARInvoiceDiscountDetail.docType,
                                                             Asc <ARInvoiceDiscountDetail.refNbr> > > >
                                     .Select(graph, doc.DocType, doc.RefNbr);

            foreach (ARInvoiceDiscountDetail discountDetail in discountDetailsSet)
            {
                ARInvoiceDiscountDetail newDiscountDetail = PXCache <ARInvoiceDiscountDetail> .CreateCopy(discountDetail);

                newDiscountDetail.DocType  = graph.Document.Current.DocType;
                newDiscountDetail.RefNbr   = graph.Document.Current.RefNbr;
                newDiscountDetail.IsManual = true;
                DiscountEngineProvider.GetEngineFor <ARTran, ARInvoiceDiscountDetail>().UpdateDiscountDetail(graph.ARDiscountDetails.Cache, graph.ARDiscountDetails, newDiscountDetail);
            }

            graph.Save.Press();

            if (docType == ARDocType.CreditMemo && !OnRelease)
            {
                CreateAdjustment(graph, doc, graph.Document.Current);
            }
        }
Esempio n. 21
0
        public virtual void CloneParts(AppointmentEntry gOriginalAppt, AppointmentEntry gNewAppt, FSAppointment newAppointmentRow, FSAppointmentDet sourceRow)
        {
            if (sourceRow == null || sourceRow.Status == ID.Status_AppointmentDet.CANCELED)
            {
                return;
            }

            FSSODet fsSODetRow = ServiceOrderCore.GetSODetFromAppointmentDet(gOriginalAppt, sourceRow);

            if (fsSODetRow == null)
            {
                return;
            }

            if (ReadingGraph == null)
            {
                ReadingGraph = new PXGraph();
            }

            FSAppointmentDet takenQtyByAppointments =
                PXSelectJoinGroupBy <FSAppointmentDet,
                                     InnerJoin <FSAppointment,
                                                On <
                                                    FSAppointment.srvOrdType, Equal <FSAppointmentDet.srvOrdType>,
                                                    And <FSAppointment.refNbr, Equal <FSAppointmentDet.refNbr> > > >,
                                     Where <
                                         FSAppointmentDet.sODetID, Equal <Required <FSAppointmentDet.sODetID> >,
                                         And <FSAppointment.status, NotEqual <FSAppointment.status.Canceled>,
                                              And <FSAppointmentDet.isCanceledNotPerformed, NotEqual <True> > > >,
                                     Aggregate <
                                         GroupBy <FSAppointmentDet.sODetID, Sum <FSAppointmentDet.billableQty> > > >
                .Select(ReadingGraph, sourceRow.SODetID);

            decimal?openQty    = fsSODetRow.BillableQty - (takenQtyByAppointments?.BillableQty ?? 0m);
            decimal?qtyFromBal = openQty >= sourceRow.BillableQty ? sourceRow.BillableQty :
                                 openQty > 0m ? openQty : 0m;
            decimal?         missingQty = sourceRow.BillableQty - qtyFromBal;
            FSAppointmentDet noteLine   = null;

            // Creates a copy to not edit the original row.
            FSAppointmentDet sourceRowCopy = PXCache <FSAppointmentDet> .CreateCopy(sourceRow);

            ClearSourceLineBeforeCopy(sourceRowCopy);

            if (qtyFromBal > 0)
            {
                sourceRowCopy.EstimatedQty = qtyFromBal;
                sourceRowCopy.BillableQty  = qtyFromBal;

                FSAppointmentDet newRow = new FSAppointmentDet();
                newRow = AppointmentEntry.InsertDetailLine <FSAppointmentDet, FSAppointmentDet>(
                    gNewAppt.AppointmentDetails.Cache,
                    newRow,
                    gOriginalAppt.AppointmentDetails.Cache,
                    sourceRowCopy,
                    null,
                    sourceRowCopy.SODetID,
                    copyTranDate: false,
                    tranDate: sourceRowCopy.TranDate,
                    SetValuesAfterAssigningSODetID: true,
                    copyingFromQuote: false);
                noteLine = newRow;
            }

            if (missingQty > 0)
            {
                sourceRowCopy.EstimatedQty = missingQty;
                sourceRowCopy.BillableQty  = missingQty;

                FSAppointmentDet newRow = new FSAppointmentDet();
                newRow = AppointmentEntry.InsertDetailLine <FSAppointmentDet, FSAppointmentDet>(
                    gNewAppt.AppointmentDetails.Cache,
                    newRow,
                    gOriginalAppt.AppointmentDetails.Cache,
                    sourceRowCopy,
                    null,
                    null,
                    copyTranDate: false,
                    tranDate: sourceRowCopy.TranDate,
                    SetValuesAfterAssigningSODetID: true,
                    copyingFromQuote: false);

                if (noteLine == null)
                {
                    noteLine = newRow;
                }
            }

            if (noteLine != null)
            {
                PXNoteAttribute.CopyNoteAndFiles(gOriginalAppt.AppointmentDetails.Cache,
                                                 sourceRow,
                                                 gNewAppt.AppointmentDetails.Cache,
                                                 noteLine,
                                                 copyNotes: true,
                                                 copyFiles: false);
            }
        }
Esempio n. 22
0
        public static void ReleaseDoc(EPExpenseClaim claim)
        {
            #region prepare required variables
            APInvoiceEntry    docgraph          = PXGraph.CreateInstance <APInvoiceEntry>();
            ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>();


            var receipts = PXSelect <EPExpenseClaimDetails,
                                     Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr).Select(
                result => (EPExpenseClaimDetails)result).GroupBy(
                item => Tuple.Create(
                    item.TaxZoneID,
                    item.TaxCalcMode
                    )).ToDictionary(x => x.Key, group => group.ToList());

            if (receipts.Count() == 0)
            {
                receipts.Add(Tuple.Create(claim.TaxZoneID, claim.TaxCalcMode), new List <EPExpenseClaimDetails>());
            }
            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

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

            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);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();
            #endregion

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (var res in receipts)
                {
                    docgraph.Clear(PXClearOption.ClearAll);
                    docgraph.SelectTimeStamp();
                    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);
                    #region CreateInoiceHeader
                    APInvoice invoice = new APInvoice();


                    bool reversedDocument = false;
                    if (res.Value.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0)
                    {
                        invoice.DocType  = APInvoiceType.DebitAdj;
                        reversedDocument = true;
                    }
                    else
                    {
                        invoice.DocType = APInvoiceType.Invoice;
                    }
                    decimal signOperation;
                    if (reversedDocument)
                    {
                        signOperation = -1;
                    }
                    else
                    {
                        signOperation = 1;
                    }

                    invoice.CuryInfoID = info.CuryInfoID;

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

                    invoice.DocDate          = claim.DocDate;
                    invoice.FinPeriodID      = claim.FinPeriodID;
                    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        = res.Key.Item1;
                    invoice.TaxCalcMode      = res.Key.Item2;
                    invoice.BranchID         = claim.BranchID;
                    invoice.OrigModule       = BatchModule.EP;
                    invoice.OrigRefNbr       = claim.RefNbr;

                    invoice = docgraph.Document.Insert(invoice);

                    PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                    info.CuryInfoID = invoice.CuryInfoID;

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

                    PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, docgraph.Document.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    #endregion
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    decimal?claimCuryTaxRoundDiff = 0m;
                    decimal?claimTaxRoundDiff     = 0m;
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        #region AddDetails

                        decimal tipQty;
                        if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                        {
                            tipQty = 1;
                        }
                        else
                        {
                            tipQty = -1;
                        }
                        Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                        if (claimdetail.TaskID != null)
                        {
                            PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, 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;
                        decimal unitCost;
                        decimal amount;
                        decimal taxableAmt;
                        decimal taxAmt;
                        if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            unitCost   = claimdetail.CuryUnitCost ?? 0m;
                            amount     = claimdetail.CuryTaxableAmt ?? 0m;
                            taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                            taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                        }
                        else
                        {
                            if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                            {
                                unitCost = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                            }
                            if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                            {
                                amount = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                            }
                            if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                            {
                                taxableAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                            }
                            if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                            {
                                taxAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                            }
                        }

                        tran.ManualPrice       = true;
                        tran.CuryUnitCost      = unitCost;
                        tran.Qty               = claimdetail.Qty * signOperation;
                        tran.UOM               = claimdetail.UOM;
                        tran.NonBillable       = claimdetail.Billable != true;
                        claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                        claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                        tran.Date              = claimdetail.ExpenseDate;

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

                        tran.TaskID        = claimdetail.TaskID;
                        tran.CostCodeID    = claimdetail.CostCodeID;
                        tran.AccountID     = claimdetail.ExpenseAccountID;
                        tran.SubID         = claimdetail.ExpenseSubID;
                        tran.TaxCategoryID = claimdetail.TaxCategoryID;
                        tran.BranchID      = claimdetail.BranchID;
                        tran                = docgraph.Transactions.Insert(tran);
                        tran.CuryLineAmt    = amount * signOperation;
                        tran.CuryTaxAmt     = 0;
                        tran.CuryTaxableAmt = taxableAmt * signOperation;
                        tran.CuryTaxAmt     = taxAmt * signOperation;
                        tran                = docgraph.Transactions.Update(tran);


                        if ((claimdetail.CuryTipAmt ?? 0) != 0)
                        {
                            APTran tranTip = new APTran();
                            if (epsetup.NonTaxableTipItem == null)
                            {
                                throw new PXException(Messages.TipItemIsNotDefined);
                            }
                            IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                                 Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                            if (tipItem == null)
                            {
                                string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                                throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                            }
                            tranTip.InventoryID = epsetup.NonTaxableTipItem;
                            tranTip.TranDesc    = tipItem.Descr;
                            if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                            {
                                tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                                tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                            }
                            else
                            {
                                decimal tipAmt;
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                                tranTip.CuryUnitCost = Math.Abs(tipAmt);
                                tranTip.CuryTranAmt  = tipAmt * signOperation;
                            }
                            tranTip.Qty         = tipQty;
                            tranTip.UOM         = tipItem.BaseUnit;
                            tranTip.NonBillable = claimdetail.Billable != true;
                            tranTip.Date        = claimdetail.ExpenseDate;

                            tranTip.BranchID = claimdetail.BranchID;
                            tranTip          = docgraph.Transactions.Insert(tranTip);

                            if (epsetup.UseReceiptAccountForTips == true)
                            {
                                tranTip.AccountID = claimdetail.ExpenseAccountID;
                                tranTip.SubID     = claimdetail.ExpenseSubID;
                            }
                            else
                            {
                                tranTip.AccountID = tipItem.COGSAcctID;
                                Location companyloc = (Location)PXSelectJoin <Location,
                                                                              InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                        And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                         InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                              Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                                PMTask task = PXSelect <PMTask,
                                                        Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                               And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                                Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                                int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                                int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                                int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                                int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                                int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                                int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                                object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                        new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                        new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                                docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                                tranTip.SubID = (int?)value;
                            }
                            tranTip = docgraph.Transactions.Update(tranTip);
                            tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                            tranTip.ProjectID     = tran.ProjectID;
                            tranTip.TaskID        = tran.TaskID;
                            tranTip = AddTaxes(docgraph, invoice, signOperation, claimdetail, tranTip, true);
                            tranTip = docgraph.Transactions.Update(tranTip);
                        }

                        PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, docgraph.Transactions.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                        claimdetail.Released = true;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                        #endregion


                        tran = AddTaxes(docgraph, invoice, signOperation, claimdetail, tran, false);
                    }

                    #region legacy taxes
                    foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                     Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                    {
                        #region Add taxes
                        APTaxTran new_aptax = docgraph.Taxes.Search <APTaxTran.taxID>(tax.TaxID);

                        if (new_aptax == null)
                        {
                            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.CuryTaxableAmt = 0m;
                                new_aptax.CuryTaxAmt     = 0m;
                                new_aptax.CuryExpenseAmt = 0m;
                                new_aptax = docgraph.Taxes.Update(new_aptax);
                            }
                        }

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

                            new_aptax.TaxRate        = tax.TaxRate;
                            new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                            new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                            new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                        #endregion
                    }
                    #endregion

                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                    invoice.Hold           = false;
                    docgraph.Document.Update(invoice);
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (APTran line in docgraph.Transactions.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }

                    docgraph.Document.Update(invoice);
                    docgraph.Save.Press();
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        claimdetail.APDocType = invoice.DocType;
                        claimdetail.APRefNbr  = invoice.RefNbr;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    }
                    claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                    claim.Released = true;
                    expenseClaimGraph.ExpenseClaim.Update(claim);

                    #region EP History Update
                    EPHistory hist = new EPHistory();
                    hist.EmployeeID  = invoice.VendorID;
                    hist.FinPeriodID = invoice.FinPeriodID;
                    hist             = (EPHistory)expenseClaimGraph.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)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                        tranhist.TranPtdClaimed += invoice.DocBal;
                        tranhist.TranYtdClaimed += invoice.DocBal;
                    }
                    expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                    #endregion

                    expenseClaimGraph.Save.Press();

                    doclist.Add(docgraph.Document.Current);
                }

                ts.Complete();
            }

            if ((bool)epsetup.AutomaticReleaseAP == true)
            {
                APDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Esempio n. 23
0
        public virtual List <PMTask> CreateProjectTrans()
        {
            var autoAllocateTasks = new List <PMTask>();

            if (Base.BatchModule.Current != null && Base.BatchModule.Current.Module != BatchModule.GL)
            {
                PXResultset <GLTran> trans = new PXSelect <GLTran,
                                                           Where <GLTran.module, Equal <Current <Batch.module> >,
                                                                  And <GLTran.batchNbr, Equal <Current <Batch.batchNbr> >,
                                                                       And <GLTran.pMTranID, IsNull,
                                                                            And <GLTran.isNonPM, NotEqual <True> > > > > >(Base).Select();

                if (trans.Count > 0)
                {
                    ProjectBalance pb = CreateProjectBalance();
                    var            tasksToAutoAllocate = new Dictionary <string, PMTask>();
                    var            sourceForAllocation = new List <PMTran>();

                    var doc = new PMRegister();
                    doc.Module      = Base.BatchModule.Current.Module;
                    doc.Date        = Base.BatchModule.Current.DateEntered;
                    doc.Description = Base.BatchModule.Current.Description;
                    doc.Released    = true;
                    doc.Status      = PMRegister.status.Released;
                    bool docInserted = false;                     //to prevent creating empty batch
                    JournalEntryTranRef entryRefGraph = PXGraph.CreateInstance <JournalEntryTranRef>();

                    foreach (GLTran tran in trans)
                    {
                        var acc = (Account)PXSelect <Account,
                                                     Where <Account.accountID, Equal <Required <GLTran.accountID> >,
                                                            And <Account.accountGroupID, IsNotNull> > > .Select(Base, tran.AccountID);

                        if (acc == null)
                        {
                            continue;
                        }

                        var ag = (PMAccountGroup)PXSelect <PMAccountGroup,
                                                           Where <PMAccountGroup.groupID, Equal <Required <Account.accountGroupID> >,
                                                                  And <PMAccountGroup.type, NotEqual <PMAccountType.offBalance> > > > .Select(Base, acc.AccountGroupID);

                        if (ag == null)
                        {
                            continue;
                        }

                        var project = (PMProject)PXSelect <PMProject,
                                                           Where <PMProject.contractID, Equal <Required <GLTran.projectID> >,
                                                                  And <PMProject.nonProject, Equal <False> > > > .Select(Base, tran.ProjectID);

                        if (project == null)
                        {
                            continue;
                        }

                        var task = (PMTask)PXSelect <PMTask,
                                                     Where <PMTask.projectID, Equal <Required <GLTran.projectID> >,
                                                            And <PMTask.taskID, Equal <Required <GLTran.taskID> > > > > .Select(Base, tran.ProjectID, tran.TaskID);

                        if (task == null)
                        {
                            continue;
                        }

                        APTran apTran = null;
                        if (Base.BatchModule.Current.Module == BatchModule.AP)
                        {
                            apTran = (APTran)PXSelect <APTran,
                                                       Where <APTran.refNbr, Equal <Required <GLTran.refNbr> >,
                                                              And <APTran.lineNbr, Equal <Required <GLTran.tranLineNbr> >,
                                                                   And <APTran.tranType, Equal <Required <GLTran.tranType> > > > > > .Select(Base, tran.RefNbr, tran.TranLineNbr, tran.TranType);
                        }

                        ARTran arTran = null;
                        if (Base.BatchModule.Current.Module == BatchModule.AR)
                        {
                            arTran = (ARTran)PXSelect <ARTran,
                                                       Where <ARTran.refNbr, Equal <Required <GLTran.refNbr> >,
                                                              And <ARTran.lineNbr, Equal <Required <GLTran.tranLineNbr> >,
                                                                   And <ARTran.tranType, Equal <Required <GLTran.tranType> > > > > > .Select(Base, tran.RefNbr, tran.TranLineNbr, tran.TranType);
                        }

                        if (!docInserted)
                        {
                            doc         = ProjectDocs.Insert(doc);
                            docInserted = true;
                        }

                        doc.OrigDocType = entryRefGraph.GetDocType(apTran, arTran, tran);
                        doc.OrigNoteID  = entryRefGraph.GetNoteID(apTran, arTran, tran);

                        PMTran pmt = (PMTran)ProjectTrans.Cache.Insert();

                        pmt.BranchID       = tran.BranchID;
                        pmt.AccountGroupID = acc.AccountGroupID;
                        pmt.AccountID      = tran.AccountID;
                        pmt.SubID          = tran.SubID;
                        entryRefGraph.AssignCustomerVendorEmployee(tran, pmt);                         //CustomerLocation is lost.
                        //pmt.BatchNbr = tran.BatchNbr;
                        pmt.Date         = tran.TranDate;
                        pmt.TranDate     = tran.TranDate;
                        pmt.Description  = tran.TranDesc;
                        pmt.FinPeriodID  = tran.FinPeriodID;
                        pmt.TranPeriodID = tran.TranPeriodID;
                        pmt.InventoryID  = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID;
                        pmt.OrigLineNbr  = tran.LineNbr;
                        pmt.OrigModule   = tran.Module;
                        pmt.OrigRefNbr   = tran.RefNbr;
                        pmt.OrigTranType = tran.TranType;
                        pmt.ProjectID    = tran.ProjectID;
                        pmt.TaskID       = tran.TaskID;
                        pmt.CostCodeID   = tran.CostCodeID;
                        if (arTran != null)
                        {
                            pmt.Billable                  = false;
                            pmt.ExcludedFromBilling       = true;
                            pmt.ExcludedFromBillingReason = arTran.TranType == ARDocType.CreditMemo ?
                                                            PXMessages.LocalizeFormatNoPrefix(Messages.ExcludedFromBillingAsCreditMemoResult, arTran.RefNbr) :
                                                            PXMessages.LocalizeFormatNoPrefix(Messages.ExcludedFromBillingAsARInvoiceResult, arTran.RefNbr);
                        }
                        else
                        {
                            pmt.Billable = tran.NonBillable != true;
                        }
                        pmt.Released = true;

                        if (apTran != null && apTran.Date != null)
                        {
                            pmt.Date = apTran.Date;
                        }

                        pmt.UseBillableQty = true;
                        pmt.UOM            = tran.UOM;

                        pmt.Amount = tran.DebitAmt - tran.CreditAmt;

                        CurrencyInfo projectCuryInfo = null;
                        if (PXAccess.FeatureInstalled <FeaturesSet.projectMultiCurrency>())
                        {
                            pmt.TranCuryID     = Base.BatchModule.Current.CuryID;
                            pmt.ProjectCuryID  = project.CuryID;
                            pmt.BaseCuryInfoID = tran.CuryInfoID;
                            pmt.TranCuryAmount = tran.CuryDebitAmt - tran.CuryCreditAmt;

                            if (project.CuryID == Base.ledger.Current.BaseCuryID)
                            {
                                pmt.ProjectCuryInfoID = tran.CuryInfoID;
                                pmt.ProjectCuryAmount = pmt.Amount;
                            }
                            else if (project.CuryID == Base.BatchModule.Current.CuryID)
                            {
                                projectCuryInfo                = new CurrencyInfo();
                                projectCuryInfo.ModuleCode     = GL.BatchModule.PM;
                                projectCuryInfo.BaseCuryID     = project.CuryID;
                                projectCuryInfo.CuryID         = project.CuryID;
                                projectCuryInfo.CuryRateTypeID = project.RateTypeID ?? Base.CMSetup.Current.PMRateTypeDflt;
                                projectCuryInfo.CuryEffDate    = tran.TranDate;
                                projectCuryInfo.CuryRate       = 1;
                                projectCuryInfo.RecipRate      = 1;
                                projectCuryInfo                = Base.currencyinfo.Insert(projectCuryInfo);
                                pmt.ProjectCuryInfoID          = projectCuryInfo.CuryInfoID;
                                pmt.ProjectCuryAmount          = pmt.TranCuryAmount;
                            }
                            else
                            {
                                CM.Extensions.IPXCurrencyService currencyService = ServiceLocator.Current.GetInstance <Func <PXGraph, CM.Extensions.IPXCurrencyService> >()(Base);

                                projectCuryInfo                = new CurrencyInfo();
                                projectCuryInfo.ModuleCode     = GL.BatchModule.PM;
                                projectCuryInfo.BaseCuryID     = project.CuryID;
                                projectCuryInfo.CuryID         = Base.BatchModule.Current.CuryID;
                                projectCuryInfo.CuryRateTypeID = project.RateTypeID ?? currencyService.DefaultRateTypeID(BatchModule.PM);
                                projectCuryInfo.CuryEffDate    = tran.TranDate;

                                var rate = currencyService.GetRate(projectCuryInfo.CuryID, projectCuryInfo.BaseCuryID, projectCuryInfo.CuryRateTypeID, projectCuryInfo.CuryEffDate);
                                if (rate == null)
                                {
                                    throw new PXException(PM.Messages.FxTranToProjectNotFound, projectCuryInfo.CuryID, projectCuryInfo.BaseCuryID, projectCuryInfo.CuryRateTypeID, tran.TranDate);
                                }

                                projectCuryInfo       = Base.currencyinfo.Insert(projectCuryInfo);
                                pmt.ProjectCuryInfoID = projectCuryInfo.CuryInfoID;
                                decimal val;
                                PXCurrencyAttribute.CuryConvBase(Base.BatchModule.Cache, projectCuryInfo, pmt.TranCuryAmount.GetValueOrDefault(), out val);
                                pmt.ProjectCuryAmount = val;
                            }
                        }
                        else
                        {
                            pmt.TranCuryAmount    = pmt.Amount;
                            pmt.ProjectCuryAmount = pmt.Amount;
                            pmt.TranCuryID        = Base.ledger.Current.BaseCuryID;
                            pmt.ProjectCuryID     = Base.ledger.Current.BaseCuryID;

                            if (Base.BatchModule.Current.CuryID != Base.ledger.Current.BaseCuryID)
                            {
                                CurrencyInfo baseCuryInfo = new CurrencyInfo();
                                baseCuryInfo.ModuleCode     = GL.BatchModule.PM;
                                baseCuryInfo.BaseCuryID     = Base.ledger.Current.BaseCuryID;
                                baseCuryInfo.CuryID         = Base.ledger.Current.BaseCuryID;
                                baseCuryInfo.CuryRateTypeID = null;
                                baseCuryInfo.CuryEffDate    = tran.TranDate;
                                baseCuryInfo.CuryRate       = 1;
                                baseCuryInfo.RecipRate      = 1;
                                baseCuryInfo          = Base.currencyinfo.Insert(baseCuryInfo);
                                pmt.ProjectCuryInfoID = baseCuryInfo.CuryInfoID;
                                pmt.BaseCuryInfoID    = baseCuryInfo.CuryInfoID;
                            }
                            else
                            {
                                pmt.ProjectCuryInfoID = tran.CuryInfoID;
                                pmt.BaseCuryInfoID    = tran.CuryInfoID;
                            }
                        }

                        pmt.Qty = tran.Qty;                        //pmt.Amount >= 0 ? tran.Qty : (tran.Qty * -1);
                        int sign = 1;
                        if (acc.Type == AccountType.Income || acc.Type == AccountType.Liability)
                        {
                            sign = -1;
                        }

                        if (ProjectBalance.IsFlipRequired(acc.Type, ag.Type))
                        {
                            pmt.ProjectCuryAmount = -pmt.ProjectCuryAmount;
                            pmt.TranCuryAmount    = -pmt.TranCuryAmount;
                            pmt.Amount            = -pmt.Amount;
                            pmt.Qty = -pmt.Qty;
                        }
                        pmt.BillableQty = pmt.Qty;


                        Base.GLTranModuleBatNbr.SetValueExt <GLTran.pMTranID>(tran, pmt.TranID);

                        if (apTran != null && apTran.NoteID != null)
                        {
                            PXNoteAttribute.CopyNoteAndFiles(Base.Caches[typeof(AP.APTran)], apTran, ProjectTrans.Cache, pmt);
                        }
                        else if (arTran != null && arTran.NoteID != null)
                        {
                            PXNoteAttribute.CopyNoteAndFiles(Base.Caches[typeof(AR.ARTran)], arTran, ProjectTrans.Cache, pmt);
                        }

                        ProjectBalance.Result balance = pb.Calculate(project, pmt, ag, acc.Type, sign, 1);

                        if (balance.Status != null)
                        {
                            PMBudgetAccum ps = new PMBudgetAccum();
                            ps.ProjectID      = balance.Status.ProjectID;
                            ps.ProjectTaskID  = balance.Status.ProjectTaskID;
                            ps.AccountGroupID = balance.Status.AccountGroupID;
                            ps.InventoryID    = balance.Status.InventoryID;
                            ps.CostCodeID     = balance.Status.CostCodeID;
                            ps.UOM            = balance.Status.UOM;
                            ps.IsProduction   = balance.Status.IsProduction;
                            ps.Type           = balance.Status.Type;
                            ps.Description    = balance.Status.Description;
                            ps.CuryInfoID     = balance.Status.CuryInfoID;

                            ps                   = ProjectBudget.Insert(ps);
                            ps.ActualQty        += balance.Status.ActualQty.GetValueOrDefault();
                            ps.CuryActualAmount += balance.Status.CuryActualAmount.GetValueOrDefault();
                            ps.ActualAmount     += balance.Status.ActualAmount.GetValueOrDefault();

                            if (arTran != null && arTran.LineNbr != null && ag.Type == GL.AccountType.Income)
                            {
                                ps.CuryInvoicedAmount -= balance.Status.CuryActualAmount.GetValueOrDefault();
                                ps.InvoicedAmount     -= balance.Status.ActualAmount.GetValueOrDefault();
                            }
                        }

                        if (balance.ForecastHistory != null)
                        {
                            PMForecastHistoryAccum forecast = new PMForecastHistoryAccum();
                            forecast.ProjectID      = balance.ForecastHistory.ProjectID;
                            forecast.ProjectTaskID  = balance.ForecastHistory.ProjectTaskID;
                            forecast.AccountGroupID = balance.ForecastHistory.AccountGroupID;
                            forecast.InventoryID    = balance.ForecastHistory.InventoryID;
                            forecast.CostCodeID     = balance.ForecastHistory.CostCodeID;
                            forecast.PeriodID       = balance.ForecastHistory.PeriodID;

                            forecast = ForecastHistory.Insert(forecast);

                            forecast.ActualQty        += balance.ForecastHistory.ActualQty.GetValueOrDefault();
                            forecast.CuryActualAmount += balance.ForecastHistory.CuryActualAmount.GetValueOrDefault();
                            forecast.ActualAmount     += balance.ForecastHistory.ActualAmount.GetValueOrDefault();
                        }

                        if (balance.TaskTotal != null)
                        {
                            PMTaskTotal ta = new PMTaskTotal();
                            ta.ProjectID = balance.TaskTotal.ProjectID;
                            ta.TaskID    = balance.TaskTotal.TaskID;

                            ta                = ProjectTaskTotals.Insert(ta);
                            ta.CuryAsset     += balance.TaskTotal.CuryAsset.GetValueOrDefault();
                            ta.Asset         += balance.TaskTotal.Asset.GetValueOrDefault();
                            ta.CuryLiability += balance.TaskTotal.CuryLiability.GetValueOrDefault();
                            ta.Liability     += balance.TaskTotal.Liability.GetValueOrDefault();
                            ta.CuryIncome    += balance.TaskTotal.CuryIncome.GetValueOrDefault();
                            ta.Income        += balance.TaskTotal.Income.GetValueOrDefault();
                            ta.CuryExpense   += balance.TaskTotal.CuryExpense.GetValueOrDefault();
                            ta.Expense       += balance.TaskTotal.Expense.GetValueOrDefault();
                        }

                        RegisterReleaseProcess.AddToUnbilledSummary(Base, pmt);

                        sourceForAllocation.Add(pmt);
                        if (pmt.Allocated != true && pmt.ExcludedFromAllocation != true && project.AutoAllocate == true)
                        {
                            if (!tasksToAutoAllocate.ContainsKey(string.Format("{0}.{1}", task.ProjectID, task.TaskID)))
                            {
                                tasksToAutoAllocate.Add(string.Format("{0}.{1}", task.ProjectID, task.TaskID), task);
                            }
                        }

                        entryRefGraph.AssignAdditionalFields(tran, pmt);
                    }
                    autoAllocateTasks.AddRange(tasksToAutoAllocate.Values);
                }
            }
            return(autoAllocateTasks);
        }
        public static void ConvertToAccount(Contact contact, AccountsFilter param)
        {
            BusinessAccountMaint accountMaint = CreateInstance <BusinessAccountMaint>();
            object cd = param.BAccountID;

            accountMaint.BAccount.Cache.RaiseFieldUpdating <BAccount.acctCD>(null, ref cd);
            BAccount account = new BAccount
            {
                AcctCD           = (string)cd,
                AcctName         = param.AccountName,
                Type             = BAccountType.ProspectType,
                ClassID          = param.AccountClass,
                ParentBAccountID = contact.ParentBAccountID
            };

            #region Set Contact and Address fields
            CRContactClass cls = PXSelect <CRContactClass, Where <CRContactClass.classID, Equal <Current <Contact.classID> > > > .SelectSingleBound(accountMaint, new object[] { contact });

            if (cls != null && cls.OwnerToBAccount == true)
            {
                account.WorkgroupID = contact.WorkgroupID;
                account.OwnerID     = contact.OwnerID;
            }

            try
            {
                object newValue = account.OwnerID;
                accountMaint.BAccount.Cache.RaiseFieldVerifying <BAccount.ownerID>(account, ref newValue);
            }
            catch (PXSetPropertyException)
            {
                account.OwnerID = null;
            }

            account = accountMaint.BAccount.Insert(account);

            accountMaint.Answers.CopyAllAttributes(account, contact);

            Contact defContact = PXCache <Contact> .CreateCopy(PXSelect <Contact, Where <Contact.contactID, Equal <Current <BAccount.defContactID> > > > .SelectSingleBound(accountMaint, new object[] { account }));

            var defContactNoteID = defContact.NoteID;
            PXCache <Contact> .RestoreCopy(defContact, contact);

            defContact.ContactType     = ContactTypesAttribute.BAccountProperty;
            defContact.FullName        = account.AcctName;
            defContact.ContactID       = account.DefContactID;
            defContact.BAccountID      = account.BAccountID;
            defContact.DuplicateStatus = DuplicateStatusAttribute.NotValidated;
            defContact.DuplicateFound  = false;
            defContact.WorkgroupID     = null;
            defContact.OwnerID         = null;
            defContact.NoteID          = defContactNoteID;
            defContact = accountMaint.DefContact.Update(defContact);

            Address contactAddress = PXSelect <Address, Where <Address.addressID, Equal <Required <Contact.defAddressID> > > > .Select(accountMaint, contact.DefAddressID);

            if (contactAddress == null)
            {
                throw new PXException(Messages.DefAddressNotExists, contact.DisplayName);
            }
            contactAddress.BAccountID = account.BAccountID;
            accountMaint.AddressCurrent.Cache.Clear();

            defContact.DefAddressID = contactAddress.AddressID;
            defContact = accountMaint.DefContact.Update(defContact);

            contactAddress = accountMaint.AddressCurrent.Update(contactAddress);

            account.DefAddressID = contactAddress.AddressID;
            accountMaint.BAccount.Update(account);

            contact.BAccountID      = account.BAccountID;
            contact.DuplicateStatus = DuplicateStatusAttribute.NotValidated;
            contact.DuplicateFound  = false;
            if (contact.QualificationDate == null)
            {
                contact.QualificationDate = PXTimeZoneInfo.Now;
            }
            accountMaint.Contacts.Cache.SetStatus(contact, PXEntryStatus.Updated);
            CR.Location location = accountMaint.DefLocation.Select();
            location.DefAddressID = contactAddress.AddressID;
            accountMaint.DefLocation.Update(location);

            account.NoteID = PXNoteAttribute.GetNoteID <CRActivity.noteID>(accountMaint.CurrentBAccount.Cache, account);
            foreach (CRPMTimeActivity a in PXSelect <CRPMTimeActivity, Where <CRPMTimeActivity.refNoteID, Equal <Required <Contact.noteID> > > > .Select(accountMaint, contact.NoteID))
            {
                a.BAccountID = account.BAccountID;
                accountMaint.Activities.Cache.Update(a);
            }
            #endregion

            // Copy Note text and Files references
            CRSetup setup = PXSetupOptional <CRSetup> .Select(accountMaint);

            PXNoteAttribute.CopyNoteAndFiles(accountMaint.Contacts.Cache, contact, accountMaint.CurrentBAccount.Cache, account, setup);

            throw new PXRedirectRequiredException(accountMaint, "Business Account");
        }
        private void CloneParts(AppointmentEntry sourceAppointmentGraph, AppointmentEntry newAppointmentGraph, FSAppointment newAppointmentRow)
        {
            foreach (FSAppointmentDetPart sourceRow in sourceAppointmentGraph.AppointmentDetParts.Select())
            {
                FSSODet fsSODetRow = ServiceOrderCore.GetSODetFromAppointmentDet(sourceAppointmentGraph, sourceRow);

                if (fsSODetRow != null &&
                    (fsSODetRow.Status == ID.Status_AppointmentDet.CANCELED ||
                     fsSODetRow.Status == ID.Status_AppointmentDet.COMPLETED))
                {
                    continue;
                }

                FSAppointmentDet sumFSAppointmentDetPartBillable =
                    PXSelectJoinGroupBy <FSAppointmentDet,
                                         InnerJoin <FSAppointment, On <FSAppointment.srvOrdType, Equal <FSAppointmentDet.srvOrdType>,
                                                                       And <FSAppointment.refNbr, Equal <FSAppointmentDetPart.refNbr> > > >,
                                         Where <FSAppointmentDet.sODetID, Equal <Required <FSAppointmentDet.sODetID> >,
                                                And <FSAppointment.status, NotEqual <FSAppointment.status.Canceled>,
                                                     And <FSAppointmentDet.status, NotEqual <FSAppointmentDet.status.Canceled> > > >,
                                         Aggregate <GroupBy <FSAppointmentDet.sODetID, Sum <FSAppointmentDet.billableQty> > > >
                    .Select(dummyGraph, sourceRow.SODetID);

                decimal?openQty    = fsSODetRow.BillableQty - sumFSAppointmentDetPartBillable.BillableQty;
                bool?   lineCloned = false;

                FSAppointmentDetPart newRow = PXCache <FSAppointmentDetPart> .CreateCopy(sourceRow);

                if (openQty >= sourceRow.BillableQty)
                {
                    newRow = AppointmentEntry.InsertServicePartLine <FSAppointmentDetPart, FSAppointmentDetPart>(
                        newAppointmentGraph.AppointmentDetParts.Cache,
                        newRow,
                        sourceAppointmentGraph.AppointmentDetParts.Cache,
                        sourceRow,
                        null,
                        sourceRow.SODetID,
                        copyTranDate: false,
                        tranDate: sourceRow.TranDate,
                        SetValuesAfterAssigningSODetID: true,
                        copyingFromQuote: false);
                    lineCloned = true;
                }
                else
                {
                    if (openQty > 0)
                    {
                        decimal?remainingQty = sourceRow.BillableQty - openQty;

                        newRow.Qty             = 0;
                        sourceRow.EstimatedQty = openQty;
                        sourceRow.BillableQty  = openQty;
                        newRow = AppointmentEntry.InsertServicePartLine <FSAppointmentDetPart, FSAppointmentDetPart>(
                            newAppointmentGraph.AppointmentDetParts.Cache,
                            newRow,
                            sourceAppointmentGraph.AppointmentDetParts.Cache,
                            sourceRow,
                            null,
                            sourceRow.SODetID,
                            copyTranDate: false,
                            tranDate: sourceRow.TranDate,
                            SetValuesAfterAssigningSODetID: true,
                            copyingFromQuote: false);
                        lineCloned = true;

                        FSAppointmentDetPart secondNewRow = PXCache <FSAppointmentDetPart> .CreateCopy(sourceRow);

                        secondNewRow.Qty       = 0;
                        sourceRow.EstimatedQty = remainingQty;
                        sourceRow.BillableQty  = remainingQty;
                        secondNewRow.SODetID   = null;
                        secondNewRow           = AppointmentEntry.InsertServicePartLine <FSAppointmentDetPart, FSAppointmentDetPart>(
                            newAppointmentGraph.AppointmentDetParts.Cache,
                            secondNewRow,
                            sourceAppointmentGraph.AppointmentDetParts.Cache,
                            sourceRow,
                            null,
                            null,
                            copyTranDate: false,
                            tranDate: sourceRow.TranDate,
                            SetValuesAfterAssigningSODetID: false,
                            copyingFromQuote: false);
                    }
                    else
                    {
                        newRow.SODetID = null;
                        newRow.Qty     = 0;
                        newRow         = AppointmentEntry.InsertServicePartLine <FSAppointmentDetPart, FSAppointmentDetPart>(
                            newAppointmentGraph.AppointmentDetParts.Cache,
                            newRow,
                            sourceAppointmentGraph.AppointmentDetParts.Cache,
                            sourceRow,
                            null,
                            null,
                            copyTranDate: false,
                            tranDate: sourceRow.TranDate,
                            SetValuesAfterAssigningSODetID: false,
                            copyingFromQuote: false);
                    }
                }


                if (lineCloned == true)
                {
                    PXNoteAttribute.CopyNoteAndFiles(
                        sourceAppointmentGraph.AppointmentDetParts.Cache,
                        sourceRow,
                        newAppointmentGraph.AppointmentDetParts.Cache,
                        newRow,
                        copyNotes: true,
                        copyFiles: false);

                    AppointmentCore.UpdateAppointmentsInfoInServiceOrder(newAppointmentGraph.AppointmentDetParts.Cache, newRow, ServiceOrderRelated);
                }
            }
        }
Esempio n. 26
0
        public virtual void GenerateProc(Schedule schedule, short times, DateTime runDate)
        {
            string lastBatchNbr = "0000000000";
            long   lastInfoID   = -1;

            IEnumerable <ScheduleDet> occurrences = new Scheduler(this).MakeSchedule(schedule, times, runDate);

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

                        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, scheduledBatch.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          = BatchStatus.Balanced;
                        copy.Scheduled       = false;
                        copy.AutoReverseCopy = false;

                        copy.DateEntered = occurrence.ScheduledDate;

                        FinPeriod finPeriod =
                            FinPeriodRepository.GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(copy.BranchID), occurrence.ScheduledPeriod)
                            .GetValueOrRaiseError();
                        copy.FinPeriodID  = finPeriod.FinPeriodID;
                        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.CopyNoteAndFiles(Caches[typeof(BatchNew)], scheduledBatch, Batch_Created.Cache, copy);

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

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

                            transactionCopy.TranDate = occurrence.ScheduledDate;
                            FinPeriodIDAttribute.SetPeriodsByMaster <GLTranNew.finPeriodID>(Tran_Created.Cache, transactionCopy, occurrence.ScheduledPeriod);

                            transactionCopy = Tran_Created.Cache.Insert(transactionCopy) as GLTranNew;
                            PXNoteAttribute.CopyNoteAndFiles(Tran_Created.Cache, scheduledBatchTransaction, Tran_Created.Cache, transactionCopy);
                        }
                    }

                    schedule.LastRunDate = occurrence.ScheduledDate;
                    Running_Schedule.Cache.Update(schedule);
                }

                Running_Schedule.Cache.Persist(PXDBOperation.Update);

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

                foreach (GLTranNew createdTransaction in Tran_Created.Cache.Inserted)
                {
                    foreach (BatchNew createdBatch in Batch_Created.Cache.Cached)
                    {
                        if (object.Equals(createdBatch.RefBatchNbr, createdTransaction.RefBatchNbr))
                        {
                            createdTransaction.BatchNbr   = createdBatch.BatchNbr;
                            createdTransaction.CuryInfoID = createdBatch.CuryInfoID;

                            if (!string.IsNullOrEmpty(createdBatch.RefNbr))
                            {
                                createdTransaction.RefNbr = createdBatch.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);
        }
Esempio n. 27
0
        public virtual void CloneAppointment(AppointmentEntry graphOriginalAppointment, AppointmentEntry graphNewAppointment)
        {
            if (AppointmentSelected.Current == null)
            {
                return;
            }

            graphNewAppointment.Clear(PXClearOption.ClearAll);
            graphNewAppointment.clearLocalServiceOrder();

            FSAppointment fsAppointmentRow = PXCache <FSAppointment> .CreateCopy(AppointmentSelected.Current);

            var itemLineRefNbr = new Dictionary <string, string>();

            //Clear key and special fields
            fsAppointmentRow.RefNbr                     = null;
            fsAppointmentRow.AppointmentID              = null;
            fsAppointmentRow.NoteID                     = null;
            fsAppointmentRow.CuryInfoID                 = null;
            fsAppointmentRow.FullNameSignature          = null;
            fsAppointmentRow.customerSignaturePath      = null;
            fsAppointmentRow.BillServiceContractID      = null;
            fsAppointmentRow.HandleManuallyActualTime   = null;
            fsAppointmentRow.HandleManuallyScheduleTime = null;
            fsAppointmentRow.LogLineCntr                = 0;
            fsAppointmentRow.FinPeriodID                = null;
            fsAppointmentRow.PostingStatusAPARSO        = ID.Status_Posting.PENDING_TO_POST;
            fsAppointmentRow.PendingAPARSOPost          = true;

            fsAppointmentRow.OriginalAppointmentID = AppointmentSelected.Current.AppointmentID;

            fsAppointmentRow.ScheduledDateTimeBegin = AppointmentCore.GetDateTimeEnd(
                Filter.Current.ScheduledDate, Filter.Current.ScheduledStartTime);

            DateTime?scheduledDateTimeEnd = null;

            fsAppointmentRow.ScheduledDateTimeEnd =
                scheduledDateTimeEnd =
                    AppointmentCore.GetDateTimeEnd(
                        Filter.Current.ScheduledDate, Filter.Current.ScheduledEndTime);

            fsAppointmentRow.ExecutionDate = fsAppointmentRow.ScheduledDateTimeBegin.Value.Date;

            fsAppointmentRow.CutOffDate
                = ServiceOrderCore.GetCutOffDate(graphNewAppointment, graphOriginalAppointment.ServiceOrderRelated.Current.CBID, fsAppointmentRow.ExecutionDate, fsAppointmentRow.SrvOrdType);

            fsAppointmentRow.Status = ID.Status_Appointment.MANUAL_SCHEDULED;
            fsAppointmentRow.Hold   = false;

            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //Clean total fields
            fsAppointmentRow.EstimatedDurationTotal = 0;
            fsAppointmentRow.ActualDurationTotal    = 0;

            fsAppointmentRow.CuryEstimatedLineTotal = 0;
            fsAppointmentRow.CuryLineTotal          = 0;
            fsAppointmentRow.CuryBillableLineTotal  = 0;
            fsAppointmentRow.CuryCostTotal          = 0;

            fsAppointmentRow.EstimatedLineTotal = 0;
            fsAppointmentRow.LineTotal          = 0;
            fsAppointmentRow.BillableLineTotal  = 0;
            fsAppointmentRow.CostTotal          = 0;
            fsAppointmentRow.LineCntr           = 0;
            //----------------------------------------------------------------------

            graphNewAppointment.IsCloningAppointment = true;
            fsAppointmentRow = graphNewAppointment.AppointmentRecords.Insert(fsAppointmentRow);

            graphNewAppointment.Answers.Current = graphNewAppointment.Answers.Select();
            graphNewAppointment.Answers.CopyAllAttributes(graphNewAppointment.AppointmentRecords.Current, AppointmentSelected.Current);

            PXNoteAttribute.CopyNoteAndFiles(AppointmentSelected.Cache,
                                             AppointmentSelected.Current,
                                             graphNewAppointment.AppointmentSelected.Cache,
                                             fsAppointmentRow,
                                             copyNotes: true,
                                             copyFiles: false);


            foreach (FSAppointmentDet sourceRow in graphOriginalAppointment.AppointmentDetails.Select())
            {
                if (sourceRow.IsInventoryItem == true)
                {
                    this.CloneParts(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow, sourceRow);
                }
                else if (sourceRow.IsInventoryItem == false && sourceRow.IsPickupDelivery == false)
                {
                    this.CloneServices(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow, sourceRow, itemLineRefNbr);
                }
            }

            this.CloneEmployees(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow, itemLineRefNbr);
            this.CloneResources(graphOriginalAppointment, graphNewAppointment, fsAppointmentRow);

            if (graphNewAppointment.AppointmentRecords.Current.ScheduledDateTimeEnd != scheduledDateTimeEnd)
            {
                graphNewAppointment.AppointmentRecords.Cache.SetValueExt <FSAppointment.handleManuallyScheduleTime>(fsAppointmentRow, true);
                graphNewAppointment.AppointmentRecords.Cache.SetValueExt <FSAppointment.scheduledDateTimeEnd>(fsAppointmentRow, scheduledDateTimeEnd);
            }

            graphNewAppointment.AppointmentRecords.Cache.SetDefaultExt <FSAppointment.billContractPeriodID>(fsAppointmentRow);
            graphNewAppointment.Save.Press();
        }