private int ProcessQueueEntries()
        {
            SqlTransaction LMSTransaction   = null;
            string         errorReason      = "";
            string         errorDescription = "";

            int liveUpdateCounter = 0;

            OrderCreateSyncRequest              orderCreateSyncRequest      = null;
            OrderUpdateSyncRequest              orderUpdateSyncRequest      = null;
            OrderCancelSyncRequest              orderCancelSyncRequest      = null;
            OrderFulfillSyncRequest             orderFulfillRequest         = null;
            OrderRollbackFulfillmentSyncRequest orderRollbackFulfillRequest = null;

            string  messageId = "";
            string  lockToken = "";
            Message message   = null;

            try
            {
                Tuple <String, String, Message> queueRequest = this.LQTools.LiveQueueToolsGetLiveRequest();
                if (queueRequest != null)
                {
                    Console.WriteLine(""); // IsAlive Hinweis für Console
                    messageId = queueRequest.Item1;
                    lockToken = queueRequest.Item2;

                    message = queueRequest.Item3;

                    bool success = false;
                    switch (message.ContentType)
                    {
                    case nameof(OrderCreateSyncRequest):
                        orderCreateSyncRequest = message.As <OrderCreateSyncRequest>().ConvertDateTimesToCEST();

                        Console.WriteLine("Bearbeite OrderCreateSyncRequest:");
                        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(orderCreateSyncRequest,
                                                                                      new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                        }));

                        LMSTransaction = this.LMSSqlConnection.BeginTransaction();
                        switch (orderCreateSyncRequest.Type)
                        {
                        case OrderType.Supply:
                            if (!orderCreateSyncRequest.IsPermanent)
                            {
                                // Normale Verfügbarkeit
                                if (LiveDBTools.CheckAvailability(this.MyConfig, LMSTransaction, orderCreateSyncRequest, out errorReason, out errorDescription) &&
                                    (success = LiveDBTools.InsertAvailability(MyConfig, LMSTransaction, orderCreateSyncRequest, out errorReason, out errorDescription)))
                                {
                                    liveUpdateCounter++;
                                }
                            }
                            else
                            {
                                // Dauerverfügbarkeit
                                if (LiveDBTools.CheckPermanentAvailability(this.MyConfig, LMSTransaction, orderCreateSyncRequest, out errorReason, out errorDescription) &&
                                    (success = LiveDBTools.InsertPermanentAvailability(MyConfig, LMSTransaction, orderCreateSyncRequest, out errorReason, out errorDescription)))
                                {
                                    liveUpdateCounter++;
                                }
                            }
                            break;

                        case OrderType.Demand:
                            if (LiveDBTools.CheckDelivery(this.MyConfig, LMSTransaction, orderCreateSyncRequest, out errorReason, out errorDescription) &&
                                (success = LiveDBTools.InsertDelivery(MyConfig, LMSTransaction, orderCreateSyncRequest, out errorReason, out errorDescription)))
                            {
                                liveUpdateCounter++;
                            }
                            break;
                        }

                        if (!success)
                        {
                            this.LogWarning("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + errorReason + "', Beschreibung: '" + errorDescription + "'");
                            this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, errorReason, errorDescription);
                            break;
                        }
                        break;

                    case nameof(OrderUpdateSyncRequest):
                        orderUpdateSyncRequest = message.As <OrderUpdateSyncRequest>().ConvertDateTimesToCEST();

                        Console.WriteLine("Bearbeite OrderUpdateSyncRequest:");
                        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(orderUpdateSyncRequest,
                                                                                      new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                        }));

                        LMSTransaction = this.LMSSqlConnection.BeginTransaction();
                        switch (orderUpdateSyncRequest.Type)
                        {
                        case OrderType.Supply:
                            if (orderUpdateSyncRequest.IsPermanent)
                            {
                                // Dauerverfügbarkeit
                                if (success = LiveDBTools.UpdatePermanentAvailability(MyConfig, LMSTransaction, orderUpdateSyncRequest, out errorReason, out errorDescription))
                                {
                                    liveUpdateCounter++;
                                }
                            }
                            else
                            {
                                errorReason      = ErrorReasonNotImplemented;
                                errorDescription = ErrorDescriptionNotImplemented;
                                success          = false;
                            }
                            break;

                        case OrderType.Demand:
                            errorReason      = ErrorReasonNotImplemented;
                            errorDescription = ErrorDescriptionNotImplemented;
                            success          = false;
                            break;
                        }

                        if (!success)
                        {
                            this.LogWarning("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + errorReason + "', Beschreibung: '" + errorDescription + "'");
                            this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, errorReason, errorDescription);
                            break;
                        }
                        break;

                    case nameof(OrderCancelSyncRequest):
                        orderCancelSyncRequest = message.As <OrderCancelSyncRequest>().ConvertDateTimesToCEST();

                        Console.WriteLine("Bearbeite OrderCancelSyncRequest:");
                        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(orderCancelSyncRequest,
                                                                                      new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                        }));

                        LMSTransaction = this.LMSSqlConnection.BeginTransaction();
                        switch (orderCancelSyncRequest.Type)
                        {
                        case OrderType.Supply:
                            if (success = LiveDBTools.CancelAvailability(MyConfig, LMSTransaction, orderCancelSyncRequest, out errorReason, out errorDescription))
                            {
                                liveUpdateCounter++;
                            }
                            break;

                        case OrderType.Demand:
                            if (success = LiveDBTools.CancelDelivery(MyConfig, LMSTransaction, orderCancelSyncRequest, out errorReason, out errorDescription))
                            {
                                liveUpdateCounter++;
                            }
                            break;
                        }

                        if (!success)
                        {
                            this.LogWarning("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + errorReason + "', Beschreibung: '" + errorDescription + "'");
                            this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, errorReason, errorDescription);
                            break;
                        }
                        break;

                    case nameof(OrderFulfillSyncRequest):
                        orderFulfillRequest = message.As <OrderFulfillSyncRequest>().ConvertDateTimesToCEST();

                        Console.WriteLine("Bearbeite OrderFulfillSyncRequest:");
                        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(orderFulfillRequest,
                                                                                      new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                        }));

                        LMSTransaction = this.LMSSqlConnection.BeginTransaction();
                        if (success = LiveDBTools.FullfillEntries(MyConfig, LMSTransaction, orderFulfillRequest, out errorReason, out errorDescription))
                        {
                            liveUpdateCounter++;
                        }

                        if (!success)
                        {
                            this.LogWarning("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + errorReason + "', Beschreibung: '" + errorDescription + "'");
                            this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, errorReason, errorDescription);
                            break;
                        }
                        break;

                    case nameof(OrderRollbackFulfillmentSyncRequest):
                        orderRollbackFulfillRequest = message.As <OrderRollbackFulfillmentSyncRequest>();

                        Console.WriteLine("Bearbeite OrderRollbackFulfillmentSyncRequest:");
                        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(orderRollbackFulfillRequest,
                                                                                      new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                        }));

                        LMSTransaction = this.LMSSqlConnection.BeginTransaction();
                        if (success = LiveDBTools.RollbackFullfillEntries(MyConfig, LMSTransaction, orderRollbackFulfillRequest, out errorReason, out errorDescription))
                        {
                            liveUpdateCounter++;
                        }

                        if (!success)
                        {
                            this.LogWarning("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + errorReason + "', Beschreibung: '" + errorDescription + "'");
                            this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, errorReason, errorDescription);
                            break;
                        }
                        break;

                    default:
                        errorDescription = ErrorDescriptionMessageType + message.ContentType;
                        this.LogError("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + ErrorReasonMessageType + "', Beschreibung: '" + errorDescription + "'");
                        this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, ErrorReasonMessageType, errorDescription);
                        break;
                    }
#if !TEST_ONLY
                    if (success)
                    {
                        success = this.LQTools.LiveQueueToolsConfirmLiveRequest(lockToken);
                        if (success)
                        {
                            LMSTransaction.Commit();
                        }
                        else
                        {
                            LMSTransaction.Rollback();
                        }
                        LMSTransaction = null;
                    }
                    if (!success)
                    {
                        liveUpdateCounter = 0;
                        if (LMSTransaction != null)
                        {
                            LMSTransaction.Rollback();
                            LMSTransaction = null;
                        }
                    }
#else
                    LMSTransaction.Rollback();
                    LMSTransaction = null;
#endif
                }
            }
            catch (Exception ex)
            {
                this.LogException("ServiceMain", ex);
                if (LMSTransaction != null)
                {
                    LMSTransaction.Rollback();
                    liveUpdateCounter = 0;
                }
                if (lockToken != "")
                {
                    errorDescription = ErrorDescriptionException + ex.Message;
                    this.LogError("Bearbeitung Queue Entry '" + messageId + "' nicht möglich, Grund: '" + ErrorReasonException + "', Beschreibung: '" + errorDescription + "'");
                    this.LQTools.LiveQueueToolsDenyLiveRequest(lockToken, ErrorReasonMessageType, errorDescription);
                }
                //this.ServiceErrorFlag = true; TODO
            }

            return(liveUpdateCounter);
        }
        /// <summary>
        /// Erzeugt eine Quittungen. Diese Action hat abhängigkeiten zum NumberSequencesService und zum PostingRequestsService.
        /// </summary>
        /// <param name="mainRule"></param>
        /// <returns></returns>
        private async Task <IWrappedResponse> CreateAction(Rules.LoadCarrierReceipts.Create.MainRule mainRule)
        {
            var request                = mainRule.Context.Parent;
            var printLanguageId        = request.PrintLanguageId;
            var loadCarrierReceipt     = mainRule.Context.LoadCarrierReceipt;
            var customerDivision       = mainRule.Context.CustomerDivision;
            var isSupply               = mainRule.Context.IsSupply;
            var targetRefLtmsAccountId = mainRule.Context.TargetRefLtmsAccountId;
            var orderLoad              = mainRule.Context.OrderLoad;
            var refLtmsTransactionId   = mainRule.Context.RefLtmsTransactionId;
            var isSelfService          = mainRule.Context.IsSelfService;
            var documentType           = mainRule.Context.DocumentType;
            var lmsAvail2deli          = mainRule.Context.LmsAvail2deli;

            var documentNumber = _numberSequencesService
                                 .GetDocumentNumber(documentType, request.CustomerDivisionId).Result;

            mainRule.Context.LoadCarrierReceipt.Document.Number = documentNumber;

            var strategy = _olmaDbContext.Database.CreateExecutionStrategy();
            var result   = await strategy.ExecuteAsync(async() =>
            {
                await using var ctxTransaction = await _olmaDbContext.Database.BeginTransactionAsync();
                var strategyResult             = _olmaLoadCarrierReceiptRepo
                                                 .Create <Olma.LoadCarrierReceipt, Olma.LoadCarrierReceipt, LoadCarrierReceipt>(
                    loadCarrierReceipt);
                var reportGeneratorServiceResponse =
                    (IWrappedResponse <Report>)_reportGeneratorService.GenerateReportForLanguage(
                        strategyResult.Data.DocumentId, printLanguageId, request.PrintCount - 1,
                        request.PrintDateTimeOffset);

                var downloadLink = (IWrappedResponse <string>) await _documentsService
                                   .GetDocumentDownload(strategyResult.Data.DocumentId, DocumentFileType.Composite);

                if (downloadLink.ResultType != ResultType.Ok)
                {
                    await ctxTransaction.RollbackAsync();
                    return(new WrappedResponse <LoadCarrierReceipt>
                    {
                        ResultType = ResultType.Failed,
                        State = ErrorHandler.Create().AddMessage(new DocumentLinkError()).GetServiceState()
                    });
                }
                strategyResult.Data.DownloadLink = downloadLink.Data;

                var postingRequestsCreateRequest = new PostingRequestsCreateRequest
                {
                    Type = isSupply
                        ? PostingRequestType.Credit
                        : PostingRequestType
                           .Charge,  //HACK Only to fix UI, from LTMS WebApp viewpoint  it would be a charge
                    ReferenceNumber      = loadCarrierReceipt.Document?.Number,
                    Reason               = PostingRequestReason.LoadCarrierReceipt,
                    LoadCarrierReceiptId = strategyResult.Data.Id,
                    IsSortingRequired    = strategyResult.Data.IsSortingRequired,
                    DocumentFileName     = reportGeneratorServiceResponse.Data.DocumentArchiveName,
                    IsSelfService        = isSelfService,
                    Positions            = loadCarrierReceipt.Positions.Select(lcr =>
                                                                               new PostingRequestPosition
                    {
                        LoadCarrierId       = lcr.LoadCarrierId,
                        LoadCarrierQuantity = lcr.LoadCarrierQuantity
                    }),
                    RefLtmsProcessId     = Guid.NewGuid(),
                    RefLtmsTransactionId = refLtmsTransactionId ?? Guid.NewGuid(),
                    PostingAccountId     = customerDivision.PostingAccountId.Value,
                    RefLtmsProcessTypeId =
                        isSupply ? (int)RefLtmsProcessType.Excemption : (int)RefLtmsProcessType.DepotAcceptance,
                    SourceRefLtmsAccountId =
                        isSupply ? customerDivision.PostingAccount.RefLtmsAccountId : targetRefLtmsAccountId,
                    DestinationRefLtmsAccountId = !isSupply
                        ? customerDivision.PostingAccount.RefLtmsAccountId
                        : targetRefLtmsAccountId,
                    DigitalCode               = loadCarrierReceipt.DigitalCode,
                    RefLmsBusinessTypeId      = request.RefLmsBusinessTypeId,
                    RefLtmsTransactionRowGuid = request.RefLtmsTransactionRowGuid,
                    DeliveryNoteNumber        = loadCarrierReceipt.DeliveryNoteNumber,
                    PickUpNoteNumber          = loadCarrierReceipt.PickUpNoteNumber
                };

                var postingRequestsServiceResponse =
                    (IWrappedResponse <IEnumerable <PostingRequest> >) await _postingRequestsService
                    .Create(postingRequestsCreateRequest);
                if (postingRequestsServiceResponse.ResultType != ResultType.Created)
                {
                    await ctxTransaction.RollbackAsync();
                    return(new WrappedResponse <LoadCarrierReceipt>
                    {
                        ResultType = postingRequestsServiceResponse.ResultType,
                        State = postingRequestsServiceResponse.State
                    });
                }

                if (lmsAvail2deli != null)
                {
                    var orderFulfillSyncRequest = new OrderFulfillSyncRequest
                    {
                        DigitalCode               = loadCarrierReceipt.DigitalCode,
                        FulfillmentDateTime       = DateTime.UtcNow,
                        RefLmsDeliveryRowGuid     = lmsAvail2deli.Delivery.RowGuid,
                        RefLmsAvailabilityRowGuid = lmsAvail2deli.Availability.RowGuid
                    };

                    var ordersSyncRequest = new OrdersSyncRequest
                    {
                        OrderFulfillSyncRequests = new List <OrderFulfillSyncRequest>
                        {
                            orderFulfillSyncRequest
                        }
                    };

                    //Reine Sync-Fehler für Updates werden geloggt und müssen manuell behoben werden.
                    await _synchronizationsService.SendOrdersAsync(ordersSyncRequest);
                }
                await ctxTransaction.CommitAsync();
                return(strategyResult);
            });

            return(result);
        }
Exemple #3
0
        public static OrderFulfillSyncRequest ConvertDateTimesToCEST(this OrderFulfillSyncRequest request)
        {
            request.FulfillmentDateTime = GetCEST(request.FulfillmentDateTime);

            return(request);
        }