Example #1
0
 public ContextModel(LoadCarrierReceiptsCreateRequest parent, MainRule rule) : base(parent, rule)
 {
 }
Example #2
0
            public RulesBundle(ContextModel context, MainRule rule)
            {
                CustomerDivisionAuthorizationRule = new ResourceAuthorizationRule <
                    Olma.CustomerDivision,
                    CanCreateLoadCarrierReceiptRequirement,
                    DivisionPermissionResource>(context.Request.CustomerDivisionId, rule)
                                                    .Include(customerDivision => customerDivision.PostingAccount);

                LicensePlateCountryIdRequired = new ValidOperatorRule <ContextModel>(context,
                                                                                     model => model.Request.LicensePlateCountryId > 0,
                                                                                     new NotAllowedByRule(),
                                                                                     parentRule: rule,
                                                                                     ruleName: nameof(LicensePlateCountryIdRequired));

                TruckDriverNameRequired = new ValidOperatorRule <ContextModel>(context,
                                                                               model => !string.IsNullOrEmpty(model.Request.TruckDriverName),
                                                                               new NotAllowedByRule(),
                                                                               parentRule: rule,
                                                                               ruleName: nameof(TruckDriverNameRequired));

                LicensePlateRequired = new ValidOperatorRule <ContextModel>(context,
                                                                            model => !string.IsNullOrEmpty(model.Request.LicensePlate),
                                                                            new NotAllowedByRule(),
                                                                            parentRule: rule,
                                                                            ruleName: nameof(LicensePlateRequired));

                PositionsValid = new ValidOperatorRule <ContextModel>(context,
                                                                      model =>
                                                                      model.Request.Positions.Any() &&
                                                                      model.Request.Positions.All(p => p.Quantity > 0),
                                                                      new NotAllowedByRule(),
                                                                      parentRule: rule,
                                                                      ruleName: nameof(PositionsValid));

                MoreInformationValid = new ValidOperatorRule <ContextModel>(context,
                                                                            model =>
                {
                    if (context.Request.DigitalCode != null)
                    {
                        return(true);
                    }

                    switch (context.Request.Type)
                    {
                    case LoadCarrierReceiptType.Delivery:
                        return(!string.IsNullOrEmpty(model.Request.DeliveryNoteNumber));

                    case LoadCarrierReceiptType.Pickup:
                        return(!string.IsNullOrEmpty(model.Request.PickUpNoteNumber));

                    case LoadCarrierReceiptType.Exchange:
                    default:
                        return(true);
                    }
                },
                                                                            new NotAllowedByRule(),
                                                                            parentRule: rule,
                                                                            ruleName: nameof(MoreInformationValid));

                DigitalCodePristine = new ValidOperatorRule <ContextModel>(
                    condition: ctx => !string.IsNullOrWhiteSpace(ctx.Request.DigitalCode),
                    context,
                    model =>
                {
                    var expressCodeRepository = rule.ServiceProvider.GetService <IRepository <Olma.ExpressCode> >();
                    var expressCodeExists     = expressCodeRepository.FindAll()
                                                .Any(code => code.DigitalCode == context.Request.DigitalCode);

                    if (expressCodeExists)
                    {
                        return(true);
                    }

                    var repository = rule.ServiceProvider.GetService <IRepository <Olma.LoadCarrierReceipt> >();
                    var exists     = repository
                                     .Exists(loadCarrierReceipt => loadCarrierReceipt.DigitalCode == context.Request.DigitalCode &&
                                             loadCarrierReceipt.Type == context.Request.Type &&
                                             !loadCarrierReceipt.Document.State.IsCanceled);

                    return(!exists);
                },
                    new DigitalCodeAlreadyUsed(),
                    parentRule: rule,
                    ruleName: nameof(DigitalCodePristine));

                BlacklistTerms = new BlacklistTermsRule(context, rule);
            }
        /// <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);
        }