Ejemplo n.º 1
0
        public override byte[] GetData(string url)
        {
            var reportInfo = _reportGeneratorService.GetReportInfoFromUrl(url);

            if (reportInfo.Mode == ReportMode.Edit)
            {
                return(_reportGeneratorService.GetReportTemplate(reportInfo.CustomerId.Value, (PrintType)reportInfo.PrintType, reportInfo.LanguageId));
            }
            else if (reportInfo.Mode == ReportMode.View)
            {
                return(((IWrappedResponse <Report>)_reportGeneratorService.GenerateReportForLanguage(reportInfo.DocumentId.Value, reportInfo.LanguageId, 1, -60)).Data.Document); //-60 is date time offset for germany
            }

            throw new ArgumentOutOfRangeException("Report mode needs to be either edit or view.");
        }
        /// <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);
        }
Ejemplo n.º 3
0
        private async Task <IWrappedResponse> CreateAction(Rules.Vouchers.Create.MainRule rule)
        {
            var voucher     = rule.Context.Rules.Voucher.Context.Voucher;
            var digitalCode = rule.Context.ExpressCode;

            #region map partner to CustomerPartner

            // if not exists: CustomerPartner has to copied from global Partner and stored in special 'ExpressCode' PartnerDirectory

            var partnerDictionary = new Dictionary <EntryType, Guid>
            {
                { EntryType.Recipient, rule.Context.RecipientGuid },
                { EntryType.Shipper, rule.Context.ShipperGuid },
                { EntryType.SubShipper, rule.Context.SubShipperGuid },
                { EntryType.Supplier, rule.Context.SupplierGuid }
            };

            //If Guid identifies a Partner, gets the matching CustomerPartner or creates a new one if does not exist

            var customerPartnerDictionary = ConvertToCustomerPartner(partnerDictionary);

            foreach (var customerPartner in customerPartnerDictionary)
            {
                switch (customerPartner.Key)
                {
                case EntryType.Default:
                    break;

                case EntryType.Recipient:
                    voucher.Recipient = customerPartner.Value;
                    break;

                case EntryType.Supplier:
                    voucher.Supplier = customerPartner.Value;
                    break;

                case EntryType.Shipper:
                    voucher.Shipper = customerPartner.Value;
                    break;

                case EntryType.SubShipper:
                    voucher.SubShipper = customerPartner.Value;
                    break;

                default:
                    return(new WrappedResponse
                    {
                        ResultType = ResultType.Failed,
                        State = ErrorHandler.Create()
                                .AddMessage(new CustomerPartnerNotFoundError())
                                .GetServiceState()
                    });
                }
            }

            #endregion

            var documentType = rule.Context.Rules.DocumentType.Context.DocumentType;

            voucher.ReceivingCustomerId       = voucher.Recipient.Partner?.Customer?.Id;
            voucher.ReceivingPostingAccountId = voucher.Recipient.Partner?.DefaultPostingAccountId;

            var strategy = _olmaDbContext.Database.CreateExecutionStrategy();
            var result   = await strategy.ExecuteAsync(operation : async() =>
            {
                await using var ctxTransaction = await _olmaDbContext.Database.BeginTransactionAsync();

                var documentNumber =
                    _numberSequencesService.GetDocumentNumber(documentType, rule.Context.CustomerDivisionId);
                var typeId = _documentTypesService.GetIdByDocumentType(documentType);

                voucher.Document = new Olma.Document()
                {
                    Number             = documentNumber.Result,
                    TypeId             = typeId,
                    StateId            = 1,
                    CustomerDivisionId = rule.Context.CustomerDivisionId,
                    IssuedDateTime     = DateTime.UtcNow,
                    LanguageId         = rule.Context.PrintLanguageId,
                };

                var wrappedResponse = _olmaVoucherRepo.Create <Olma.Voucher, Olma.Voucher, Voucher>(voucher);

                var reportGeneratorServiceResponse = _reportGeneratorService.GenerateReportForLanguage(
                    wrappedResponse.Data.DocumentId,
                    rule.Context.PrintLanguageId,
                    rule.Context.PrintCount - 1,
                    rule.Context.PrintDateTimeOffset);
                if (reportGeneratorServiceResponse.ResultType != ResultType.Created)
                {
                    await ctxTransaction.RollbackAsync();
                    return(new WrappedResponse <Voucher>
                    {
                        ResultType = ResultType.Failed,
                        State = ErrorHandler.Create().AddMessage(new GenerateReportError()).GetServiceState()
                    });
                }

                var downloadLink =
                    (WrappedResponse <string>) await _documentsService.GetDocumentDownload(
                        wrappedResponse.Data.DocumentId, DocumentFileType.Composite);
                if (downloadLink.ResultType != ResultType.Ok)
                {
                    await ctxTransaction.RollbackAsync();
                    return(new WrappedResponse <Voucher>
                    {
                        ResultType = ResultType.Failed,
                        State = ErrorHandler.Create().AddMessage(new DocumentLinkError()).GetServiceState()
                    });
                }
                wrappedResponse.Data.DownloadLink = downloadLink.Data;
                var refLtmsTransactionId          = Guid.NewGuid();

                #region Send Voucher to LTMS

                //Make sure voucher.Position.Loadcarrier is loaded, because RefLtmsPalettId is need when
                //mapping to VoucherCreateSyncRequest
                foreach (var position in voucher.Positions)
                {
                    _olmaDbContext.Entry(position).Reference(c => c.LoadCarrier).Load();
                }

                //Make sure voucher.ReasonType is loaded, because RefLtmsReasonTypeId is needed when mapping to VoucherCreateSyncRequest
                _olmaDbContext.Entry(voucher).Reference(r => r.ReasonType).Load();
                var voucherCreateRequest = Mapper.Map <VoucherCreateSyncRequest>(voucher);
                var voucherSyncRequest   = new VoucherSyncRequest {
                    VoucherCreateSyncRequest = voucherCreateRequest
                };
                voucherSyncRequest.VoucherCreateSyncRequest.RefLtmsTransactionRowGuid = refLtmsTransactionId;
                var synchronizationsServiceResponse =
                    await _synchronizationsService.SendVoucherRequestsAsync(voucherSyncRequest);
                if (synchronizationsServiceResponse.ResultType == ResultType.Failed)
                {
                    await ctxTransaction.RollbackAsync();
                    return(new WrappedResponse <Voucher>
                    {
                        ResultType = ResultType.Failed,
                        State = ErrorHandler.Create().AddMessage(new TechnicalError()).GetServiceState()
                    });
                }

                #endregion

                if (rule.Context.Type == VoucherType.Direct && rule.Context.CustomerDivision != null)
                {
                    var postingRequestsCreateRequest = new PostingRequestsCreateRequest
                    {
                        Type                 = PostingRequestType.Charge, //HACK Only to fix UI, from LTMS W
                        ReferenceNumber      = voucher.Document.Number,
                        Reason               = PostingRequestReason.Voucher,
                        VoucherId            = wrappedResponse.Data.Id,
                        RefLtmsProcessId     = Guid.NewGuid(),
                        RefLtmsProcessTypeId = (int)RefLtmsProcessType.DirectBooking,
                        RefLtmsTransactionId = refLtmsTransactionId,
                        // ReSharper disable once PossibleInvalidOperationException -> secured by rule
                        PostingAccountId = rule.Context.CustomerDivision.PostingAccountId.Value,
                        // ReSharper disable once PossibleInvalidOperationException -> secured by rule
                        SourceRefLtmsAccountId =
                            (int)voucher.Recipient.Partner?.DefaultPostingAccount.RefLtmsAccountId,
                        DestinationRefLtmsAccountId =
                            rule.Context.CustomerDivision.PostingAccount.RefLtmsAccountId,
                        Positions = voucher.Positions.Select(v => new PostingRequestPosition()
                        {
                            LoadCarrierId       = v.LoadCarrierId,
                            LoadCarrierQuantity = v.LoadCarrierQuantity
                        }),
                        Note        = voucher.Shipper?.CompanyName,
                        DigitalCode = digitalCode
                    };

                    var postingRequestsServiceResponse =
                        (IWrappedResponse <IEnumerable <PostingRequest> >) await _postingRequestsService.Create(
                            postingRequestsCreateRequest);

                    if (postingRequestsServiceResponse.ResultType != ResultType.Created)
                    {
                        await ctxTransaction.RollbackAsync();
                        return(new WrappedResponse <Voucher>
                        {
                            ResultType = ResultType.Failed,
                            State = ErrorHandler.Create().AddMessage(new TechnicalError()).GetServiceState()
                        });
                    }
                }
                await ctxTransaction.CommitAsync();

                return(wrappedResponse);
            });

            return(result);
        }