Exemplo n.º 1
0
        public PickupInformationViewModel(CustomerOrderTransaction custTransaction)
        {
            this.transaction = custTransaction;

            // Get list of addresses
            storeDataManager = new DM.StoreDataManager(
                SalesOrder.InternalApplication.Settings.Database.Connection,
                SalesOrder.InternalApplication.Settings.Database.DataAreaID);

            customerDataManager = new DM.CustomerDataManager(
                SalesOrder.InternalApplication.Settings.Database.Connection,
                SalesOrder.InternalApplication.Settings.Database.DataAreaID);

            // Create a read-only collection
            stores = new ReadOnlyCollection <DataEntity.Store>(storeDataManager.GetStoresForPickup(SalesOrder.InternalApplication.Settings.Database.DataAreaID));

            // Load date
            if (custTransaction.RequestedDeliveryDate > DateTime.MinValue)
            {
                this.pickUpDate = custTransaction.RequestedDeliveryDate;
            }

            // Load store
            if (!string.IsNullOrWhiteSpace(custTransaction.WarehouseId))
            {
                this.selectedStore = storeDataManager.GetWarehouseStore(custTransaction.WarehouseId);
            }
            else
            {
                this.selectedStore = storeDataManager.GetStore(LSRetailPosis.Settings.ApplicationSettings.Terminal.StoreId);
            }
        }
Exemplo n.º 2
0
        public void AuthorizeCustomerAccountPayment(ref bool valid, ref string comment, ref string manualAuthenticationCode, string customerId, decimal amount, DE.IRetailTransaction retailTransaction)
        {
            try
            {
                LSRetailPosis.ApplicationLog.Log(this.ToString(), "Customer.AuthorizeCustomerAccountPayment()", LSRetailPosis.LogTraceLevel.Trace);
                //Get the customer information for the customer
                DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                    ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);
                DE.ICustomer tempCust = customerDataManager.GetTransactionalCustomer(customerId);

                if (!string.IsNullOrEmpty(tempCust.InvoiceAccount))
                {
                    DE.ICustomer tempInvCust = customerDataManager.GetTransactionalCustomer(tempCust.InvoiceAccount);
                    if (tempInvCust.Blocked == DE.BlockedEnum.All)
                    {
                        tempCust.Blocked = tempInvCust.Blocked;
                    }
                    else if (tempInvCust.Blocked == DE.BlockedEnum.Invoice && tempCust.Blocked != DE.BlockedEnum.All)
                    {
                        tempCust.Blocked = DE.BlockedEnum.Invoice;
                    }
                }

                valid = true;

                if (LSRetailPosis.Settings.ApplicationSettings.Terminal.Standalone == true)
                {
                    decimal balance = customerDataManager.GetBalance(tempCust.CustomerId);
                    if (((balance * -1) + Convert.ToDecimal(amount)) > tempCust.CreditLimit)
                    {
                        valid   = false;
                        comment = LSRetailPosis.ApplicationLocalizer.Language.Translate(51007);  // The amount charged is higher than existing creditlimit
                    }
                    return;
                }

                // Using the transaction services to validate the transaction
                this.Application.TransactionServices.ValidateCustomerStatus(ref valid, ref comment, customerId, amount, retailTransaction.StoreCurrencyCode);
                if (comment.Length > 0)
                {
                    if (comment.Substring(0, 1) == "\t")
                    {
                        comment = comment.Remove(0, 1);
                    }
                }
            }
            catch (LSRetailPosis.PosisException px)
            {
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), px);
                throw;
            }
            catch (Exception x)
            {
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), x);
                throw;
            }
        }
Exemplo n.º 3
0
        public void Print()
        {
            DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);

            //Get the balances
            IList <DE.CustomerBalanceInfo> customerBalances = customerDataManager.GetCustomersBalances();

            if ((customerBalances != null) && (customerBalances.Count > 0))
            {
                //Print header information
                int    charsInLine = 44;
                string line        = "--------------------------------------------" + "\n";
                string reportName  = LSRetailPosis.ApplicationLocalizer.Language.Translate(51020); //"BALANCE REPORT"
                int    leftPad     = (charsInLine - reportName.Length) / 2;
                string report      = "\n" + reportName.PadLeft(leftPad + reportName.Length) + "\n\n\n";
                report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51021) + " " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "\n\n"; //"Report printed"
                //Customer         //Name               //Balance
                report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51022).PadRight(10).Substring(0, 10) + " " + LSRetailPosis.ApplicationLocalizer.Language.Translate(51023).PadRight(20).Substring(0, 20) + " " + LSRetailPosis.ApplicationLocalizer.Language.Translate(51024).PadLeft(12).Substring(0, 12) + "\n";
                report += line;

                string  customerId = string.Empty;
                string  name       = string.Empty;
                decimal balance    = 0;
                decimal total      = 0;

                //Loop throug the customer balances
                foreach (var customerBalance in customerBalances)
                {
                    customerId = customerBalance.AccountNumber;
                    name       = customerBalance.Name;
                    balance    = customerBalance.Balance;
                    total     += balance;

                    report += customerId.PadRight(10) + " " + name.PadRight(20).Substring(0, 20) + " " + (balance.ToString("n2")).PadLeft(12) + "\n";
                }

                //Printer footer
                report += line;
                string totalText = LSRetailPosis.ApplicationLocalizer.Language.Translate(51025) + ": "; //TOTAL
                report += totalText.PadLeft(32) + (total.ToString("n2")).PadLeft(12) + "\n\n\n";

                //Send text to printer
                if (((object)Customer.InternalApplication.Services.Printing) is IPrintingV2)
                {   // Print to the default printer
                    Customer.InternalApplication.Services.Printing.PrintDefault(true, report);
                }
                else
                {   // Legacy support - direct print to printer #1
                    NetTracer.Warning("BalanceReport.Print - Printing service does not support default printer.  Using printer #1");
                    Customer.InternalApplication.Services.Peripherals.Printer.PrintReceipt(report);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Invoke the 'Add Shipping Address' dialog to edit an existing address
        /// </summary>
        /// <param name="addressRecId">address rec id</param>
        /// <param name="existingCustomer">customer that this address is to be associated with</param>
        internal static DE.IAddress EditShippingAddress(long addressRecId, DE.ICustomer existingCustomer)
        {
            DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                ApplicationSettings.Database.LocalConnection,
                ApplicationSettings.Database.DATAAREAID);

            DE.IAddress address = customerDataManager.GetAddress(addressRecId);

            using (frmNewShippingAddress dlg = new frmNewShippingAddress(existingCustomer, address))
            {
                InternalApplication.ApplicationFramework.POSShowForm(dlg);

                if (dlg.DialogResult == DialogResult.OK)
                {
                    address = dlg.Address;
                }
            }
            return(address);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Updates the customer information in the database
        /// </summary>
        /// <param name="customerId">The customer id</param>
        /// <returns>Returns the updated customer if succeded, null otherwise</returns>
        public DE.ICustomer UpdateCustomer(string customerId)
        {
            DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);

            DE.ICustomer customer = customerDataManager.GetTransactionalCustomer(customerId);
            DE.IAddress  address  = customerDataManager.GetAddress(customer.PrimaryAddress.Id);

            using (frmNewCustomer newCustDialog = new frmNewCustomer(customer, address))
            {
                this.Application.ApplicationFramework.POSShowForm(newCustDialog);

                if (newCustDialog.DialogResult == DialogResult.OK)
                {
                    return(customer);
                }
            }

            return(null);
        }
Exemplo n.º 6
0
        public void SearchShippingAddress(DE.IPosTransaction posTransaction)
        {
            RetailTransaction retailTransaction = (RetailTransaction)posTransaction;

            string shippingname    = string.Empty;
            string shippingaddress = string.Empty;

            DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(Application.Settings.Database.Connection, Application.Settings.Database.DataAreaID);
            DE.IAddress            address             = null;
            if (customerDataManager.HasAddress(retailTransaction.Customer.PartyId))
            {
                address = SearchShippingAddress(retailTransaction.Customer);
            }
            else
            {
                // Create and add customer in AX
                address = AddNewShippingAddress(retailTransaction.Customer);
            }

            if (address != null)
            {
                Customer.InternalApplication.BusinessLogic.CustomerSystem.SetShippingAddress(retailTransaction, address);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Validating the payment transaction from database.
        /// Print the transaction report in a specific format.
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="numberOfMonths"></param>
        public void Print(string customerId, int numberOfMonths)
        {
            const string returnSign = "\r\n";

            try
            {
                //Find the start date
                DateTime fromDate = DateTime.Now;
                if (numberOfMonths == -1)
                {
                    fromDate = fromDate.AddYears(-100);
                }
                else
                {
                    fromDate = fromDate.AddMonths(-1 * numberOfMonths + 1);
                }

                fromDate = fromDate.AddDays(-1 * fromDate.Day + 1);
                fromDate = fromDate.AddHours(-1 * fromDate.Hour);
                fromDate = fromDate.AddMinutes(-1 * fromDate.Minute);
                fromDate = fromDate.AddSeconds(-1 * fromDate.Second);

                //Get the transactions
                customerData         = new CustomerData(LSRetailPosis.Settings.ApplicationSettings.Database.LocalConnection, LSRetailPosis.Settings.ApplicationSettings.Database.DATAAREAID);
                customerTransactions = customerData.GetCustomerTransactions(customerId, fromDate);

                if (customerTransactions.Rows.Count > 0)
                {
                    //Get customer information
                    DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                        ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);
                    ICustomer customerInfo = customerDataManager.GetTransactionalCustomer(customerId);

                    string line = "--------------------------------------------" + returnSign;
                    #region Create the report
                    //Print header information

                    string report = "\n" + LSRetailPosis.ApplicationLocalizer.Language.Translate(51040) + " " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + returnSign + returnSign; //Report printed
                    report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51041).PadRight(15, '.').Substring(0, 15) + ": " + customerId + returnSign;                                                      //Customer Id
                    report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51042).PadRight(15, '.').Substring(0, 15) + ": " + customerInfo.Name + returnSign + returnSign;                                  //Name

                    //ReceiptId         //Date          //Type          //Amount
                    report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51043).PadRight(10).Substring(0, 10) + " " + LSRetailPosis.ApplicationLocalizer.Language.Translate(51044).PadRight(10).Substring(0, 10) + " " + LSRetailPosis.ApplicationLocalizer.Language.Translate(51045).PadRight(8) + " " + LSRetailPosis.ApplicationLocalizer.Language.Translate(51046).PadLeft(13) + returnSign;
                    report += line;

                    Decimal  subTotal        = 0;
                    Decimal  total           = 0;
                    Decimal  amount          = 0;
                    int      prevMonthNumber = 0;
                    string   prevMonthName   = string.Empty;
                    DateTime transDate;
                    string   receiptId       = string.Empty;
                    string   transactionType = string.Empty;
                    string   subTotalText    = string.Empty;

                    //Loop throug the customer transactions
                    foreach (DataRow row in customerTransactions.Select())
                    {
                        transDate       = (DateTime)row["TRANSDATE"];
                        amount          = (Decimal)row["AMOUNT"];
                        transactionType = (String)row["TRANSACTIONTYPE"];

                        if (row["RECEIPTID"] == DBNull.Value)
                        {
                            receiptId = string.Empty;
                        }
                        else
                        {
                            receiptId = (String)row["RECEIPTID"];
                        }

                        if (prevMonthNumber == 0)
                        {
                            prevMonthNumber = transDate.Month;
                        }

                        if (transDate.Month != prevMonthNumber)
                        {
                            //Print subtotals
                            report      += line;
                            subTotalText = LSRetailPosis.ApplicationLocalizer.Language.Translate(51047) + " " + prevMonthName.ToUpper() + ": ";
                            report      += subTotalText.PadLeft(32) + subTotal.ToString("n2").PadLeft(12) + returnSign;
                            report      += line;
                            subTotal     = 0;
                        }

                        subTotal += amount;
                        total    += amount;

                        //Print tranactions
                        report += receiptId.PadRight(10) + " " + transDate.ToShortDateString().PadRight(10) + " " + transactionType.PadRight(8) + amount.ToString("n2").PadLeft(14) + returnSign;

                        prevMonthNumber = transDate.Month;
                        prevMonthName   = transDate.ToString("MMMM");
                    }

                    report += line;

                    //Print subtotals for the last month if more than one.
                    if (numberOfMonths > 1)
                    {
                        subTotalText = LSRetailPosis.ApplicationLocalizer.Language.Translate(51047) + " " + prevMonthName.ToUpper() + ": ";
                        report      += subTotalText.PadLeft(32) + subTotal.ToString("n2").PadLeft(12) + returnSign;
                        report      += "============================================" + returnSign;;
                    }

                    //Print totals
                    report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51048).PadLeft(27) + ": " + total.ToString("n2").PadLeft(15) + returnSign + returnSign;
                    decimal balanceNow = customerDataManager.GetBalance(customerId);
                    report += LSRetailPosis.ApplicationLocalizer.Language.Translate(51049).PadRight(15, '.') + ": " + balanceNow.ToString("n2") + returnSign + returnSign + returnSign;
                    //Send the report to the printer
                    #endregion

                    //System.Windows.Forms.DialogResult result = System.Windows.Forms.DialogResult.No;

                    using (frmReportList reportPreview = new frmReportList(report))
                    {
                        POSFormsManager.ShowPOSForm(reportPreview);
                        if (reportPreview.DialogResult == DialogResult.OK)
                        {
                            if (Customer.InternalApplication.Services.Printing is Microsoft.Dynamics.Retail.Pos.Contracts.Services.IPrintingV2)
                            {   // Print to the default printer
                                Customer.InternalApplication.Services.Printing.PrintDefault(true, report);
                            }
                            else
                            {   // Legacy support - direct print to printer #1
                                NetTracer.Warning("TransactionReport.Print - Printing service does not support default printer.  Using printer #1");
                                Customer.InternalApplication.Services.Peripherals.Printer.PrintReceipt(report);
                            }


                            Customer.InternalApplication.Services.Peripherals.Printer.PrintReceipt(report);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                NetTracer.Error(ex, "TransactionReport::Print failed for customerId {0} numberOfMonths {1}", customerId, numberOfMonths);
                throw;
            }
        }
Exemplo n.º 8
0
        internal static CustomerOrderTransaction GetTransactionFromInfo(CustomerOrderInfo orderInfo, SalesOrder salesOrderService)
        {
            CustomerOrderTransaction transaction = (CustomerOrderTransaction)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateCustomerOrderTransaction(
                ApplicationSettings.Terminal.StoreId,
                ApplicationSettings.Terminal.StoreCurrency,
                ApplicationSettings.Terminal.TaxIncludedInPrice,
                SalesOrder.InternalApplication.Services.Rounding,
                salesOrderService);

            // Get all the defaults
            SalesOrder.InternalApplication.BusinessLogic.TransactionSystem.LoadTransactionStatus(transaction);

            // General header properties
            transaction.OrderId   = orderInfo.Id;
            transaction.OrderType = orderInfo.OrderType;

            if (orderInfo.OrderType == CustomerOrderType.Quote)
            {
                transaction.QuotationId = orderInfo.Id;
            }

            transaction.OriginalOrderType = orderInfo.OrderType;

            switch (orderInfo.OrderType)
            {
            case CustomerOrderType.Quote:
                transaction.OrderStatus = GetSalesStatus((SalesQuotationStatus)orderInfo.Status);
                break;

            case CustomerOrderType.SalesOrder:
                transaction.OrderStatus = GetSalesStatus((SalesOrderStatus)orderInfo.Status, (DocumentStatus)orderInfo.DocumentStatus);
                break;

            default:
                transaction.OrderStatus = SalesStatus.Unknown;
                NetTracer.Information("SalesOrder::CustomerOrderTransaction: CustomerOrderInfo OrderType is unknown: {0}", orderInfo.OrderType);
                break;
            }

            transaction.LockPrices = true;

            transaction.ExpirationDate = ParseDateString(orderInfo.ExpiryDateString, DateTime.Today);

            // RequestedDeliveryDate is directly input from user. It is stored in the local timezone
            transaction.RequestedDeliveryDate = ParseDateString(orderInfo.RequestedDeliveryDateString, DateTime.Today);

            // CreationDate is stored in UTC. It needs to be converted to local time zone where order is accessed.
            ((IPosTransactionV2)transaction).BeginDateTime = ParseDateString(orderInfo.CreationDateString, DateTime.UtcNow, DateTimeStyles.AdjustToUniversal).ToLocalTime();
            transaction.LocalHourOfDay = orderInfo.LocalHourOfDay;

            ((IPosTransactionV2)transaction).Comment = orderInfo.Comment;

            // Header delivery
            DM.StoreDataManager storeDataManager = new DM.StoreDataManager(
                SalesOrder.InternalApplication.Settings.Database.Connection,
                SalesOrder.InternalApplication.Settings.Database.DataAreaID);

            transaction.WarehouseId  = orderInfo.WarehouseId;
            transaction.DeliveryMode = storeDataManager.GetDeliveryMode(orderInfo.DeliveryMode);
            transaction.CurrencyCode = orderInfo.CurrencyCode;

            foreach (var code in orderInfo.DiscountCodes)
            {
                transaction.DiscountCodes.AddLast(code);
            }

            // Header affiliation
            DM.AffiliationDataManager affiliationDataManager = new DM.AffiliationDataManager(
                SalesOrder.InternalApplication.Settings.Database.Connection,
                SalesOrder.InternalApplication.Settings.Database.DataAreaID);

            if (orderInfo.Affiliations != null && orderInfo.Affiliations.Any())
            {
                foreach (AffiliationInfo affiliationInfo in orderInfo.Affiliations)
                {
                    transaction.AffiliationLines.AddLast(
                        new AffiliationItem()
                    {
                        RecId           = affiliationInfo.AffiliationId,
                        LoyaltyTier     = affiliationInfo.LoyaltyTierId,
                        AffiliationType = affiliationInfo.AffiliationType
                    });
                }
            }

            // Customer info
            ICustomerSystem customerSystem = SalesOrder.InternalApplication.BusinessLogic.CustomerSystem;

            DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                SalesOrder.InternalApplication.Settings.Database.Connection,
                SalesOrder.InternalApplication.Settings.Database.DataAreaID);

            DE.ICustomer customer = customerSystem.GetCustomerInfo(orderInfo.CustomerAccount);

            // try to get the customer from transaction service
            if (customer == null || customer.IsEmptyCustomer())
            {
                DE.ICustomer tempCustomer = SalesOrder.GetCustomerFromAX(orderInfo.CustomerAccount, customerSystem, customerDataManager);
                if (tempCustomer != null)
                {
                    customer = tempCustomer;
                }
            }

            DE.ICustomer invoicedCustomer = customerSystem.GetCustomerInfo(customer.InvoiceAccount);

            // try to get the invoicedCustomer from transaction service
            if (invoicedCustomer == null || invoicedCustomer.IsEmptyCustomer())
            {
                DE.ICustomer tempinvoicedCustomer = SalesOrder.GetCustomerFromAX(customer.InvoiceAccount, customerSystem, customerDataManager);
                if (tempinvoicedCustomer != null)
                {
                    invoicedCustomer = tempinvoicedCustomer;
                }
            }

            // If InvoiceCustomer is *still* blank/empty then fallback to Customer so that the UI fields are populated.
            if (invoicedCustomer == null || invoicedCustomer.IsEmptyCustomer())
            {
                invoicedCustomer = customer;
            }

            customerSystem.SetCustomer(transaction, customer, invoicedCustomer);

            if (transaction.DeliveryMode != null && !string.IsNullOrWhiteSpace(orderInfo.AddressRecordId))
            {
                DE.IAddress shippingAddress = customerDataManager.GetAddress(Int64.Parse(orderInfo.AddressRecordId));
                customerSystem.SetShippingAddress(transaction, shippingAddress);
            }

            if (!string.IsNullOrEmpty(orderInfo.SalespersonStaffId))
            {
                // Sets the sales person id and name according to AX values
                // This is done because we do not know whether the sales person information is available on this store
                transaction.SalesPersonId   = orderInfo.SalespersonStaffId;
                transaction.SalesPersonName = orderInfo.SalespersonName;

                DM.EmployeeDataManager employees = new DM.EmployeeDataManager(
                    SalesOrder.InternalApplication.Settings.Database.Connection,
                    SalesOrder.InternalApplication.Settings.Database.DataAreaID);

                Employee employee = employees.GetEmployee(ApplicationSettings.Terminal.StoreId, orderInfo.SalespersonStaffId);
                if (employee != null)
                {
                    transaction.SalesPersonId            = employee.StaffId;
                    transaction.SalesPersonName          = employee.Name;
                    transaction.SalesPersonNameOnReceipt = employee.NameOnReceipt;
                }
            }

            transaction.ChannelReferenceId = orderInfo.ChannelReferenceId;
            if (transaction.LoyaltyItem != null && !string.IsNullOrEmpty(orderInfo.LoyaltyCardId))
            {
                transaction.LoyaltyItem.LoyaltyCardNumber = orderInfo.LoyaltyCardId;
            }

            transaction.ReceiptEmailAddress = orderInfo.Email;

            transaction.TotalManualDiscountAmount = orderInfo.TotalManualDiscountAmount;
            transaction.TotalManualPctDiscount    = orderInfo.TotalManualDiscountPercentage;

            DateTime earliestDeliveryDate = DateTime.MaxValue;

            // Items
            foreach (ItemInfo item in orderInfo.Items)
            {
                Collection <Tax.MiscellaneousCharge> lineCharges = new Collection <Tax.MiscellaneousCharge>();
                foreach (ChargeInfo charge in item.Charges)
                {
                    Tax.MiscellaneousCharge lineCharge = (Tax.MiscellaneousCharge)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateMiscellaneousCharge(
                        charge.Amount, charge.SalesTaxGroup, charge.TaxGroup, charge.Code, string.Empty, transaction);
                    lineCharges.Add(lineCharge);
                }

                // add item
                SaleLineItem lineItem = (SaleLineItem)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateSaleLineItem(
                    ApplicationSettings.Terminal.StoreCurrency,
                    SalesOrder.InternalApplication.Services.Rounding,
                    transaction);

                lineItem.Found                        = true;
                lineItem.OrderLineRecordId            = item.RecId;
                lineItem.ItemId                       = item.ItemId;
                lineItem.Quantity                     = item.Quantity;
                lineItem.ReturnQtyAllowed             = item.Quantity;
                lineItem.SalesOrderUnitOfMeasure      = item.Unit;
                lineItem.Price                        = item.Price;
                lineItem.NetAmount                    = item.NetAmount;
                lineItem.QuantityOrdered              = item.Quantity;
                lineItem.QuantityPickedUp             = item.QuantityPicked;
                lineItem.DeliveryMode                 = storeDataManager.GetDeliveryMode(item.DeliveryMode);
                lineItem.DeliveryDate                 = ParseDateString(item.RequestedDeliveryDateString, DateTime.Today);
                lineItem.DeliveryStoreNumber          = item.StoreId;
                lineItem.DeliveryWarehouse            = item.WarehouseId;
                lineItem.SerialId                     = item.SerialId;
                lineItem.BatchId                      = item.BatchId;
                lineItem.HasBeenRecalled              = true;
                lineItem.SalesMarkup                  = item.SalesMarkup;
                lineItem.Comment                      = string.IsNullOrEmpty(item.Comment) ? string.Empty : item.Comment;
                lineItem.LineStatus                   = GetSalesStatus((SalesOrderStatus)item.Status);
                lineItem.LineDiscount                 = item.LineDscAmount;
                lineItem.PeriodicDiscount             = item.PeriodicDiscount;
                lineItem.PeriodicPctDiscount          = item.PeriodicPercentageDiscount;
                lineItem.LineManualDiscountAmount     = item.LineManualDiscountAmount;
                lineItem.LineManualDiscountPercentage = item.LineManualDiscountPercentage;
                lineItem.TotalDiscount                = item.TotalDiscount;
                lineItem.TotalPctDiscount             = item.TotalPctDiscount;

                foreach (Tax.MiscellaneousCharge charge in lineCharges)
                {
                    lineItem.MiscellaneousCharges.Add(charge);
                }

                if (lineItem.DeliveryMode != null && !string.IsNullOrWhiteSpace(item.AddressRecordId))
                {
                    lineItem.ShippingAddress = customerDataManager.GetAddress(Int64.Parse(item.AddressRecordId));
                }

                lineItem.Dimension.VariantId  = item.VariantId;
                lineItem.Dimension.ColorId    = item.ColorId;
                lineItem.Dimension.StyleId    = item.StyleId;
                lineItem.Dimension.SizeId     = item.SizeId;
                lineItem.Dimension.ConfigId   = item.ConfigId;
                lineItem.Dimension.ColorName  = item.ColorName;
                lineItem.Dimension.StyleName  = item.StyleName;
                lineItem.Dimension.SizeName   = item.SizeName;
                lineItem.Dimension.ConfigName = item.ConfigName;

                if (!string.IsNullOrEmpty(lineItem.Dimension.VariantId))
                {
                    Dimensions dimension = (Dimensions)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateDimension();
                    dimension.VariantId = lineItem.Dimension.VariantId;
                    SalesOrder.InternalApplication.Services.Dimension.GetDimensionForVariant(dimension);
                    lineItem.Dimension = dimension;
                }

                if (item.Discounts.Count > 0)
                {
                    lineItem.QuantityDiscounted = item.Quantity;
                    lineItem.LinePctDiscount    = lineItem.CalculateLinePercentDiscount();
                }

                // create discount line from discount info object
                foreach (DiscountInfo discountInfo in item.Discounts)
                {
                    DiscountItem discountItem = ConvertToDiscountItem(
                        discountInfo.DiscountOriginType,
                        discountInfo.ManualDiscountType,
                        discountInfo.CustomerDiscountType,
                        discountInfo.EffectiveAmount,
                        discountInfo.DealPrice,
                        discountInfo.DiscountAmount,
                        discountInfo.Percentage,
                        discountInfo.PeriodicDiscountOfferId,
                        discountInfo.OfferName,
                        discountInfo.DiscountCode);

                    SalesOrder.InternalApplication.Services.Discount.AddDiscountLine(lineItem, discountItem);
                }

                // Set other default properties for this item
                SalesOrder.InternalApplication.Services.Item.ProcessItem(lineItem, bypassSerialNumberEntry: true);

                // Set tax info after defaults, as it may have been overridden.
                lineItem.SalesTaxGroupId         = item.SalesTaxGroup;
                lineItem.SalesTaxGroupIdOriginal = item.SalesTaxGroup;
                lineItem.TaxGroupId         = item.ItemTaxGroup;
                lineItem.TaxGroupIdOriginal = item.ItemTaxGroup;

                // Add it to the transaction
                transaction.Add(lineItem);

                if (lineItem.DeliveryDate < earliestDeliveryDate)
                {
                    earliestDeliveryDate = lineItem.DeliveryDate.HasValue ? lineItem.DeliveryDate.Value : earliestDeliveryDate;
                }
            }

            // Once Items are populated - Reset Customer Tax Group
            //GRW Linea comentada para poder recoger la orden de venta en una tienda distinta a la configurada en AX
            //customerSystem.ResetCustomerTaxGroup(transaction);

            // The order can be created through some other channel other than POS which has set header delivery date as NoDate.
            // This must not be interpreted as a valid date. Instead the earliestDeliveryDate is used.
            if (transaction.RequestedDeliveryDate == NoDate)
            {
                transaction.RequestedDeliveryDate = earliestDeliveryDate;
            }

            // Charges
            foreach (ChargeInfo charge in orderInfo.Charges)
            {
                // add charges
                Tax.MiscellaneousCharge newCharge = (Tax.MiscellaneousCharge)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateMiscellaneousCharge(
                    charge.Amount, charge.SalesTaxGroup, charge.TaxGroup, charge.Code, string.Empty, transaction);
                transaction.Add(newCharge);
            }

            SalesOrder.InternalApplication.BusinessLogic.ItemSystem.CalculatePriceTaxDiscount(transaction);
            transaction.CalculateAmountDue();

            // Payments
            // - total up amounts
            // - add history entries
            transaction.PrepaymentAmountPaid     = decimal.Zero;
            transaction.PrepaymentAmountInvoiced = decimal.Zero;
            decimal nonPrepayments = decimal.Zero;

            PaymentInfo pinfo = new PaymentInfo();

            pinfo.Amount   = -111;
            pinfo.Currency = "MXN";
            orderInfo.Payments.Add(pinfo);

            foreach (PaymentInfo payment in orderInfo.Payments)
            {
                // sum up payments
                decimal amount = (string.IsNullOrWhiteSpace(payment.Currency))
                    ? payment.Amount
                    : (SalesOrder.InternalApplication.Services.Currency.CurrencyToCurrency(
                           payment.Currency,
                           ApplicationSettings.Terminal.StoreCurrency,
                           payment.Amount));

                if (payment.Prepayment)
                {
                    // Sum prepayments to track total deposits paid
                    transaction.PrepaymentAmountPaid += amount;
                }
                else
                {
                    // Sum non-prepayments as base for calculating deposits applied to pickups
                    nonPrepayments += amount;
                }

                CustomerOrderPaymentHistory paymentHistory = (CustomerOrderPaymentHistory)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateCustomerOrderPaymentHistory();
                paymentHistory.Amount   = payment.Amount;
                paymentHistory.Currency = payment.Currency;
                paymentHistory.Date     = ParseDateString(payment.DateString, DateTime.MinValue);
                paymentHistory.Balance  = transaction.NetAmountWithTaxAndCharges - transaction.PrepaymentAmountPaid;

                transaction.PaymentHistory.Add(paymentHistory);
            }

            // Prepayment/Deposit override info
            transaction.PrepaymentAmountOverridden = orderInfo.PrepaymentAmountOverridden;
            if (transaction.PrepaymentAmountOverridden)
            {
                transaction.PrepaymentAmountRequired = transaction.PrepaymentAmountPaid;
            }

            // Amount that has been previously invoiced (picked-up)
            transaction.PreviouslyInvoicedAmount = orderInfo.PreviouslyInvoicedAmount;

            // Portion of the prepayment that has been applied to invoices.
            // If .PrepaymentAmountApplied is non-NULL then use the explicit amount, otherwise fall back to computing the amount based on payment history.
            transaction.PrepaymentAmountInvoiced = orderInfo.PrepaymentAmountApplied
                                                   ?? (transaction.PreviouslyInvoicedAmount - nonPrepayments);

            transaction.HasLoyaltyPayment = orderInfo.HasLoyaltyPayment;

            return(transaction);
        }
Exemplo n.º 9
0
        private bool SaveCustomer()
        {
            try
            {
                bool   createdLocal = false;
                bool   createdAx    = false;
                string comment      = null;

                string sReligion = null;
                string sCustClassificationFGrp = null;


                sReligion = "";
                sCustClassificationFGrp = txtCustClassificationGroup.Text;

                DialogResult prompt = Pos.Customer.Customer.InternalApplication.Services.Dialog.ShowMessage(51148, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (prompt == System.Windows.Forms.DialogResult.Yes)
                {
                    IList <Int64> entityKeys      = new List <Int64>();
                    ICustomer     tempCustomer    = MergeAddress(this.viewModel.Customer, this.addressViewModel.Address);
                    bool          isEmptyCustomer = this.viewModel.Customer.IsEmptyCustomer();
                    sCustTaxGrp = this.addressViewModel.SalesTaxGroup;//added on 300318

                    // this.isEmptyCustomer is initialized at form load and uses the incoming customer object
                    if (isEmptyCustomer)
                    {
                        if (ValidateControls()) // nimbus
                        // Attempt to save in AX
                        {
                            Pos.Customer.Customer.InternalApplication.TransactionServices.NewCustomer(ref createdAx, ref comment, ref tempCustomer, ApplicationSettings.Terminal.StorePrimaryId, ref entityKeys);
                        }

                        tempCustomer.SalesTaxGroup = sCustTaxGrp;//added on 300318

                        #region Nimbus
                        if (createdAx)
                        {
                            //UpdateRetailCustomerInfo
                            //  ReadOnlyCollection<object> containerArray;

                            //DateTime dBirthDate = Convert.ToDateTime("1900/01/01 00:00:00.000");
                            //DateTime dtMarriageDate = Convert.ToDateTime("1900/01/01 00:00:00.000");

                            //if (dtDOB.EditValue == null)
                            //{
                            //    dtDOB.EditValue = dBirthDate;
                            //}
                            //if (dtMarriage.EditValue == null)
                            //{
                            //    dtMarriage.EditValue = dtMarriageDate;
                            //}
                            int intRes = 0;
                            if (chkResidence.Checked)// added on 07/12/2015 req by K.Saha
                            {
                                intRes = 1;
                            }
                            else
                            {
                                intRes = 0;
                            }
                            string sCustId  = tempCustomer.CustomerId;
                            string sStoreId = ApplicationSettings.Database.StoreID;
                            Pos.Customer.Customer.InternalApplication.TransactionServices.InvokeExtension("UpdateRetailCustomerInfo",
                                                                                                          sCustId, iSalutation, iGender,               //dtDOB.EditValue,
                                                                                                          sReligion.Trim(), txtOccupation.Text.Trim(), // dtMarriage.EditValue,
                                                                                                          txtSTD.Text.Trim(), txtMobilePrimary.Text.Trim(), txtMobileSecondary.Text.Trim(),
                                                                                                          textNationality.Text.Trim(), textCustAgeBracket.Text.Trim(), cmbBMonth.SelectedIndex,
                                                                                                          txtBDay.Text.Trim(), txtBYear.Text.Trim(), cmbAnnMonth.SelectedIndex, txtAnnDay.Text.Trim(),
                                                                                                          txtAnnYear.Text.Trim(), sStoreId, intRes, sCustTaxGrp, txtCustClassificationGroup.Text.Trim() // added this 2 field RH on 05/11/2014
                                                                                                          );
                        }
                        #endregion
                    }
                    else
                    {
                        Pos.Customer.Customer.UpdateCustomer(ref createdAx, ref comment, ref tempCustomer, ref entityKeys);
                    }

                    // Was the customer created in AX
                    if (createdAx)
                    {
                        // Was the customer created locally
                        DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                            ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);

                        LSRetailPosis.Transaction.Customer transactionalCustomer = tempCustomer as LSRetailPosis.Transaction.Customer;

                        if (isEmptyCustomer)
                        {
                            createdLocal = customerDataManager.SaveTransactionalCustomer(transactionalCustomer, entityKeys);
                        }
                        else
                        {
                            createdLocal = customerDataManager.UpdateTransactionalCustomer(transactionalCustomer, entityKeys);
                        }

                        //Update the VM
                        this.viewModel = new CustomerViewModel(tempCustomer);

                        #region Nimbus

                        UpdateCustomerInfo(tempCustomer.CustomerId);  // blocked on 12.08.2013

                        #endregion
                    }

                    if (!createdAx)
                    {
                        Pos.Customer.Customer.InternalApplication.Services.Dialog.ShowMessage(51159, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else if (!createdLocal)
                    {
                        Pos.Customer.Customer.InternalApplication.Services.Dialog.ShowMessage(51156, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                return(createdAx && createdLocal);
            }
            catch (Exception ex)
            {
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), ex);
                Pos.Customer.Customer.InternalApplication.Services.Dialog.ShowMessage(51158, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Saves the shipping address under the given customer.
        /// </summary>
        /// <param name="customer">The customer.</param>
        /// <returns><value>True</value> if the address was saved, or <value>false</value> otherwise.</returns>
        internal bool SaveShippingAddress(ICustomer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            try
            {
                bool   createdAx    = false;
                bool   createdLocal = false;
                string comment      = null;

                IDirPartyAddressRelationship        dirRelationship = null;
                IDirPartyAddressRelationshipMapping dirMap          = null;
                IList <Int64> entityKeys = new List <Int64>();

                IAddress tempAddress = this.Address;

                if (tempAddress.Id != 0)
                {
                    // address already has an ID, so try to update the existing entities.
                    CS.InternalApplication.TransactionServices.UpdateAddress(ref createdAx, ref comment, ref tempAddress, ref entityKeys);
                }
                else
                {
                    // try to create new entities under the created customer.
                    dirRelationship = CS.InternalApplication.BusinessLogic.Utility.CreateDirPartyAddressRelationship();
                    dirMap          = CS.InternalApplication.BusinessLogic.Utility.CreateDirPartyAddressRelationshipMapping();

                    CS.InternalApplication.TransactionServices.CreateAddress(ref createdAx, ref comment, ref customer, ref tempAddress, ref dirRelationship, ref dirMap, ref entityKeys);
                }

                // Was the address created in AX
                if (createdAx)
                {
                    DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager(
                        ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);
                    createdLocal = customerDataManager.SaveCustomerAddressContactInfo((Address)tempAddress, entityKeys);

                    if (AddressViewModel.AddressRecordIdIndex < entityKeys.Count)
                    {
                        tempAddress.Id = entityKeys[AddressViewModel.AddressRecordIdIndex];
                    }
                }

                if (!createdAx)
                {
                    CS.InternalApplication.Services.Dialog.ShowMessage(51159, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (!createdLocal)
                {
                    CS.InternalApplication.Services.Dialog.ShowMessage(51156, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                return(createdAx && createdLocal);
            }
            catch (Exception ex)
            {
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), ex);
                CS.InternalApplication.Services.Dialog.ShowMessage(51193, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }