public void Rollback()
		{
		  _caches.ForEach(c => c.Restore());
		  _dbTransactionScope.Dispose();
		  _dbTransactionScope = new PXTransactionScope();
		  _commited = false;
		  _rolledBack = true;
		}
		protected void PersistRecord(Package package, object record)
		{
			if (record == null) return;

			var cache = package.Graph.Caches[record.GetType()];
			var status = cache.GetStatus(record);
			try
			{
				using(var ts = new PXTransactionScope())
				{
					switch (status)
					{
						case PXEntryStatus.Updated:
							cache.Persist(record, PXDBOperation.Update);
							break;
						case PXEntryStatus.Inserted:
							cache.Persist(record, PXDBOperation.Insert);
							break;
						case PXEntryStatus.Deleted:
							cache.Persist(record, PXDBOperation.Delete);
							break;
						default:
							throw new InvalidOperationException();
					}
					ts.Complete();
				}
			}
			catch (Exception)
			{
				cache.Remove(record);
				throw;
			}
		}
		public override void Persist()
		{
			CopyFreightNotesAndFilesToARTran();

			foreach (ARTran tran in Transactions.Cache.Deleted)
			{
				ARTran siblings = PXSelect<ARTran, Where<ARTran.sOOrderType, Equal<Required<ARTran.sOOrderType>>,
					And<ARTran.sOOrderNbr, Equal<Required<ARTran.sOOrderNbr>>,
					And<ARTran.sOShipmentType, Equal<Required<ARTran.sOShipmentType>>,
					And<ARTran.sOShipmentNbr, Equal<Required<ARTran.sOShipmentNbr>>,
					And<ARTran.tranType, Equal<Required<ARTran.tranType>>,
					And<ARTran.refNbr, Equal<Required<ARTran.refNbr>>>>>>>>>.SelectWindowed(this, 0, 1,
					tran.SOOrderType, tran.SOOrderNbr, tran.SOShipmentType, tran.SOShipmentNbr, tran.TranType, tran.RefNbr);

				if (siblings != null && siblings.LineType != SOLineType.Freight)
				{
					throw new PXException(Messages.PartialInvoice);
				}
			}

			foreach (ARInvoice invoice in Document.Cache.Deleted)
			{
				foreach (SOInvoice ext in SODocument.Cache.Deleted)
				{
					if (string.Equals(ext.DocType, invoice.DocType) && string.Equals(ext.RefNbr, invoice.RefNbr) && 
						(invoice.IsCCPayment == true ||ext.IsCCPayment == true) && ccProcTran.View.SelectMultiBound( new object[] { invoice, ext }).Count > 0)
					{
						ARPaymentEntry docgraph = PXGraph.CreateInstance<ARPaymentEntry>();
						docgraph.AutoPaymentApp = true;
						docgraph.arsetup.Current.HoldEntry = false;
						docgraph.arsetup.Current.RequireControlTotal = false;

						ARPayment payment = new ARPayment()
						{
							DocType = ARDocType.Payment,
							AdjDate = ext.AdjDate,
							AdjFinPeriodID = ext.AdjFinPeriodID
						};

						payment = PXCache<ARPayment>.CreateCopy(docgraph.Document.Insert(payment));
						payment.CustomerID = invoice.CustomerID;
						payment.CustomerLocationID = invoice.CustomerLocationID;
						payment.ARAccountID = invoice.ARAccountID;
						payment.ARSubID = invoice.ARSubID;

                        payment.PaymentMethodID = ext.PaymentMethodID;
                        payment.PMInstanceID = ext.PMInstanceID;
						payment.CashAccountID = ext.CashAccountID;
						payment.ExtRefNbr = ext.ExtRefNbr ?? string.Format(AR.Messages.ARAutoPaymentRefNbrFormat, payment.DocDate);
						payment.CuryOrigDocAmt = ext.CuryPaymentAmt;

						docgraph.Document.Update(payment);

						using (PXTransactionScope ts = new PXTransactionScope())
						{
							docgraph.Save.Press();

							PXDatabase.Update<CCProcTran>(
								new PXDataFieldAssign("DocType", docgraph.Document.Current.DocType),
								new PXDataFieldAssign("RefNbr", docgraph.Document.Current.RefNbr),
								new PXDataFieldRestrict("DocType", PXDbType.Char, 3, ext.DocType, PXComp.EQ),
								new PXDataFieldRestrict("RefNbr", PXDbType.NVarChar, 15, ext.RefNbr, PXComp.EQ)
								);

							int i = 0;
							bool ccproctranupdated = false;

							foreach (SOOrderShipment order in PXSelect<SOOrderShipment,
								Where<SOOrderShipment.invoiceType, Equal<Required<SOOrderShipment.invoiceType>>,
								And<SOOrderShipment.invoiceNbr, Equal<Required<SOOrderShipment.invoiceNbr>>>>>.Select(docgraph, ext.DocType, ext.RefNbr))
							{
								ccproctranupdated |= PXDatabase.Update<CCProcTran>(
									new PXDataFieldAssign("DocType", docgraph.Document.Current.DocType),
									new PXDataFieldAssign("RefNbr", docgraph.Document.Current.RefNbr),
									new PXDataFieldRestrict("OrigDocType", PXDbType.Char, 3, order.OrderType, PXComp.EQ),
									new PXDataFieldRestrict("OrigRefNbr", PXDbType.NVarChar, 15, order.OrderNbr, PXComp.EQ),
									new PXDataFieldRestrict("RefNbr", PXDbType.NVarChar, 15, null, PXComp.ISNULL)
									);

								if (ccproctranupdated && i > 0)
								{
									throw new PXException(AR.Messages.ERR_CCMultiplyPreauthCombined);
								}

								i++;
							}

							docgraph.ccProcTran.View.Clear();
							docgraph.Document.Cache.RaiseRowSelected(docgraph.Document.Current);

							PXFieldState voidState;
							if ((voidState = (PXFieldState)docgraph.voidCheck.GetState(Document.Current)) == null || voidState.Enabled == false)
							{
								throw new PXException(AR.Messages.ERR_CCTransactionMustBeVoided);
							}

							List<object> tovoid = new List<object>();
							tovoid.Add(docgraph.Document.Current);

							foreach(object item in docgraph.voidCheck.Press(new PXAdapter(new DummyView(docgraph, docgraph.Document.View.BqlSelect, tovoid)))) { ; }

							base.Persist();

							ts.Complete();
						}

						return;
					}
				}
			}

			foreach (ARAdjust adj in Adjustments.Cache.Inserted)
			{
				if (adj.CuryAdjdAmt == 0m)
				{
					Adjustments.Cache.SetStatus(adj, PXEntryStatus.InsertedDeleted);
				}
			}

			foreach (ARAdjust adj in Adjustments.Cache.Updated)
			{
				if (adj.CuryAdjdAmt == 0m)
				{
					Adjustments.Cache.SetStatus(adj, PXEntryStatus.Deleted);
				}
			}

			foreach (ARInvoice ardoc in Document.Cache.Cached)
			{
				if ((Document.Cache.GetStatus(ardoc) == PXEntryStatus.Inserted || Document.Cache.GetStatus(ardoc) == PXEntryStatus.Updated) && ardoc.DocType == ARDocType.Invoice && ardoc.Released == false && ardoc.ApplyPaymentWhenTaxAvailable != true)
				{
					SOInvoice ext = SODocument.Select(ardoc.DocType, ardoc.RefNbr);

					if (ardoc.CuryDocBal - ardoc.CuryOrigDiscAmt - ext.CuryPaymentTotal - ext.CuryCCCapturedAmt < 0m)
					{
						foreach (PXResult<ARAdjust> res in Adjustments_Raw.View.SelectMultiBound(new object[] { ardoc }))
						{
							ARAdjust adj = res;
							if (Adjustments.Cache.GetStatus(adj) == PXEntryStatus.Notchanged)
							{
								Adjustments.Cache.SetStatus(adj, PXEntryStatus.Updated);
							}
							Adjustments.Cache.RaiseExceptionHandling<ARAdjust.curyAdjdAmt>(adj, adj.CuryAdjdAmt, new PXSetPropertyException(AR.Messages.Application_Amount_Cannot_Exceed_Document_Amount));
							throw new PXException(AR.Messages.Application_Amount_Cannot_Exceed_Document_Amount);
						}
					}
				}
			}

			base.Persist();
		}
        public virtual void ReleaseLCTrans(IEnumerable <LandedCostTran> aTranSet, DocumentList <INRegister> aINCreated, DocumentList <APInvoice> aAPCreated)
        {
            Dictionary <int, APInvoiceEntry>    apGraphs = new Dictionary <int, APInvoiceEntry>();
            Dictionary <int, INAdjustmentEntry> inGraphs = new Dictionary <int, INAdjustmentEntry>();
            Dictionary <int, int>    combinations        = new Dictionary <int, int>();
            List <APRegister>        forReleaseAP        = new List <APRegister>();
            List <INRegister>        forReleaseIN        = new List <INRegister>();
            DocumentList <APInvoice> apDocuments         = new DocumentList <APInvoice>(this);
            POSetup poSetupR          = this.poSetup.Select();
            bool    autoReleaseIN     = poSetupR.AutoReleaseLCIN.Value;
            bool    autoReleaseAP     = poSetupR.AutoReleaseAP.Value;
            bool    noApplicableItems = false;

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

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

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

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

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

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

                        if (inGraphs.ContainsKey(tran.LCTranID.Value))
                        {
                            INAdjustmentEntry inGraph = inGraphs[iTran.LCTranID.Value];
                            inGraph.Save.Press();
                            tran.INDocType = inGraph.adjustment.Current.DocType;
                            tran.INRefNbr  = inGraph.adjustment.Current.RefNbr;
                            tran.Processed = true;
                            forReleaseIN.Add(inGraph.adjustment.Current);
                            if (aINCreated != null)
                            {
                                aINCreated.Add(inGraph.adjustment.Current);
                            }
                            needUpdate = true;
                        }
                        if (needUpdate)
                        {
                            LandedCostTran copy = (LandedCostTran)this.landedCostTrans.Cache.CreateCopy(tran);
                            tran = this.landedCostTrans.Update(copy);
                        }
                    }
                    this.Actions.PressSave();
                    ts.Complete();
                }
            }
            if (noApplicableItems == true)
            {
                throw new NoApplicableSourceException(Messages.LandedCostAmountRemainderCannotBeDistributedMultyLines);
            }

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

            if (autoReleaseIN)
            {
                if (forReleaseIN.Count > 0)
                {
                    INDocumentRelease.ReleaseDoc(forReleaseIN, false);
                }
            }
        }
Example #5
0
        public virtual IEnumerable Clone(PXAdapter adapter)
        {
            if (this.Filter.Current.ScheduledEndTime == null)
            {
                Filter.Cache.RaiseExceptionHandling <FSCloneAppointmentFilter.scheduledEndTime>(
                    Filter.Current,
                    null,
                    new PXSetPropertyException(
                        PXMessages.LocalizeFormatNoPrefix(
                            TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                            PXUIFieldAttribute.GetDisplayName <FSCloneAppointmentFilter.scheduledEndTime>(Filter.Cache)),
                        PXErrorLevel.Error));

                return(adapter.Get());
            }

            if (this.Filter.Current.CloningType == ID.CloningType_CloneAppointment.MULTIPLE)
            {
                if (this.Filter.Current.ScheduledFromDate == null)
                {
                    Filter.Cache.RaiseExceptionHandling <FSCloneAppointmentFilter.scheduledFromDate>(
                        Filter.Current,
                        null,
                        new PXSetPropertyException(
                            PXMessages.LocalizeFormatNoPrefix(
                                TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                                PXUIFieldAttribute.GetDisplayName <FSCloneAppointmentFilter.scheduledFromDate>(Filter.Cache)),
                            PXErrorLevel.Error));

                    return(adapter.Get());
                }

                if (this.Filter.Current.ScheduledToDate == null)
                {
                    Filter.Cache.RaiseExceptionHandling <FSCloneAppointmentFilter.scheduledToDate>(
                        Filter.Current,
                        null,
                        new PXSetPropertyException(
                            PXMessages.LocalizeFormatNoPrefix(
                                TX.Error.FIELD_MAY_NOT_BE_EMPTY,
                                PXUIFieldAttribute.GetDisplayName <FSCloneAppointmentFilter.scheduledToDate>(Filter.Cache)),
                            PXErrorLevel.Error));

                    return(adapter.Get());
                }
            }

            FSServiceOrder fsServiceOrderRow = PXSelectJoin <FSServiceOrder,
                                                             InnerJoin <
                                                                 FSAppointment, On <FSAppointment.sOID, Equal <FSServiceOrder.sOID> > >,
                                                             Where <
                                                                 FSAppointment.appointmentID, Equal <Required <FSAppointment.appointmentID> > > >
                                               .Select(this, this.Filter.Current.AppointmentID);

            if (fsServiceOrderRow != null &&
                fsServiceOrderRow.Status == ID.Status_ServiceOrder.COMPLETED)
            {
                throw new PXException(TX.Error.CANNOT_CLONE_APPOINMENT_SERVICE_ORDER_COMPLETED);
            }

            CloneAppointmentProcess graphCloneAppointmentProcess = PXGraph.CreateInstance <CloneAppointmentProcess>();

            graphCloneAppointmentProcess.Filter.Current.SrvOrdType         = this.Filter.Current.SrvOrdType;
            graphCloneAppointmentProcess.Filter.Current.RefNbr             = this.Filter.Current.RefNbr;
            graphCloneAppointmentProcess.Filter.Current.KeepTimeDuration   = this.Filter.Current.KeepTimeDuration;
            graphCloneAppointmentProcess.Filter.Current.ScheduledDate      = this.Filter.Current.ScheduledDate;
            graphCloneAppointmentProcess.Filter.Current.ScheduledStartTime = this.Filter.Current.ScheduledStartTime;
            graphCloneAppointmentProcess.Filter.Current.ScheduledEndTime   = this.Filter.Current.ScheduledEndTime;

            graphCloneAppointmentProcess.Filter.Current.ScheduledFromDate = this.Filter.Current.ScheduledFromDate;
            graphCloneAppointmentProcess.Filter.Current.ScheduledToDate   = this.Filter.Current.ScheduledToDate;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnMonday    = this.Filter.Current.ActiveOnMonday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnThursday  = this.Filter.Current.ActiveOnThursday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnWednesday = this.Filter.Current.ActiveOnWednesday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnTuesday   = this.Filter.Current.ActiveOnTuesday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnFriday    = this.Filter.Current.ActiveOnFriday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnSaturday  = this.Filter.Current.ActiveOnSaturday;
            graphCloneAppointmentProcess.Filter.Current.ActiveOnSunday    = this.Filter.Current.ActiveOnSunday;

            graphCloneAppointmentProcess.AppointmentSelected.Current = this.AppointmentSelected.Current;

            PXLongOperation.StartOperation(
                this,
                delegate
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    if (this.Filter.Current.CloningType == ID.CloningType_CloneAppointment.SINGLE)
                    {
                        AppointmentEntry graphOriginalAppointment = PXGraph.CreateInstance <AppointmentEntry>();

                        graphOriginalAppointment.AppointmentSelected.Current = graphOriginalAppointment.AppointmentRecords.Search <FSAppointment.appointmentID>
                                                                                   (AppointmentSelected.Current.AppointmentID, AppointmentSelected.Current.SrvOrdType);

                        graphCloneAppointmentProcess.CloneAppointment(graphOriginalAppointment, PXGraph.CreateInstance <AppointmentEntry>());
                    }

                    if (this.Filter.Current.CloningType == ID.CloningType_CloneAppointment.MULTIPLE)
                    {
                        graphCloneAppointmentProcess.CloneMultipleAppointments(graphCloneAppointmentProcess);
                    }

                    ts.Complete();
                }
            });

            return(adapter.Get());
        }