Example #1
0
            public RulesBundle(ContextModel context, MainRule rule)
            {
                CustomerDivisionAuthorization =
                    new ResourceAuthorizationRule <
                        Olma.CustomerDivision,
                        CanCreateVoucherRequirement,
                        DivisionPermissionResource>(context.CustomerDivisionId, parentRule: rule)
                    .Include(i => i.PostingAccount);

                IssuerDivisionHasPostingAccount = new ValidOperatorRule <ContextModel>(
                    (ctx) => ctx.Type == VoucherType.Direct,
                    context,
                    ctx => ctx.CustomerDivision.PostingAccount != null,
                    new PostingAccountRequired(),
                    parentRule: rule,
                    nameof(IssuerDivisionHasPostingAccount));

                RecipientHasDefaultPostingAccount = new ValidOperatorRule <ContextModel>(
                    (ctx) => ctx.Type == VoucherType.Direct,
                    context,
                    ctx =>
                {
                    var repository = rule.ServiceProvider.GetService <IRepository <Olma.CustomerPartner> >();

                    var customerPartner = repository.FindByCondition(cp =>
                                                                     cp.RowGuid == ctx.Parent.RecipientGuid &&
                                                                     !cp.IsDeleted)
                                          .IgnoreQueryFilters()
                                          .Include(cp => cp.Partner).ThenInclude(p => p.DefaultPostingAccount)
                                          .FirstOrDefault();

                    return(customerPartner?.Partner?.DefaultPostingAccount != null);
                },
                    new RecipientHasDefaultPostingAccount(),
                    parentRule: rule,
                    nameof(RecipientHasDefaultPostingAccount));

                PrintCountValid = new ValidOperatorRule <ContextModel>(
                    context,
                    ctx => ctx.PrintCount > 0,
                    new NotAllowedByRule(),
                    parentRule: rule,
                    nameof(PrintCountValid));

                DocumentType = new DocumentTypeRule(context, parentRule: rule);

                Voucher = new VoucherRule(context, parentRule: rule);

                LocalizationLanguageValid = new LocalizationLanguageValidRule(context.PrintLanguageId, parentRule: rule);

                BlacklistTerms = new BlacklistTermsRule(context, parentRule: rule);
            }
Example #2
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);
        }