Esempio n. 1
0
        public void IssueCreditMemo(ICreditMemoTenderLineItem creditMemoItem, IRetailTransaction transaction)
        {
            if (creditMemoItem == null)
            {
                throw new ArgumentNullException("creditMemoItem");
            }

            RetailTransaction retailTransaction = transaction as RetailTransaction;

            if (retailTransaction == null)
            {
                throw new ArgumentNullException("retailTransaction");
            }
            else
            {
                if (retailTransaction.SaleIsReturnSale == true && retailTransaction.AmountDue < 0)
                {
                    InputConfirmation inC = new InputConfirmation();
                    inC.PromptText = "Remarks";
                    inC.InputType  = InputType.Normal;

                    Interaction.frmInput Oinput = new Interaction.frmInput(inC);
                    Oinput.ShowDialog();
                    if (!string.IsNullOrEmpty(Oinput.InputText))
                    {
                        retailTransaction.PartnerData.Remarks = Oinput.InputText;
                    }
                    else
                    {
                        retailTransaction.PartnerData.Remarks = "";
                    }
                }
            }

            try
            {
                LogMessage("Issuing a credit memo....", LogTraceLevel.Trace, "CreditMemo.IssueCreditMemo");

                bool   retVal           = false;
                string comment          = string.Empty;
                string creditMemoNumber = string.Empty;
                string currencyCode     = ApplicationSettings.Terminal.StoreCurrency;

                try
                {
                    // Begin by checking if there is a connection to the Transaction Service
                    this.Application.TransactionServices.CheckConnection();

                    // Publish the credit memo to the Head Office through the Transaction Services...
                    this.Application.TransactionServices.IssueCreditMemo(ref retVal, ref comment, ref creditMemoNumber,
                                                                         retailTransaction.StoreId,
                                                                         retailTransaction.TerminalId,
                                                                         retailTransaction.OperatorId,
                                                                         retailTransaction.TransactionId,
                                                                         retailTransaction.ReceiptId,
                                                                         "1",
                                                                         currencyCode,
                                                                         creditMemoItem.Amount * -1,
                                                                         DateTime.Now);

                    retailTransaction.CreditMemoItem.CreditMemoNumber = creditMemoNumber;
                    retailTransaction.CreditMemoItem.Amount           = creditMemoItem.Amount * -1;
                    creditMemoItem.SerialNumber = creditMemoNumber;
                    creditMemoItem.Comment      = creditMemoNumber;
                }
                catch (LSRetailPosis.PosisException px)
                {
                    // We cannot publish the credit memo to the HO, so we need to take action...

                    retailTransaction.TenderLines.RemoveLast();
                    retailTransaction.CalcTotals();

                    retailTransaction.CreditMemoItem = (CreditMemoItem)this.Application.BusinessLogic.Utility.CreateCreditMemoItem();

                    LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), px);
                    throw;
                }
                catch (Exception x)
                {
                    // We cannot publish the credit memo to the HO, so we need to take action...

                    retailTransaction.TenderLines.RemoveLast();
                    retailTransaction.CalcTotals();
                    retailTransaction.CreditMemoItem = (CreditMemoItem)this.Application.BusinessLogic.Utility.CreateCreditMemoItem();

                    LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), x);
                    throw new LSRetailPosis.PosisException(52300, x);
                }

                if (!retVal)
                {
                    LogMessage("Error storing the credit memo centrally...",
                               LSRetailPosis.LogTraceLevel.Error,
                               "CreditMemo.IssueCreditMemo");

                    retailTransaction.TenderLines.RemoveLast();
                    retailTransaction.CalcTotals();
                    retailTransaction.CreditMemoItem = (CreditMemoItem)this.Application.BusinessLogic.Utility.CreateCreditMemoItem();

                    throw new LSRetailPosis.PosisException(52300, new Exception(comment));
                }
            }
            catch (Exception x)
            {
                // Start :  On 14/07/2014
                foreach (SaleLineItem saleLineItem in retailTransaction.SaleItems)
                {
                    if (saleLineItem.ItemType == LSRetailPosis.Transaction.Line.SaleItem.BaseSaleItem.ItemTypes.Service)
                    {
                        updateCustomerAdvanceAdjustment(Convert.ToString(saleLineItem.PartnerData.ServiceItemCashAdjustmentTransactionID),
                                                        Convert.ToString(saleLineItem.PartnerData.ServiceItemCashAdjustmentStoreId),
                                                        Convert.ToString(saleLineItem.PartnerData.ServiceItemCashAdjustmentTerminalId), 0);
                    }
                }
                // End :  On 14/07/2014

                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), x);
                throw;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Processes the card payment by establishing a connection with the configured payment processor.
        /// </summary>
        /// <param name="eftInfo">Reference to an EftInfo object.</param>
        /// <param name="posTransaction">Current transaction.</param>
        /// <returns>True if the processing succeeded.</returns>
        public bool ProcessCardPayment(ref IEFTInfo eftInfo, IPosTransaction posTransaction)
        {
            //eftInfo.Authorized = true;
            //eftInfo.IsPendingCapture = true;

            //return eftInfo.Authorized;

            // This is the main entry point for the actual card processing.  All card information that was
            //    gathered by GetCardInfoAndAmount() has been copied to similar fields in the "eftInfo" object.
            //    Use this information when calling your provider's service.

            // Our example will simulate successful authorization (or refund) randomly based on whether
            //    this method gets hit on an odd or even second.  In a real scenario, this is where you
            //    would call your payment provider directly (web service, direct sockets, etc.) or call
            //    out to a DLL with the necessary parameters.

            // All information is stored back to the eftInfo object which is used for printing the receipt,
            //    storing information to the database (RetailTransactionPaymentTrans table),  statement posting, etc.

            // In this example, we are simulating a 1-step Auth/Capture process, so we will
            //    always leave "IsPendingCapture" as false.

            // The eftInfo class has many properties; most of them are used only for printing on the receipt.
            //      See the EFT_NewSample2012_Readme.docx file for a mapping.
            //
            // Only a few are stored to the RetailTransactionPaymentTrans table:
            //      eftInfo.BatchCode = BATCHID
            //      eftInfo.AuthCode = EFTAUTHENTICATIONCODE
            //      eftInfo.IssuerNumber = CARDTYPEID  ** Only used if cardInfo.CardTypeId was blank after ID'ing the card
            // In addition, the cardInfo.CardNumber (masked) is stored to the CARDORACCOUNT column.
            // You may wish to save additional information to your own table.

            // Note:  Both a SALE and a REFUND process will end up here.  To determine if we're charging the card
            //  or refunding money to the card, simply look at eftInfo.Amount.  If the amount is negative, send a refund request.

            //if (DateTime.Now.Second % 2 == 1) //Uncomment this line to RANDOMLY succeed (odd or even second)
            ////if (true)  //Uncomment this line to ALWAYS succeed
            //{
            //    //Auth was successful
            //    eftInfo.Authorized = true;

            //    //Authorization code returned from processor.
            //    eftInfo.AuthCode = "123456";

            //    // Some fields only for printing on the receipt (see note above)
            //    eftInfo.TransactionDateTime = DateTime.Now;
            //    eftInfo.Message = String.Empty;
            //    eftInfo.SequenceCode = String.Empty;
            //    eftInfo.EntrySourceCode = String.Empty;
            //    eftInfo.RetrievalReferenceNumber = String.Empty;
            //    eftInfo.AccountType = "Checking";
            //    eftInfo.ResponseCode = String.Empty;
            //    eftInfo.AuthorizedText = "Success";  // Printed on receipt as "EFT Info Message" field

            //    // If performing a two-step Auth/Capture process, would set this to true in order
            //    //    to be caught by the Capture process at the end of the transaction.  Otherwise,
            //    //    the Authorization process must send a Capture request at the same time as the Auth request.
            //    eftInfo.IsPendingCapture = false;

            //}
            //else
            //{
            //    //Authorization failed
            //    eftInfo.Authorized = false;

            //    eftInfo.TransactionDateTime = DateTime.Now;
            //    eftInfo.ProviderResponseCode = "99";
            //    eftInfo.NotAuthorizedText = "Not Approved";

            //    //Error Code and Error Message are shown to the user in pop-up window.
            //    eftInfo.ErrorCode = "99999";
            //    eftInfo.ErrorMessage = "This is why the auth failed.";
            //}

            //if (!eftInfo.Authorized)
            //{
            //    // May want to print decline receipt if authorization failed.
            //    PrintDeclineReceipt(eftInfo);

            //    // Otherwise, set ErrorCode and ErrorMessage will be shown on the screen if Authorized = false
            //    // Note:  If authorization was successful, by default no message is given.  You can add functionality
            //    //      to notify user of success.

            //}

            /* Blocked on 29.07.2013 //
             *
             * string sReqXML = "22,0,<?xml version='1.0' encoding='UTF-8' ?><purchase-request><TransactionInput ID='ID000001'><Card><IsManualEntry>false</IsManualEntry><Track1>4550381512383001^SUBHANKAR  KUNDU          ^1012101154730000000000774000000</Track1><Track2>5566204200063157=10031010019400</Track2></Card><Amount><BaseAmount>100</BaseAmount><CurrencyCode>INR</CurrencyCode></Amount><POS><POSReferenceNumber>TL993812</POSReferenceNumber><TransactionTime>2008-09-17T09:30:47.0Z</TransactionTime><Product><Code>SK9881277736</Code><Name>NOKIA 6610</Name><Description>Nokia mobile phone</Description><Category>MBL</Category></Product><Product><Code>SK9881277788</Code><Name>NOKIA 78GL ADPTR</Name><Description>Nokia travel adaptor</Description><Category>MBA</Category></Product><User><ID>16</ID><Name>AMITKUMAR</Name></User><TrackingNumber>818</TrackingNumber></POS></TransactionInput></purchase-request>";
             * Project1.Class1 oEFTClass = new Project1.Class1();
             * String sResponseXML = oEFTClass.Inno(sReqXML);
             *
             * DataSet ds = new DataSet();
             * using (StringReader stringReader = new StringReader(sResponseXML))
             * {
             *  ds = new DataSet();
             *  ds.ReadXml(stringReader);
             * }
             *
             * DataTable dt = new DataTable();
             * if (ds != null && ds.Tables.Count > 0)
             * {
             *   dt = ds.Tables["HostResponse"];
             * }
             *
             * if (dt != null && dt.Rows.Count > 0)
             * {
             *  string code = Convert.ToString(dt.Rows[0]["ResponseCode"]);
             *  string message = Convert.ToString(dt.Rows[0]["ResponseMessage"]);
             *  string approvalcode = Convert.ToString(dt.Rows[0]["ApprovalCode"]);
             *  if (string.IsNullOrEmpty(approvalcode))
             *  {
             *      eftInfo.Authorized = false;
             *      eftInfo.ErrorCode = code;
             *      eftInfo.ErrorMessage = message;
             *  }
             * }
             * else
             * {
             *  eftInfo.Authorized = false;
             *  eftInfo.ErrorCode = "99999";
             *  eftInfo.ErrorMessage = "No Connection Available to authorize the connection.";
             * }
             */

            //using (LSRetailPosis.POSProcesses.frmMessage dialog = new frmMessage(sResponseXML, MessageBoxButtons.OK, MessageBoxIcon.Information))
            //{
            //    Application.ApplicationFramework.POSShowForm(dialog);
            //}
            // eftInfo.Authorized = true;

            eftInfo.Authorized = true;

            string sTblName = "EXTNDCARDINFO" + ApplicationSettings.Terminal.TerminalId;
            string sCardNo  = EFT.InternalApplication.BusinessLogic.Utility.MaskCardNumber(eftInfo.CardNumber);

            RetailTransaction retailTrans = posTransaction as RetailTransaction;

            if (retailTrans != null)
            {
                retailTrans.PartnerData.EFTCardNo = eftInfo.CardNumber;
                UpdateCardIfo(sTblName, retailTrans.TransactionId, sCardNo, sEFTApprovalCode, sCExpMonth, sCExpYear);
            }

            LSRetailPosis.Transaction.CustomerPaymentTransaction custTrans = posTransaction as LSRetailPosis.Transaction.CustomerPaymentTransaction;
            if (custTrans != null)
            {
                custTrans.PartnerData.EFTCardNo = eftInfo.CardNumber;
                UpdateCardIfo(sTblName, custTrans.TransactionId, sCardNo, sEFTApprovalCode, sCExpMonth, sCExpYear);
            }

            return(eftInfo.Authorized);
        }
Esempio n. 3
0
        /// <summary>
        /// Process Linked InfoCodes for InfoCodeLineItem
        /// </summary>
        /// <param name="posTransaction"></param>
        /// <param name="tableRefId"></param>
        /// <param name="infoCodeType"></param>
        public void ProcessLinkedInfoCodes(IPosTransaction posTransaction, InfoCodeTableRefType tableRefId, InfoCodeType infoCodeType)
        {
            CustomerPaymentTransaction customerTransaction = posTransaction as CustomerPaymentTransaction;
            TenderCountTransaction     tenderTransaction   = posTransaction as TenderCountTransaction;

            if (customerTransaction != null)
            {
                //Loop while a linkedInfoCode is found
                int i = 0; //Set as a stop for a infinite loop
                LinkedListNode <InfoCodeLineItem> infoCodeItem = customerTransaction.InfoCodeLines.Last;
                if (infoCodeItem != null)
                {
                    while (!string.IsNullOrEmpty(infoCodeItem.Value.LinkedInfoCodeId) && (i < 10))
                    {
                        ProcessInfoCode(posTransaction, 0, 0, customerTransaction.Customer.CustomerId, string.Empty, string.Empty, InfoCodeTableRefType.Customer, infoCodeItem.Value.LinkedInfoCodeId, (IInfoCodeLineItem)infoCodeItem.Value, InfoCodeType.Header);
                        // This is to prevent an infinite loop when infocodes link to themselves..
                        if (infoCodeItem.Value.LinkedInfoCodeId == customerTransaction.InfoCodeLines.Last.Value.LinkedInfoCodeId)
                        {
                            break;
                        }

                        infoCodeItem = customerTransaction.InfoCodeLines.Last;
                        i++;
                    }
                }
            }
            else if (tenderTransaction != null)
            {
                //Loop while a linkedInfoCode is found
                int i = 0; //Set as a stop for a infinite loop
                LinkedListNode <InfoCodeLineItem> infoCodeItem = tenderTransaction.InfoCodeLines.Last;
                if (infoCodeItem != null)
                {
                    while (!string.IsNullOrEmpty(infoCodeItem.Value.LinkedInfoCodeId) && (i < 10))
                    {
                        infoCodeItem = tenderTransaction.InfoCodeLines.Last;
                        i++;
                    }
                }
            }
            else
            {
                RetailTransaction asRetailTransaction = (RetailTransaction)posTransaction;

                //Loop while a linkedInfoCode is found
                int i = 0; //Set as a stop for a infinite loop
                LinkedListNode <InfoCodeLineItem> infoCodeItem = asRetailTransaction.InfoCodeLines.Last;
                if (infoCodeItem != null)
                {
                    while (!string.IsNullOrEmpty(infoCodeItem.Value.LinkedInfoCodeId) && (i < 10))
                    {
                        ProcessInfoCode(posTransaction, 0, 0, asRetailTransaction.Customer.CustomerId, string.Empty, string.Empty, tableRefId, infoCodeItem.Value.LinkedInfoCodeId, (IInfoCodeLineItem)infoCodeItem.Value, infoCodeType);
                        // This is to prevent an infinite loop when infocodes link to themselves..
                        if (infoCodeItem.Value.LinkedInfoCodeId == asRetailTransaction.InfoCodeLines.Last.Value.LinkedInfoCodeId)
                        {
                            break;
                        }

                        infoCodeItem = asRetailTransaction.InfoCodeLines.Last;
                        i++;
                    }
                }
            }
        }
Esempio n. 4
0
        public void PreEndTransaction(IPreTriggerResult preTriggerResult, IPosTransaction posTransaction)
        {
            if (preTriggerResult == null)
            {
                throw new ArgumentNullException("preTriggerResult");
            }

            if (posTransaction == null)
            {
                throw new ArgumentNullException("posTransaction");
            }

            Debug.WriteLine("PreEndTransaction");
            bool abortTransaction = false;


            FiscalPrinterSingleton fiscalCore    = FiscalPrinterSingleton.Instance;
            IFiscalOperations      fiscalPrinter = fiscalCore.FiscalPrinter;
            PersistentPrinterData  printerData   = fiscalCore.PrinterData;

            RetailTransaction           retailTransaction = posTransaction as RetailTransaction;
            LinkedList <TenderLineItem> tenderLines       = null;
            LinkedList <SaleLineItem>   salesLines        = null;

            ComputePosExeMD5Text();

            // Note: Other transaction types (CustomerPaymentTransaction) may also apply.
            if (retailTransaction != null)
            {   // We are a retail transaction
                // Add all payments to the fiscal printer
                // Alternative option is to do this as ar result of IPaymentTriggers

                tenderLines = retailTransaction.TenderLines;
                salesLines  = retailTransaction.SaleItems;


                if (fiscalPrinter.OperatingState == FiscalPrinterState.FiscalReceipt)
                {
                    Decimal totalDiscountAmount  = 0m;
                    Decimal totalDiscountPercent = 0m;

                    // Post any quantity changes to the printer
                    fiscalCore.UpdateFiscalCouponSalesItemsQty(retailTransaction);

                    UpdateFiscalPrinterTransactionData(fiscalCore, fiscalPrinter, salesLines, ref totalDiscountAmount, ref totalDiscountPercent);

                    // Start payment, apply total/transaction discount or surcharge
                    // Note: we are not implementing a surcharge
                    if (totalDiscountPercent != 0)
                    {   // Transaction level % discount
                        fiscalPrinter.StartTotalPaymentWithDiscount((int)(totalDiscountPercent * 100));
                    }
                    else if (totalDiscountAmount != 0)
                    {   // Transaction level amount discount
                        fiscalPrinter.StartTotalPaymentWithDiscount(totalDiscountAmount);
                    }
                    else
                    {   // No transaction level discounts or surcharge
                        fiscalPrinter.StartTotalPayment();
                    }

                    // Process Payments...
                    Decimal posPaymentTotal = 0m;
                    foreach (TenderLineItem tenderLine in tenderLines)
                    {
                        if (!tenderLine.Voided)
                        {
                            string  paymentMethod = fiscalCore.MapTenderTypeIdToPaymentMethod(tenderLine.TenderTypeId);
                            decimal paymentAmount = tenderLine.Amount;

                            if (paymentAmount > 0m)
                            {   // only process positive payments with the fiscal printer
                                // Cash-back should is ignored
                                fiscalPrinter.MakePayment(paymentMethod, paymentAmount);

                                posPaymentTotal += paymentAmount;
                            }
                        }
                    }

                    string couponNumber = fiscalPrinter.GetCouponNumber();
                    posTransaction.FiscalDocumentId = couponNumber;
                    string serialNumber = fiscalPrinter.GetSerialNumber();
                    posTransaction.FiscalSerialId = serialNumber;

                    Debug.WriteLine("Balance due: " + fiscalPrinter.GetBalanceDue());
                    Debug.WriteLine("Subtotal " + fiscalPrinter.GetSubtotal());
                    Debug.WriteLine("Pos Payment total " + posPaymentTotal);
                    Debug.Assert(fiscalPrinter.GetBalanceDue() == 0m, "Not enough payment was made as expected by the fiscal printer");

                    if (fiscalPrinter.GetBalanceDue() > 0m)
                    {   // user will need to void transaction or fix the shortage to proceed.
                        preTriggerResult.ContinueOperation = false;

                        preTriggerResult.MessageId = 4042; // The action is not valid for this type of transaction.
                    }
                    else
                    {   // End and finalize the Fiscal Coupon
                        fiscalPrinter.EndReceipt(string.Format(CultureInfo.CurrentCulture, "Thank you! MD5:{0}", _posExeMd5Text));
                        printerData.SetGrandTotal(fiscalPrinter.GetGrandTotal());

                        PrintTenderManagementReports(tenderLines);
                    }
                }
                else
                {
                    // Check to see if there are sales items on this transaction

                    if (ContainsItemsRequiringFiscalPrinter(retailTransaction))
                    {
                        // A Fiscal Coupon has not been created - Abort this operation.
                        preTriggerResult.ContinueOperation = false;

                        preTriggerResult.MessageId = 4042; // The action is not valid for this type of transaction.
                    }
                }

                if (abortTransaction)
                {   // Abort the transaction
                    fiscalPrinter.CancelReceipt();
                    preTriggerResult.ContinueOperation = false;

                    preTriggerResult.MessageId = 4042; // The action is not valid for this type of transaction.
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Copy items from one transaction, and add them as returns to another
        /// </summary>
        /// <param name="returnedItems"></param>
        /// <param name="transToReturn"></param>
        /// <param name="retailTransaction"></param>
        internal static void InsertReturnedItemsIntoTransaction(IEnumerable <int> returnedItems, RetailTransaction transToReturn, RetailTransaction retailTransaction)
        {
            SaleLineItem returnedItem;

            foreach (int lineNum in returnedItems)
            {
                returnedItem = transToReturn.GetItem(lineNum);

                // Transfer the lineId from the returned transaction to the proper property in the new transaction.
                returnedItem.ReturnLineId = returnedItem.LineId;

                // Transfer the transactionId from the returned transacton to the proper property in the new transaction.
                returnedItem.ReturnTransId    = returnedItem.Transaction.TransactionId;
                returnedItem.ReturnStoreId    = returnedItem.Transaction.StoreId;
                returnedItem.ReturnTerminalId = returnedItem.Transaction.TerminalId;

                returnedItem.Quantity           = returnedItem.ReturnQtyAllowed * -1;
                returnedItem.QuantityDiscounted = returnedItem.QuantityDiscounted * -1;

                retailTransaction.Add(returnedItem);
            }

            //Transfer the original customer information to the "actual" transaction
            //this.Application.BusinessLogic.CustomerSystem.SetCustomer(retailTransaction, transToReturn.Customer, transToReturn.Customer);
            retailTransaction.Customer.ReturnCustomer = true;

            SalesOrder.InternalApplication.Services.Tax.CalculateTax(retailTransaction);
            retailTransaction.CalcTotals();
        }
Esempio n. 6
0
        public void IssueGiftCard(IPosTransaction posTransaction, ITender gcTenderInfo)
        {
            //Start: added on 16/07/2014 for customer selection is must
            RetailTransaction retailTrans = posTransaction as RetailTransaction;

            if (retailTrans != null)
            {
                if (Convert.ToString(retailTrans.Customer.CustomerId) == string.Empty || string.IsNullOrEmpty(retailTrans.Customer.CustomerId))
                {
                    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("Add a customer to transaction before making a deposit", MessageBoxButtons.OK, MessageBoxIcon.Error))
                    {
                        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                    }
                    return;
                }
            }
            //End :added on 16/07/2014 for customer selection is must

            LogMessage("Issuing a gift card",
                       LSRetailPosis.LogTraceLevel.Trace,
                       "GiftCard.IssueGiftCard");

            if (FiscalPrinter.FiscalPrinter.Instance.FiscalPrinterEnabled())
            {
                //The operation should proceed after the fiscal printer handles IssueGiftCard
                FiscalPrinter.FiscalPrinter.Instance.IssueGiftCard(posTransaction, gcTenderInfo);
            }

            GiftCardController controller = new GiftCardController(GiftCardController.ContextType.GiftCardIssue, (PosTransaction)posTransaction, (Tender)gcTenderInfo);

            //controller.CardNumber = "111111"; testing for autogenerate no req sailendra da

            using (GiftCardForm giftCardForm = new GiftCardForm(controller))
            {
                POSFormsManager.ShowPOSForm(giftCardForm);

                if (giftCardForm.DialogResult == DialogResult.OK)
                {
                    // Add the gift card to the transaction.
                    RetailTransaction   retailTransaction = posTransaction as RetailTransaction;
                    GiftCertificateItem giftCardItem      = (GiftCertificateItem)this.Application.BusinessLogic.Utility.CreateGiftCardLineItem(
                        ApplicationSettings.Terminal.StoreCurrency,
                        this.Application.Services.Rounding, retailTransaction);

                    giftCardItem.SerialNumber  = controller.CardNumber;
                    giftCardItem.StoreId       = posTransaction.StoreId;
                    giftCardItem.TerminalId    = posTransaction.TerminalId;
                    giftCardItem.StaffId       = posTransaction.OperatorId;
                    giftCardItem.TransactionId = posTransaction.TransactionId;
                    giftCardItem.ReceiptId     = posTransaction.ReceiptId;
                    giftCardItem.Amount        = controller.Amount;
                    giftCardItem.Balance       = controller.Balance;
                    giftCardItem.Date          = DateTime.Now;

                    // Necessary property settings for the the gift certificate "item"...
                    giftCardItem.Price = giftCardItem.Amount;
                    giftCardItem.StandardRetailPrice = giftCardItem.Amount;
                    giftCardItem.Quantity            = 1;
                    giftCardItem.TaxRatePct          = 0;
                    giftCardItem.Description         = ApplicationLocalizer.Language.Translate(55001); // Gift Card
                    giftCardItem.Comment             = controller.CardNumber;
                    giftCardItem.NoDiscountAllowed   = true;
                    giftCardItem.Found = true;

                    retailTransaction.Add(giftCardItem);
                }
            }
        }
        /// <summary>
        /// Find and total all multiline discount trade agreements that match the given relations and quantity
        /// </summary>
        /// <param name="itemCode">The item code to search by (item group or all)</param>
        /// <param name="retailTransaction">The transaction context with Id and customer Id</param>
        /// <param name="discountRow">Current row in multiline discount working table. Will be populated and returned.</param>
        /// <param name="currencyCode">The currency code to filter by</param>
        /// <returns>Discount row populated with sums for all discounts found</returns>
        private DataRow GetMultiLineDiscountLine(PriceDiscItemCode itemCode, RetailTransaction retailTransaction, DataRow discountRow, string currencyCode)
        {
            PriceDiscType relation  = PriceDiscType.MultiLineDiscSales; //Sales multiline discount - 6
            Dimensions    dimension = (Dimensions)this.Application.BusinessLogic.Utility.CreateDimension();

            bool searchAgain = true;
            var  codes       = new PriceDiscAccountCode[] { PriceDiscAccountCode.Table, PriceDiscAccountCode.GroupId, PriceDiscAccountCode.All };

            foreach (var accountCode in codes)
            {
                // skip to next configuration if this one isn't enabled
                if (!DiscountParameters.Activation(relation, accountCode, itemCode))
                {
                    continue;
                }

                // get item relation based on item code
                string itemRelation = (itemCode == PriceDiscItemCode.GroupId) ? discountRow.Field <string>("MULTILINEGROUP") : string.Empty;
                itemRelation = itemRelation ?? String.Empty;

                // get customer relation based on account code
                string accountRelation = String.Empty;
                if (accountCode == PriceDiscAccountCode.Table)
                {
                    accountRelation = retailTransaction.Customer.CustomerId;
                }
                else if (accountCode == PriceDiscAccountCode.GroupId)
                {
                    accountRelation = retailTransaction.Customer.MultiLineDiscountGroup;
                }
                accountRelation = accountRelation ?? String.Empty;

                // if both relations are valid for the given item and account codes, look for trade agreements matching these relations
                if ((Discount.ValidRelation(accountCode, accountRelation)) &&
                    (Discount.ValidRelation(itemCode, itemRelation)))
                {
                    // get any active multiline discount trade agreement matching relations and quantity
                    decimal quantityAmount = discountRow.Field <decimal>("QUANTITY");
                    var     priceDiscTable = this.DiscountService.GetPriceDiscDataCached(
                        retailTransaction.TransactionId, relation, itemRelation, accountRelation, (int)itemCode, (int)accountCode, quantityAmount, currencyCode, dimension, false);

                    // compute running sum of discount values found
                    foreach (Discount.DiscountAgreementArgs row in priceDiscTable)
                    {
                        discountRow["PERCENT1"] = discountRow.Field <decimal>("PERCENT1");
                        discountRow["PERCENT1"] = discountRow.Field <decimal>("PERCENT1") + row.Percent1;
                        discountRow["PERCENT2"] = discountRow.Field <decimal>("PERCENT2") + row.Percent2;
                        discountRow["AMOUNT"]   = discountRow.Field <decimal>("AMOUNT") + row.Amount;
                        discountRow["MINQTY"]   = discountRow.Field <decimal>("MINQTY") + row.QuantityAmountFrom;

                        // stop search when we find a trade agreement set to not find next trade agreement
                        if (!row.SearchAgain)
                        {
                            searchAgain = false;
                        }
                    }
                }

                // stop search if we found a discount without "find next" marked
                if (!searchAgain)
                {
                    break;
                }
            }

            return(discountRow);
        }
Esempio n. 8
0
 public frmAddLocalCustomer(RetailTransaction RTrans)
 {
     InitializeComponent();
     RetailTrans = RTrans;
 }
Esempio n. 9
0
        private void PaySalesInvoice(IPosTransaction posTransaction)
        {
            try
            {
                DataTable salesInvoices = new DataTable();
                GetSalesInvoicesForCustomer(ref salesInvoices, posTransaction);

                if (salesInvoices.Rows.Count == 0)
                {
                    // There are no sales invoices in the database for this customer....
                    using (LSRetailPosis.POSProcesses.frmMessage messageDialog = new LSRetailPosis.POSProcesses.frmMessage(57001, MessageBoxButtons.OK, MessageBoxIcon.Exclamation))
                    {
                        this.Application.ApplicationFramework.POSShowForm(messageDialog);

                        return;
                    }
                }

                // Show the available sales invoices for selection...
                using (WinFormsTouch.frmGetSalesInvoice salesInvoicesDialog = new global::Microsoft.Dynamics.Retail.Pos.SalesInvoice.WinFormsTouch.frmGetSalesInvoice())
                {
                    salesInvoicesDialog.SalesInvoices = salesInvoices;
                    this.Application.ApplicationFramework.POSShowForm(salesInvoicesDialog);

                    RetailTransaction retailTransaction = posTransaction as RetailTransaction;

                    if (salesInvoicesDialog.SelectedSalesInvoiceId != null && retailTransaction != null)
                    {
                        // Check if this Sales Invoice has already been added to the transaction
                        foreach (ISaleLineItem salesInvoiceInTrans in retailTransaction.SaleItems)
                        {
                            if (salesInvoiceInTrans is SalesInvoiceLineItem)
                            {
                                if (!salesInvoiceInTrans.Voided)
                                {
                                    if (((SalesInvoiceLineItem)salesInvoiceInTrans).SalesInvoiceId == salesInvoicesDialog.SelectedSalesInvoiceId)
                                    {
                                        using (LSRetailPosis.POSProcesses.frmMessage msgDialog = new LSRetailPosis.POSProcesses.frmMessage(57003, MessageBoxButtons.OK, MessageBoxIcon.Error))  // This sales invoice has already been added to the transaction
                                        {
                                            this.Application.ApplicationFramework.POSShowForm(msgDialog);
                                            return;
                                        }
                                    }
                                }
                            }
                        }

                        // There is a valid sales invoice selected and it's not been already added to the transaction. So let's get the details for it...
                        SalesInvoiceLineItem salesInvoiceLineItem = (SalesInvoiceLineItem)this.Application.BusinessLogic.Utility.CreateSalesInvoiceLineItem(
                            ApplicationSettings.Terminal.StoreCurrency,
                            this.Application.Services.Rounding, retailTransaction);

                        GetSalesInvoice(posTransaction, ref salesInvoiceLineItem, salesInvoicesDialog.SelectedSalesInvoiceId);

                        // And add it to the transaction
                        retailTransaction.Add(salesInvoiceLineItem);
                        retailTransaction.SalesInvoiceAmounts += salesInvoiceLineItem.Amount;
                    }
                }
            }
            catch (PosisException px)
            {
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), px);
                throw;
            }
            catch (Exception x)
            {
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), x);
                throw;
            }
            finally
            {
                if (posTransaction is SalesInvoiceTransaction)
                {
                    ((SalesInvoiceTransaction)posTransaction).CalcTotals();
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Print the standard slip, returns false if printing should be aborted altogether.
        /// </summary>
        /// <param name="formType"></param>
        /// <param name="posTransaction"></param>
        /// <param name="copyReceipt"></param>
        /// <returns></returns>
        public bool PrintReceipt(FormType formType, IPosTransaction posTransaction, bool copyReceipt)
        {
            bool result = false;

            if (formType == FormType.Receipt)
            {
                //SqlConnection SqlCon = new SqlConnection(ApplicationSettings.Database.LocalConnectionString);

                SqlConnection connection = new SqlConnection();
                if (application != null)
                {
                    connection = application.Settings.Database.Connection;
                }
                else
                {
                    connection = ApplicationSettings.Database.LocalConnection;
                }

                //Start :02/07/2014
                if (posTransaction is IRetailTransaction)
                {
                    RetailTransaction retailTransaction = (RetailTransaction)posTransaction;
                    SaleLineItem      item = retailTransaction.SaleItems.Last.Value;

                    if (item.Description == "Add to gift card")
                    {
                        //====
                        if (application != null)
                        {
                            connection = application.Settings.Database.Connection;
                        }
                        else
                        {
                            connection = ApplicationSettings.Database.LocalConnection;
                        }
                        string  sTransactionId = retailTransaction.TransactionId;
                        string  sTerminalId    = retailTransaction.TerminalId;
                        string  sCardNo        = string.Empty;
                        decimal sAmt           = 0;

                        DataTable dt = GetGiftCardAmountInfo(connection, sTransactionId, sTerminalId);

                        if (dt != null && dt.Rows.Count > 0)
                        {
                            for (int i = 0; i <= dt.Rows.Count - 1; i++)
                            {
                                if (string.IsNullOrEmpty(sCardNo))
                                {
                                    sAmt = Convert.ToDecimal(dt.Rows[i]["AMOUNT"]);

                                    sCardNo = Convert.ToString(dt.Rows[i]["COMMENT"]);
                                    sCardNo = new String('x', Convert.ToInt16(sCardNo.Length) - 4) + sCardNo.Substring(Convert.ToInt16(sCardNo.Length) - 4);
                                }
                                else
                                {
                                    sCardNo = sCardNo + "  / " + new String('x', Convert.ToInt16(Convert.ToString(dt.Rows[i]["COMMENT"]).Length) - 4) + Convert.ToString(dt.Rows[i]["COMMENT"]).Substring(Convert.ToInt16(Convert.ToString(dt.Rows[i]["COMMENT"]).Length) - 4);
                                    sAmt    = sAmt + Convert.ToDecimal(dt.Rows[i]["AMOUNT"]);
                                }
                            }
                        }
                        frmR_ProductAdvanceReceipt objProdAdv = new frmR_ProductAdvanceReceipt(posTransaction, connection, sTransactionId, Convert.ToString(sAmt), sTerminalId, item.Description, sCardNo);
                        objProdAdv.ShowDialog();
                    }
                    else
                    {
                        if (retailTransaction.RefundReceiptId == "1")
                        {
                            string  sTransactionId = retailTransaction.TransactionId;
                            string  sTerminalId    = retailTransaction.TerminalId;
                            string  sCardNo        = string.Empty;
                            decimal sAmt           = 0;

                            DataTable dt = GetGiftCardAmountInfo(connection, sTransactionId, sTerminalId);

                            if (dt != null && dt.Rows.Count > 0)
                            {
                                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                                {
                                    if (string.IsNullOrEmpty(sCardNo))
                                    {
                                        sAmt = Convert.ToDecimal(dt.Rows[i]["AMOUNT"]);

                                        sCardNo = Convert.ToString(dt.Rows[i]["COMMENT"]);
                                        sCardNo = new String('x', Convert.ToInt16(sCardNo.Length) - 4) + sCardNo.Substring(Convert.ToInt16(sCardNo.Length) - 4);
                                    }
                                    else
                                    {
                                        sCardNo = sCardNo + "  / " + new String('x', Convert.ToInt16(Convert.ToString(dt.Rows[i]["COMMENT"]).Length) - 4) + Convert.ToString(dt.Rows[i]["COMMENT"]).Substring(Convert.ToInt16(Convert.ToString(dt.Rows[i]["COMMENT"]).Length) - 4);
                                        sAmt    = sAmt + Convert.ToDecimal(dt.Rows[i]["AMOUNT"]);
                                    }
                                }
                            }

                            frmR_ProductAdvanceReceipt objProdAdv = new frmR_ProductAdvanceReceipt(posTransaction, connection, sTransactionId, Convert.ToString(sAmt), sTerminalId, item.Description, sCardNo, 1);
                            objProdAdv.ShowDialog();
                        }
                        else
                        {
                            if (retailTransaction.SaleIsReturnSale)
                            {
                                frmSaleInv reportfrm = new frmSaleInv(posTransaction, connection, copyReceipt, 0, 0, iPrintFromShowJournal);
                                reportfrm.ShowDialog();
                                frmSaleInvAccountsCopy reportfrmAcc = new frmSaleInvAccountsCopy(posTransaction, connection, copyReceipt, 0, 0, iPrintFromShowJournal);
                                reportfrmAcc.ShowDialog();
                                //frmSaleInvControlCopy reportfrmCon = new frmSaleInvControlCopy(posTransaction, connection, copyReceipt, 0, 0, iPrintFromShowJournal);
                                //reportfrmCon.ShowDialog();// commented on 080819/ req by Soudip paul
                            }
                            else
                            {
                                //Microsoft.Dynamics.Retail.Pos.BlankOperations.WinFormsTouch.frmLanguageForInvoice
                                //    objLI = new BlankOperations.WinFormsTouch.frmLanguageForInvoice();

                                //objLI.ShowDialog();
                                //int iLanguage = 0;
                                //if (objLI.isEnglish == true)
                                //    iLanguage = 1;
                                //else if (objLI.isArabic == true)
                                //    iLanguage = 2;
                                //else if (objLI.isBoth == true)
                                //    iLanguage = 3;


                                if (iPrintFromShowJournal == 1)
                                {
                                    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("Is this a gift invoice?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                                    {
                                        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                                        if (Convert.ToString(dialog.DialogResult).ToUpper().Trim() == "YES")
                                        {
                                            frmSaleInv reportfrm = new frmSaleInv(posTransaction, connection, copyReceipt, 1, 0, iPrintFromShowJournal);//Default English for Sales Return
                                            reportfrm.ShowDialog();

                                            frmSaleInv reportfrm1 = new frmSaleInv(posTransaction, connection, copyReceipt, 0, 1, iPrintFromShowJournal);
                                            reportfrm1.ShowDialog();
                                        }
                                        else
                                        {
                                            ChooseInvoiceLanguage(posTransaction, copyReceipt, connection, iPrintFromShowJournal);
                                        }
                                    }
                                    iPrintFromShowJournal = 0;
                                }
                                else
                                {
                                    ChooseInvoiceLanguage(posTransaction, copyReceipt, connection, iPrintFromShowJournal);
                                }
                            }
                        }
                    }


                    //retailTransaction
                }

                //End : 02/07/2014
            }
            else if (formType == FormType.CustomerAccountDeposit)
            {
                RetailTransaction retailTransaction = posTransaction as RetailTransaction;
                string            sGSSNo            = string.Empty;
                if (retailTransaction != null)
                {
                    SqlConnection connection = new SqlConnection();
                    if (application != null)
                    {
                        connection = application.Settings.Database.Connection;
                    }
                    else
                    {
                        connection = ApplicationSettings.Database.LocalConnection;
                    }
                    string sTransactionId = retailTransaction.TransactionId;
                    // string sTerminalId = ApplicationSettings.Terminal.TerminalId;

                    string sTerminalId = retailTransaction.TerminalId;

                    DataTable dtAdv = GetAdvanceInfo(connection, sTransactionId, sTerminalId);

                    if (dtAdv != null && dtAdv.Rows.Count > 0)
                    {
                        sGSSNo = Convert.ToString(dtAdv.Rows[0]["GSSNUMBER"]);

                        if (sGSSNo != string.Empty)
                        {
                            frmR_GSSInstalmentReceipt objRGSS = new frmR_GSSInstalmentReceipt(posTransaction, connection, sTransactionId, Convert.ToString(dtAdv.Rows[0]["AMOUNT"]), sGSSNo, sTerminalId);
                            objRGSS.ShowDialog();
                        }
                        else
                        {
                            Microsoft.Dynamics.Retail.Pos.BlankOperations.WinFormsTouch.frmLanguageForInvoice
                                objLI = new BlankOperations.WinFormsTouch.frmLanguageForInvoice();

                            objLI.ShowDialog();
                            int iLanguage = 0;
                            if (objLI.isEnglish == true)
                            {
                                iLanguage = 1;
                            }
                            else if (objLI.isArabic == true)
                            {
                                iLanguage = 2;
                            }
                            else if (objLI.isBoth == true)
                            {
                                iLanguage = 3;
                            }

                            frmR_ProductAdvanceReceipt objProdAdv = new frmR_ProductAdvanceReceipt(posTransaction, connection, sTransactionId, Convert.ToString(dtAdv.Rows[0]["AMOUNT"]), sTerminalId, "", "", 0, iLanguage);
                            objProdAdv.ShowDialog();
                        }
                    }
                }
            }
            else
            {
                if (FiscalPrinter.FiscalPrinter.Instance.FiscalPrinterEnabled())
                {
                    return(FiscalPrinter.FiscalPrinter.Instance.PrintReceipt(formType, posTransaction, copyReceipt));
                }

                FormModulation             formMod        = new FormModulation(Application.Settings.Database.Connection);
                IList <PrinterAssociation> printerMapping = PrintingActions.GetActivePrinters(formMod, formType, copyReceipt);

                // bool result = false;
                foreach (PrinterAssociation printerMap in printerMapping)
                {
                    bool printResult = PrintingActions.PrintFormTransaction(printerMap, formMod, formType, posTransaction, copyReceipt);

                    result = result || printResult;
                }
            }

            return(result);
        }
        /// <summary>
        /// Return dictionary that, given offergroup, call tell the concurrency mode of the offer
        /// </summary>
        /// <param name="retailTransaction"></param>
        /// <returns></returns>
        private static Dictionary <OfferGroup, ConcurrencySettings> ConcurrencySettingsPerOfferGroup(RetailTransaction retailTransaction)
        {
            Dictionary <OfferGroup, ConcurrencySettings> concurrencySettingsPerGroup = new Dictionary <OfferGroup, ConcurrencySettings>();

            foreach (var saleItem in retailTransaction.SaleItems)
            {
                foreach (var discountItem in saleItem.PeriodicDiscountPossibilities)
                {
                    OfferGroup offerGroup = GetOfferGroup(discountItem);
                    if (!concurrencySettingsPerGroup.ContainsKey(offerGroup))
                    {
                        concurrencySettingsPerGroup.Add(offerGroup,
                                                        new ConcurrencySettings
                        {
                            ConcurrencyMode = discountItem.ConcurrencyMode,
                            IsCompoundable  = discountItem.IsCompoundable
                        });
                    }
                }
            }

            return(concurrencySettingsPerGroup);
        }
Esempio n. 12
0
        public frmR_GSSInstalmentReceipt(IPosTransaction posTransaction, SqlConnection conn, string _sTransId, string _sAmt, string sGSSAccNo, string sTerminalId)
        {
            InitializeComponent();
            sTerminal = sTerminalId;

            #region [Param Info]
            RetailTransaction retailTrans = posTransaction as RetailTransaction;
            if (retailTrans != null)
            {
                if (Convert.ToString(retailTrans.Customer.Name) != string.Empty)
                {
                    sCustName = Convert.ToString(retailTrans.Customer.Name);
                }
                if (!string.IsNullOrEmpty(Convert.ToString(retailTrans.Customer.CustomerId)))
                {
                    sCustId = Convert.ToString(retailTrans.Customer.CustomerId);
                }
                if (Convert.ToString(retailTrans.Customer.Address) != string.Empty)  //PrimaryAddress
                {
                    sCustAddress = Convert.ToString(retailTrans.Customer.Address);
                }
                if (Convert.ToString(retailTrans.Customer.PostalCode) != string.Empty)
                {
                    sCPinCode = Convert.ToString(retailTrans.Customer.PostalCode);
                }
                //if(Convert.ToString(retailTrans.Customer.MobilePhone) != string.Empty)
                //    sContactNo = Convert.ToString(retailTrans.Customer.MobilePhone);

                if (!string.IsNullOrEmpty(retailTrans.Customer.Telephone))
                {
                    sContactNo = Convert.ToString(retailTrans.Customer.Telephone);
                }
                //sCPanNo
                sCurrencySymbol = oBlank.GetCurrencySymbol();
                //-------
                if (Convert.ToString(retailTrans.TransactionId) != string.Empty)
                {
                    sReceiptNo        = _sTransId;// Convert.ToString(retailTrans.TransactionId);
                    sReceiptVoucherNo = retailTrans.ReceiptId;
                }

                if (Convert.ToString(sReceiptVoucherNo) == string.Empty)
                {
                    sReceiptVoucherNo = GetReciptVouNo(_sTransId, conn);
                }

                //if(retailTrans.BeginDateTime != null)
                //    sReceiptDate = retailTrans.BeginDateTime.ToShortDateString();

                sAmount      = oBlank.Amtinwds(Convert.ToDouble(_sAmt));
                sDetailsLine = "Received with thanks from " + "" + sCustName + "                                                                          " + sCurrencySymbol + " " + _sAmt;
                //----------store Info

                GetGSSMaturityDate(sGSSAccNo, conn); // added on 29/03/2014 req by Sailendra da. dev by R.Hossain
                //if(Convert.ToString(retailTrans.StoreName) != string.Empty)
                //    sStoreName = Convert.ToString(retailTrans.StoreName);
                //if(Convert.ToString(retailTrans.StoreAddress) != string.Empty)
                //    sStoreAddress = Convert.ToString(retailTrans.StoreAddress);
                ////if(Convert.ToString(retailTrans.StorePhone) != string.Empty)
                //if (!string.IsNullOrEmpty(Convert.ToString(retailTrans.StorePhone)))
                //    sStorePhNo = Convert.ToString(retailTrans.StorePhone);


                if (Convert.ToString(ApplicationSettings.Terminal.StoreName) != string.Empty)
                {
                    sStoreName = Convert.ToString(ApplicationSettings.Terminal.StoreName);
                }
                if (Convert.ToString(ApplicationSettings.Terminal.StoreAddress) != string.Empty)
                {
                    sStoreAddress = Convert.ToString(ApplicationSettings.Terminal.StoreAddress);
                }
                if (!string.IsNullOrEmpty(Convert.ToString(ApplicationSettings.Terminal.StorePhone)))
                {
                    sStorePhNo = Convert.ToString(ApplicationSettings.Terminal.StorePhone);
                }

                sDataAreaId = Convert.ToString(ApplicationSettings.Database.DATAAREAID);

                //if(Convert.ToString(retailTrans.InventLocationId) != string.Empty)
                //    sInventLocationId = Convert.ToString(retailTrans.InventLocationId);
                sInventLocationId = ApplicationSettings.Terminal.InventLocationId;
            }
            connection = conn;
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            GetStoreInfo(ref sStorePhNo, ref sInvoiceFooter, ref sCINNo);
            sCompanyName  = oBlank.GetCompanyName(conn); //aded on 14/04/2014 R.Hossain
            sGSSAccNumber = sGSSAccNo;                   // added on 18/04/2014
            #endregion
        }
Esempio n. 13
0
        /// <summary>
        /// Calculate taxes for the transaction
        /// </summary>
        /// <param name="retailTransaction"></param>
        public void CalculateTax(IRetailTransaction retailTransaction)
        {
            RetailTransaction transaction = retailTransaction as RetailTransaction;

            if (transaction == null)
            {
                throw new ArgumentNullException("retailTransaction");
            }

            // Clear the cache if transaction is changed.
            if (string.IsNullOrWhiteSpace(cachedTransactionID) ||
                (taxCodeCache.Count > 0 && !cachedTransactionID.Equals(transaction.TransactionId, StringComparison.OrdinalIgnoreCase)))
            {
                cachedTransactionID = transaction.TransactionId;
                taxCodeCache.Clear();
            }

            // at different we have different implementations of Itaxable. Flatten them into a list and loop.
            List <ITaxableItem> taxableItems = new List <ITaxableItem>();

            // Order level charges
            taxableItems.AddRange(transaction.MiscellaneousCharges);

            // Line Level
            foreach (SaleLineItem lineItem in transaction.SaleItems)
            {
                // lineitem itself
                taxableItems.Add(lineItem);

                // associated charges
                taxableItems.AddRange(lineItem.MiscellaneousCharges);
            }

            // Calculate tax on order-level miscellaneous charges
            foreach (ITaxableItem taxableItem in taxableItems)
            {
                //Start : ************AM added on 18/01/2018
                int    iIsTaxableAdv = 0;
                string sAdJustItem   = AdjustmentItemID(ref iIsTaxableAdv);
                int    iTaxIncluded  = getPriceTaxIncludedOrNo();//added RH on 120718

                if (taxableItem.ItemId == sAdJustItem)
                {
                    if (iIsTaxableAdv == 1)
                    {
                        transaction.TaxIncludedInPrice = true;
                    }
                    else
                    {
                        transaction.TaxIncludedInPrice = false;
                    }
                }
                //else if (iTaxIncluded == 0)//added RH on 120718
                //{
                //    transaction.TaxIncludedInPrice = false;
                //}
                //End : ************AM added on 18/01/2018

                this.CalculateTax(taxableItem, transaction);
            }

            //Round by Tax Group if required.
            IEnumerable <string> groups = GetTaxGroupsToRound();

            foreach (string group in groups)
            {
                foreach (BaseSaleItem lineItem in transaction.SaleItems)
                {
                    RoundTaxGroup(lineItem, group);
                }
            }
        }
Esempio n. 14
0
        protected virtual ReadOnlyCollection <TaxCode> GetTaxCodes(ITaxableItem taxableItem)
        {
            if (taxableItem == null)
            {
                throw new ArgumentNullException("taxableItem");
            }

            RetailTransaction transaction = (RetailTransaction)taxableItem.RetailTransaction;
            string            customerId  = string.Empty;

            // If the line has an EndDate specified (usually because it's a Returned line),
            // then use that value to calculate taxes, otherwise use BeginDate
            DateTime itemSaleDateTime = (taxableItem.EndDateTime <= NoDate) ? taxableItem.BeginDateTime : taxableItem.EndDateTime;

            if (transaction != null && transaction.Customer != null)
            {
                customerId = transaction.Customer.CustomerId;
            }

            CacheKey cacheKey = new CacheKey(taxableItem.ItemId,
                                             customerId,
                                             taxableItem.TaxGroupId,
                                             taxableItem.SalesTaxGroupId,
                                             itemSaleDateTime);

            if (taxCodeCache.ContainsKey(cacheKey))
            {
                List <TaxCode> taxCodes = taxCodeCache[cacheKey];

                // Update the lineItem object in cached Taxcode object (Everytime we get new SalesLine Object)
                taxCodes.ForEach(t => t.LineItem = taxableItem);

                return(SortCodes(taxCodes));
            }

            NetTracer.Information("TaxCodeProvider::GetTaxCodes(): Quering database.");

            SqlConnection connection = Application.Settings.Database.Connection;
            string        dataAreaId = Application.Settings.Database.DataAreaID;

            try
            {
                Dictionary <string, TaxCode> codes = new Dictionary <string, TaxCode>();

                bool useDefaultTaxGroups = (cacheKey.TaxGroupID == null) || (cacheKey.SalesTaxGroupID == null);

                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connection;

                    string sb = string.Format(@"SELECT DISTINCT {0}    FROM TAXGROUPHEADING  ", TaxSelectSqlText);

                    if (useDefaultTaxGroups)
                    {
                        // #1 Look in the DB for the default Customer/Store tax group mapping
                        if (String.IsNullOrWhiteSpace(cacheKey.CustomerID))
                        {
                            sb += @"INNER JOIN RETAILSTORETABLE ON 
                                TAXGROUPHEADING.TAXGROUP = RETAILSTORETABLE.TAXGROUP 
                                AND  RETAILSTORETABLE.STORENUMBER = @STOREID ";

                            command.Parameters.AddWithValue("@STOREID", ApplicationSettings.Terminal.StoreId);
                        }
                        else
                        {
                            sb += @"INNER JOIN CUSTTABLE ON 
                                TAXGROUPHEADING.TAXGROUP = CUSTTABLE.TAXGROUP 
                                AND CUSTTABLE.DATAAREAID = @DATAAREAID 
                                AND CUSTTABLE.ACCOUNTNUM = @CUSTOMERID ";

                            command.Parameters.AddWithValue("@CUSTOMERID", cacheKey.CustomerID);
                        }
                    }

                    sb += @"INNER JOIN TAXGROUPDATA ON 
                        TAXGROUPDATA.DATAAREAID = @DATAAREAID 
                        AND TAXGROUPHEADING.TAXGROUP = TAXGROUPDATA.TAXGROUP 

                        INNER JOIN TAXONITEM ON 
                        TAXONITEM.DATAAREAID = @DATAAREAID 
                        AND TAXGROUPDATA.TAXCODE = TAXONITEM.TAXCODE  ";

                    if (useDefaultTaxGroups)
                    {
                        // Join against the Item's default Item tax group
                        sb += @"INNER JOIN INVENTTABLEMODULE ON 
                            INVENTTABLEMODULE.DATAAREAID = @DATAAREAID 
                            AND INVENTTABLEMODULE.TAXITEMGROUPID = TAXONITEM.TAXITEMGROUP  ";
                    }

                    sb += @"INNER JOIN TAXDATA ON 
                        TAXDATA.DATAAREAID = @DATAAREAID 
                        AND TAXONITEM.TAXCODE = TAXDATA.TAXCODE 

                        INNER JOIN TAXTABLE ON 
                        TAXTABLE.DATAAREAID = @DATAAREAID 
                        AND TAXTABLE.TAXCODE = TAXDATA.TAXCODE 

                        LEFT JOIN TAXCOLLECTLIMIT ON 
                        TAXCOLLECTLIMIT.DATAAREAID = @DATAAREAID 
                        AND TAXCOLLECTLIMIT.TAXCODE = TAXDATA.TAXCODE 
                        AND (TAXCOLLECTLIMIT.TAXFROMDATE IS NULL 
                        OR @TRANSACTIONDATE >= TAXCOLLECTLIMIT.TAXFROMDATE 
                        OR TAXCOLLECTLIMIT.TAXFROMDATE < @NODATEBOUNDRY ) 
                        AND (TAXCOLLECTLIMIT.TAXTODATE IS NULL 
                        OR @TRANSACTIONDATE < DATEADD(d, 1, TAXCOLLECTLIMIT.TAXTODATE) 
                        OR TAXCOLLECTLIMIT.TAXTODATE < @NODATEBOUNDRY) 

                        WHERE (TAXGROUPHEADING.DATAAREAID = @DATAAREAID)  ";

                    command.Parameters.AddWithValue("@DATAAREAID", dataAreaId);

                    if (useDefaultTaxGroups)
                    {
                        sb += @"AND (INVENTTABLEMODULE.ITEMID = @ITEMID) 
                            AND (INVENTTABLEMODULE.MODULETYPE = @MODULETYPE)  ";

                        command.Parameters.AddWithValue("@ITEMID", cacheKey.ItemID);
                        command.Parameters.AddWithValue("@MODULETYPE", (int)ModuleType.Sales);
                    }
                    else
                    {
                        // Filter against the item's current Item Tax Group and Customer/Store tax group
                        sb += @"AND TAXONITEM.TAXITEMGROUP = @ITEMTAXGROUP 
                            AND TAXGROUPHEADING.TAXGROUP = @SALESTAXGROUP  ";

                        command.Parameters.AddWithValue("@SALESTAXGROUP", cacheKey.SalesTaxGroupID ?? string.Empty);
                        command.Parameters.AddWithValue("@ITEMTAXGROUP", cacheKey.TaxGroupID ?? string.Empty);
                    }

                    // Currently only evaluate taxes against the current time.
                    // Note that the date value of '1900-01-01 00:00.000' is the marker for "no boundry".
                    sb += @"AND 
                        ((@TRANSACTIONDATE >= TAXDATA.TAXFROMDATE OR TAXDATA.TAXFROMDATE < @NODATEBOUNDRY ) 
                        AND (@TRANSACTIONDATE < DATEADD(d, 1, TAXDATA.TAXTODATE) OR TAXDATA.TAXTODATE < @NODATEBOUNDRY)) ";

                    command.Parameters.AddWithValue("@NODATEBOUNDRY", NoDate);
                    command.Parameters.AddWithValue("@TRANSACTIONDATE", cacheKey.SaleDateTime);

                    sb += AddTaxSelectSqlCondition(command);

                    command.CommandText = sb.ToString();

                    if (connection.State != ConnectionState.Open)
                    {
                        connection.Open();
                    }

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        string taxCodeKey = string.Empty;

                        while (reader.Read())
                        {
                            taxCodeKey = reader["TAXCODE"] as string;

                            if (codes.ContainsKey(taxCodeKey))
                            {
                                // Add a new 'value' entry for an existing tax code
                                codes[taxCodeKey].TaxIntervals.Add(
                                    new TaxInterval(
                                        (decimal)reader["TAXLIMITMIN"],
                                        (decimal)reader["TAXLIMITMAX"],
                                        (decimal)reader["TAXVALUE"]));
                            }
                            else
                            {
                                AddTaxCode(cacheKey, reader, taxableItem, codes);
                            }
                        }
                    }
                }

                // Link any taxes which rely on other taxes
                foreach (TaxCode tax in codes.Values)
                {
                    if (!string.IsNullOrEmpty(tax.TaxOnTax) &&
                        (tax.TaxBase == TaxBase.PercentPerTax || tax.TaxBase == TaxBase.PercentPerGross) &&
                        codes.Keys.Contains(tax.TaxOnTax))
                    {
                        tax.TaxOnTaxInstance = codes[tax.TaxOnTax] as TaxCode;
                    }
                }

                return(SortCodes(codes.Values));
            }
            catch (Exception ex)
            {
                NetTracer.Error(ex, "GetTaxCodes() failed in an Exception");
                throw;
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }
Esempio n. 15
0
        public bool AddLoyaltyRequest(IRetailTransaction retailTransaction, ICardInfo cardInfo)
        {
            try
            {
                try
                {
                    NewMessageWindow(50050, LSPosMessageTypeButton.NoButtons, System.Windows.Forms.MessageBoxIcon.Information);

                    LogMessage("Adding a loyalty record to the transaction...",
                               LSRetailPosis.LogTraceLevel.Trace,
                               "Loyalty.AddLoyaltyItem");

                    this.transaction = (RetailTransaction)retailTransaction;

                    // If a previous loyalty item exists on the transaction, the system should prompt the user whether to
                    // overwrite the existing loyalty item or cancel the operation.
                    if (transaction.LoyaltyItem.LoyaltyCardNumber != null)
                    {
                        // Display the dialog
                        using (frmMessage dialog = new frmMessage(50055, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            LP.POSFormsManager.ShowPOSForm(dialog);
                            DialogResult result = dialog.DialogResult;

                            if (result != System.Windows.Forms.DialogResult.Yes)
                            {
                                return(false);
                            }
                        }

                        // If card to be overridden is being used as tender type then block loyalty payment.
                        if (transaction.LoyaltyItem.UsageType == LoyaltyItemUsageType.UsedForLoyaltyTender)
                        {
                            LP.POSFormsManager.ShowPOSMessageDialog(3223);  // This transaction already contains a loyalty request.
                            return(false);
                        }
                    }

                    // Add the loyalty item to the transaction

                    LoyaltyItem loyaltyItem = GetLoyaltyItem(ref cardInfo);

                    if (loyaltyItem != null)
                    {
                        transaction.LoyaltyItem = loyaltyItem;
                        this.transaction.LoyaltyItem.UsageType = LoyaltyItemUsageType.UsedForLoyaltyRequest;

                        UpdateTransactionWithNewCustomer(loyaltyItem.CustID);

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                finally
                {
                    CloseExistingMessageWindow();
                }
            }
            catch (Exception ex)
            {
                NetTracer.Error(ex, "Loyalty::AddLoyaltyRequest failed for retailTransaction {0} cardInfo {1}", retailTransaction.TransactionId, cardInfo.CardNumber);
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), ex);
                throw;
            }
        }
 public Task Save(RetailTransaction transaction)
 {
     return(Task.CompletedTask);
 }
Esempio n. 17
0
        public void AddLoyaltyPayment(IRetailTransaction retailTransaction, ICardInfo cardInfo, decimal amount)
        {
            try
            {
                try
                {
                    NewMessageWindow(50051, LSPosMessageTypeButton.NoButtons, System.Windows.Forms.MessageBoxIcon.Information);

                    this.transaction = (RetailTransaction)retailTransaction;

                    // Getting the loyalty info for the card, how many points have previously been earned
                    LoyaltyItem paymentLoyaltyItem = GetLoyaltyItem(ref cardInfo);

                    if (paymentLoyaltyItem != null)
                    {
                        //customerData.
                        if (this.transaction.Customer == null || string.Equals(this.transaction.Customer.CustomerId, paymentLoyaltyItem.CustID, StringComparison.OrdinalIgnoreCase) == false)
                        {
                            UpdateTransactionWithNewCustomer(paymentLoyaltyItem.CustID);
                        }

                        // if the amount is higher than the "new" NetAmountWithTax, then it is acceptable to lower the amount
                        if (Math.Abs(amount) > Math.Abs(this.transaction.TransSalePmtDiff))
                        {
                            amount = this.transaction.TransSalePmtDiff;
                        }

                        // Getting all possible loyalty posssiblities for the found scheme id
                        DataTable loyaltyPointsTable = GetLoyaltyPointsSchemeFromDB(paymentLoyaltyItem.SchemeID);

                        decimal totalNumberOfPoints = 0;
                        bool    tenderRuleFound     = false;

                        // now we add the points needed to pay current tender
                        totalNumberOfPoints = CalculatePointsForTender(ref tenderRuleFound, cardInfo.TenderTypeId, amount, loyaltyPointsTable);

                        if (tenderRuleFound)
                        {
                            bool    cardIsValid           = false;
                            string  comment               = string.Empty;
                            int     loyaltyTenderTypeBase = 0;
                            decimal pointsEarned          = 0;

                            // check to see if the user can afford so many points
                            GetPointStatus(ref pointsEarned, ref cardIsValid, ref comment, ref loyaltyTenderTypeBase, paymentLoyaltyItem.LoyaltyCardNumber);

                            if ((cardIsValid) && ((LoyaltyTenderTypeBase)loyaltyTenderTypeBase != LoyaltyTenderTypeBase.NoTender))
                            {
                                if (pointsEarned >= (totalNumberOfPoints * -1))
                                {
                                    //customerData.
                                    if (this.transaction.Customer == null || string.Equals(this.transaction.Customer.CustomerId, paymentLoyaltyItem.CustID, StringComparison.OrdinalIgnoreCase) == false)
                                    {
                                        UpdateTransactionWithNewCustomer(paymentLoyaltyItem.CustID);
                                    }

                                    //Add loyalty item to transaction.
                                    this.transaction.LoyaltyItem           = paymentLoyaltyItem;
                                    this.transaction.LoyaltyItem.UsageType = LoyaltyItemUsageType.UsedForLoyaltyTender;

                                    // Gathering tender information
                                    TenderData tenderData = new TenderData(ApplicationSettings.Database.LocalConnection, ApplicationSettings.Database.DATAAREAID);
                                    ITender    tenderInfo = tenderData.GetTender(cardInfo.TenderTypeId, ApplicationSettings.Terminal.StoreId);

                                    // this is the grand total
                                    decimal totalAmountDue = this.transaction.TransSalePmtDiff - amount;

                                    TenderRequirement tenderRequirement = new TenderRequirement((Tender)tenderInfo, amount, true, this.transaction.TransSalePmtDiff);
                                    if (!string.IsNullOrWhiteSpace(tenderRequirement.ErrorText))
                                    {
                                        using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage(tenderRequirement.ErrorText, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error))
                                        {
                                            LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                                        }
                                    }

                                    //Add a loyalty tender item to transaction.
                                    LoyaltyTenderLineItem loyaltyTenderItem = (LoyaltyTenderLineItem)this.Application.BusinessLogic.Utility.CreateLoyaltyTenderLineItem();
                                    loyaltyTenderItem.CardNumber = paymentLoyaltyItem.LoyaltyCardNumber;
                                    loyaltyTenderItem.CardTypeId = cardInfo.CardTypeId;
                                    loyaltyTenderItem.Amount     = amount;

                                    //tenderInfo.
                                    loyaltyTenderItem.Description   = tenderInfo.TenderName;
                                    loyaltyTenderItem.TenderTypeId  = cardInfo.TenderTypeId;
                                    loyaltyTenderItem.LoyaltyPoints = totalNumberOfPoints;

                                    //convert from the store-currency to the company-currency...
                                    loyaltyTenderItem.CompanyCurrencyAmount = this.Application.Services.Currency.CurrencyToCurrency(
                                        ApplicationSettings.Terminal.StoreCurrency,
                                        ApplicationSettings.Terminal.CompanyCurrency,
                                        amount);

                                    // the exchange rate between the store amount(not the paid amount) and the company currency
                                    loyaltyTenderItem.ExchrateMST = this.Application.Services.Currency.ExchangeRate(
                                        ApplicationSettings.Terminal.StoreCurrency) * 100;

                                    // card tender processing and printing require an EFTInfo object to be attached.
                                    // however, we don't want loyalty info to show up where other EFT card info would on the receipt
                                    //  because loyalty has its own receipt template fields, so we just assign empty EFTInfo object
                                    loyaltyTenderItem.EFTInfo = Application.BusinessLogic.Utility.CreateEFTInfo();
                                    // we don't want Loyalty to be 'captured' by payment service, so explicitly set not to capture to be safe
                                    loyaltyTenderItem.EFTInfo.IsPendingCapture = false;

                                    loyaltyTenderItem.SignatureData = LSRetailPosis.POSProcesses.TenderOperation.ProcessSignatureCapture(tenderInfo, loyaltyTenderItem);

                                    this.transaction.Add(loyaltyTenderItem);
                                }
                                else
                                {
                                    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage(50057, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error))
                                    {
                                        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                                    } // Not enough points available to complete payment
                                }
                            }
                            else
                            {
                                LSRetailPosis.POSProcesses.frmMessage dialog = null;
                                try
                                {
                                    if (string.IsNullOrEmpty(comment))
                                    {
                                        dialog = new LSRetailPosis.POSProcesses.frmMessage(50058, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        dialog = new LSRetailPosis.POSProcesses.frmMessage(comment, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                                    }

                                    LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);    // Invalid loyaltycard
                                }
                                finally
                                {
                                    if (dialog != null)
                                    {
                                        dialog.Dispose();
                                    }
                                }
                            }
                        }
                        else
                        {
                            using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage(50059, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error))
                            {
                                LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog); // Not enough points available to complete payment
                            }
                        }
                    }
                }
                finally
                {
                    CloseExistingMessageWindow();
                }
            }
            catch (Exception ex)
            {
                NetTracer.Error(ex, "Loyalty::AddLoyaltyPayment failed for retailTransaction {0} cardInfo {1} amount {2}", retailTransaction.TransactionId, cardInfo.CardNumber, amount);
                LSRetailPosis.ApplicationExceptionHandler.HandleException(this.ToString(), ex);
                throw;
            }
        }
 public Task Create(string operationId, int orderId)
 {
     current = new RetailTransaction(operationId, orderId, "md");
     return(Task.CompletedTask);
 }
        public frmR_ProductAdvanceReceipt(IPosTransaction posTransaction, SqlConnection conn, string _sTransId, string _sAmt, string sTerminalId, string sGiftCardItemName = "", string sGiftCardNo = "", int iIsAdvRefund = 0, int iLanguage = 0)
        {
            InitializeComponent();
            sTerminal = sTerminalId;

            #region [Param Info]
            RetailTransaction retailTrans = posTransaction as RetailTransaction;
            if (retailTrans != null)
            {
                iInvLang = iLanguage;
                if (Convert.ToString(retailTrans.Customer.Name) != string.Empty)
                {
                    sCustName = Convert.ToString(retailTrans.Customer.Name);
                }
                if (!string.IsNullOrEmpty(Convert.ToString(retailTrans.Customer.CustomerId)))
                {
                    sCustId = Convert.ToString(retailTrans.Customer.CustomerId);
                }
                if (Convert.ToString(retailTrans.Customer.Address) != string.Empty)  //PrimaryAddress
                {
                    sCustAddress = Convert.ToString(retailTrans.Customer.Address);
                }
                if (Convert.ToString(retailTrans.Customer.PostalCode) != string.Empty)
                {
                    sCPinCode = Convert.ToString(retailTrans.Customer.PostalCode);
                }
                if (Convert.ToString(retailTrans.Customer.Email) != string.Empty)
                {
                    sCustEmail = Convert.ToString(retailTrans.Customer.Email);
                }

                //if(Convert.ToString(retailTrans.Customer.MobilePhone) != string.Empty)
                //    sContactNo = Convert.ToString(retailTrans.Customer.MobilePhone);

                if (!string.IsNullOrEmpty(retailTrans.Customer.Telephone))
                {
                    sContactNo = Convert.ToString(retailTrans.Customer.Telephone);
                }

                //sCPanNo

                //-------
                if (Convert.ToString(retailTrans.TransactionId) != string.Empty)
                {
                    sReceiptNo        = _sTransId;// Convert.ToString(retailTrans.TransactionId);
                    sReceiptVoucherNo = retailTrans.ReceiptId;
                }


                sInvoiceNo = sReceiptNo;

                if (retailTrans.EndDateTime != null)
                {
                    sInvDt = retailTrans.EndDateTime.ToShortDateString();
                }

                if (retailTrans.EndDateTime != null)
                {
                    sTime = retailTrans.EndDateTime.ToString("hh:mm tt"); //("HH:mm")
                }
                //if(retailTrans.BeginDateTime != null)
                //    sReceiptDate = retailTrans.BeginDateTime.ToShortDateString();

                sAmount = oBlank.Amtinwds(Convert.ToDouble(_sAmt));

                sAmtinwdsArabic = oBlank.AmtinwdsInArabic(Convert.ToDouble(_sAmt));

                if (iInvLang == 2)
                {
                    sAmount = sAmtinwdsArabic;
                }
                else if (iInvLang == 3)
                {
                    sAmount = sAmount + System.Environment.NewLine + "" + sAmtinwdsArabic;
                }


                sCurrencySymbol = oBlank.GetCurrencySymbol();
                string sAdJustItem = AdjustmentItemID();
                string ItemTaxCode = getTaxGropCode(sAdJustItem);

                dTaxPct = getTaxPctValue(ItemTaxCode);                                                    //getItemTaxPercentage();// ;
                decimal dAmt = decimal.Round(Convert.ToDecimal(_sAmt), 2, MidpointRounding.AwayFromZero); //Convert.ToDecimal(_sAmt);
                dTaxAmt       = decimal.Round(Convert.ToDecimal(dAmt * dTaxPct / (100 + dTaxPct)), 2, MidpointRounding.AwayFromZero);
                dExcludTaxAmt = dAmt - dTaxAmt;


                if (string.IsNullOrEmpty(sGiftCardItemName))
                {
                    sFooterText  = "Request to handover Advance Receipt at the time of billing";
                    sRTitle      = "Advance Receipt" + "  " + "وصل بالدفعة المسبقة";
                    sDetailsLine = "Received with thanks from " + "" + sCustName + "                                                                         " + sCurrencySymbol + " " + _sAmt;
                }
                else if (iIsAdvRefund == 1)
                {
                    sFooterText  = "";
                    sRTitle      = "Advance Refund";
                    sDetailsLine = "Advance Refund" + "                                                                                                                " + sCurrencySymbol + " " + _sAmt;
                }
                else
                {
                    sFooterText  = "";
                    sRTitle      = "GIFT CARD RECEIPT";
                    sDetailsLine = sGiftCardItemName + "            " + sGiftCardNo + "                                                                         " + sCurrencySymbol + " " + _sAmt;
                }
                //----------store Info

                //if(Convert.ToString(retailTrans.StoreName) != string.Empty)
                //    sStoreName = Convert.ToString(retailTrans.StoreName);
                //if(Convert.ToString(retailTrans.StoreAddress) != string.Empty)
                //    sStoreAddress = Convert.ToString(retailTrans.StoreAddress);

                //if (! string.IsNullOrEmpty(Convert.ToString(retailTrans.StorePhone)))
                //    sStorePhNo = Convert.ToString(retailTrans.StorePhone);

                if (Convert.ToString(ApplicationSettings.Terminal.StoreName) != string.Empty)
                {
                    sStoreName = Convert.ToString(ApplicationSettings.Terminal.StoreName);
                }
                if (Convert.ToString(ApplicationSettings.Terminal.StoreAddress) != string.Empty)
                {
                    sStoreAddress = Convert.ToString(ApplicationSettings.Terminal.StoreAddress);
                }
                if (!string.IsNullOrEmpty(Convert.ToString(ApplicationSettings.Terminal.StorePhone)))
                {
                    sStorePhNo = Convert.ToString(ApplicationSettings.Terminal.StorePhone);
                }

                if (Convert.ToString(retailTrans.OperatorId) != string.Empty)
                {
                    sOperatorId = getStaffName(Convert.ToString(retailTrans.OperatorId));
                }

                sDataAreaId = Convert.ToString(ApplicationSettings.Database.DATAAREAID);

                // if (Convert.ToString(retailTrans.InventLocationId) != string.Empty)

                sInventLocationId = ApplicationSettings.Terminal.InventLocationId; //Convert.ToString(retailTrans.InventLocationId);
            }
            connection = conn;
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            GetStoreInfo(ref sStorePhNo, ref sInvoiceFooter, ref sCINNo);

            //sCINNo = oBlank.getValue("select CINNO  from RETAILSTORETABLE where STORENUMBER ='" + Convert.ToString(ApplicationSettings.Terminal.StoreId) + "'");
            sCompanyName = oBlank.GetCompanyName(conn);//aded on 14/04/2014 R.Hossain

            if (iIsAdvRefund == 1)
            {
                sRefRceiptNo = GetRefReciptId(retailTrans.TransactionId);
            }

            sRemarks = getTransactionRemarks(retailTrans.TransactionId, retailTrans.TerminalId);

            sStorePhNo = getStoreEmailAndFax("PRIMARYCONTACTPHONE");

            sStoreEmail = getStoreEmailAndFax("PrimaryContactEmail");

            sStoreFax = getStoreEmailAndFax("PrimaryContactFax"); // PrimaryContactEmail/PrimaryContactFax

            sTRN = GetCompanyTRN();
            //sCurrencySymbol = ApplicationSettings.Terminal.StoreCurrency;

            #endregion
        }
        public void PrintApprovalVoucher(string sOrderNo, DataTable dtItemdetails, IPosTransaction posTransaction, string Title, DataTable dtIngr = null)
        {
            //PageSettings ps = new PageSettings { Landscape = false, PaperSize = new PaperSize { RawKind = (int)PaperKind.A4 }, Margins = new Margins { Top = 0, Right = 0, Bottom = 0, Left = 0 } };
            sCurrencySymbol = oBlank.GetCurrencySymbol();
            //datasources
            List <ReportDataSource> rds = new List <ReportDataSource>();

            rds.Add(new ReportDataSource("HEADERINFO", (DataTable)GetHeaderInfo(sOrderNo)));
            //dtItemDetails = dtItemdetails;
            //rds.Add(new ReportDataSource("DETAILSINFO", (DataTable)GetDetailInfo(sOrderNo, dtItemdetails)));

            rds.Add(new ReportDataSource("DETAILSINFO", (DataTable)GetDetailInfo(sOrderNo, dtItemdetails, dtIngr)));
            rds.Add(new ReportDataSource("DETAILSFOOTERINFO", (DataTable)GetDetailFooterInfo(dtItemDetails_Main)));

            //parameters
            List <ReportParameter> rps = new List <ReportParameter>();
            decimal dTotalAmt          = 0;
            decimal dRoweTotal         = 0;


            foreach (DataRow dr in dtItemDetails_Main.Rows)
            {
                decimal dVatAmt = 0;
                if (!string.IsNullOrEmpty(Convert.ToString(dr["VATAMOUNT"])))
                {
                    dVatAmt = Convert.ToDecimal(dr["VATAMOUNT"]);
                }

                if (!string.IsNullOrEmpty(Convert.ToString(dr["ROWTOTALAMOUNT"])))
                {
                    dTotalAmt += Convert.ToDecimal(dr["ROWTOTALAMOUNT"]) + dVatAmt;
                }
                //dTotalAmt += Convert.ToDecimal(dr["ROWTOTALAMOUNT"]);
            }


            Currency = GetCurrencyText(GetHeaderInfo(sOrderNo).Rows[0]["Currency"].ToString());
            string            sAmtInWords = Currency + " " + Amtinwds(Math.Abs(Convert.ToDouble(dTotalAmt)));
            RetailTransaction retailTrans = posTransaction as RetailTransaction;

            if (retailTrans != null)
            {
                sCPinCode = Convert.ToString(retailTrans.Customer.PostalCode);
            }
            else
            {
                var SelectedCust = customerDataManager.GetTransactionalCustomer(GetHeaderInfo(sOrderNo).Rows[0]["CUSTACCOUNT"].ToString());
                sCPinCode = SelectedCust.PostalCode;
            }
            string sCompanyName = GetCompanyName();

            rps.Add(new ReportParameter("prmTransactionId", string.IsNullOrEmpty(posTransaction.TransactionId) ? " " : posTransaction.TransactionId, true));
            rps.Add(new ReportParameter("prmTotalInWrd", string.IsNullOrEmpty(sAmtInWords) ? " " : sAmtInWords, true));
            string sDate = string.Empty;


            rps.Add(new ReportParameter("prmPinCode", string.IsNullOrEmpty(sCPinCode) ? " " : sCPinCode, true));
            rps.Add(new ReportParameter("prmCompany", string.IsNullOrEmpty(sCompanyName) ? " " : sCompanyName, true));
            rps.Add(new ReportParameter("prmTitle", Title, true));
            rps.Add(new ReportParameter("Remarks", sRemarks, true));

            if (Title == "INWARD")
            {
                rps.Add(new ReportParameter("prmSubTiltle", "", true));
                sDate = System.DateTime.Now.ToShortDateString();
                rps.Add(new ReportParameter("prmApprDt", string.IsNullOrEmpty(sDate) ? " " : sDate, true));
                // rds.Add(new ReportDataSource("BARCODEIMGTABLE", (DataTable)GetBarcodeInfo(Title, "")));
                rps.Add(new ReportParameter("prmBarcode", string.IsNullOrEmpty("") ? " " : "", true));
                rps.Add(new ReportParameter("pIsVisibleTentative", "0", true));
            }
            else
            {
                sDate = Convert.ToString(GetHeaderInfo(sOrderNo).Rows[0]["ApprovalDate"]);
                rps.Add(new ReportParameter("prmApprDt", string.IsNullOrEmpty(sDate) ? " " : sDate, true));
                rps.Add(new ReportParameter("prmSubTiltle", "SUSPENSE ITEM ON APPROVAL", true));
                //rds.Add(new ReportDataSource("BARCODEIMGTABLE", (DataTable)GetBarcodeInfo(Title, sOrderNo)));
                rps.Add(new ReportParameter("prmBarcode", string.IsNullOrEmpty(sOrderNo) ? " " : sOrderNo, true));
                rps.Add(new ReportParameter("pIsVisibleTentative", "1", true));
            }
            rps.Add(new ReportParameter("cs", string.IsNullOrEmpty(sCurrencySymbol) ? " " : sCurrencySymbol, true));

            string reportName = @"rptApprvDeliveryNote";
            //string reportName = @"Copy of rptCustOrdVoucher";
            string reportPath = @"Microsoft.Dynamics.Retail.Pos.BlankOperations.Report." + reportName + ".rdlc";
            //RdlcViewer rptView = new RdlcViewer("Approval Sale Voucher", reportPath, rds, rps, null,2);
            //rptView.ShowDialog();
            //rptView.Close();
        }
        /// <summary>
        /// Initializes the given multiline discount working table. It is filled with
        /// the quantities of items on the transaction which belong to each multiline discount group.
        /// </summary>
        /// <param name="multiLineDiscTable">The working table which will be initialized</param>
        /// <param name="transaction">The transaction to initialize from</param>
        private static void InitializeMultilineDiscTable(DataTable multiLineDiscTable, RetailTransaction transaction)
        {
            // start with empty working table
            multiLineDiscTable.Clear();

            //Sum upp all the linegroup discount lines in the same group
            foreach (var saleItem in transaction.SaleItems)
            {
                if (!saleItem.Voided)
                {
                    // collect quantities for multi-line discount groups
                    if (!string.IsNullOrEmpty(saleItem.MultiLineDiscountGroup))
                    {
                        UpdateMultiLineDiscTable(multiLineDiscTable, saleItem.MultiLineDiscountGroup, saleItem.Quantity);
                    }
                }
            }
        }
Esempio n. 22
0
        public void PostSuspendTransaction(IPosTransaction posTransaction)
        {
            decimal dNetWt = 0;

            #region
            RetailTransaction retailTrans = posTransaction as RetailTransaction;
            if (retailTrans != null)
            {
                DataTable dtDetail     = new DataTable("Detail");
                DataTable dtIngredient = new DataTable("Ingredient");
                DataRow   drDtl;
                DataRow   drIngrd;

                dtDetail.Columns.Add("ITEMID", typeof(string));
                dtDetail.Columns.Add("LINENUM", typeof(int));
                dtDetail.Columns.Add("MAKINGAMOUNT", typeof(decimal));
                dtDetail.Columns.Add("MakingDisc", typeof(decimal));
                dtDetail.Columns.Add("WastageAmount", typeof(decimal));
                dtDetail.AcceptChanges();

                dtIngredient.Columns.Add("SKUNUMBER", typeof(string));
                dtIngredient.Columns.Add("ITEMID", typeof(string));
                dtIngredient.Columns.Add("LINENUM", typeof(int));
                dtIngredient.Columns.Add("REFLINENUM", typeof(int));

                dtIngredient.Columns.Add("InventSizeID", typeof(string));
                dtIngredient.Columns.Add("InventColorID", typeof(string));
                dtIngredient.Columns.Add("ConfigID", typeof(string));

                dtIngredient.Columns.Add("UnitID", typeof(string));
                dtIngredient.Columns.Add("METALTYPE", typeof(int));

                dtIngredient.Columns.Add("QTY", typeof(decimal));
                dtIngredient.Columns.Add("PCS", typeof(decimal));
                dtIngredient.Columns.Add("CRATE", typeof(decimal));
                dtIngredient.Columns.Add("CVALUE", typeof(decimal));
                dtIngredient.Columns.Add("INGRDDISCAMT", typeof(decimal));
                dtIngredient.AcceptChanges();

                int i = 1;
                foreach (SaleLineItem saleLineItem in retailTrans.SaleItems)
                {
                    DataSet dsIngredients = new DataSet();
                    if (!string.IsNullOrEmpty(Convert.ToString(saleLineItem.PartnerData.Ingredients)) && Convert.ToString(saleLineItem.PartnerData.Ingredients) != "0")
                    {
                        StringReader reader = new StringReader(Convert.ToString(saleLineItem.PartnerData.Ingredients));
                        dsIngredients.ReadXml(reader);
                    }
                    else
                    {
                        dsIngredients = null;
                    }

                    drDtl = dtDetail.NewRow();

                    drDtl["ITEMID"]        = saleLineItem.ItemId;
                    drDtl["LINENUM"]       = i;
                    drDtl["MAKINGAMOUNT"]  = decimal.Round(Convert.ToDecimal(saleLineItem.PartnerData.MakingAmount), 2, MidpointRounding.AwayFromZero);
                    drDtl["MakingDisc"]    = decimal.Round(Convert.ToDecimal(saleLineItem.PartnerData.MakingTotalDiscount), 2, MidpointRounding.AwayFromZero);
                    drDtl["WastageAmount"] = decimal.Round(Convert.ToDecimal(saleLineItem.PartnerData.WastageAmount), 2, MidpointRounding.AwayFromZero);

                    dtDetail.Rows.Add(drDtl);
                    dtDetail.AcceptChanges();

                    if (dsIngredients != null && dsIngredients.Tables[0].Rows.Count > 0)
                    {
                        int iGrd = 1;

                        foreach (DataRow dr in dsIngredients.Tables[0].Rows)
                        {
                            drIngrd = dtIngredient.NewRow();

                            drIngrd["SKUNUMBER"] = Convert.ToString(dr["SKUNUMBER"]);
                            drIngrd["ITEMID"]    = Convert.ToString(dr["ITEMID"]);
                            drIngrd["LINENUM"]   = iGrd;

                            drIngrd["REFLINENUM"]    = i;
                            drIngrd["InventSizeID"]  = Convert.ToString(dr["InventSizeID"]);
                            drIngrd["InventColorID"] = Convert.ToString(dr["InventColorID"]);
                            drIngrd["ConfigID"]      = Convert.ToString(dr["ConfigID"]);

                            drIngrd["UnitID"]    = Convert.ToString(dr["UnitID"]);
                            drIngrd["METALTYPE"] = Convert.ToInt32(dr["METALTYPE"]);

                            if (iGrd == 1)
                            {
                                dNetWt = decimal.Round(Convert.ToDecimal(dr["QTY"]), 3, MidpointRounding.AwayFromZero); // added on 24/03/2014 R.Hossain
                            }
                            drIngrd["QTY"]   = decimal.Round(Convert.ToDecimal(dr["QTY"]), 3, MidpointRounding.AwayFromZero);
                            drIngrd["PCS"]   = decimal.Round(Convert.ToDecimal(dr["PCS"]), 3, MidpointRounding.AwayFromZero);
                            drIngrd["CRATE"] = decimal.Round(Convert.ToDecimal(dr["RATE"]), 2, MidpointRounding.AwayFromZero);
                            if (Convert.ToBoolean(saleLineItem.PartnerData.isMRP) == true) // added on 31/03/2014 and mod on 25/04/14
                            {
                                if (iGrd == 1)                                             // added on 08/07/2014-- for esteemate of mrp item-- bom value should not come
                                {
                                    drIngrd["CVALUE"] = decimal.Round(Convert.ToDecimal(retailTrans.NetAmountWithNoTax), 2, MidpointRounding.AwayFromZero);
                                }
                                else
                                {
                                    drIngrd["CVALUE"] = decimal.Round(Convert.ToDecimal(dr["CVALUE"]), 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            drIngrd["INGRDDISCAMT"] = decimal.Round(Convert.ToDecimal(dr["IngrdDiscTotAmt"]), 2, MidpointRounding.AwayFromZero);

                            dtIngredient.Rows.Add(drIngrd);
                            dtIngredient.AcceptChanges();

                            iGrd++;
                        }
                    }

                    i++;
                }

                if ((dtDetail != null && dtDetail.Rows.Count > 0) &&
                    (dtIngredient != null && dtIngredient.Rows.Count > 0))
                {
                    DataRow drLIngrd;

                    foreach (DataRow dr in dtDetail.Rows)
                    {
                        drLIngrd = dtIngredient.NewRow();
                        drLIngrd["SKUNUMBER"] = Convert.ToString(dr["ITEMID"]);
                        drLIngrd["ITEMID"]    = "Labour";
                        drLIngrd["LINENUM"]   = dtIngredient.Rows.Count + 1;

                        drLIngrd["REFLINENUM"]    = Convert.ToInt32(dr["LINENUM"]);
                        drLIngrd["InventSizeID"]  = string.Empty;
                        drLIngrd["InventColorID"] = string.Empty;
                        drLIngrd["ConfigID"]      = string.Empty;

                        drLIngrd["UnitID"]    = string.Empty;
                        drLIngrd["METALTYPE"] = 0;

                        drLIngrd["QTY"]          = 0;
                        drLIngrd["PCS"]          = 0;
                        drLIngrd["CRATE"]        = Convert.ToString(decimal.Round((Convert.ToDecimal(dr["MAKINGAMOUNT"]) + Convert.ToDecimal(dr["WastageAmount"])) / Convert.ToDecimal(dNetWt), 2, MidpointRounding.AwayFromZero));
                        drLIngrd["CVALUE"]       = Convert.ToDecimal(dr["MAKINGAMOUNT"]) + Convert.ToDecimal(dr["WastageAmount"]);
                        drLIngrd["INGRDDISCAMT"] = Convert.ToDecimal(dr["MakingDisc"]);
                        dtIngredient.Rows.Add(drLIngrd);
                        dtIngredient.AcceptChanges();
                    }
                }

                if ((dtDetail != null && dtDetail.Rows.Count > 0) &&
                    (dtIngredient != null && dtIngredient.Rows.Count > 0))
                {
                    frmEstimationReport objEstimationReport = new frmEstimationReport(posTransaction, dtDetail, dtIngredient);
                    objEstimationReport.ShowDialog();
                }
                else
                {
                    #region Nimbus
                    FormModulation    formMod           = new FormModulation(ApplicationSettings.Database.LocalConnection);
                    RetailTransaction retailTransaction = posTransaction as RetailTransaction;
                    if (retailTransaction != null)
                    {
                        ICollection <Point> signaturePoints = null;
                        if (retailTransaction.TenderLines != null &&
                            retailTransaction.TenderLines.Count > 0 &&
                            retailTransaction.TenderLines.First.Value != null)
                        {
                            signaturePoints = retailTransaction.TenderLines.First.Value.SignatureData;
                        }
                        FormInfo formInfo = formMod.GetInfoForForm(Microsoft.Dynamics.Retail.Pos.Contracts.Services.FormType.QuotationReceipt, false, LSRetailPosis.Settings.HardwareProfiles.Printer.ReceiptProfileId);
                        formMod.GetTransformedTransaction(formInfo, retailTransaction);

                        string textForPreview = formInfo.Header;
                        textForPreview += formInfo.Details;
                        textForPreview += formInfo.Footer;
                        textForPreview  = textForPreview.Replace("|1C", string.Empty);
                        textForPreview  = textForPreview.Replace("|2C", string.Empty);
                        frmReportList preview = new frmReportList(textForPreview, signaturePoints);
                        LSRetailPosis.POSControls.POSFormsManager.ShowPOSForm(preview);
                    }
                    #endregion
                }
            }

            #endregion


            LSRetailPosis.ApplicationLog.Log("SuspendTriggers.PostSuspendTransaction", "After the suspension of a transaction...", LSRetailPosis.LogTraceLevel.Trace);
        }
        public DataRow AmountToBeAdjusted(string custAccount, bool isTranIdExists = false, string custaccount = null, string ordernum = null)
        {
            string TransID = string.Empty;

            #region Multiple Adjustment
            if (custaccount != null && ordernum != null)
            {
                BlankOperations   oBlank      = new BlankOperations();
                DataTable         dt          = oBlank.CustomerAdvanceData(custAccount);
                RetailTransaction retailTrans = pos as RetailTransaction;
                string            order       = Convert.ToString(retailTrans.PartnerData.AdjustmentOrderNum);
                string            cust        = Convert.ToString(retailTrans.PartnerData.AdjustmentCustAccount);
                DataRow           drReturn    = null;
                foreach (DataRow drNew in dt.Select("ORDERNUM='" + order + "' AND  CustomerAccount='" + cust + "' AND ISADJUSTED=0"))
                {
                    if (string.IsNullOrEmpty(TransID))
                    {
                        TransID = "'" + Convert.ToString(drNew["TransactionID"]) + "'";
                    }
                    else
                    {
                        TransID += ",'" + Convert.ToString(drNew["TransactionID"]) + "'";
                    }
                    drNew["ISADJUSTED"] = 1;
                    drReturn            = drNew;
                    break;
                }
                return(drReturn);
            }
            #endregion

            #region Single Adjustment
            else
            {
                System.Collections.Generic.LinkedList <LSRetailPosis.Transaction.Line.SaleItem.SaleLineItem> saleline = new System.Collections.Generic.LinkedList <LSRetailPosis.Transaction.Line.SaleItem.SaleLineItem>(((LSRetailPosis.Transaction.RetailTransaction)(pos)).SaleItems);
                if (isTranIdExists)
                {
                    foreach (var sale in saleline)
                    {
                        if (sale.ItemType == LSRetailPosis.Transaction.Line.SaleItem.SaleLineItem.ItemTypes.Service && !sale.Voided)
                        {
                            if (string.IsNullOrEmpty(TransID))
                            {
                                TransID = "'" + sale.PartnerData.ServiceItemCashAdjustmentTransactionID + "'";
                            }
                            else
                            {
                                TransID += ",'" + sale.PartnerData.ServiceItemCashAdjustmentTransactionID + "'";
                            }
                        }
                    }
                }
                SqlConnection SqlCon = new SqlConnection(ApplicationSettings.Database.LocalConnectionString);
                SqlCon.Open();

                // Create a Command
                SqlCommand SqlComm = new SqlCommand();
                SqlComm.Connection  = SqlCon;
                SqlComm.CommandType = CommandType.Text;
                DataRow drSelected = null;
                #region Commented qUERY
                //SqlComm.CommandText = " SELECT     RETAILTRANSACTIONTABLE.TRANSACTIONID AS [Transaction ID], RETAILTRANSACTIONTABLE.CUSTACCOUNT AS [Customer Account], " +
                //    " DIRPARTYTABLE.NAMEALIAS AS [Customer Name], CAST(SUM(RETAILTRANSACTIONPAYMENTTRANS.AMOUNTCUR) AS NUMERIC(28,3)) AS [Total Amount] " +
                //    " FROM         DIRPARTYTABLE INNER JOIN CUSTTABLE ON DIRPARTYTABLE.RECID = CUSTTABLE.PARTY INNER JOIN " +
                //    " RETAILTRANSACTIONTABLE INNER JOIN RETAILTRANSACTIONPAYMENTTRANS ON RETAILTRANSACTIONTABLE.TRANSACTIONID = RETAILTRANSACTIONPAYMENTTRANS.TRANSACTIONID ON  " +
                //    " CUSTTABLE.ACCOUNTNUM = RETAILTRANSACTIONTABLE.CUSTACCOUNT WHERE     (RETAILTRANSACTIONTABLE.CUSTACCOUNT = '" + custAccount + "') " +
                //    " AND (RETAILTRANSACTIONPAYMENTTRANS.isAdjusted = 0) AND (RETAILTRANSACTIONTABLE.[TYPE] = 3) ";
                //if (isTranIdExists && !string.IsNullOrEmpty(TransID))
                //{
                //    SqlComm.CommandText += " AND (RETAILTRANSACTIONPAYMENTTRANS.TRANSACTIONID NOT IN (" + TransID + ")) ";
                //}
                //SqlComm.CommandText += " GROUP BY RETAILTRANSACTIONTABLE.TRANSACTIONID, RETAILTRANSACTIONTABLE.CUSTACCOUNT,DIRPARTYTABLE.NAMEALIAS ";
                #endregion

                ////SqlComm.CommandText = " SELECT     RETAILADJUSTMENTTABLE.TRANSACTIONID AS [TransactionID], " +
                ////   " RETAILADJUSTMENTTABLE.CUSTACCOUNT AS [CustomerAccount], " +
                ////   " DIRPARTYTABLE.NAMEALIAS AS [CustomerName],   " +
                ////   //" CAST(RETAILADJUSTMENTTABLE.AMOUNT AS NUMERIC(28,3)) AS [TotalAmount]  " +
                ////   " CAST(RETAILADJUSTMENTTABLE.AMOUNT AS NUMERIC(28,2)) AS [TotalAmount],ISNULL(GOLDFIXING,0) AS GoldFixing,(CASE WHEN GOLDFIXING = 0 THEN 0 ELSE CAST(ISNULL(GOLDQUANTITY,0) AS NUMERIC(28,3)) END) AS GoldQty " +  // Avg Gold Rate Adjustment
                ////   " ,ISNULL(RETAILADJUSTMENTTABLE.RETAILSTOREID,'') AS RETAILSTOREID,ISNULL(RETAILADJUSTMENTTABLE.RETAILTERMINALID,'') AS RETAILTERMINALID" +
                ////   " FROM         DIRPARTYTABLE INNER JOIN " +
                ////   " CUSTTABLE ON DIRPARTYTABLE.RECID = CUSTTABLE.PARTY INNER JOIN " +
                ////   " RETAILADJUSTMENTTABLE ON CUSTTABLE.ACCOUNTNUM = RETAILADJUSTMENTTABLE.CUSTACCOUNT " +
                ////   " WHERE     (RETAILADJUSTMENTTABLE.ISADJUSTED = 0) AND (RETAILADJUSTMENTTABLE.RETAILDEPOSITTYPE = 1) " +
                ////   " AND (RETAILADJUSTMENTTABLE.CUSTACCOUNT = '" + custAccount + "') ";
                try
                {
                    if (PosApplication.Instance.TransactionServices.CheckConnection())
                    {
                        ReadOnlyCollection <object> containerArray;
                        string sStoreId = ApplicationSettings.Terminal.StoreId;
                        containerArray = PosApplication.Instance.TransactionServices.InvokeExtension("getUnadjustedAdvance", custAccount);

                        DataSet      dsWH          = new DataSet();
                        StringReader srTransDetail = new StringReader(Convert.ToString(containerArray[3]));

                        if (Convert.ToString(containerArray[3]).Trim().Length > 38)
                        {
                            dsWH.ReadXml(srTransDetail);
                        }
                        if (dsWH != null && dsWH.Tables[0].Rows.Count > 0)
                        {
                            Dialog.WinFormsTouch.frmGenericSearch OSearch = new Dialog.WinFormsTouch.frmGenericSearch(dsWH.Tables[0], drSelected, "Advance Adjustment");
                            OSearch.ShowDialog();
                            drSelected = OSearch.SelectedDataRow;
                        }
                        else
                        {
                            using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("No Active Deposit found for the selected customer.", MessageBoxButtons.OK, MessageBoxIcon.Error))
                            {
                                LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                return(drSelected);


                //DataRow drSelected = null;
                //DataTable AdjustmentDT = new DataTable();


                //SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
                //SqlDa.Fill(AdjustmentDT);
                //if (AdjustmentDT != null && AdjustmentDT.Rows.Count > 0)
                //{
                //    Dialog.WinFormsTouch.frmGenericSearch OSearch = new Dialog.WinFormsTouch.frmGenericSearch(AdjustmentDT, drSelected, "Advance Adjustment");
                //    OSearch.ShowDialog();
                //    drSelected = OSearch.SelectedDataRow;

                //    return drSelected;

                //}
                //else
                //{
                //    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("No Active Deposit found for the selected customer.", MessageBoxButtons.OK, MessageBoxIcon.Error))
                //    {
                //        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                //    }
                //    return null;
                //}
            }
            #endregion
        }
        public decimal FindTenderRestriction(IRetailTransaction retailTransaction, ICardInfo cardInfo)
        {
            NetTracer.Information("TenderRestriction::FindTenderRestriction - Start");
            RetailTransaction transaction = retailTransaction as RetailTransaction;

            if (transaction == null)
            {
                throw new ArgumentNullException("retailTransaction");
            }

            if (cardInfo == null)
            {
                throw new ArgumentNullException("cardInfo");
            }

            decimal    payableAmount = 0; //the return value of total amount payd with tender id
            ItemStatus itemStatus;        //is the item included / excluded by the tender id

            // Check if there are items in the transaction
            if (transaction.SaleItems.Count == 0)
            {
                POSFormsManager.ShowPOSMessageDialog(50251); //"There are no sales items to check."
                return(payableAmount);
            }

            // Calclulating how much amount of the original amount can be paid.
            foreach (ISaleLineItem lineItem in transaction.SaleItems)
            {
                if (string.IsNullOrEmpty(lineItem.TenderRestrictionId) && (!lineItem.Voided))
                {
                    itemStatus = CheckTenderRestriction(cardInfo.RestrictionCode, cardInfo.TenderTypeId, lineItem.ItemId, lineItem.ItemGroupId);

                    if (itemStatus == ItemStatus.INCLUDE)
                    {
                        lineItem.TenderRestrictionId = cardInfo.RestrictionCode;
                        lineItem.FleetCardNumber     = cardInfo.CardNumber;
                        lineItem.PaymentIndex        = transaction.TenderLines.Count;
                        payableAmount += lineItem.NetAmountWithTax;
                    }
                }
            }

            if (payableAmount != retailTransaction.NetAmountWithTax)
            {
                // If nothing can be paid, then it can be concluded that this card is prohibited
                if (payableAmount == 0)
                {
                    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage(50253))
                    {
                        this.Application.ApplicationFramework.POSShowForm(dialog);
                    }
                }
                else
                {
                    string message = string.Format(
                        LSRetailPosis.ApplicationLocalizer.Language.Translate(50151),
                        this.Application.Services.Rounding.Round(payableAmount, false));

                    using (frmTenderRestriction frmExcluded = new frmTenderRestriction(transaction))
                    {
                        frmExcluded.DisplayMsg = message;
                        this.Application.ApplicationFramework.POSShowForm(frmExcluded);

                        if (frmExcluded.DialogResult == DialogResult.No)
                        {
                            ClearTenderRestriction(retailTransaction);
                            return(0);
                        }
                    }
                }
            }

            NetTracer.Information("TenderRestriction::FindTenderRestriction - End");
            return(payableAmount);
        }
        public void PrePayment(IPreTriggerResult preTriggerResult, IPosTransaction posTransaction, object posOperation, string tenderId)
        {
            RetailTransaction retailTransaction = posTransaction as RetailTransaction;

            LSRetailPosis.Transaction.CustomerPaymentTransaction custTrans = posTransaction as LSRetailPosis.Transaction.CustomerPaymentTransaction;
            if (custTrans != null)
            {
                InputConfirmation inputconfirm = new InputConfirmation();
                inputconfirm.PromptText = "Remarks ";
                inputconfirm.InputType  = InputType.Normal;

                Interaction.frmInput Oinput = new Interaction.frmInput(inputconfirm);
                Oinput.ShowDialog();
                if (!string.IsNullOrEmpty(Oinput.InputText))
                {
                    custTrans.PartnerData.Remarks = Oinput.InputText;
                }
                else
                {
                    custTrans.PartnerData.Remarks = "";
                }

                if ((PosisOperations)posOperation == PosisOperations.PayCreditMemo)
                {
                    preTriggerResult.ContinueOperation = false;
                    return;
                }

                SqlConnection connection = new SqlConnection();

                if (application != null)
                {
                    connection = application.Settings.Database.Connection;
                }
                else
                {
                    connection = ApplicationSettings.Database.LocalConnection;
                }

                Enums.EnumClass oEnum       = new Enums.EnumClass();
                string          sMaxAmount  = string.Empty;
                string          sTerminalID = ApplicationSettings.Terminal.TerminalId;
                string          sMinAmt     = Convert.ToString(oEnum.ValidateMinDeposit(connection, out sMaxAmount, sTerminalID, Convert.ToDecimal((((LSRetailPosis.Transaction.CustomerPaymentTransaction)(posTransaction))).CustomerDepositItem.Amount)));
                if (Convert.ToDecimal(sMinAmt) != 0 && Convert.ToDecimal(sMaxAmount) != 0)
                {
                    if (Convert.ToDecimal(sMinAmt) > Convert.ToDecimal((((LSRetailPosis.Transaction.CustomerPaymentTransaction)(posTransaction))).CustomerDepositItem.Amount) ||
                        Convert.ToDecimal(sMaxAmount) < Convert.ToDecimal((((LSRetailPosis.Transaction.CustomerPaymentTransaction)(posTransaction))).CustomerDepositItem.Amount))
                    {
                        preTriggerResult.ContinueOperation = false;
                        preTriggerResult.MessageId         = 50448;
                        return;
                    }
                }
            }

            //start : RH on 05/11/2014
            if (retailTransaction != null)
            {
                /* InputConfirmation inC = new InputConfirmation();
                 * inC.PromptText = "Remarks";
                 * inC.InputType = InputType.Normal;
                 *
                 * Interaction.frmInput Oinput = new Interaction.frmInput(inC);
                 * Oinput.ShowDialog();
                 * if(!string.IsNullOrEmpty(Oinput.InputText))
                 *   retailTransaction.PartnerData.Remarks = Oinput.InputText;
                 * else
                 *   retailTransaction.PartnerData.Remarks = "";*/

                int iPM    = 100;
                int iCF    = 100;
                int isSale = 0;
                foreach (SaleLineItem saleLineItem in retailTransaction.SaleItems)
                {
                    if (!saleLineItem.Voided)
                    {
                        isSale = 1;
                        iPM    = getMetalType(saleLineItem.ItemId);
                        if (iPM == (int)MetalType.PackingMaterial)
                        {
                            break;
                        }
                    }
                }
                if (isSale == 1 && string.IsNullOrEmpty(retailTransaction.PartnerData.Remarks))
                {
                    InputConfirmation inC = new InputConfirmation();
                    inC.PromptText = "Remarks";
                    inC.InputType  = InputType.Normal;

                    Interaction.frmInput Oinput = new Interaction.frmInput(inC);
                    Oinput.ShowDialog();
                    if (!string.IsNullOrEmpty(Oinput.InputText))
                    {
                        retailTransaction.PartnerData.Remarks = Oinput.InputText;
                    }
                    else
                    {
                        retailTransaction.PartnerData.Remarks = "";
                    }
                }



                if ((isSale == 1 || retailTransaction.SaleIsReturnSale) && string.IsNullOrEmpty(retailTransaction.PartnerData.TouristNumber))
                {
                    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("Tourist VAT Applicable.", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                        //command.Parameters.Add("@GOLDFIXING", SqlDbType.Bit).Value = Convert.ToString(dialog.DialogResult).ToUpper().Trim() == "YES" ? "True" : "False";
                        if (Convert.ToString(dialog.DialogResult).ToUpper().Trim() == "YES")
                        {
                            InputConfirmation inC = new InputConfirmation();
                            inC.PromptText = "Tourist VAT Applicable";
                            inC.InputType  = InputType.Normal;
                            inC.MaxLength  = 20;

                            Interaction.frmInput Oinput = new Interaction.frmInput(inC);
                            Oinput.ShowDialog();
                            if (!string.IsNullOrEmpty(Oinput.InputText))
                            {
                                retailTransaction.PartnerData.TouristNumber = Oinput.InputText;
                            }
                            else
                            {
                                retailTransaction.PartnerData.TouristNumber = "";
                            }
                        }
                    }
                }



                string sAdjustmentId = AdjustmentItemID();
                foreach (SaleLineItem SLineItem in retailTransaction.SaleItems)
                {
                    //if(SLineItem.ItemId == sAdjustmentId && retailTransaction.SaleItems.Count == 1)
                    //{
                    //    retailTransaction.RefundReceiptId = "1";
                    //    //break;
                    //}

                    if (SLineItem.ItemId == sAdjustmentId && retailTransaction.SaleItems.Count > 0)
                    {
                        retailTransaction.RefundReceiptId = "1";
                    }
                    if (SLineItem.ItemId != sAdjustmentId)
                    {
                        retailTransaction.RefundReceiptId = "";
                        break;
                    }
                }


                foreach (SaleLineItem saleLineItem in retailTransaction.SaleItems)
                {
                    if (!saleLineItem.Voided)
                    {
                        iCF = getMetalType(saleLineItem.ItemId);
                        if (iCF == (int)MetalType.Certificate)
                        {
                            break;
                        }
                    }
                }

                foreach (SaleLineItem saleLineItem in retailTransaction.SaleItems)
                {
                    if (saleLineItem.ReturnLineId == 0)
                    {
                        if (retailTransaction.PartnerData.PackingMaterial != "Y")
                        {
                            if (IsRetailItem(saleLineItem.ItemId))
                            {
                                if (iPM != (int)MetalType.PackingMaterial)
                                {
                                    #region Commented
                                    //using(LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("Have you issued packing material?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                                    //{
                                    //    LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                                    //    if(Convert.ToString(dialog.DialogResult).ToUpper().Trim() == "NO")
                                    //    {
                                    //        preTriggerResult.ContinueOperation = false;
                                    //        return;
                                    //    }
                                    //    else
                                    //    {
                                    //        retailTransaction.PartnerData.PackingMaterial = "Y";

                                    //        if(IsCertificateItem(saleLineItem.ItemId))
                                    //        {
                                    //            if(iCF != (int)MetalType.Certificate)
                                    //            {
                                    //                using(LSRetailPosis.POSProcesses.frmMessage dialog1 = new LSRetailPosis.POSProcesses.frmMessage("Have you issued the certificate?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                                    //                {
                                    //                    LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog1);
                                    //                    if(Convert.ToString(dialog1.DialogResult).ToUpper().Trim() == "NO")
                                    //                    {
                                    //                        preTriggerResult.ContinueOperation = false;
                                    //                        return;
                                    //                    }
                                    //                    else
                                    //                        retailTransaction.PartnerData.CertificateIssue = "Y";
                                    //                }
                                    //            }
                                    //            else
                                    //                retailTransaction.PartnerData.CertificateIssue = "Y";
                                    //        }
                                    //    }
                                    //}
                                    #endregion
                                    using (LSRetailPosis.POSProcesses.frmMessage dialog = new LSRetailPosis.POSProcesses.frmMessage("Proceed without packing material?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                                    {
                                        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog);
                                        if (Convert.ToString(dialog.DialogResult).ToUpper().Trim() == "NO")
                                        {
                                            preTriggerResult.ContinueOperation = false;
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    retailTransaction.PartnerData.PackingMaterial = "Y";

                                    #region Commented
                                    //if(IsCertificateItem(saleLineItem.ItemId))
                                    //{
                                    //    if(iCF != (int)MetalType.Certificate)
                                    //    {
                                    //        using(LSRetailPosis.POSProcesses.frmMessage dialog1 = new LSRetailPosis.POSProcesses.frmMessage("Have you issued the certificate?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                                    //        {
                                    //            LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog1);
                                    //            if(Convert.ToString(dialog1.DialogResult).ToUpper().Trim() == "NO")
                                    //            {
                                    //                preTriggerResult.ContinueOperation = false;
                                    //                return;
                                    //            }
                                    //            else
                                    //                retailTransaction.PartnerData.CertificateIssue = "Y";
                                    //        }
                                    //    }
                                    //    else
                                    //        retailTransaction.PartnerData.CertificateIssue = "Y";
                                    //}
                                    #endregion
                                }
                            }
                        }
                        #region Commented
                        //    else if(retailTransaction.PartnerData.CertificateIssue != "Y")
                        //    {
                        //        if(IsCertificateItem(saleLineItem.ItemId))
                        //        {
                        //            if(iCF != (int)MetalType.Certificate)
                        //            {
                        //                using(LSRetailPosis.POSProcesses.frmMessage dialog1 = new LSRetailPosis.POSProcesses.frmMessage("Have you issued the certificate?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        //                {
                        //                    LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSForm(dialog1);
                        //                    if(Convert.ToString(dialog1.DialogResult).ToUpper().Trim() == "NO")
                        //                    {
                        //                        preTriggerResult.ContinueOperation = false;
                        //                        return;
                        //                    }
                        //                    else
                        //                        retailTransaction.PartnerData.CertificateIssue = "Y";
                        //                }
                        //            }
                        //            else
                        //                retailTransaction.PartnerData.CertificateIssue = "Y";
                        //        }
                        //    }
                        #endregion
                    }
                }
            }
            // end: RH on 05/11/2014

            LSRetailPosis.ApplicationLog.Log("PaymentTriggers.PrePayment", "On the start of a payment operation...", LSRetailPosis.LogTraceLevel.Trace);

            switch ((PosisOperations)posOperation)
            {
            case PosisOperations.PayCash:
                // Insert code here...
                break;

            case PosisOperations.PayCard:
                // Insert code here...
                break;

            case PosisOperations.PayCheque:
                // Insert code here...
                break;

            case PosisOperations.PayCorporateCard:
                // Insert code here...
                break;

            case PosisOperations.PayCreditMemo:
                // Insert code here...
                break;

            case PosisOperations.PayCurrency:
                // Insert code here...
                break;

            case PosisOperations.PayCustomerAccount:
                // Insert code here...
                break;

            case PosisOperations.PayGiftCertificate:
                // Insert code here...
                break;

            case PosisOperations.PayLoyalty:
                // Insert code here...
                break;

                // etc.....
            }
        }
Esempio n. 26
0
        private void checkItemPrice(string barcode)
        {
            System.Diagnostics.Debug.Assert(barcode != null, "barcode should not be null.");

            if (string.IsNullOrEmpty(barcode))
            {
                return;
            }

            SaleLineItem saleLineItem = (SaleLineItem)Dialog.InternalApplication.BusinessLogic.Utility.CreateSaleLineItem(
                ApplicationSettings.Terminal.StoreCurrency,
                Dialog.InternalApplication.Services.Rounding,
                posTransaction);

            IScanInfo scaninfo = Dialog.InternalApplication.BusinessLogic.Utility.CreateScanInfo();

            scaninfo.ScanDataLabel = barcode;
            IBarcodeInfo barcodeInfo = Dialog.InternalApplication.Services.Barcode.ProcessBarcode(scaninfo);

            if ((barcodeInfo.InternalType == BarcodeInternalType.Item) && (barcodeInfo.ItemId != null))
            {
                // The entry was a barcode which was found and now we have the item id...
                saleLineItem.ItemId    = barcodeInfo.ItemId;
                saleLineItem.BarcodeId = barcodeInfo.BarcodeId;
                saleLineItem.SalesOrderUnitOfMeasure = barcodeInfo.UnitId;

                if (barcodeInfo.BarcodeQuantity > 0)
                {
                    saleLineItem.Quantity = barcodeInfo.BarcodeQuantity;
                }
                else
                {
                    saleLineItem.Quantity = 1;
                }

                if (barcodeInfo.BarcodePrice > 0)
                {
                    saleLineItem.Price = barcodeInfo.BarcodePrice;
                }

                saleLineItem.EntryType = barcodeInfo.EntryType;
                //saleLineItem.DimensionGroupId = barcodeInfo.DimensionGroupId;
                saleLineItem.Dimension.ColorId   = barcodeInfo.InventColorId;
                saleLineItem.Dimension.SizeId    = barcodeInfo.InventSizeId;
                saleLineItem.Dimension.StyleId   = barcodeInfo.InventStyleId;
                saleLineItem.Dimension.VariantId = barcodeInfo.VariantId;
            }
            else
            {
                saleLineItem.ItemId    = barcodeInfo.BarcodeId;
                saleLineItem.EntryType = barcodeInfo.EntryType;
                saleLineItem.Quantity  = 1;
            }

            Dialog.InternalApplication.Services.Item.ProcessItem(saleLineItem, true);

            if (!saleLineItem.Found)
            {
                LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSMessageDialog(3341);
            }
            else
            {
                //Color,Size,Style,Config
                if (saleLineItem.Dimension.EnterDimensions)
                {
                    if (!SetItemDimensions(saleLineItem))
                    {
                        return;
                    }
                }

                // Create a deep copy of the transaction to get the correct price calculation.
                RetailTransaction tempTransaction = (RetailTransaction)this.posTransaction.CloneTransaction();
                tempTransaction.Add(saleLineItem);

                // Get the item info...
                // Get the price, tax and discount info
                Dialog.InternalApplication.BusinessLogic.ItemSystem.CalculatePriceTaxDiscount(tempTransaction);

                saleLineItem = tempTransaction.GetItem(saleLineItem.LineId);
                saleLineItem.CalculateLine();

                // Find the last ItemSale entry..
                LinkedListNode <SaleLineItem> lastItem = tempTransaction.SaleItems.Last;

                ISaleLineItem lineItem = lastItem.Value;
                this.ItemId          = lineItem.ItemId;
                this.ItemDescription = lineItem.Description;
                this.Price           = lineItem.NetAmount;

                this.CustomerId   = tempTransaction.Customer.CustomerId;
                this.CustomerName = tempTransaction.Customer.Name;
                loadItemInfo();
                this.barcode = numPad1.EnteredValue;
            }

            numPad1.ClearValue();
        }
Esempio n. 27
0
        /// <summary>
        /// Add customer to transaction
        /// </summary>
        /// <param name="customer">Customer to add</param>
        /// <param name="posTransaction">Transaction</param>
        public void AddCustomerToTransaction(DE.ICustomer customer, DE.IPosTransaction posTransaction)
        {
            // !! Note - this code should follow the same steps to set the customer as PosProcesses\Customer.cs :: Execute()
            //Get information about the selected customer and add it to the transaction
            if (customer != null)
            {
                SalesOrderTransaction soTransaction = posTransaction as SalesOrderTransaction;
                if (soTransaction != null)
                {
                    // Must check for ISalesOrderTransaction before IRetailTransaction because it derives from IRetailTransaction
                    soTransaction.Customer = customer as LSRetailPosis.Transaction.Customer;
                }
                else
                {
                    RetailTransaction asRetailTransaction = posTransaction as RetailTransaction;
                    if (asRetailTransaction != null)
                    {
                        if (!asRetailTransaction.IsCustomerAllowed())
                        {
                            LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSMessageDialog(4544);
                            return;
                        }

                        DE.ICustomer invoicedCustomer = customer;
                        string       invoiceAccount   = customer.InvoiceAccount;

                        //If the customer has another account as invoice account
                        if (!string.IsNullOrWhiteSpace(invoiceAccount))
                        {
                            invoicedCustomer = this.CustomerSystem.GetCustomerInfo(invoiceAccount);
                        }

                        // Trigger: PreCustomerSet trigger for the operation
                        var preTriggerResult = new PreTriggerResult();

                        PosApplication.Instance.Triggers.Invoke <ICustomerTrigger>(t => t.PreCustomerSet(preTriggerResult, posTransaction, customer.CustomerId));

                        if (!TriggerHelpers.ProcessPreTriggerResults(preTriggerResult))
                        {
                            return;
                        }

                        this.CustomerSystem.SetCustomer(asRetailTransaction, customer, invoicedCustomer);

                        //If CheckCustomer returns false then the customer isn't allowed to be added to the transaction. Msg has already been displayed
                        if (!CheckCustomer(posTransaction))
                        {
                            return;
                        }

                        //If CheckInvoicedCustomer removed the customer then it isn't allowed to be added to the transaction. Msg has already been displayed
                        if (!CheckInvoicedCustomer(posTransaction))
                        {
                            return;
                        }

                        if (asRetailTransaction.Customer.UsePurchRequest)
                        {
                            asRetailTransaction.CustomerPurchRequestId = GetPurchRequestId();
                        }
                    }
                    else if (posTransaction is CustomerPaymentTransaction)
                    {
                        // Customer is not allowed to be changed  (or cleared) once a customer account deposit has been made.
                        LSRetailPosis.POSProcesses.POSFormsManager.ShowPOSMessageDialog(3084);
                    }
                }
            }
            else
            {
                NetTracer.Warning("Customer::AddCustomerToTransaction: customer parameter is null");
            }
        }
Esempio n. 28
0
        public bool ProcessInfoCode(IPosTransaction posTransaction, decimal quantity, decimal amount, string refRelation, string refRelation2, string refRelation3,
                                    InfoCodeTableRefType tableRefId, string linkedInfoCodeId, IInfoCodeLineItem orgInfoCode, InfoCodeType infoCodeType)
        {
            RetailTransaction      retailTransaction      = posTransaction as RetailTransaction;
            TenderCountTransaction tenderCountTransaction = posTransaction as TenderCountTransaction;

            // Other possible transaction types at this point include CustomerPayment

            if (refRelation == null)
            {
                refRelation = string.Empty;
            }

            if (refRelation2 == null)
            {
                refRelation2 = string.Empty;
            }

            if (refRelation3 == null)
            {
                refRelation3 = string.Empty;
            }

            //Infocode
            IInfoCodeSystem infoCodeSystem = this.Application.BusinessLogic.InfoCodeSystem;

            IInfoCodeLineItem[] infoCodes = new IInfoCodeLineItem[0];

            if (!string.IsNullOrEmpty(linkedInfoCodeId))
            {
                infoCodes = infoCodeSystem.GetInfocodes(linkedInfoCodeId);
            }
            else if (tableRefId == InfoCodeTableRefType.FunctionalityProfile)
            {
                infoCodes    = infoCodeSystem.GetInfocodes(refRelation2);
                refRelation2 = string.Empty;
            }
            else if (tableRefId == InfoCodeTableRefType.PreItem)
            {
                // Pre item is just a table ref id of item, but handled during different processing
                infoCodes = infoCodeSystem.GetInfocodes(refRelation, refRelation2, refRelation3, InfoCodeTableRefType.Item);
            }
            else
            {
                infoCodes = infoCodeSystem.GetInfocodes(refRelation, refRelation2, refRelation3, tableRefId);
            }

            foreach (InfoCodeLineItem infoCode in infoCodes)
            {
                if (infoCode.InfocodeId == null)
                {
                    return(false);
                }                                                  //If no infocode is found

                // Process age limit info codes as pre item.  I.e. stop processing on this info code if it is pre item
                // and not of type age limit.
                // Low impact fix that should be reevaluated if any info code other than age limit is ever added
                // pre item.  Using continue because indentation of if/else sequence already too much.
                if (((tableRefId == InfoCodeTableRefType.PreItem) && (infoCode.InputType != InfoCodeInputType.AgeLimit)))
                {
                    continue;
                }

                //If bug in data, fixes division by zero
                if (infoCode.RandomFactor == 0)
                {
                    infoCode.RandomFactor = 100;
                }

                infoCode.OriginType   = infoCodeType;
                infoCode.RefRelation  = refRelation;
                infoCode.RefRelation2 = refRelation2;
                infoCode.RefRelation3 = refRelation3;
                switch (infoCode.OriginType)
                {
                case InfoCodeType.Header:
                    infoCode.Amount = amount;
                    break;

                case InfoCodeType.Sales:
                    infoCode.Amount = (amount * -1);
                    break;

                case InfoCodeType.Payment:
                    infoCode.Amount = amount;
                    break;

                case InfoCodeType.IncomeExpense:
                    infoCode.Amount = amount;
                    break;
                }

                int    randomFactor = (int)(100 / infoCode.RandomFactor); //infoCode.RandomFactor = 100 means ask 100% for a infocode
                Random random       = new Random();
                int    randomNumber = random.Next(randomFactor);          //Creates numbers from 0 to randomFactor-1
                //Only get the infocode if randomfactor is set to zero or generated random number is the sama as the randomfactor-1
                if (infoCode.RandomFactor == 100 || randomNumber == (randomFactor - 1))
                {
                    Boolean infoCodeNeeded = true;
                    if (infoCode.OncePerTransaction)
                    {
                        if (tenderCountTransaction != null)
                        {
                            infoCodeNeeded = tenderCountTransaction.InfoCodeNeeded(infoCode.InfocodeId);
                        }
                        else
                        {
                            infoCodeNeeded = retailTransaction.InfoCodeNeeded(infoCode.InfocodeId);
                        }
                    }

                    if (infoCodeNeeded)
                    {
                        // If the required type is negative but the quantity is positive, do not continue
                        if (infoCode.InputRequiredType == InfoCodeInputRequiredType.Negative && quantity > 0)
                        {
                            infoCodeNeeded = false;
                        }

                        // If the required type is positive but the quantity is negative, do not continue
                        if (infoCode.InputRequiredType == InfoCodeInputRequiredType.Positive && quantity < 0)
                        {
                            infoCodeNeeded = false;
                        }
                    }
                    // If there is some infocodeID existing, and infocod is needed
                    if (infoCode.InfocodeId != null && infoCodeNeeded == true)
                    {
                        #region Text and General
                        if (infoCode.InputType == InfoCodeInputType.Text || infoCode.InputType == InfoCodeInputType.General)
                        {
                            Boolean inputValid = true;
                            bool    abort      = false;
                            // Get a infocode text
                            do
                            {
                                inputValid = true;

                                InputConfirmation inputConfirmation = new InputConfirmation()
                                {
                                    MaxLength  = MaxInfocodeInformationLengh,
                                    PromptText = infoCode.Prompt,
                                };

                                InteractionRequestedEventArgs request = new InteractionRequestedEventArgs(inputConfirmation, () =>
                                {
                                    if (inputConfirmation.Confirmed)
                                    {
                                        if (string.IsNullOrEmpty(inputConfirmation.EnteredText))
                                        {
                                            abort = true;
                                            POSFormsManager.ShowPOSMessageDialog(3593);
                                        }
                                        else
                                        {
                                            int textId = 0;
                                            if (inputConfirmation.EnteredText.Length == 0 && infoCode.InputRequired)
                                            {
                                                textId     = 3590; //The input text is required
                                                inputValid = false;
                                            }

                                            if (inputValid && infoCode.MinimumLength > 0 && inputConfirmation.EnteredText.Length < infoCode.MinimumLength)
                                            {
                                                textId     = 3591; //The input text is too short.
                                                inputValid = false;
                                            }

                                            if (inputValid && infoCode.MaximumLength > 0 && inputConfirmation.EnteredText.Length > infoCode.MaximumLength)
                                            {
                                                textId     = 3592; //The input text exceeds the maximum length.
                                                inputValid = false;
                                            }

                                            if (inputValid && infoCode.AdditionalCheck == 1)
                                            {
                                                inputValid = CheckKennitala(inputConfirmation.EnteredText);
                                                if (!inputValid)
                                                {
                                                    textId = 3603;
                                                }
                                            }

                                            if (!inputValid)
                                            {
                                                POSFormsManager.ShowPOSMessageDialog(textId);
                                            }
                                        }
                                        infoCode.Information = inputConfirmation.EnteredText;
                                    }
                                    else
                                    {
                                        inputValid = infoCode.InputRequired;
                                    }
                                }
                                                                                                          );


                                Application.Services.Interaction.InteractionRequest(request);

                                if (abort)
                                {
                                    return(false);
                                }
                            } while (!inputValid);
                            //Adding the result to the infocode
                        }

                        #endregion

                        #region Date
                        else if (infoCode.InputType == InfoCodeInputType.Date)
                        {
                            Boolean inputValid = true;
                            do
                            {
                                inputValid = true;

                                string inputText;
                                //Show the input form
                                using (frmInputNumpad inputDialog = new frmInputNumpad())
                                {
                                    inputDialog.EntryTypes = NumpadEntryTypes.Date;
                                    inputDialog.PromptText = infoCode.Prompt;
                                    POSFormsManager.ShowPOSForm(inputDialog);
                                    // Quit if cancel is pressed...
                                    if (inputDialog.DialogResult == System.Windows.Forms.DialogResult.Cancel && !infoCode.InputRequired)
                                    {
                                        return(false);
                                    }

                                    inputText = inputDialog.InputText;
                                }

                                //Is input valid?
                                if (!string.IsNullOrEmpty(inputText))
                                {
                                    int      textId   = 0;
                                    bool     isDate   = true;
                                    DateTime infoDate = DateTime.Now;

                                    try
                                    {
                                        infoDate = Convert.ToDateTime(inputText, (IFormatProvider)Thread.CurrentThread.CurrentCulture.DateTimeFormat);
                                    }
                                    catch
                                    {
                                        isDate = false;
                                    }

                                    if (!isDate)
                                    {
                                        textId     = 3602; //Date entered is not valid
                                        inputValid = false;
                                    }

                                    if (inputText.Length == 0 && infoCode.InputRequired)
                                    {
                                        textId     = 3594; //A number input is required
                                        inputValid = false;
                                    }

                                    if (!inputValid)
                                    {
                                        POSFormsManager.ShowPOSMessageDialog(textId);
                                    }
                                    else
                                    {
                                        //Setting the result to the infocode
                                        infoCode.Information = infoDate.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
                                    }
                                }
                                else if (infoCode.InputRequired)
                                {
                                    inputValid = false;
                                    POSFormsManager.ShowPOSMessageDialog(3597);//A number input is required
                                }
                            } while (!inputValid);
                        }

                        #endregion

                        #region Numeric and Operator/Staff

                        else if (infoCode.InputType == InfoCodeInputType.Numeric || infoCode.InputType == InfoCodeInputType.Operator)
                        {
                            Boolean inputValid = true;

                            do
                            {
                                inputValid = true;

                                string inputText = string.Empty;
                                //Show the input form
                                using (frmInputNumpad inputDialog = new frmInputNumpad())
                                {
                                    inputDialog.EntryTypes = NumpadEntryTypes.Price;
                                    inputDialog.PromptText = infoCode.Prompt;
                                    POSFormsManager.ShowPOSForm(inputDialog);
                                    // Quit if cancel is pressed and input not required...
                                    if (inputDialog.DialogResult == System.Windows.Forms.DialogResult.Cancel && !infoCode.InputRequired)
                                    {
                                        return(false);
                                    }

                                    // If input required then only valid result is Ok.
                                    if (inputDialog.DialogResult == System.Windows.Forms.DialogResult.OK)
                                    {
                                        inputText = inputDialog.InputText;
                                    }
                                }

                                //Is input empty?
                                if (!string.IsNullOrWhiteSpace(inputText))
                                {
                                    int textId = 0;
                                    if (inputText.Length == 0 && infoCode.InputRequired)
                                    {
                                        textId     = 3594; //A number input is required
                                        inputValid = false;
                                    }

                                    if (infoCode.MinimumValue != 0 && Convert.ToDecimal(inputText) < infoCode.MinimumValue)
                                    {
                                        textId     = 3595; //The number is lower than the minimum value
                                        inputValid = false;
                                    }

                                    if (infoCode.MaximumValue != 0 && Convert.ToDecimal(inputText) > infoCode.MaximumValue)
                                    {
                                        textId     = 3596; //The number exceeds the maximum value
                                        inputValid = false;
                                    }

                                    if (!inputValid)
                                    {
                                        POSFormsManager.ShowPOSMessageDialog(textId);
                                    }
                                }
                                else
                                {
                                    inputValid = false;
                                    POSFormsManager.ShowPOSMessageDialog(3597); //A number input is required
                                }

                                //Setting the result to the infocode
                                infoCode.Information = inputText;
                            } while (!inputValid);
                        }

                        #endregion

                        #region Customer

                        else if (infoCode.InputType == InfoCodeInputType.Customer)
                        {
                            bool inputValid = true;
                            do
                            {
                                inputValid = true;
                                Contracts.DataEntity.ICustomer customer = this.Application.Services.Customer.Search();
                                if (customer != null)
                                {
                                    infoCode.Information = customer.CustomerId;
                                    inputValid           = true;
                                }
                                else
                                {
                                    if (infoCode.InputRequired)
                                    {
                                        inputValid = false;
                                        POSFormsManager.ShowPOSMessageDialog(3598); //A customer needs to be selected
                                    }
                                }
                            } while (!inputValid);
                        }
                        #endregion

                        #region Item

                        else if (infoCode.InputType == InfoCodeInputType.Item)
                        {
                            Boolean inputValid = true;
                            do
                            {
                                string       selectedItemID = string.Empty;
                                DialogResult dialogResult   = this.Application.Services.Dialog.ItemSearch(500, ref selectedItemID);
                                // Quit if cancel is pressed...
                                if (dialogResult == System.Windows.Forms.DialogResult.Cancel && !infoCode.InputRequired)
                                {
                                    return(false);
                                }

                                if (!string.IsNullOrEmpty(selectedItemID))
                                {
                                    infoCode.Information = selectedItemID;
                                    inputValid           = true;
                                }
                                else
                                {
                                    if (infoCode.InputRequired)
                                    {
                                        inputValid = false;
                                        POSFormsManager.ShowPOSMessageDialog(3599);//A items needs to be selected
                                    }
                                }
                            } while (!inputValid);
                        }
                        #endregion

                        #region SubCode

                        else if ((infoCode.InputType == InfoCodeInputType.SubCodeList) || (infoCode.InputType == InfoCodeInputType.SubCodeButtons))
                        {
                            FormInfoCodeSubCodeBase infoSubCodeDialog;
                            if (infoCode.InputType == InfoCodeInputType.SubCodeList)
                            {
                                infoSubCodeDialog = new FormInfoCodeSubCodeList();
                            }
                            else
                            {
                                infoSubCodeDialog = new FormInfoSubCode();
                            }

                            using (infoSubCodeDialog)
                            {
                                bool inputValid = false;
                                do
                                {
                                    infoSubCodeDialog.InfoCodePrompt = infoCode.Prompt;
                                    infoSubCodeDialog.InfoCodeId     = infoCode.InfocodeId;
                                    infoSubCodeDialog.InputRequired  = infoCode.InputRequired;

                                    POSFormsManager.ShowPOSForm(infoSubCodeDialog);
                                    switch (infoSubCodeDialog.DialogResult)
                                    {
                                    case DialogResult.OK:
                                        inputValid = true;
                                        break;

                                    case DialogResult.No:
                                        return(false);

                                    default:
                                        if (!infoCode.InputRequired)
                                        {
                                            return(false);
                                        }
                                        break;
                                    }

                                    //if InputValid is false then nothing was selected in the dialog and there is no point in going through this code
                                    if (inputValid)
                                    {
                                        infoCode.Information = infoSubCodeDialog.SelectedDescription;
                                        infoCode.Subcode     = infoSubCodeDialog.SelectedSubcodeId;

                                        //TenderDeclarationTransaction also has infocodes but it can't have any sale items so no need
                                        //to go through this code.
                                        if (retailTransaction != null)
                                        {
                                            //Look through the information on the subcode that was selected and see if an item is to be sold
                                            //and if a discount and/or price needs to be modified
                                            //foreach (SubcodeInfo subcodeInfo in infoSubCodeDialog.SubCodes)
                                            //{
                                            if ((infoSubCodeDialog.SelectedTriggerFunction == (int)TriggerFunctionEnum.Item) && (infoSubCodeDialog.SelectedTriggerCode.Length != 0))
                                            {
                                                OperationInfo opInfo = new OperationInfo();

                                                ItemSale itemSale = new ItemSale();
                                                itemSale.OperationID    = PosisOperations.ItemSale;
                                                itemSale.OperationInfo  = opInfo;
                                                itemSale.Barcode        = infoSubCodeDialog.SelectedTriggerCode;
                                                itemSale.POSTransaction = retailTransaction;
                                                itemSale.RunOperation();

                                                //The infocode item has been added.
                                                //Look at the last item on the transaction and if it is the same item that the ItemSale was supposed to sell
                                                //then check to see if it is to have a special price or discount
                                                if (retailTransaction.SaleItems.Last.Value.ItemId == infoSubCodeDialog.SelectedTriggerCode)
                                                {
                                                    //set the property of that item to being an infocode item such that if the same item is added again, then
                                                    //these will not be aggregated (since the item as infocode item might receive a different discount than the same
                                                    //item added regularly.
                                                    retailTransaction.SaleItems.Last.Value.IsInfoCodeItem = true;

                                                    infoCode.SubcodeSaleLineId = retailTransaction.SaleItems.Last.Value.LineId;

                                                    if (infoSubCodeDialog.SelectedPriceType == (int)PriceTypeEnum.Price)
                                                    {
                                                        PriceOverride priceOverride = new PriceOverride();

                                                        opInfo.NumpadValue = infoSubCodeDialog.SelectedAmountPercent.ToString("n2");
                                                        opInfo.ItemLineId  = retailTransaction.SaleItems.Last.Value.LineId;

                                                        priceOverride.OperationInfo  = opInfo;
                                                        priceOverride.OperationID    = PosisOperations.PriceOverride;
                                                        priceOverride.POSTransaction = retailTransaction;
                                                        priceOverride.LineId         = retailTransaction.SaleItems.Last.Value.LineId;
                                                        priceOverride.RunOperation();
                                                    }
                                                    else if (infoSubCodeDialog.SelectedPriceType == (int)PriceTypeEnum.Percent)
                                                    {
                                                        LineDiscountPercent lineDiscount = new LineDiscountPercent();

                                                        opInfo.NumpadValue = infoSubCodeDialog.SelectedAmountPercent.ToString("n2");
                                                        opInfo.ItemLineId  = retailTransaction.SaleItems.Last.Value.LineId;

                                                        lineDiscount.OperationInfo  = opInfo;
                                                        lineDiscount.OperationID    = PosisOperations.LineDiscountPercent;
                                                        lineDiscount.POSTransaction = retailTransaction;
                                                        lineDiscount.RunOperation();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } while (!inputValid);
                            }
                        }
                        #endregion

                        #region Age limit

                        else if ((infoCode.InputType == InfoCodeInputType.AgeLimit))
                        {
                            int ageLimit = (int)infoCode.MinimumValue;
                            if (ageLimit >= 0)
                            {
                                //Calculate birthdate corresponding to minimum age limit
                                DateTime dtBirthDate = DateTime.Today.AddYears(-ageLimit);

                                //Convert the date time value according to the current culture information
                                string birthDate = dtBirthDate.ToString(System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
                                string msg       = ApplicationLocalizer.Language.Translate(3606, ageLimit, birthDate);

                                // Process age limit info codes if it is pre item and prompt the message to user for processing.
                                // Also Info Code type is an item and Age Limit is a link to reason code then process the info code with prompt to user.
                                if (((tableRefId == InfoCodeTableRefType.PreItem) && (infoCode.InputType == InfoCodeInputType.AgeLimit)) || (!string.IsNullOrEmpty(linkedInfoCodeId) && tableRefId == InfoCodeTableRefType.Item))
                                {
                                    using (frmMessage frmMsg = new frmMessage(msg, MessageBoxButtons.YesNo, MessageBoxIcon.Information, false))
                                    {
                                        POSFormsManager.ShowPOSForm(frmMsg);
                                        if (frmMsg.DialogResult != DialogResult.Yes)
                                        {
                                            return(false);
                                        }
                                    }
                                }
                                infoCode.Information = msg;
                            }
                        }
                        #endregion

                        else
                        {
                            POSFormsManager.ShowPOSMessageDialog(3589);
                            return(false);
                        }

                        // Add the infocode to the transaction
                        if (infoCode.Information != null && infoCode.Information.Length > 0)
                        {
                            string infoComment = string.Empty;
                            if (infoCode.PrintPromptOnReceipt || infoCode.PrintInputOnReceipt || infoCode.PrintInputNameOnReceipt)
                            {
                                if (infoCode.PrintPromptOnReceipt && (infoCode.Prompt.Length != 0))
                                {
                                    infoComment = infoCode.Prompt;
                                }

                                if (infoCode.PrintInputOnReceipt && (infoCode.Subcode != null) && (infoCode.Subcode.Length != 0))
                                {
                                    if (infoComment.Length != 0)
                                    {
                                        infoComment += " - " + infoCode.Subcode;
                                    }
                                    else
                                    {
                                        infoComment = infoCode.Subcode;
                                    }
                                }

                                if (infoCode.PrintInputNameOnReceipt && (infoCode.Information.Length != 0))
                                {
                                    if (infoComment.Length != 0)
                                    {
                                        infoComment += " - " + infoCode.Information;
                                    }
                                    else
                                    {
                                        infoComment = infoCode.Information;
                                    }
                                }
                            }

                            if (infoCodeType == InfoCodeType.Sales)
                            {
                                int lineId;
                                if (infoCode.SubcodeSaleLineId != -1)
                                {
                                    SaleLineItem saleLineItem = retailTransaction.GetItem(infoCode.SubcodeSaleLineId - 1);
                                    saleLineItem.Add(infoCode);
                                    lineId = saleLineItem.LineId;
                                }
                                else
                                {
                                    // don't save if this is pre-item. the same infocodes will be found next pass for normal item infocodes.
                                    if (tableRefId == InfoCodeTableRefType.PreItem)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        LinkedListNode <SaleLineItem> saleLineItem = retailTransaction.SaleItems.Last;
                                        saleLineItem.Value.Add(infoCode);
                                        lineId = saleLineItem.Value.LineId;
                                    }
                                }

                                if (infoComment.Trim().Length != 0)
                                {
                                    OperationInfo opInfo = new OperationInfo();
                                    opInfo.NumpadValue = infoComment.Trim();
                                    opInfo.ItemLineId  = lineId;

                                    ItemComment itemComment = new ItemComment();
                                    itemComment.OperationID    = PosisOperations.ItemComment;
                                    itemComment.POSTransaction = (PosTransaction)posTransaction;
                                    itemComment.OperationInfo  = opInfo;
                                    itemComment.RunOperation();
                                }
                            }
                            else if (infoCodeType == InfoCodeType.Payment)
                            {
                                if (retailTransaction != null)
                                {
                                    LinkedListNode <TenderLineItem> tenderLineItem = retailTransaction.TenderLines.Last;
                                    tenderLineItem.Value.Add(infoCode);

                                    if (infoComment.Trim().Length != 0)
                                    {
                                        tenderLineItem.Value.Comment = infoComment.Trim();
                                    }
                                }
                                else
                                {
                                    LSRetailPosis.Transaction.CustomerPaymentTransaction custPayTrans = posTransaction as LSRetailPosis.Transaction.CustomerPaymentTransaction;
                                    LinkedListNode <TenderLineItem> tenderLineItem = custPayTrans.TenderLines.Last;
                                    tenderLineItem.Value.Add(infoCode);

                                    if (infoComment.Trim().Length != 0)
                                    {
                                        tenderLineItem.Value.Comment = infoComment.Trim();
                                    }
                                }

                                //LinkedListNode<TenderLineItem> tenderLineItem = retailTransaction.TenderLines.Last; //
                                //tenderLineItem.Value.Add(infoCode);

                                //if (infoComment.Trim().Length != 0)
                                //{
                                //    tenderLineItem.Value.Comment = infoComment.Trim();
                                //}
                            }
                            else
                            {
                                if (retailTransaction != null)
                                {
                                    retailTransaction.Add(infoCode);
                                    if (infoComment.Trim().Length != 0)
                                    {
                                        retailTransaction.InvoiceComment += infoComment.Trim();
                                    }
                                }
                                else
                                {
                                    tenderCountTransaction.Add(infoCode);
                                    //No invoice comment on TenderDeclarationTransaction
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }