Exemple #1
0
        private void dishDel()
        {
            DishItem dishItem = (DishItem)lstDishes.SelectedItem;

            if (dishItem == null)
            {
                return;
            }
            OrderItem order = AppLib.GetCurrentOrder();

            AppLib.WriteAppAction($"CartWin|Удаление блюда '{dishItem.langNames["ru"]}'...");

            string           title  = AppLib.GetLangTextFromAppProp("cartDelDishTitle");
            string           msg    = string.Format("{0} \"{1}\" ?", AppLib.GetLangTextFromAppProp("cartDelDishQuestion"), AppLib.GetLangText(dishItem.langNames));
            MessageBoxResult result = AppLib.ShowChoiceBox(title, msg);

            AppLib.WriteAppAction($"CartWin|Удаление блюда '{dishItem.langNames["ru"]}': {result.ToString()}");

            if (result == MessageBoxResult.Yes)
            {
                order.Dishes.Remove(dishItem);
                lstDishes.Items.Refresh();
                scrollDishes.ScrollToTop();

                updatePriceOrder();
            }
        }
Exemple #2
0
        private void resetLang()
        {
            AppLib.WriteLogTraceMessage(" - язык приложения: " + AppLib.AppLang);
            string textOut = AppLib.GetLangTextFromAppProp("takeOrderOut");
            string textOr  = AppLib.GetLangTextFromAppProp("wordOr");
            string textIn  = AppLib.GetLangTextFromAppProp("takeOrderIn");

            AppLib.WriteLogTraceMessage($" - тексты на кнопках: takeOut='{textOut}', wordOr='{textOr}', takeIn='{textIn}'");

            txtTakeOut.Text = textOut;
            txtWordOr.Text  = textOr;
            txtTakeIn.Text  = textIn;
        }
Exemple #3
0
        private MsgBoxExt getDelMsgBox()
        {
            string sYes = AppLib.GetLangTextFromAppProp("dialogBoxYesText");
            string sNo  = AppLib.GetLangTextFromAppProp("dialogBoxNoText");

            MsgBoxExt mBox = new MsgBoxExt()
            {
                TitleFontSize        = (double)AppLib.GetAppGlobalValue("appFontSize6"),
                MessageFontSize      = (double)AppLib.GetAppGlobalValue("appFontSize2"),
                MsgBoxButton         = MessageBoxButton.YesNo,
                ButtonsText          = string.Format(";;{0};{1}", sYes, sNo),
                ButtonBackground     = (System.Windows.Media.Brush)AppLib.GetAppGlobalValue("appBackgroundColor"),
                ButtonBackgroundOver = (System.Windows.Media.Brush)AppLib.GetAppGlobalValue("appBackgroundColor"),
                ButtonForeground     = Brushes.White,
                ButtonFontSize       = (double)AppLib.GetAppGlobalValue("appFontSize4")
            };

            return(mBox);
        }
Exemple #4
0
        // удаление ингредиента
        private void ingrDel(object sender, Point point)
        {
            // получить контролы из нажатого элемента
            //    listbox ингредиентов
            ListBoxItem lbiIngr = (ListBoxItem)AppLib.FindVisualParentByType((FrameworkElement)sender, typeof(ListBoxItem));
            ListBox     lbIngr  = (ListBox)AppLib.FindVisualParentByType((FrameworkElement)lbiIngr, typeof(ListBox));
            DishAdding  tmpIngr = (DishAdding)lbIngr.ItemContainerGenerator.ItemFromContainer(lbiIngr);

            int iCnt = lbIngr.ItemContainerGenerator.IndexFromContainer(lbiIngr);

            if (lbIngr.SelectedIndex != iCnt)
            {
                lbIngr.SelectedIndex = iCnt;
            }

            //    listbox блюд
            AppLib.SelectListBoxItemByHisInnerControl((FrameworkElement)lbIngr, lstDishes); // делаем это принудетельно

            DishItem   dishItem = (DishItem)lstDishes.SelectedItem;
            DishAdding ingrItem = (DishAdding)lbIngr.SelectedItem;

            AppLib.WriteAppAction($"CartWin|Нажата кнопка удаления ингредиента '{ingrItem.langNames["ru"]}' для блюда '{dishItem.langNames["ru"]}'");

            string           title  = AppLib.GetLangTextFromAppProp("cartDelIngrTitle");
            string           msg    = string.Format("{0} \"{1}\" ?", AppLib.GetLangTextFromAppProp("cartDelIngrQuestion"), AppLib.GetLangText(ingrItem.langNames));
            MessageBoxResult result = AppLib.ShowChoiceBox(title, msg);

            AppLib.WriteAppAction($"CartWin|Удаление ингредиента {ingrItem.langNames["ru"]}: {result.ToString()}");
            if (result == MessageBoxResult.Yes)
            {
                dishItem.SelectedIngredients.Remove(ingrItem);
                lbIngr.Items.Refresh();

                updatePriceControls();
            }
            this.Activate();
        }
Exemple #5
0
        }  // method

        private void printClientInvoice()
        {
            decimal orderValue = _currentOrder.GetOrderValue();

            AppLib.WriteAppAction($"CartWin|Нажата кнопка PrintCheck (заказ {App.OrderNumber??"-"}, стоимость {orderValue.ToStringMoneyFormat()})");

            // если стоимость чека == 0, то выйти
            if (orderValue == 0)
            {
                return;
            }

            TakeOrder takeOrderWin = new TakeOrder();

            takeOrderWin.ShowDialog();

            // сохранить в заказе флажок "с собой"
            _currentOrder.takeAway = (takeOrderWin.TakeOrderMode == TakeOrderEnum.TakeAway);

            if (takeOrderWin.TakeOrderMode != TakeOrderEnum.None)
            {
                AppLib.WriteAppAction($"CartWin|Печать заказа '{_currentOrder.OrderNumberForPrint}' от {((_currentOrder.OrderDate==null) ? "--" : ((DateTime)_currentOrder.OrderDate).ToString())} на устройстве '{_currentOrder.DeviceID}'");
                PrintBill prn        = new PrintBill(_currentOrder);
                string    userErrMsg = null;
                bool      result     = prn.CreateBill(out userErrMsg);

                AppLib.WriteAppAction($"CartWin|Результат печати заказа '{_currentOrder.OrderNumberForPrint}' - {(result ? "Ok" : "error: " + userErrMsg)}");

                string title = (string)AppLib.GetLangTextFromAppProp("printOrderTitle");
                string msgText;
                // формирование чека и печать завершилась успешно - сохраняем заказ в БД
                if (result == true)
                {
                    AppLib.WriteLogTraceMessage($"Сохранение заказа '{_currentOrder.OrderNumberForPrint}' в БД...");
                    bool saveRes = _currentOrder.SaveToDB(out userErrMsg);
                    AppLib.WriteLogTraceMessage(" - результат сохранени в БД - " + (result ? "Ok" : "error: " + userErrMsg));

                    if (saveRes == true)
                    {
                        //msgText = (string)AppLib.GetLangTextFromAppProp("lblGoText");
                        //int delayInfoWin = AppLib.GetAppSetting("AutoCloseMsgBoxAfterPrintOrder").ToInt();
                        // 2017-02-17 убрать окно "Теперь можете подходить с чеком к кассе для оплаты"
                        //AppLib.ShowMessage(title, msgText, delayInfoWin);

                        // вернуть интерфейс в исходное состояние и создать новый заказ
                        AppLib.ReStartApp(false, true, true);
                        // поставить таймер бездействия на паузу
                        if (App.IdleHandler != null)
                        {
                            App.IdleHandler.SetPause();
                        }
                    }
                    // ошибка сохранения в БД
                    else
                    {
                        AppLib.WriteLogErrorMessage(userErrMsg);
                        msgText = (string)AppLib.GetLangTextFromAppProp("saveOrderErrorMessage");
                        msgText = msgText.Replace("\\n", Environment.NewLine);
                        AppLib.ShowMessageBox(title, msgText);
                    }
                }

                // ошибка формирования чека и/или печати - сообщение пользователю на экран
                else
                {
                    AppLib.ShowMessageBox(title, userErrMsg);
                }
            }  // if
        }
Exemple #6
0
        public bool CreateBill(out string msgBoxText)
        {
            bool retVal = true;

            msgBoxText = null;
            string userErrMsgSuffix = Environment.NewLine + AppLib.GetLangTextFromAppProp("userErrMsgSuffix");

            userErrMsgSuffix = userErrMsgSuffix.Replace("\\n", Environment.NewLine);

            AppLib.WriteLogTraceMessage("Создание пречека для заказа " + _order.OrderNumberForPrint.ToString());

            // свойства заказа, созадаваемые перед печатью чека:
            //      1. BarCodeValue - значение штрих-кода, 12 цифр (6 - yymmdd, 2 - код источника, 4 - номер чека для печати)
            //      2. LanguageTypeId - язык, который был выбран при создании чека (ua/en/ru)
            //--------------------------------------------------

            string deviceName = (string)AppLib.GetAppGlobalValue("ssdID", string.Empty);

            if (deviceName == string.Empty)
            {
                AppLib.WriteLogErrorMessage("В config-файле не найден элемент \"ssdID\" - идентификатор терминала самообслуживания.\n\t\tTrace: PrintBill.cs, CreateBill()");
                msgBoxText = "App config error: don't find 'ssdID' element." + userErrMsgSuffix;
                return(false);
            }
            if (deviceName.Length > 2)
            {
                deviceName = deviceName.Substring(0, 2);
            }

            // 1. OrderNumberForPrint
            if (_order.OrderNumberForPrint == -1)
            {
                AppLib.WriteLogErrorMessage("Класс PrintBill. Не указан номер заказа");
                msgBoxText = "App error: no order number." + userErrMsgSuffix;
                return(false);
            }

            // дату заказа создаем ПЕРЕД печатью
            _order.OrderDate = DateTime.Now;

            // 2. BarCodeValue
            //    идент.устройства - 2 символа
            if (deviceName.Length <= 2)
            {
                deviceName = string.Format("{0:D2}", deviceName);
            }
            else
            {
                deviceName = deviceName.Substring(0, 2);
            }
            //    дата заказа в формате yyMMdd - 6 символов
            //    номер заказа (для печати - случайный) в формате 0000 - 4 символа
            // т.к. в формате EAN-13 если первый символ - 0, то он удаляется, используем в начале дату
            string sBuf = (_order.OrderDate == null) ? "000000" : string.Format("{0:yyMMdd}", _order.OrderDate);

            _order.BarCodeValue = sBuf + _order.OrderNumberForPrint.ToString("000000");

            // 3. LanguageTypeId
            _order.LanguageTypeId = AppLib.AppLang;

            // ширина из config-файла
            int width = (int)AppLib.GetAppGlobalValue("BillPageWidht", 0);

            if (width == 0)
            {
                AppLib.WriteLogErrorMessage("В config-файле не указан элемент BillPageWidht с шириной чека. Берется значение по умолчанию - 300 (7,8см)");
                width = 300;
            }

            // принтеры в системе
            List <PrintQueue> printers = PrintHelper.getPrintersList();

            if (printers == null)
            {
                AppLib.WriteLogErrorMessage("В системе не зарегистрирован ни один принтер!!");
                msgBoxText = AppLib.GetLangTextFromAppProp("printConfigError");
                return(false);
            }
            else
            {
                try
                {
                    string sLog = string.Join(Environment.NewLine + "\t", printers.Select(pq => pq.Name + ", status '" + getPrinterStatus(pq) + "', driver '" + pq.QueueDriver.Name + "'"));
                    AppLib.WriteLogTraceMessage("Системные принтеры: " + Environment.NewLine + "\t" + sLog);
                }
                catch (Exception) { }
            }

            // имя принтера для печати чека
            string printerName = null;
            string result      = null;

            #region поиск принтера для печати чека
            printerName = AppLib.GetAppSetting("PrinterName");
            PrintQueue printer = PrintHelper.GetPrintQueueByName(printerName);
            if (printer == null)
            {
                AppLib.WriteLogErrorMessage("В config-файле не указан элемент PrinterName или в системе не найден принтер: " + printerName);
                printerName = null;
            }
            else
            {
                result = getPrinterStatus(printer);
                AppLib.WriteLogTraceMessage($"Принтер '{printerName}' находится в состоянии '{result}'");
            }

            // если принтер из настроек не Ок, то берем принтер по умолчанию
            if ((printer == null) || ((result != null) && (result != "OK")))
            {
                AppLib.WriteLogTraceMessage("Предпринимается попытка использовать принтер по умолчанию...");
                printer = PrintHelper.GetDefaultPrinter();
                if ((printer != null) &&
                    ((printerName == null) || ((printerName != null) && (printer.Name != printerName))))
                {
                    printerName = printer.Name;
                    result      = getPrinterStatus(printer);
                    AppLib.WriteLogTraceMessage($"Найден принтер по умолчанию: {printerName}");
                    AppLib.WriteLogTraceMessage($"Принтер '{printerName}' находится в состоянии '{result}'");
                }
            }

            // если принтер по умолчанию не ОК, то берем первый в системе
            if (printer == null)
            {
                AppLib.WriteLogTraceMessage("Предпринимается попытка использовать первый найденный принтер в ОС...");
                printer = PrintHelper.GetFirstPrinter();
                if ((printer != null) &&
                    ((printerName == null) || ((printerName != null) && (printer.Name != printerName))))
                {
                    printerName = printer.Name;
                    result      = getPrinterStatus(printer);
                    AppLib.WriteLogTraceMessage($"Найден первый принтер: {printerName}");
                    AppLib.WriteLogTraceMessage($"Принтер '{printerName}' находится в состоянии '{result}'");
                }
            }
            // принтер не найден - досвидос
            if (printer == null)
            {
                msgBoxText = "App print error: not found any printer." + userErrMsgSuffix;
                return(false);
            }
            // найден, но статус не ОК - досвидос
            else if ((result != null) && (result != "OK"))
            {
                string sFormat = AppLib.GetLangTextFromAppProp("printerStatusMsg");
                if (sFormat != null)
                {
                    sFormat = sFormat.Replace("\\n", Environment.NewLine);
                }
                msgBoxText = string.Format(sFormat, printerName, result) + userErrMsgSuffix;
                return(false);
            }
            #endregion

            // создание документа
            AppLib.WriteLogTraceMessage($" Создаю документ для печати...");
            FlowDocument doc = null;
            try
            {
                doc = createDocument(width);
                AppLib.WriteLogTraceMessage($" - документ создан успешно");
            }
            catch (Exception ex)
            {
                result = AppLib.GetLangTextFromAppProp("afterPrintingErrMsg");
                if (result != null)
                {
                    result = result.Replace("\\n", Environment.NewLine);
                }
                msgBoxText = result + userErrMsgSuffix;
                AppLib.WriteLogErrorMessage(" Ошибка формирования документа: " + ex.ToString());
                return(false);
            }

            // имя задания на принтер
            string prnTaskName = "bill " + _order.OrderNumberForPrint.ToString();
            // вывод документа на принтер
            AppLib.WriteLogTraceMessage($" Вывожу пречек на принтер...");
            retVal = PrintHelper.PrintFlowDocument(doc, prnTaskName, printerName, out msgBoxText);
            if (retVal == false)
            {
                // сообщение об ошибке в лог
                AppLib.WriteLogErrorMessage(" Ошибка печати документа: " + msgBoxText);
                // и на экран пользователю
                result = AppLib.GetLangTextFromAppProp("afterPrintingErrMsg");
                if (result != null)
                {
                    result = result.Replace("\\n", Environment.NewLine);
                }
                msgBoxText = result + userErrMsgSuffix;
            }
            else
            {
                AppLib.WriteLogTraceMessage("Пречек распечатан успешно");
                if (msgBoxText != null)
                {
                    AppLib.WriteLogErrorMessage(msgBoxText);
                }
            }

            return(retVal);
        }
Exemple #7
0
        private FlowDocument createDocument(int width)
        {
            // создать объекты верхнего и нижнего колонтитулов
            XmlDocument xmlHeader = new XmlDocument();

            xmlHeader.Load(AppDomain.CurrentDomain.BaseDirectory + string.Format(@"PrinterBill\Header-{0}.xml", _langId));
            XmlDocument xmlFooter = new XmlDocument();

            xmlFooter.Load(AppDomain.CurrentDomain.BaseDirectory + string.Format(@"PrinterBill\Footer-{0}.xml", _langId));
            TextModel textHeader = new TextModel();
            TextModel textFooter = new TextModel();

            textHeader = DeSerialize <TextModel>(xmlHeader.OuterXml);
            textFooter = DeSerialize <TextModel>(xmlFooter.OuterXml);
            int       leftMargin     = getLineMargin("BillLineLeftMargin");
            Thickness lineMargin     = getLineMargin();
            Thickness lineMarginIngr = lineMargin;

            lineMarginIngr.Top = getLineMargin("BillLineIngrTopMargin");
            Thickness lineMarginPrice = lineMargin;

            lineMarginPrice.Top = getLineMargin("BillLinePriceTopMargin");

            var doc = new FlowDocument();

            doc.PageWidth = width;
            // значения по умолчанию
            doc.FontFamily = new FontFamily("Panton-Bold");
            doc.FontWeight = FontWeights.Normal;
            doc.FontStyle  = FontStyles.Normal;
            doc.FontSize   = Convert.ToInt32(AppLib.GetAppGlobalValue("BillLineFontSize", 12));

            // вставить изображение в заголовок
            addImageToDoc(textHeader, doc);
            // метка, если заказ С СОБОЙ
            if (_order.takeAway == true)
            {
                string langText = AppLib.GetLangTextFromAppProp("takeOrderOut");
                langText = string.Concat(" **** ", langText.ToUpper(), " ****");
                addParagraph(doc, langText, 1.5 * doc.FontSize, FontWeights.Bold, FontStyles.Normal, new Thickness(leftMargin, 20, 0, 10), TextAlignment.Center);
            }
            // добавить форматированный заголовок
            addSectionToDoc(textHeader, doc);

            // добавить строки заказа
            string  currencyName = AppLib.GetLangTextFromAppProp("CurrencyName");
            string  sAppSet;
            decimal totalPrice = 0; string itemName, stringRow;

            foreach (DishItem item in _order.Dishes)
            {
                // блюдо
                itemName = AppLib.GetLangText(item.langNames);
                // c гарниром?
                if ((item.SelectedGarnishes != null) && (item.SelectedGarnishes.Count > 0))
                {
                    DishAdding garn     = item.SelectedGarnishes[0];
                    string     garnName = AppLib.GetLangText(garn.langNames);
                    // 2017-02-02 Формирование полного наименования блюда с гарниром
                    // если DishFullNameInGargnish = true, то полное имя берем из гарнира,
                    // иначе к имени блюда добавляем имя гарнира
                    sAppSet = AppLib.GetAppSetting("DishFullNameInGarnish");
                    if (sAppSet != null && sAppSet.ToBool())
                    {
                        itemName = garnName;
                    }
                    else
                    {
                        itemName += " " + AppLib.GetLangTextFromAppProp("withGarnish") + " " + garnName;
                    }
                }
                //string stringRow = itemName.Substring(0, itemName.Count() > 30 ? 30 : itemName.Count());
                addParagraph(doc, itemName, doc.FontSize, doc.FontWeight, doc.FontStyle, lineMargin);

                // добавить ингредиенты
                if (item.SelectedIngredients != null)
                {
                    stringRow = "  + "; bool isFirst = true;
                    foreach (DishAdding ingr in item.SelectedIngredients)
                    {
                        itemName   = AppLib.GetLangText(ingr.langNames);
                        stringRow += ((isFirst) ? "" : "; ") + itemName;
                        isFirst    = false;
                    }
                    addParagraph(doc, stringRow, 0.9 * doc.FontSize, doc.FontWeight, FontStyles.Italic, lineMarginIngr);
                }

                // стоимость блюда
                decimal price       = item.GetPrice();
                string  priceString = string.Format("{0} x {1:0.00} {3} = {2:0.00} {3}", item.Count, price, item.Count * price, currencyName);
                addParagraph(doc, priceString, doc.FontSize, doc.FontWeight, doc.FontStyle, lineMarginPrice, TextAlignment.Right);
                totalPrice += item.Count * price;
            }
            // итог
            addTotalLine(doc, doc.FontSize, totalPrice, currencyName, leftMargin);

            // добавить форматированный "подвал"
            addSectionToDoc(textFooter, doc);
            // вставить изображение в "подвал"
            addImageToDoc(textFooter, doc);

            // печать штрих-кода
            string           bcVal13      = _order.BarCodeValue + BarCodeLib.getUPCACheckDigit(_order.BarCodeValue);
            Image            imageBarCode = BarCodeLib.GetBarcodeImage(bcVal13, (int)(1.2 * doc.PageWidth), 50);
            BlockUIContainer bcContainer  = new BlockUIContainer()
            {
                Child  = imageBarCode,
                Margin = new Thickness(leftMargin, 10, 0, 0)
            };

            doc.Blocks.Add(bcContainer);
            // вывести значение баркода в чек
            //string bcDisplay = string.Format("{0} {1} {2} {3}", bcVal13.Substring(0,2), bcVal13.Substring(2, 6), bcVal13.Substring(8, 4), bcVal13.Substring(12,1));
            string bcDisplay = string.Format("{0}  {1}  {2}", bcVal13.Substring(0, 1), bcVal13.Substring(1, 6), bcVal13.Substring(7));

            addParagraph(doc, bcDisplay, 0.75 * doc.FontSize, doc.FontWeight, doc.FontStyle, new Thickness(leftMargin, 5, 0, 0), TextAlignment.Center);

            return(doc);
        }