Example #1
0
        protected static FR_L5SO_SSHwP_1030 Execute(DbConnection Connection, DbTransaction Transaction, P_L5SO_SSHwP_1030 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_L5SO_SSHwP_1030();
            returnValue.Result = new L5SO_SSHwP_1030();

            var oldShipmentHeader = new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Header();
            oldShipmentHeader.Load(Connection, Transaction, Parameter.HeaderID);

            var oldPositions = CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Position.Query.Search(Connection, Transaction,
                                                                                      new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Position.Query
            {
                LOG_SHP_Shipment_Header_RefID = Parameter.HeaderID,
                IsDeleted    = false,
                Tenant_RefID = securityTicket.TenantID
            });

            bool isThereAnyDifference = false;
            foreach (var item in Parameter.Positions)
            {
                var oldPosition = oldPositions.Single(x => x.LOG_SHP_Shipment_PositionID == item.PositionID);

                if (oldPosition.QuantityToShip > item.PickingQuantity)
                {
                    isThereAnyDifference = true;
                    break;
                }
            }

            if (!isThereAnyDifference)
            {
                throw new ShipmentHeaderException(ResultMessage.SplitShipment_ThereIsNoDifferenceBetweenNewAndOldOne);
            }

            #region Create New ShippmentHeader

            var incrNumberParam = new P_L2NR_GaIINfUA_1454()
            {
                GlobalStaticMatchingID = EnumUtils.GetEnumDescription(ENumberRangeUsageAreaType.ShipmentNumber)
            };
            var shipmentOrderNumber = cls_Get_and_Increase_IncreasingNumber_for_UsageArea.Invoke(Connection, Transaction, incrNumberParam, securityTicket).Result.Current_IncreasingNumber;


            var newShipmentHeader = new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Header();
            newShipmentHeader.LOG_SHP_Shipment_HeaderID = Guid.NewGuid();
            newShipmentHeader.ShipmentHeader_Number     = shipmentOrderNumber;
            newShipmentHeader.Tenant_RefID               = securityTicket.TenantID;
            newShipmentHeader.Creation_Timestamp         = DateTime.Now;
            newShipmentHeader.IsPartialShippingAllowed   = oldShipmentHeader.IsPartialShippingAllowed;
            newShipmentHeader.Shippipng_AddressUCD_RefID = oldShipmentHeader.Shippipng_AddressUCD_RefID;
            newShipmentHeader.Source_Warehouse_RefID     = oldShipmentHeader.Source_Warehouse_RefID;
            newShipmentHeader.ShipmentPriority           = oldShipmentHeader.ShipmentPriority;
            newShipmentHeader.ShipmentType_RefID         = oldShipmentHeader.ShipmentType_RefID;

            newShipmentHeader.RecipientBusinessParticipant_RefID = oldShipmentHeader.RecipientBusinessParticipant_RefID;

            newShipmentHeader.Save(Connection, Transaction);

            var assignmentQuery = new CL1_LOG_SHP.ORM_LOG_SHP_ShipmentHeader_2_CustomerOrderHeader.Query();
            assignmentQuery.LOG_SHP_Shipment_Header_RefID = oldShipmentHeader.LOG_SHP_Shipment_HeaderID;
            assignmentQuery.IsDeleted    = false;
            assignmentQuery.Tenant_RefID = securityTicket.TenantID;

            var oldAssignment = CL1_LOG_SHP.ORM_LOG_SHP_ShipmentHeader_2_CustomerOrderHeader.Query.Search(Connection, Transaction, assignmentQuery).Single();

            var shipmentToCustomerOrderHeader = new CL1_LOG_SHP.ORM_LOG_SHP_ShipmentHeader_2_CustomerOrderHeader();
            shipmentToCustomerOrderHeader.ORD_CUO_CustomerOrder_Header_RefID = oldAssignment.ORD_CUO_CustomerOrder_Header_RefID;
            shipmentToCustomerOrderHeader.LOG_SHP_Shipment_Header_RefID      = newShipmentHeader.LOG_SHP_Shipment_HeaderID;
            shipmentToCustomerOrderHeader.Tenant_RefID       = securityTicket.TenantID;
            shipmentToCustomerOrderHeader.Creation_Timestamp = DateTime.Now;
            shipmentToCustomerOrderHeader.Save(Connection, Transaction);

            #region Status

            var statusCreated = CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Status.Query.Search(Connection, Transaction,
                                                                                     new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Status.Query()
            {
                GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EShipmentStatus.Created),
                Tenant_RefID             = securityTicket.TenantID,
                IsDeleted = false
            }).Single();

            var account = new CL1_USR.ORM_USR_Account();
            account.Load(Connection, Transaction, securityTicket.AccountID);

            var shipmentStatusHistory = new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_StatusHistory();
            shipmentStatusHistory.LOG_SHP_Shipment_Header_RefID         = newShipmentHeader.LOG_SHP_Shipment_HeaderID;
            shipmentStatusHistory.LOG_SHP_Shipment_Status_RefID         = statusCreated.LOG_SHP_Shipment_StatusID;
            shipmentStatusHistory.PerformedBy_BusinessParticipant_RefID = account.BusinessParticipant_RefID;
            shipmentStatusHistory.Tenant_RefID = account.Tenant_RefID;
            shipmentStatusHistory.Save(Connection, Transaction);

            #endregion

            #endregion

            var param = new P_L5SO_GSPwPaSfSH_1141()
            {
                ShippmentHeaderID = Parameter.HeaderID,
                LanguageID        = Parameter.LanguageID
            };
            var splittingPositions = cls_Get_ShipmentPositions_with_Prices_and_Stock_for_ShipmentHeaderID.Invoke(Connection, Transaction, param, securityTicket).Result;

            decimal totalAmountForOldHeader = 0;
            decimal totalAmountForNewHeader = 0;
            foreach (var item in Parameter.Positions)
            {
                var oldPosition = oldPositions.Single(x => x.LOG_SHP_Shipment_PositionID == item.PositionID);

                var newQuantity       = oldPosition.QuantityToShip - item.PickingQuantity;
                var positionToSplit   = splittingPositions.Single(x => x.ShipmentPositionID == item.PositionID);
                var availableQuantity = positionToSplit.QuantityAvailable;

                decimal unitPrice = oldPosition.ShipmentPosition_PricePerUnitValueWithoutTax;

                if (item.PickingQuantity > availableQuantity + positionToSplit.ReservedQuantity)
                {
                    throw new ShipmentHeaderException(ResultMessage.SplitShipment_FreeQuantityNotAvailable);
                }

                if (newQuantity > 0)
                {
                    var newPosition = new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Position
                    {
                        LOG_SHP_Shipment_PositionID   = Guid.NewGuid(),
                        LOG_SHP_Shipment_Header_RefID = newShipmentHeader.LOG_SHP_Shipment_HeaderID,
                        Tenant_RefID          = securityTicket.TenantID,
                        CMN_PRO_Product_RefID = oldPosition.CMN_PRO_Product_RefID,
                        QuantityToShip        = newQuantity,
                        ShipmentPosition_PricePerUnitValueWithoutTax = unitPrice,
                        ShipmentPosition_ValueWithoutTax             = unitPrice * (decimal)newQuantity
                    };
                    newPosition.Save(Connection, Transaction);

                    totalAmountForNewHeader += newPosition.ShipmentPosition_ValueWithoutTax;

                    var oldAssignmentCustomerOrderToShipmentPosition = CL1_ORD_CUO.ORM_ORD_CUO_CustomerOrder_Position_2_ShipmentPosition.Query.Search(Connection, Transaction,
                                                                                                                                                      new CL1_ORD_CUO.ORM_ORD_CUO_CustomerOrder_Position_2_ShipmentPosition.Query
                    {
                        LOG_SHP_Shipment_Position_RefID = oldPosition.LOG_SHP_Shipment_PositionID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).Single();

                    var customerOrder2ShipmentPosition = new CL1_ORD_CUO.ORM_ORD_CUO_CustomerOrder_Position_2_ShipmentPosition
                    {
                        AssignmentID       = Guid.NewGuid(),
                        Creation_Timestamp = DateTime.Now,
                        Tenant_RefID       = securityTicket.TenantID,
                        IsDeleted          = false,
                        LOG_SHP_Shipment_Position_RefID      = newPosition.LOG_SHP_Shipment_PositionID,
                        ORD_CUO_CustomerOrder_Position_RefID = oldAssignmentCustomerOrderToShipmentPosition.ORD_CUO_CustomerOrder_Position_RefID,
                        CMN_BPT_CTM_OrganizationalUnit_RefID = oldAssignmentCustomerOrderToShipmentPosition.CMN_BPT_CTM_OrganizationalUnit_RefID
                    };
                    customerOrder2ShipmentPosition.Save(Connection, Transaction);
                }

                oldPosition.QuantityToShip = item.PickingQuantity;
                oldPosition.ShipmentPosition_ValueWithoutTax = unitPrice * (decimal)item.PickingQuantity;
                oldPosition.IsDeleted = (oldPosition.QuantityToShip == 0);

                oldPosition.Save(Connection, Transaction);

                totalAmountForOldHeader += oldPosition.ShipmentPosition_ValueWithoutTax;
            }

            oldShipmentHeader.ShipmentHeader_ValueWithoutTax = totalAmountForOldHeader;
            oldShipmentHeader.Save(Connection, Transaction);

            newShipmentHeader.ShipmentHeader_ValueWithoutTax = totalAmountForNewHeader;
            newShipmentHeader.Save(Connection, Transaction);

            // set return value to ok and new header's id
            returnValue.Result.NewHeaderID = newShipmentHeader.LOG_SHP_Shipment_HeaderID;
            returnValue.Result.Message     = CL5_APOLogistic_ShippingOrder.Utils.ResultMessage.SplitShipment_OK;

            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5BL_SBPfSP_1632 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            // shipped status for tenant
            var statusParam = new CL5_APOBilling_Shipment.Atomic.Retrieval.P_L5SH_GSSfGPMaT_1700
            {
                GlobalPropertyMatchingID = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(DLCore_DBCommons.APODemand.EShipmentStatus.Shipped)
            };
            var statusResult = CL5_APOBilling_Shipment.Atomic.Retrieval.cls_Get_Shipment_Status_for_GlobalPropertyMatchingID_and_TenantID.Invoke(Connection, Transaction, statusParam, securityTicket).Result;

            // Get bill positions for header ID
            var parameterBillPosition = new CL5_APOBilling_Bill.Atomic.Retrieval.P_L5BL_GBPfBH_1534();
            parameterBillPosition.BillHeaderID     = Parameter.BillHeaderID;
            parameterBillPosition.ShipmentStatusID = statusResult.LOG_SHP_Shipment_StatusID;
            var alreadyAddedBillPositions = CL5_APOBilling_Bill.Atomic.Retrieval.cls_Get_BillPositions_for_BillHeader.Invoke(Connection, Transaction, parameterBillPosition, securityTicket).Result;

            // It must be the same RecipientBusinessParticipant_RefID for all bill positions on one header.
            if (alreadyAddedBillPositions.Select(x => x.RecipientBusinessParticipant_RefID).Distinct().ToList().Count > 1)
            {
                throw new ArgumentException(string.Format("There are duplicates for RecipientBusinessParticipant_RefID in database. BillHeaderID={1}", Parameter.BillHeaderID));
            }
            Guid recipientBusinessParticipantID = alreadyAddedBillPositions.Select(x => x.RecipientBusinessParticipant_RefID).Distinct().SingleOrDefault();

            var billHeader = new CL1_BIL.ORM_BIL_BillHeader();
            billHeader.Load(Connection, Transaction, Parameter.BillHeaderID);

            int positionCounter = 0;
            foreach (var id in Parameter.ShipmentPositions)
            {
                #region Find Shipment Position
                // Find Shipment Position
                var shipmentPosition = new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Position();
                shipmentPosition.Load(Connection, Transaction, id);

                // Check if Position is good
                if (shipmentPosition == null || shipmentPosition.LOG_SHP_Shipment_PositionID == Guid.Empty)
                {
                    continue;
                }

                #endregion

                #region Find Product and Taxes
                // Find Product
                var product = new CL1_CMN_PRO.ORM_CMN_PRO_Product();
                product.Load(Connection, Transaction, shipmentPosition.CMN_PRO_Product_RefID);

                // Find taxes
                var productTax = CL1_CMN_PRO.ORM_CMN_PRO_Product_SalesTaxAssignmnet.Query.Search(Connection, Transaction,
                                                                                                 new CL1_CMN_PRO.ORM_CMN_PRO_Product_SalesTaxAssignmnet.Query
                {
                    Product_RefID = product.CMN_PRO_ProductID,
                    Tenant_RefID  = securityTicket.TenantID,
                    IsDeleted     = false
                }).FirstOrDefault();

                var tax = new CL1_ACC_TAX.ORM_ACC_TAX_Tax();
                if (productTax != null)
                {
                    tax.Load(Connection, Transaction, productTax.ApplicableSalesTax_RefID);
                }
                else
                {
                    tax = null;
                }
                #endregion

                #region Find Bill Header and Shipment Header
                // Find Bill Header

                // Find Shipment Header
                var shipmentHeader = new CL1_LOG_SHP.ORM_LOG_SHP_Shipment_Header();
                shipmentHeader.Load(Connection, Transaction, shipmentPosition.LOG_SHP_Shipment_Header_RefID);
                #endregion

                #region Check Bill Header status
                // Get status for bill header
                var statusCreated = CL1_BIL.ORM_BIL_BillStatus.Query.Search(Connection, Transaction,
                                                                            new CL1_BIL.ORM_BIL_BillStatus.Query
                {
                    GlobalPropertyMatchingID = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(DLCore_DBCommons.APODemand.EBillStatus.Created),
                    Tenant_RefID             = securityTicket.TenantID,
                    IsDeleted = false
                }).Single();

                // Check current bill header status
                var billHeaderStatuses = CL1_BIL.ORM_BIL_BillHeader_2_BillStatus.Query.Search(Connection, Transaction,
                                                                                              new CL1_BIL.ORM_BIL_BillHeader_2_BillStatus.Query
                {
                    BIL_BillHeader_RefID = billHeader.BIL_BillHeaderID,
                    IsCurrentStatus      = true,
                    Tenant_RefID         = securityTicket.TenantID,
                    IsDeleted            = false
                });

                var billHeaderStatusesExists = billHeaderStatuses.Any(x => x.BIL_BillStatus_RefID == statusCreated.BIL_BillStatusID);

                // Throw exception if bill doesn't have a good status
                if (!billHeaderStatusesExists)
                {
                    throw new Exception("Bill header doesn't have created status!");
                }
                #endregion

                #region Check does current bill position have the same customer
                // Check does current bill position have the same customer
                if (recipientBusinessParticipantID == Guid.Empty)
                {
                    recipientBusinessParticipantID = shipmentHeader.RecipientBusinessParticipant_RefID;
                }
                else
                {
                    if (recipientBusinessParticipantID != shipmentHeader.RecipientBusinessParticipant_RefID)
                    {
                        throw new ArgumentException("All Shipment positions must have the same RecipientBusinessParticipant_RefID");
                    }
                }
                #endregion

                #region Check does exist bill position for current order position
                bool exist = CL1_BIL.ORM_BIL_BillPosition_2_ShipmentPosition.Query.Exists(Connection, Transaction,
                                                                                          new CL1_BIL.ORM_BIL_BillPosition_2_ShipmentPosition.Query
                {
                    LOG_SHP_Shipment_Position_RefID = shipmentPosition.LOG_SHP_Shipment_PositionID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                });
                if (exist)
                {
                    throw new ArgumentException("There is already Bill position for some Shipment position");
                }
                #endregion

                #region Create Bill Position
                // Create Bill position for Customer order position
                var billPosition = new CL1_BIL.ORM_BIL_BillPosition();
                billPosition.BIL_BilHeader_RefID          = billHeader.BIL_BillHeaderID;
                billPosition.BIL_BillPosition_Group_RefID = Guid.Empty;
                billPosition.ApplicableSalesTax_RefID     = (tax != null ? tax.ACC_TAX_TaxeID : Guid.Empty);
                billPosition.PositionNumber                         = string.Empty;
                billPosition.BillPosition_Description               = string.Empty;
                billPosition.BillPosition_Comment                   = string.Empty;
                billPosition.PositionIndex                          = positionCounter++;
                billPosition.PositionValue_BeforeTax                = Convert.ToDecimal(shipmentPosition.ShipmentPosition_ValueWithoutTax);
                billPosition.PositionPricePerUnitValue_BeforeTax    = shipmentPosition.ShipmentPosition_PricePerUnitValueWithoutTax;
                billPosition.PositionPricePerUnitValue_IncludingTax = DLUtils_Common.Calculations.MoneyUtils.CalculateGrossPriceForTaxInPercent(billPosition.PositionPricePerUnitValue_BeforeTax, Convert.ToDecimal(tax == null ? 0 : tax.TaxRate));
                billPosition.PositionValue_IncludingTax             = billPosition.PositionPricePerUnitValue_IncludingTax * (decimal)shipmentPosition.QuantityToShip;
                billPosition.BillPosition_ProductNumber             = product.Product_Number;
                billPosition.Quantity           = (decimal)shipmentPosition.QuantityToShip;
                billPosition.Tenant_RefID       = securityTicket.TenantID;
                billPosition.Creation_Timestamp = DateTime.Now;
                billPosition.Save(Connection, Transaction);

                // Create relationship between Bill position and Shipment position
                var billPosition2ShipmentPosition = new CL1_BIL.ORM_BIL_BillPosition_2_ShipmentPosition();
                billPosition2ShipmentPosition.BIL_BillPosition_RefID          = billPosition.BIL_BillPositionID;
                billPosition2ShipmentPosition.LOG_SHP_Shipment_Position_RefID = shipmentPosition.LOG_SHP_Shipment_PositionID;
                billPosition2ShipmentPosition.Tenant_RefID       = securityTicket.TenantID;
                billPosition2ShipmentPosition.Creation_Timestamp = DateTime.Now;
                billPosition2ShipmentPosition.Save(Connection, Transaction);

                // Change Bill Header total values
                billHeader.TotalValue_BeforeTax    = alreadyAddedBillPositions.Sum(x => x.PositionValue_BeforeTax) + billPosition.PositionValue_BeforeTax;
                billHeader.TotalValue_IncludingTax = alreadyAddedBillPositions.Sum(x => x.PositionValue_IncludingTax) + billPosition.PositionValue_IncludingTax;

                #endregion
            }

            // Save Bill Header with new total values
            billHeader.Save(Connection, Transaction);
            return(new FR_Guid(Guid.NewGuid()));

            #endregion UserCode
        }