public void Index_CallsReadPaymentService_WithFilter()
        {
            //Arrange
            var filter = new PaymentFilter()
            {
                Amount = 324,
                Take   = 1,
                Skip   = 1
            };
            var payments         = GetTestsPayments();
            var paymentsRepo     = new Mock <IPaymentService>();
            var guestsRepo       = new Mock <IGuestService>();
            var reservationsRepo = new Mock <IReservationService>();

            paymentsRepo.Setup(s => s.ReadPayments(It.Is <PaymentFilter>(f => f.Amount == filter.Amount && f.Take == filter.Take && f.Skip == filter.Skip && f.PayTime == filter.PayTime)))
            .Returns((payments, payments.Count));
            var controller = new PaymentController(paymentsRepo.Object, guestsRepo.Object, reservationsRepo.Object);

            // Act
            var result = controller.Index(null, filter);

            //Assert

            paymentsRepo.Verify(s => s.ReadPayments(filter), Times.Once);
        }
        public (IEnumerable <PaymentViewModel> models, int count) ReadPayments(PaymentFilter filter)
        {
            var(payments, count) = paymentRepository.ReadPayments(filter);
            var paymentModel = mapper.Map <IEnumerable <PaymentViewModel> >(payments);

            return(paymentModel, count);
        }
        protected PaymentFilter GetPaymentsFilter()
        {
            // CREATE CRITERIA INSTANCE
            PaymentFilter criteria = new PaymentFilter();

            if (StartDate.SelectedStartDate > DateTime.MinValue)
            {
                criteria.DateStart = StartDate.SelectedStartDate;
            }
            if (EndDate.SelectedEndDate > DateTime.MinValue && EndDate.SelectedEndDate < DateTime.MaxValue)
            {
                criteria.DateEnd = EndDate.SelectedEndDate;
            }
            criteria.PaymentStatusId  = AlwaysConvert.ToInt16(PaymentStatusFilter.SelectedValue);
            criteria.OrderNumberRange = OrderNumberFilter.Text.Trim();
            criteria.TransactionId    = TransactionIdFilter.Text.Trim();

            List <int> paymentMethodIds = new List <int>();

            foreach (ListItem item in PaymentMethodFilter.Items)
            {
                if (item.Selected)
                {
                    paymentMethodIds.Add(AlwaysConvert.ToInt(item.Value));
                }
            }
            if (paymentMethodIds.Count > 0)
            {
                criteria.PaymentMethodIds = paymentMethodIds.ToArray();
            }

            return(criteria);
        }
Esempio n. 4
0
        internal async Task <InvoiceEntity> CreateInvoiceCoreRaw(CreateInvoiceRequest invoice, StoreData store, string serverUrl, List <string> additionalTags = null, CancellationToken cancellationToken = default)
        {
            var storeBlob = store.GetStoreBlob();
            var entity    = _InvoiceRepository.CreateNewInvoice();

            entity.ExpirationTime       = entity.InvoiceTime + (invoice.Checkout.Expiration ?? storeBlob.InvoiceExpiration);
            entity.MonitoringExpiration = entity.ExpirationTime + (invoice.Checkout.Monitoring ?? storeBlob.MonitoringExpiration);
            if (invoice.Metadata != null)
            {
                entity.Metadata = InvoiceMetadata.FromJObject(invoice.Metadata);
            }
            invoice.Checkout ??= new CreateInvoiceRequest.CheckoutOptions();
            entity.Currency        = invoice.Currency;
            entity.Price           = invoice.Amount;
            entity.SpeedPolicy     = invoice.Checkout.SpeedPolicy ?? store.SpeedPolicy;
            entity.DefaultLanguage = invoice.Checkout.DefaultLanguage;
            IPaymentFilter excludeFilter = null;

            if (invoice.Checkout.PaymentMethods != null)
            {
                var supportedTransactionCurrencies = invoice.Checkout.PaymentMethods
                                                     .Select(c => PaymentMethodId.TryParse(c, out var p) ? p : null)
                                                     .ToHashSet();
                excludeFilter = PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p));
            }
            entity.PaymentTolerance    = invoice.Checkout.PaymentTolerance ?? storeBlob.PaymentTolerance;
            entity.RedirectURLTemplate = invoice.Checkout.RedirectURL?.Trim();
            if (additionalTags != null)
            {
                entity.InternalTags.AddRange(additionalTags);
            }
            return(await CreateInvoiceCoreRaw(entity, store, excludeFilter, cancellationToken));
        }
Esempio n. 5
0
        public void Index([SmartBinder] PaymentFilter filter)
        {
            filter.Session = DbSession;
            var payments = filter.Find();

            PropertyBag["filter"]   = filter;
            PropertyBag["payments"] = payments;
        }
        protected virtual void PaymentFilter_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            PaymentFilter filter = e.Row as PaymentFilter;

            if (filter != null)
            {
                CurrencyInfo info = CurrencyInfo_CuryInfoID.Select(filter.CuryInfoID);
            }
        }
        public async Task <IActionResult> Get([FromQuery] PaymentFilter filter, [FromQuery] EntityOrder order, [FromQuery] PagingParams pagination)
        {
            var list = await paymentRepository.Browse()
                       .AplyFilter(filter)
                       .AplyOrder(order)
                       .ToEntityPaginated(pagination);

            return(Ok(list));
        }
Esempio n. 8
0
        public IPaymentFilter GetExcludedPaymentMethods()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            if (ExcludedPaymentMethods == null || ExcludedPaymentMethods.Length == 0)
            {
                return(PaymentFilter.Never());
            }
            return(PaymentFilter.Any(ExcludedPaymentMethods.Select(p => PaymentFilter.WhereIs(PaymentMethodId.Parse(p))).ToArray()));

#pragma warning restore CS0618 // Type or member is obsolete
        }
Esempio n. 9
0
 public async Task <ActionResult <decimal> > GetSum([FromQuery] PaymentFilter filter)
 {
     return(await _context.Payments
            .Where(x => (!filter.Year.HasValue || filter.Year == -1 || x.TransactionDate.Year == filter.Year) &&
                   (!filter.Month.HasValue || filter.Month == -1 || x.TransactionDate.Month == filter.Month) &&
                   (!filter.Day.HasValue || filter.Day == -1 || x.TransactionDate.Day == filter.Day) &&
                   (!filter.DepartmentId.HasValue || filter.DepartmentId == -1 || x.Vacancy.Recruiter.DepartmentId == filter.DepartmentId) &&
                   (!filter.RecruiterId.HasValue || filter.RecruiterId == -1 || x.Vacancy.RecruiterId == filter.RecruiterId) &&
                   (!filter.CustomerId.HasValue || filter.CustomerId == -1 || x.Vacancy.CustomerId == filter.CustomerId))
            .SumAsync(x => x.Sum));
 }
Esempio n. 10
0
        public static List <PaymentModel> GetPaymentsFiltered(PaymentFilter filter)
        {
            using (var ctx = new DFAppEntities())
            {
                if (filter != null)
                {
                    var q = ctx.Payments.AsQueryable();

                    if (!string.IsNullOrEmpty(filter.Name))
                    {
                        q = q.Where(x => x.Name.ToLower().Contains(filter.Name.ToLower()));
                    }

                    if (filter.ExcludeID != null && filter.ExcludeID.Count() > 0)
                    {
                        q = q.Where(x => !filter.ExcludeID.Contains(x.ID));
                    }

                    if (filter.Active.HasValue)
                    {
                        q = q.Where(x => x.Active == filter.Active);
                    }

                    return(q.Select(x =>
                                    new PaymentModel()
                    {
                        ID = x.ID,
                        Name = x.Name,
                        Description = x.Description,
                        Type = x.Type,
                        Currency = x.Currency,
                        Amount = x.Amount,
                        DueDate = x.DueDate,
                        StopDate = x.StopDate,
                        NumberOfInstallments = x.NumberOfInstallments,
                        InstallmentAmounts = x.InstallmentAmounts,
                        AmountForCompanion = x.AmountForCompanion,
                        InstallmentAmountsForCompanion = x.InstallmentAmountsForCompanion,
                        Active = x.Active,
                        EventID = x.EventID,
                        CostumeID = x.CostumeID,
                        OutfitID = x.OutfitID
                    }
                                    )
                           .OrderBy(x => x.Name)
                           .ToList());
                }

                return(null);
            }
        }
Esempio n. 11
0
        public bool IsSatisfiedBy(Domain.Payments.Payment entity)
        {
            // I'm assuming these field are enough to check if the payment is duplicated.
            var paymentFilter = new PaymentFilter()
            {
                Amount       = entity.Amount,
                CardNumber   = entity.CardNumber,
                CurrencyCode = entity.CurrencyCode,
                CVV          = entity.CVV
            };

            // TODO: Extend ISpecification to support async
            return(_paymentRepository.GetByFilterAsync(paymentFilter).Result == null);
        }
        public void Index_IsNotNull_ViewResultIsNotNull()
        {
            // arrange
            int pageNumber       = 1;
            var filter           = new PaymentFilter();
            var paymentsRepo     = new Mock <IPaymentService>();
            var guestsRepo       = new Mock <IGuestService>();
            var reservationsRepo = new Mock <IReservationService>();
            var controller       = new PaymentController(paymentsRepo.Object, guestsRepo.Object, reservationsRepo.Object);
            // act
            var result = controller.Index(pageNumber, filter);
            //assert
            var res = result as ViewResult;

            Assert.IsNotNull(res);
        }
Esempio n. 13
0
        public virtual Task <Payment> GetByFilterAsync(PaymentFilter paymentFilter)
        {
            Task <Payment> task = new Task <Payment>(() =>
            {
                var entity = _paymentsDbContext.Payments.FirstOrDefault(p =>
                                                                        p.Amount == paymentFilter.Amount &&
                                                                        p.CardNumber == paymentFilter.CardNumber &&
                                                                        p.CurrencyCode == paymentFilter.CurrencyCode &&
                                                                        p.CVV == paymentFilter.CVV);

                return(_mapper.Map <Payment>(entity));
            });

            task.Start();

            return(task);
        }
Esempio n. 14
0
 public IActionResult Index(int?pageNumber, PaymentFilter paymentFilter)
 {
     try
     {
         ViewData["CurrentSort"]     = paymentFilter.SortOrder;
         ViewData["AmountSortParm"]  = String.IsNullOrEmpty(paymentFilter.SortOrder) ? "amount" : "";
         ViewData["PayTimeSortParm"] = paymentFilter.SortOrder == "PayTime" ? "payTime" : "PayTime";
         paymentFilter.Take          = 5;
         pageNumber ??= 1;
         paymentFilter.Skip   = (pageNumber.Value - 1) * paymentFilter.Take;
         var(payments, count) = paymentService.ReadPayments(paymentFilter);
         return(View(PaginatedList <PaymentViewModel> .Create(payments, count, pageNumber.Value, paymentFilter.Take)));
     }
     catch (Exception)
     {
         return(BadRequest());
     }
 }
        public void Search_by_payer_name()
        {
            var payer = DataMother.CreatePayerForBillingDocumentTest();

            payer.Name = "Тестовый плательщик " + payer.Id;
            var payment = new Payment(payer, DateTime.Now, 800);

            session.Save(payment);
            var filter = new PaymentFilter(session)
            {
                SearchText = "Тестовый плательщик " + payer.Id
            };

            session.Flush();
            var payments = filter.Find();

            Assert.That(payments.Count, Is.EqualTo(1));
            Assert.That(payments[0].Id, Is.EqualTo(payment.Id));
        }
Esempio n. 16
0
        public (IEnumerable <Payment>, int) ReadPayments(PaymentFilter filter)
        {
            var query = context.Payments.Include(p => p.Guest).Take(filter.Take).Skip(filter.Skip);

            switch (filter.SortOrder)
            {
            case "amount":
                query = query.OrderBy(p => p.Amount);
                break;

            case "payTime":
                query = query.OrderBy(p => p.PayTime);
                break;

            default:
                query = query.OrderBy(p => p.Id);
                break;
            }
            var payments = query.ToList();

            return(payments, payments.Count);
        }
        public void ReadGuests_Success_ResultIsInstanseOfExpectedTuple()
        {
            //Arrenge
            var filter          = new PaymentFilter();
            var payments        = GetTestsPayments();
            var paymentRepoMock = new Mock <IPaymentRepository>();

            paymentRepoMock.Setup(r => r.ReadPayments(It.Is <PaymentFilter>(f => f.Amount == filter.Amount && f.Take == filter.Take && f.Skip == filter.Skip && f.PayTime == filter.PayTime)))
            .Returns((payments, payments.Count));
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });
            IMapper mapper         = mappingConfig.CreateMapper();
            var     paymentService = new PaymentService(paymentRepoMock.Object, mapper);

            //Act
            var result = paymentService.ReadPayments(filter);

            //Assert
            Assert.IsInstanceOf <(IEnumerable <PaymentViewModel>, int)>(result);
        }
        internal async Task <InvoiceEntity> CreateInvoiceCoreRaw(InvoiceEntity entity, StoreData store, IPaymentFilter?invoicePaymentMethodFilter, string[]?additionalSearchTerms = null, CancellationToken cancellationToken = default)
        {
            InvoiceLogs logs = new InvoiceLogs();

            logs.Write("Creation of invoice starting", InvoiceEventData.EventSeverity.Info);
            var storeBlob = store.GetStoreBlob();

            if (string.IsNullOrEmpty(entity.Currency))
            {
                entity.Currency = storeBlob.DefaultCurrency;
            }
            entity.Currency = entity.Currency.Trim().ToUpperInvariant();
            entity.Price    = Math.Max(0.0m, entity.Price);
            var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(entity.Currency, false);

            if (currencyInfo != null)
            {
                entity.Price = entity.Price.RoundToSignificant(currencyInfo.CurrencyDecimalDigits);
            }
            if (entity.Metadata.TaxIncluded is decimal taxIncluded)
            {
                if (currencyInfo != null)
                {
                    taxIncluded = taxIncluded.RoundToSignificant(currencyInfo.CurrencyDecimalDigits);
                }
                taxIncluded = Math.Max(0.0m, taxIncluded);
                taxIncluded = Math.Min(taxIncluded, entity.Price);
                entity.Metadata.TaxIncluded = taxIncluded;
            }

            var getAppsTaggingStore = _InvoiceRepository.GetAppsTaggingStore(store.Id);

            if (entity.Metadata.BuyerEmail != null)
            {
                if (!EmailValidator.IsEmail(entity.Metadata.BuyerEmail))
                {
                    throw new BitpayHttpException(400, "Invalid email");
                }
                entity.RefundMail = entity.Metadata.BuyerEmail;
            }
            entity.Status = InvoiceStatusLegacy.New;
            HashSet <CurrencyPair> currencyPairsToFetch = new HashSet <CurrencyPair>();
            var rules         = storeBlob.GetRateRules(_NetworkProvider);
            var excludeFilter = storeBlob.GetExcludedPaymentMethods(); // Here we can compose filters from other origin with PaymentFilter.Any()

            if (invoicePaymentMethodFilter != null)
            {
                excludeFilter = PaymentFilter.Or(excludeFilter,
                                                 invoicePaymentMethodFilter);
            }
            foreach (var network in store.GetSupportedPaymentMethods(_NetworkProvider)
                     .Where(s => !excludeFilter.Match(s.PaymentId))
                     .Select(c => _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode))
                     .Where(c => c != null))
            {
                currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, entity.Currency));
                foreach (var paymentMethodCriteria in storeBlob.PaymentMethodCriteria)
                {
                    if (paymentMethodCriteria.Value != null)
                    {
                        currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, paymentMethodCriteria.Value.Currency));
                    }
                }
            }

            var rateRules = storeBlob.GetRateRules(_NetworkProvider);
            var fetchingByCurrencyPair = _RateProvider.FetchRates(currencyPairsToFetch, rateRules, cancellationToken);
            var fetchingAll            = WhenAllFetched(logs, fetchingByCurrencyPair);

            List <ISupportedPaymentMethod> supported = new List <ISupportedPaymentMethod>();
            var paymentMethods = new PaymentMethodDictionary();

            bool noNeedForMethods = entity.Type != InvoiceType.TopUp && entity.Price == 0m;

            if (!noNeedForMethods)
            {
                // This loop ends with .ToList so we are querying all payment methods at once
                // instead of sequentially to improve response time
                foreach (var o in store.GetSupportedPaymentMethods(_NetworkProvider)
                         .Where(s => !excludeFilter.Match(s.PaymentId) &&
                                _paymentMethodHandlerDictionary.Support(s.PaymentId))
                         .Select(c =>
                                 (Handler: _paymentMethodHandlerDictionary[c.PaymentId],
                                  SupportedPaymentMethod: c,
                                  Network: _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode)))
                         .Where(c => c.Network != null)
                         .Select(o =>
                                 (SupportedPaymentMethod: o.SupportedPaymentMethod,
                                  PaymentMethod: CreatePaymentMethodAsync(fetchingByCurrencyPair, o.Handler,
                                                                          o.SupportedPaymentMethod, o.Network, entity, store, logs)))
                         .ToList())
                {
                    var paymentMethod = await o.PaymentMethod;
                    if (paymentMethod == null)
                    {
                        continue;
                    }
                    supported.Add(o.SupportedPaymentMethod);
                    paymentMethods.Add(paymentMethod);
                }

                if (supported.Count == 0)
                {
                    StringBuilder errors = new StringBuilder();
                    if (!store.GetSupportedPaymentMethods(_NetworkProvider).Any())
                    {
                        errors.AppendLine(
                            "Warning: No wallet has been linked to your BTCPay Store. See the following link for more information on how to connect your store and wallet. (https://docs.btcpayserver.org/WalletSetup/)");
                    }
                    foreach (var error in logs.ToList())
                    {
                        errors.AppendLine(error.ToString());
                    }

                    throw new BitpayHttpException(400, errors.ToString());
                }
            }
            entity.SetSupportedPaymentMethods(supported);
            entity.SetPaymentMethods(paymentMethods);
            foreach (var app in await getAppsTaggingStore)
            {
                entity.InternalTags.Add(AppService.GetAppInternalTag(app.Id));
            }

            using (logs.Measure("Saving invoice"))
            {
                entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity, additionalSearchTerms);
            }
            _ = Task.Run(async() =>
            {
                try
                {
                    await fetchingAll;
                }
                catch (AggregateException ex)
                {
                    ex.Handle(e => { logs.Write($"Error while fetching rates {ex}", InvoiceEventData.EventSeverity.Error); return(true); });
                }
                await _InvoiceRepository.AddInvoiceLogs(entity.Id, logs);
            });
            _EventAggregator.Publish(new Events.InvoiceEvent(entity, InvoiceEvent.Created));
            return(entity);
        }
        internal async Task <InvoiceEntity> CreateInvoiceCoreRaw(BitpayCreateInvoiceRequest invoice, StoreData store, string serverUrl, List <string>?additionalTags = null, CancellationToken cancellationToken = default)
        {
            var storeBlob = store.GetStoreBlob();
            var entity    = _InvoiceRepository.CreateNewInvoice();

            entity.ExpirationTime       = invoice.ExpirationTime is DateTimeOffset v ? v : entity.InvoiceTime + storeBlob.InvoiceExpiration;
            entity.MonitoringExpiration = entity.ExpirationTime + storeBlob.MonitoringExpiration;
            if (entity.ExpirationTime - TimeSpan.FromSeconds(30.0) < entity.InvoiceTime)
            {
                throw new BitpayHttpException(400, "The expirationTime is set too soon");
            }
            entity.Metadata.OrderId        = invoice.OrderId;
            entity.Metadata.PosData        = invoice.PosData;
            entity.ServerUrl               = serverUrl;
            entity.FullNotifications       = invoice.FullNotifications || invoice.ExtendedNotifications;
            entity.ExtendedNotifications   = invoice.ExtendedNotifications;
            entity.NotificationURLTemplate = invoice.NotificationURL;
            entity.NotificationEmail       = invoice.NotificationEmail;
            if (additionalTags != null)
            {
                entity.InternalTags.AddRange(additionalTags);
            }
            FillBuyerInfo(invoice, entity);

            var taxIncluded = invoice.TaxIncluded.HasValue ? invoice.TaxIncluded.Value : 0m;
            var price       = invoice.Price;

            entity.Metadata.ItemCode    = invoice.ItemCode;
            entity.Metadata.ItemDesc    = invoice.ItemDesc;
            entity.Metadata.Physical    = invoice.Physical;
            entity.Metadata.TaxIncluded = invoice.TaxIncluded;
            entity.Currency             = invoice.Currency;
            if (price is decimal vv)
            {
                entity.Price = vv;
                entity.Type  = InvoiceType.Standard;
            }
            else
            {
                entity.Price = 0m;
                entity.Type  = InvoiceType.TopUp;
            }

            entity.RedirectURLTemplate   = invoice.RedirectURL ?? store.StoreWebsite;
            entity.RedirectAutomatically =
                invoice.RedirectAutomatically.GetValueOrDefault(storeBlob.RedirectAutomatically);
            entity.RequiresRefundEmail = invoice.RequiresRefundEmail;
            entity.SpeedPolicy         = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy);

            IPaymentFilter?excludeFilter = null;

            if (invoice.PaymentCurrencies?.Any() is true)
            {
                invoice.SupportedTransactionCurrencies ??=
                new Dictionary <string, InvoiceSupportedTransactionCurrency>();
                foreach (string paymentCurrency in invoice.PaymentCurrencies)
                {
                    invoice.SupportedTransactionCurrencies.TryAdd(paymentCurrency,
                                                                  new InvoiceSupportedTransactionCurrency()
                    {
                        Enabled = true
                    });
                }
            }
            if (invoice.SupportedTransactionCurrencies != null && invoice.SupportedTransactionCurrencies.Count != 0)
            {
                var supportedTransactionCurrencies = invoice.SupportedTransactionCurrencies
                                                     .Where(c => c.Value.Enabled)
                                                     .Select(c => PaymentMethodId.TryParse(c.Key, out var p) ? p : null)
                                                     .Where(c => c != null)
                                                     .ToHashSet();
                excludeFilter = PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p));
            }
            entity.PaymentTolerance     = storeBlob.PaymentTolerance;
            entity.DefaultPaymentMethod = invoice.DefaultPaymentMethod;
            entity.RequiresRefundEmail  = invoice.RequiresRefundEmail;
            return(await CreateInvoiceCoreRaw(entity, store, excludeFilter, null, cancellationToken));
        }
Esempio n. 20
0
        public virtual IEnumerable availablePayments()
        {
            PaymentFilter flt = this.filter.Current;
            CABatch       doc = this.Document.Current;

            if (doc == null || doc.CashAccountID == null || doc.Released == true)
            {
                yield break;
            }
            PXSelectBase <ARPayment> paymentSelect = new PXSelectJoin <ARPayment,
                                                                       LeftJoin <CADepositDetail, On <CADepositDetail.origDocType, Equal <ARPayment.docType>,
                                                                                                      And <CADepositDetail.origRefNbr, Equal <ARPayment.refNbr>,
                                                                                                           And <CADepositDetail.tranType, Equal <CATranType.cADeposit> > > >,
                                                                                 LeftJoin <CABatch, On <CABatch.tranType, Equal <CADepositDetail.tranType>,
                                                                                                        And <CABatch.refNbr, Equal <CADepositDetail.refNbr> > >,
                                                                                           InnerJoin <CashAccountDeposit, On <CashAccountDeposit.depositAcctID, Equal <ARPayment.cashAccountID>,
                                                                                                                              And <Where <CashAccountDeposit.paymentMethodID, Equal <ARPayment.paymentMethodID>,
                                                                                                                                          Or <CashAccountDeposit.paymentMethodID, Equal <BQLConstants.EmptyString> > > > > > > >,
                                                                       Where <CashAccountDeposit.accountID, Equal <Current <CABatch.cashAccountID> >,
                                                                              And <ARPayment.docType, NotEqual <ARPaymentType.voidPayment>,
                                                                                   And <ARPayment.docType, NotEqual <ARPaymentType.cashReturn>,
                                                                                        And <ARPayment.released, Equal <boolTrue>,
                                                                                             And <ARPayment.voided, Equal <boolFalse>,
                                                                                                  And <ARPayment.depositAsBatch, Equal <boolTrue>,
                                                                                                       And <ARPayment.depositNbr, IsNull,
                                                                                                            And <ARPayment.depositAfter, LessEqual <Current <CABatch.tranDate> >,
                                                                                                                 And <Where <CADepositDetail.refNbr, IsNull, Or <CABatch.voided, Equal <boolTrue> > > > > > > > > > > >,
                                                                       OrderBy <Asc <ARPayment.docType, Asc <ARPayment.refNbr, Desc <CashAccountDeposit.paymentMethodID> > > > >(this);

            if (flt.CashAccountID.HasValue)
            {
                paymentSelect.WhereAnd <Where <ARPayment.cashAccountID, Equal <Current <PaymentFilter.cashAccountID> > > >();
            }
            if (!String.IsNullOrEmpty(flt.PaymentMethodID))
            {
                paymentSelect.WhereAnd <Where <ARPayment.paymentMethodID, Equal <Current <PaymentFilter.paymentMethodID> > > >();
            }
            ARPayment last = null;

            foreach (PXResult <ARPayment, CADepositDetail, CABatch, CashAccountDeposit> it in paymentSelect.Select())
            {
                ARPayment       payment = it;
                CADepositDetail detail  = it;
                bool            exist   = false;
                if (last != null && last.DocType == payment.DocType && last.RefNbr == payment.RefNbr)
                {
                    continue;                                                                                                   //Skip duplicates
                }
                last = payment;
                //Add filter for CashAccountDeposit.paymentMethodID according to priorities
                foreach (CADepositDetail iDet in this.Details.Select())
                {
                    if (iDet.OrigDocType == payment.DocType && iDet.OrigRefNbr == payment.RefNbr)
                    {
                        exist = true;
                        break;
                    }
                }
                if (exist)
                {
                    continue;
                }

                yield return(it);
            }
        }
Esempio n. 21
0
 public FilterPaymentCommand(PaymentFilter options)
 {
     _options = options;
 }
        public (IEnumerable <Payment>, int) ReadPayments(PaymentFilter filter)
        {
            var payments = new List <Payment>();
            var count    = 0;

            using (var conn = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand();
                cmd.Connection = conn;
                var orderBy = "";
                switch (filter.SortOrder)
                {
                case "amount":
                    orderBy = "Amount";
                    break;

                case "payTime":
                    orderBy = "PayTime";
                    break;

                default:
                    orderBy = "Id";
                    break;
                }

                var selectCmd = $@"SELECT P.*, G.FirstName, G.LastName 
                    FROM Payments P
                      JOIN Guests G
                       ON P.GuestId = G.Id
                    ORDER BY {orderBy}
                    OFFSET {filter.Skip} ROWS
                    FETCH NEXT {filter.Take} ROWS ONLY;
                    SELECT COUNT(*) 
                    FROM Payments;";


                cmd.CommandText = selectCmd;

                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                using (var dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        var p = new Payment();
                        p.Id            = dr.GetInt32("Id");
                        p.GuestId       = dr.GetInt32("GuestId");
                        p.ReservationId = dr.GetInt32("ReservationId");
                        p.Amount        = dr.GetDecimal("Amount");
                        p.PayTime       = dr.GetDateTime("PayTime");
                        p.Guest         = new Guest
                        {
                            FirstName = dr.GetString("FirstName"),
                            LastName  = dr.GetString("LastName")
                        };
                        payments.Add(p);
                    }
                    dr.NextResult();
                    if (dr.Read())
                    {
                        count = dr.GetInt32(0);
                    }
                }
            }
            return(payments, count);
        }
Esempio n. 23
0
        internal async Task <InvoiceEntity> CreateInvoiceCoreRaw(BitpayCreateInvoiceRequest invoice, StoreData store, string serverUrl, List <string> additionalTags = null, CancellationToken cancellationToken = default)
        {
            var storeBlob = store.GetStoreBlob();
            var entity    = _InvoiceRepository.CreateNewInvoice();

            entity.ExpirationTime       = invoice.ExpirationTime is DateTimeOffset v ? v : entity.InvoiceTime + storeBlob.InvoiceExpiration;
            entity.MonitoringExpiration = entity.ExpirationTime + storeBlob.MonitoringExpiration;
            if (entity.ExpirationTime - TimeSpan.FromSeconds(30.0) < entity.InvoiceTime)
            {
                throw new BitpayHttpException(400, "The expirationTime is set too soon");
            }
            invoice.Currency               = invoice.Currency?.Trim().ToUpperInvariant() ?? "USD";
            entity.Metadata.OrderId        = invoice.OrderId;
            entity.Metadata.PosData        = invoice.PosData;
            entity.ServerUrl               = serverUrl;
            entity.FullNotifications       = invoice.FullNotifications || invoice.ExtendedNotifications;
            entity.ExtendedNotifications   = invoice.ExtendedNotifications;
            entity.NotificationURLTemplate = invoice.NotificationURL;
            entity.NotificationEmail       = invoice.NotificationEmail;
            if (additionalTags != null)
            {
                entity.InternalTags.AddRange(additionalTags);
            }
            FillBuyerInfo(invoice, entity);

            var taxIncluded = invoice.TaxIncluded.HasValue ? invoice.TaxIncluded.Value : 0m;

            var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(invoice.Currency, false);

            if (currencyInfo != null)
            {
                int divisibility = currencyInfo.CurrencyDecimalDigits;
                invoice.Price       = invoice.Price.RoundToSignificant(ref divisibility);
                divisibility        = currencyInfo.CurrencyDecimalDigits;
                invoice.TaxIncluded = taxIncluded.RoundToSignificant(ref divisibility);
            }
            invoice.Price               = Math.Max(0.0m, invoice.Price);
            invoice.TaxIncluded         = Math.Max(0.0m, taxIncluded);
            invoice.TaxIncluded         = Math.Min(taxIncluded, invoice.Price);
            entity.Metadata.ItemCode    = invoice.ItemCode;
            entity.Metadata.ItemDesc    = invoice.ItemDesc;
            entity.Metadata.Physical    = invoice.Physical;
            entity.Metadata.TaxIncluded = invoice.TaxIncluded;
            entity.Currency             = invoice.Currency;
            entity.Price = invoice.Price;

            entity.RedirectURLTemplate   = invoice.RedirectURL ?? store.StoreWebsite;
            entity.RedirectAutomatically =
                invoice.RedirectAutomatically.GetValueOrDefault(storeBlob.RedirectAutomatically);
            entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy);

            IPaymentFilter excludeFilter = null;

            if (invoice.PaymentCurrencies?.Any() is true)
            {
                invoice.SupportedTransactionCurrencies ??=
                new Dictionary <string, InvoiceSupportedTransactionCurrency>();
                foreach (string paymentCurrency in invoice.PaymentCurrencies)
                {
                    invoice.SupportedTransactionCurrencies.TryAdd(paymentCurrency,
                                                                  new InvoiceSupportedTransactionCurrency()
                    {
                        Enabled = true
                    });
                }
            }
            if (invoice.SupportedTransactionCurrencies != null && invoice.SupportedTransactionCurrencies.Count != 0)
            {
                var supportedTransactionCurrencies = invoice.SupportedTransactionCurrencies
                                                     .Where(c => c.Value.Enabled)
                                                     .Select(c => PaymentMethodId.TryParse(c.Key, out var p) ? p : null)
                                                     .Where(c => c != null)
                                                     .ToHashSet();
                excludeFilter = PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p));
            }
            entity.PaymentTolerance = storeBlob.PaymentTolerance;
            return(await CreateInvoiceCoreRaw(entity, store, excludeFilter, cancellationToken));
        }
Esempio n. 24
0
 public List <PaymentModel> GetFiltered(PaymentFilter filter)
 {
     return(DB.Payments.GetPaymentsFiltered(filter));
 }
Esempio n. 25
0
        internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(CreateInvoiceRequest invoice, StoreData store, string serverUrl, List <string> additionalTags = null, CancellationToken cancellationToken = default)
        {
            if (!store.HasClaim(Policies.CanCreateInvoice.Key))
            {
                throw new UnauthorizedAccessException();
            }
            InvoiceLogs logs = new InvoiceLogs();

            logs.Write("Creation of invoice starting");
            var entity = new InvoiceEntity
            {
                Version     = InvoiceEntity.Lastest_Version,
                InvoiceTime = DateTimeOffset.UtcNow,
                Networks    = _NetworkProvider
            };

            var getAppsTaggingStore = _InvoiceRepository.GetAppsTaggingStore(store.Id);
            var storeBlob           = store.GetStoreBlob();
            EmailAddressAttribute emailValidator = new EmailAddressAttribute();

            entity.ExpirationTime       = entity.InvoiceTime.AddMinutes(storeBlob.InvoiceExpiration);
            entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration);
            entity.OrderId               = invoice.OrderId;
            entity.ServerUrl             = serverUrl;
            entity.FullNotifications     = invoice.FullNotifications || invoice.ExtendedNotifications;
            entity.ExtendedNotifications = invoice.ExtendedNotifications;

            if (invoice.NotificationURL != null &&
                Uri.TryCreate(invoice.NotificationURL, UriKind.Absolute, out var notificationUri) &&
                (notificationUri.Scheme == "http" || notificationUri.Scheme == "https"))
            {
                entity.NotificationURL = notificationUri.AbsoluteUri;
            }
            entity.NotificationEmail = invoice.NotificationEmail;
            entity.BuyerInformation  = Map <CreateInvoiceRequest, BuyerInformation>(invoice);
            entity.PaymentTolerance  = storeBlob.PaymentTolerance;
            if (additionalTags != null)
            {
                entity.InternalTags.AddRange(additionalTags);
            }
            //Another way of passing buyer info to support
            FillBuyerInfo(invoice.Buyer, entity.BuyerInformation);
            if (entity?.BuyerInformation?.BuyerEmail != null)
            {
                if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail))
                {
                    throw new BitpayHttpException(400, "Invalid email");
                }
                entity.RefundMail = entity.BuyerInformation.BuyerEmail;
            }

            var taxIncluded = invoice.TaxIncluded.HasValue ? invoice.TaxIncluded.Value : 0m;

            var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(invoice.Currency, false);

            if (currencyInfo != null)
            {
                int divisibility = currencyInfo.CurrencyDecimalDigits;
                invoice.Price       = invoice.Price.RoundToSignificant(ref divisibility);
                divisibility        = currencyInfo.CurrencyDecimalDigits;
                invoice.TaxIncluded = taxIncluded.RoundToSignificant(ref divisibility);
            }
            invoice.Price       = Math.Max(0.0m, invoice.Price);
            invoice.TaxIncluded = Math.Max(0.0m, taxIncluded);
            invoice.TaxIncluded = Math.Min(taxIncluded, invoice.Price);

            entity.ProductInformation = Map <CreateInvoiceRequest, ProductInformation>(invoice);


            entity.RedirectURL = invoice.RedirectURL ?? store.StoreWebsite;
            if (!Uri.IsWellFormedUriString(entity.RedirectURL, UriKind.Absolute))
            {
                entity.RedirectURL = null;
            }

            entity.RedirectAutomatically =
                invoice.RedirectAutomatically.GetValueOrDefault(storeBlob.RedirectAutomatically);

            entity.Status      = InvoiceStatus.New;
            entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy);

            HashSet <CurrencyPair> currencyPairsToFetch = new HashSet <CurrencyPair>();
            var rules         = storeBlob.GetRateRules(_NetworkProvider);
            var excludeFilter = storeBlob.GetExcludedPaymentMethods(); // Here we can compose filters from other origin with PaymentFilter.Any()

            if (invoice.SupportedTransactionCurrencies != null && invoice.SupportedTransactionCurrencies.Count != 0)
            {
                var supportedTransactionCurrencies = invoice.SupportedTransactionCurrencies
                                                     .Where(c => c.Value.Enabled)
                                                     .Select(c => PaymentMethodId.TryParse(c.Key, out var p) ? p : null)
                                                     .ToHashSet();
                excludeFilter = PaymentFilter.Or(excludeFilter,
                                                 PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p)));
            }

            foreach (var network in store.GetSupportedPaymentMethods(_NetworkProvider)
                     .Where(s => !excludeFilter.Match(s.PaymentId))
                     .Select(c => _NetworkProvider.GetNetwork(c.PaymentId.CryptoCode))
                     .Where(c => c != null))
            {
                currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, invoice.Currency));
                if (storeBlob.LightningMaxValue != null)
                {
                    currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.LightningMaxValue.Currency));
                }
                if (storeBlob.OnChainMinValue != null)
                {
                    currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.OnChainMinValue.Currency));
                }
            }

            var rateRules = storeBlob.GetRateRules(_NetworkProvider);
            var fetchingByCurrencyPair  = _RateProvider.FetchRates(currencyPairsToFetch, rateRules, cancellationToken);
            var fetchingAll             = WhenAllFetched(logs, fetchingByCurrencyPair);
            var supportedPaymentMethods = store.GetSupportedPaymentMethods(_NetworkProvider)
                                          .Where(s => !excludeFilter.Match(s.PaymentId))
                                          .Select(c =>
                                                  (Handler: (IPaymentMethodHandler)_ServiceProvider.GetService(typeof(IPaymentMethodHandler <>).MakeGenericType(c.GetType())),
                                                   SupportedPaymentMethod: c,
                                                   Network: _NetworkProvider.GetNetwork(c.PaymentId.CryptoCode)))
                                          .Where(c => c.Network != null)
                                          .Select(o =>
                                                  (SupportedPaymentMethod: o.SupportedPaymentMethod,
                                                   PaymentMethod: CreatePaymentMethodAsync(fetchingByCurrencyPair, o.Handler, o.SupportedPaymentMethod, o.Network, entity, store, logs)))
                                          .ToList();
            List <ISupportedPaymentMethod> supported = new List <ISupportedPaymentMethod>();
            var paymentMethods = new PaymentMethodDictionary();

            foreach (var o in supportedPaymentMethods)
            {
                var paymentMethod = await o.PaymentMethod;
                if (paymentMethod == null)
                {
                    continue;
                }
                supported.Add(o.SupportedPaymentMethod);
                paymentMethods.Add(paymentMethod);
            }

            if (supported.Count == 0)
            {
                StringBuilder errors = new StringBuilder();
                errors.AppendLine("Warning: No wallet has been linked to your BTCPay Store. See the following link for more information on how to connect your store and wallet. (https://docs.btcpayserver.org/btcpay-basics/gettingstarted#connecting-btcpay-store-to-your-wallet)");
                foreach (var error in logs.ToList())
                {
                    errors.AppendLine(error.ToString());
                }
                throw new BitpayHttpException(400, errors.ToString());
            }

            entity.SetSupportedPaymentMethods(supported);
            entity.SetPaymentMethods(paymentMethods);
            entity.PosData = invoice.PosData;

            foreach (var app in await getAppsTaggingStore)
            {
                entity.InternalTags.Add(AppService.GetAppInternalTag(app.Id));
            }

            using (logs.Measure("Saving invoice"))
            {
                entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity);
            }
            _ = Task.Run(async() =>
            {
                try
                {
                    await fetchingAll;
                }
                catch (AggregateException ex)
                {
                    ex.Handle(e => { logs.Write($"Error while fetching rates {ex}"); return(true); });
                }
                await _InvoiceRepository.AddInvoiceLogs(entity.Id, logs);
            });
            _EventAggregator.Publish(new Events.InvoiceEvent(entity, 1001, InvoiceEvent.Created));
            var resp = entity.EntityToDTO();

            return(new DataWrapper <InvoiceResponse>(resp)
            {
                Facade = "pos/invoice"
            });
        }
Esempio n. 26
0
 public async Task <IList <Model.Payment> > List(PaymentFilter filter)
 {
     return(await _apiClient.PaymentSdk.List(filter));
 }