Esempio n. 1
0
        private string GetTrackingNumber(IPurchaseOrder order)
        {
            if (order.ErpId == null)
            {
                throw new InvalidOperationException($"Neocekavany stav objednavky '{order.OrderNumber}' - objednavka nema prirazeny ERP system");
            }

            var erpClient = m_erpClientFactory.GetErpClient(order.ErpId.Value);

            return(erpClient.GetPackingReferenceNumber(order));
        }
Esempio n. 2
0
        private IErpDataMapper GetMapper(IErpOrderModel model)
        {
            IErpDataMapper mapper;

            if (!m_mapperIndex.TryGetValue(model.ErpSystemId, out mapper))
            {
                mapper = m_erpClientFactory.GetErpClient(model.ErpSystemId)?.Mapper;
                if (mapper == null)
                {
                    throw new InvalidOperationException($"Cannot find DataMapper for ErpSystem Id={model.ErpSystemId}");
                }

                m_mapperIndex.Add(model.ErpSystemId, mapper);
            }

            return(mapper);
        }
Esempio n. 3
0
        public void Run(string customDataJson)
        {
            var cuData = JsonConvert.DeserializeObject <ImportOrdersCustomData>(customDataJson);

            var erp = m_erpClientFactory.GetErpClient(cuData.ErpId);

            m_log.Info($"ERP = {erp.Erp.Description}");

            try
            {
                var minDate =
                    m_database.Sql()
                    .Execute("SELECT MAX(PurchaseDate) FROM PurchaseOrder WHERE ProjectId = @p AND ErpId = @e")
                    .WithParam("@p", m_session.Project.Id)
                    .WithParam("@e", erp.Erp.Id)
                    .Scalar();

                var startDate = erp.CommonSettings.HistoryStart;
                if ((minDate != null) && (DBNull.Value != minDate))
                {
                    startDate = (DateTime)minDate;

                    if (startDate > DateTime.Now.AddDays(-1 * erp.CommonSettings.OrderSyncHistoryDays))
                    {
                        startDate = DateTime.Now.AddDays(-1 * erp.CommonSettings.OrderSyncHistoryDays);
                    }
                }

                if (cuData.HistoryDepthDays != null)
                {
                    startDate = startDate.AddDays(-1 * cuData.HistoryDepthDays.Value);
                    if (startDate < erp.CommonSettings.HistoryStart)
                    {
                        startDate = erp.CommonSettings.HistoryStart;
                    }
                }

                while (startDate < DateTime.Now)
                {
                    var queryDays = erp.CommonSettings.MaxQueryDays;

                    while (queryDays > 0)
                    {
                        try
                        {
                            var endDate = startDate.AddDays(queryDays);

                            m_purchaseOrderRepository.PreloadOrders(startDate, endDate);

                            m_log.Info($"Stahuji objednavky {startDate} - {endDate}");

                            var erpOrders = erp.LoadOrders(startDate, endDate).ToList();

                            m_log.Info($"Stazeno {erpOrders.Count} zaznamu");

                            foreach (var srcOrder in erpOrders)
                            {
                                m_purchaseOrderRepository.ImportErpOrder(srcOrder);
                            }

                            m_log.Info("Ulozeno");

                            startDate = endDate;
                            break;
                        }
                        catch (Exception ex)
                        {
                            queryDays = queryDays / 2;

                            if (queryDays < 1)
                            {
                                m_log.Error($"Nepodarilo se stahnout objednavky: {ex.Message}");
                                throw;
                            }
                            else
                            {
                                m_log.Info($"Stazeni objednavek z ERP selhalo, zkracuji interval dotazu na {queryDays} dnu");
                            }
                        }
                    }
                }

                ProcessReturns();

                m_log.Info("Job dokoncen");
            }
            finally
            {
                (erp as IDisposable)?.Dispose();
            }
        }
Esempio n. 4
0
        private IPurchaseOrder PerformErpActionSafe(
            IPurchaseOrder order,
            Action <IErpClient, IPurchaseOrder> erpAction,
            Action <IPurchaseOrder> validateSyncedOrder,
            string actionLogDescription)
        {
            m_log.Info($"PerformErpActionSafe started: orderId={order.Id} orderNr={order.OrderNumber} action={actionLogDescription} statusId={order.OrderStatusId} erpStatus={order.ErpStatusName}");

            m_database.Save(order);

            var orderId = order.Id;

            if (order.ErpId == null)
            {
                throw new InvalidOperationException("Cannot perform ERP operation for order without ERP");
            }

            var erp = m_clientFactory.GetErpClient(order.ErpId.Value);

            try
            {
                erpAction(erp, order);
                m_log.Info($"PerformErpActionSafe - erpAction performed ok: orderId={order.Id} orderNr={order.OrderNumber} action={actionLogDescription}");
            }
            catch (Exception ex)
            {
                m_log.Error($"PerformErpActionSafe - erpAction failed: orderId={order.Id} orderNr={order.OrderNumber} action={actionLogDescription}", ex);
                throw;
            }

            m_log.Info($"Downloading order from ERP by orderNumber={order.OrderNumber}");

            var erpOrder = erp.LoadOrder(order.OrderNumber);

            if (erpOrder == null)
            {
                m_log.Error($"Downloading order from ERP by orderNumber={order.OrderNumber} failed!");

                throw new InvalidOperationException(
                          $"Nepodarilo se stahnout objednavku '{order.OrderNumber}' ze systemu '{order.Erp?.Description}'");
            }

            var importedOrderId = m_orderRepository.ImportErpOrder(erpOrder);

            if (importedOrderId != orderId)
            {
                throw new InvalidOperationException(
                          $"Chyba synchronizace objednavky '{order.OrderNumber}' ze systemu '{order.Erp?.Description}'");
            }

            order = m_orderRepository.GetOrder(importedOrderId);

            try
            {
                validateSyncedOrder(order);
            }
            catch (Exception ex)
            {
                m_log.Error($"Chyba pri pokusu o zpracovani objednavky '{order.OrderNumber}' po pozadavku na zmenu v systemu '{order.Erp?.Description}': {ex.Message}", ex);
                throw new InvalidOperationException($"Chyba pri pokusu o zpracovani objednavky '{order.OrderNumber}' po pozadavku na zmenu v systemu '{order.Erp?.Description}': {ex.Message}");
            }

            m_log.Info($"PerformErpActionSafe finished ok; order reloaded from database: orderId={order.Id} orderNr={order.OrderNumber} action={actionLogDescription} statusId={order.OrderStatusId} erpStatus={order.ErpStatusName}");

            return(order);
        }
Esempio n. 5
0
        public byte[] GenerateShipmentRequestDocument(IEnumerable <IPurchaseOrder> orders)
        {
            var orderList = orders.ToList();

            m_log.Info($"Zacinam vytvareni dokumentu pro Zasilkovnu, zdroj = {orderList.Count} objednavek");

            using (var stream = new MemoryStream())
                using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
                {
                    var generator = new CsvGenerator(streamWriter, ZasilkovnaColIndex);

                    foreach (var order in orderList)
                    {
                        try
                        {
                            var shipmentTitle = order.ShippingMethodName;

                            var dobirkovaCastka = StringUtil.FormatDecimal(order.PriceWithVat);

                            if (!string.IsNullOrWhiteSpace(dobirkovaCastka) && order.Currency.Symbol == "CZK")
                            {
                                dobirkovaCastka = ((int)double.Parse(dobirkovaCastka)).ToString();
                            }

                            if (!order.IsPayOnDelivery)
                            {
                                dobirkovaCastka = string.Empty;
                            }

                            var pobockaId = GetPobockaId(order);

                            if (string.IsNullOrWhiteSpace(order.CustomerEmail) &&
                                string.IsNullOrWhiteSpace(order.DeliveryAddress?.Phone) &&
                                string.IsNullOrWhiteSpace(order.InvoiceAddress?.Phone))
                            {
                                throw new Exception("Musi byt telefon nebo e-mail");
                            }

                            var externalDeliveryProvider = false;
                            if (string.IsNullOrWhiteSpace(pobockaId))
                            {
                                externalDeliveryProvider = true;

                                pobockaId = GetBranches().GetPobockaId(shipmentTitle, GetShipmentMethodsMapping());
                            }

                            if (order.ErpId == null)
                            {
                                throw new InvalidOperationException("Unexpected order without Erp");
                            }

                            var erpClient      = m_erpClientFactory.GetErpClient(order.ErpId.Value);
                            var trackingNumber = erpClient.GetPackingReferenceNumber(order);

                            decimal?weight = null;

                            try
                            {
                                weight = m_orderWeightCalculator.GetWeight(order);
                            }
                            catch (Exception e)
                            {
                                m_log.Error($"Weight calc failed", e);
                            }

                            // not sure about Version 4 used by Elsa, but ver. 6 is documented here: https://docs.packetery.com/03-creating-packets/01-csv-import.html
                            generator.CellOpt(null)                                                     //1 Vyhrazeno
                            .CellMan(trackingNumber)                                                    //2 Číslo objednávky
                            .CellMan(order.DeliveryAddress?.FirstName, order.InvoiceAddress?.FirstName) //3 Jméno
                            .CellMan(order.DeliveryAddress?.LastName, order.InvoiceAddress?.LastName)   //4 Příjmení
                            .CellOpt(
                                externalDeliveryProvider
                                    ? (string.IsNullOrWhiteSpace(order.DeliveryAddress?.CompanyName)
                                           ? order.InvoiceAddress?.CompanyName
                                           : order.DeliveryAddress?.CompanyName)
                                    : string.Empty)                                             //5 Firma
                            .CellOpt(order.CustomerEmail)                                       //6 E-mail
                            .CellOpt(order.DeliveryAddress?.Phone, order.InvoiceAddress?.Phone) //7 Mobil
                            .CellOpt(dobirkovaCastka)                                           //8 Dobírková částka
                            .CellMan(order.Currency.Symbol)                                     //9 Měna
                            .CellMan(StringUtil.FormatDecimal(order.PriceWithVat))              //10 Hodnota zásilky
                            .CellOpt(StringUtil.FormatDecimal(weight))                          //11 Hmotnost zásilky
                            .CellMan(pobockaId)                                                 //12 Cílová pobočka
                            .CellMan(/*"biorythme.cz"*/ m_config.ClientName)                    //13 Odesilatel
                            .CellMan(0)                                                         //14 Obsah 18+
                            .CellOpt(null)                                                      //15 Zpožděný výdej
                            ;

                            if (externalDeliveryProvider)
                            {
                                generator.CellMan(order.DeliveryAddress?.Street, order.InvoiceAddress?.Street) //16
                                .CellMan(
                                    GetFormattedHouseNumber(order.DeliveryAddress),
                                    GetFormattedHouseNumber(order.InvoiceAddress))                //17
                                .CellMan(order.DeliveryAddress?.City, order.InvoiceAddress?.City) //18
                                .CellMan(order.DeliveryAddress?.Zip, order.InvoiceAddress?.Zip)   //19
                                ;
                            }

                            generator.CommitRow();
                        }
                        catch (Exception ex)
                        {
                            generator.RollbackRow();
                            throw new InvalidOperationException(
                                      "Chyba objednavky " + order.OrderNumber + ":" + ex.Message,
                                      ex);
                        }
                    }

                    streamWriter.Flush();
                    return(stream.ToArray());
                }
        }