public InvoiceResponse Delete(Guid identifier) { InvoiceResponse response = new InvoiceResponse(); using (SqliteConnection db = new SqliteConnection("Filename=SirmiumERPGFC.db")) { db.Open(); SqliteCommand insertCommand = new SqliteCommand(); insertCommand.Connection = db; //Use parameterized query to prevent SQL injection attacks insertCommand.CommandText = "DELETE FROM Invoices WHERE Identifier = @Identifier"; insertCommand.Parameters.AddWithValue("@Identifier", identifier); try { insertCommand.ExecuteNonQuery(); } catch (SqliteException error) { MainWindow.ErrorMessage = error.Message; response.Success = false; response.Message = error.Message; return(response); } db.Close(); response.Success = true; return(response); } }
public InvoiceResponse GetInvoiceDetails(string invoiceNumber) { using (var scope = _context.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService <InvoiceContext>(); var invoice = db.InvoiceDetails.Where(x => x.InvoiceNumber == invoiceNumber).FirstOrDefault(); var company = db.Company.Where(c => c.Id == invoice.CompanyId).Select(x => new CompanyRequest { CompanyName = x.CompanyName, Address = new Address { City = x.City, State = x.State, Country = x.Country } }).FirstOrDefault(); var customer = db.Customer.Where(c => c.Id == invoice.CustomerId).Select(c => new Models.Customer { CustomerName = c.Name, ShippingDetails = new Address { City = c.City, State = c.State, Country = c.Country } }).FirstOrDefault(); var orderItem = db.OrderDetails.Where(o => o.InvoiceId == invoice.Id).ToList <OrderDetails>(); var productIds = orderItem.Select(p => p.ProuductId).ToArray <int>(); var product = db.Product.Where(p => productIds.Contains(p.Id)).ToList <DataAccess.Models.Product>(); var productItem = product.Join(orderItem, pro => pro.Id, order => order.ProuductId, (pro, order) => new Models.Product { Name = pro.Name, Price = pro.price, Quantity = order.Quantity }).ToList(); var invoiceResponse = new InvoiceResponse { InvoiceDate = invoice.Date, CompanyDetails = company, CustomerDetails = customer, ProductDetails = productItem }; return(invoiceResponse); } }
public static async Task <InvoiceResponse> ProcessInvoice(string myQueueItem, ILogger log, IConfigurationRoot config) { var paymentRequest = JsonConvert.DeserializeObject <InvoiceRequest>(myQueueItem); var requestCustomer = MapToCustomer(paymentRequest); var response = new InvoiceResponse(); try { var greenInvoiceClient = new GreenInvoiceClient(config, log); var customer = await greenInvoiceClient.SaveCustomer(requestCustomer); var invoice = CreateInvoiceReceiptRequest(customer, paymentRequest); response = await greenInvoiceClient.AddInvoice(invoice); } catch (Exception anyException) { log.LogCritical(anyException, "Unable to create customer or invoice."); response.Error = anyException.ToString(); } response.BillingId = paymentRequest.BillingId; response.TenantId = paymentRequest.Tenant.Id; response.UserId = paymentRequest.User.UserId; return(response); }
// POST: api/FileExtractor public async Task <JsonResult <InvoiceResponse> > Post() { string output = string.Empty; var httpRequest = HttpContext.Current.Request; var files = httpRequest.Files; var file = files[0]; var resultPost = new RootObject(); var resList = new List <Field>(); if (file.ContentLength > 0) { resultPost = await GetOcrText(file); } if (resultPost != null) { resList = resultPost.data.fields; var returnList = _invoiceContext.GetTagDetailIdentifier(resultPost.data.text); resList.AddRange(returnList); } var res = new InvoiceResponse { fields = resList }; return(Json(res)); }
/// <summary> /// Determines the payment status of the user from an updated list of invoices from Visma using the the userId and the type of membership the user has. /// </summary> /// <returns> /// <c>True</c> if the user has valid payment status based on information from Visma /// </returns> /// <param name="user">The user to be evaluated by the method</param> /// <param name="invoiceList">An updated list of invoices from Visma.</param> private bool DeterminePaymentStatus(User user, InvoiceResponse invoiceList) { try { // Returns true if the membership is marked as livsvarig if (user.Membership == "Livsvarig") { return(true); } // Finds an invoice from the invoice list with matching userId from the parameters var userInvoice = invoiceList.Data.ToList().Find(x => x.CustomerId.ToString() == user.UserId); // If the user has been issued an invoice this year and the remaining amount is 0 or less the user has valid payment if (userInvoice.DueDate.Year == DateTime.Now.Year && userInvoice.RemainingAmount <= 0) { return(true); } return(false); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, bool DeterminePaymentStatus(User user, InvoiceResponse invoiceList)"); } return(false); }
public override void PrepareInvoiceDto(InvoiceResponse invoiceResponse, InvoiceEntity invoiceEntity, InvoiceCryptoInfo invoiceCryptoInfo, PaymentMethodAccounting accounting, PaymentMethod info) { var scheme = info.Network.UriScheme; var minerInfo = new MinerFeeInfo(); minerInfo.TotalFee = accounting.NetworkFee.Satoshi; minerInfo.SatoshiPerBytes = ((BitcoinLikeOnChainPaymentMethod)info.GetPaymentMethodDetails()).FeeRate .GetFee(1).Satoshi; invoiceResponse.MinerFees.TryAdd(invoiceCryptoInfo.CryptoCode, minerInfo); invoiceCryptoInfo.PaymentUrls = new NBitpayClient.InvoicePaymentUrls() { BIP21 = $"{scheme}:{invoiceCryptoInfo.Address}?amount={invoiceCryptoInfo.Due}", }; #pragma warning disable 618 if (info.CryptoCode == "BTC") { invoiceResponse.BTCPrice = invoiceCryptoInfo.Price; invoiceResponse.Rate = invoiceCryptoInfo.Rate; invoiceResponse.ExRates = invoiceCryptoInfo.ExRates; invoiceResponse.BitcoinAddress = invoiceCryptoInfo.Address; invoiceResponse.BTCPaid = invoiceCryptoInfo.Paid; invoiceResponse.BTCDue = invoiceCryptoInfo.Due; invoiceResponse.PaymentUrls = invoiceCryptoInfo.PaymentUrls; } #pragma warning restore 618 }
public async Task <ActionResult <InvoiceResponse> > Put(int id, [FromBody] InvoiceResponse input, CancellationToken ct = default) { try { if (input == null) { return(BadRequest()); } if (await _chinookSupervisor.GetInvoiceByIdAsync(id, ct) == null) { return(NotFound()); } var errors = JsonConvert.SerializeObject(ModelState.Values .SelectMany(state => state.Errors) .Select(error => error.ErrorMessage)); Debug.WriteLine(errors); if (await _chinookSupervisor.UpdateInvoiceAsync(input, ct)) { return(Ok(input)); } return(StatusCode(500)); } catch (Exception ex) { return(StatusCode(500, ex)); } }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob, IPaymentMethod paymentMethod) { var paymentMethodId = paymentMethod.GetId(); var network = _networkProvider.GetNetwork <ZcashLikeSpecificBtcPayNetwork>(model.CryptoCode); model.PaymentMethodName = GetPaymentMethodName(network); model.CryptoImage = GetCryptoImage(network); if (model.Activated) { var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); model.InvoiceBitcoinUrl = ZcashPaymentType.Instance.GetPaymentLink(network, new ZcashLikeOnChainPaymentMethodDetails() { DepositAddress = cryptoInfo.Address }, cryptoInfo.Due, null); model.InvoiceBitcoinUrlQR = model.InvoiceBitcoinUrl; } else { model.InvoiceBitcoinUrl = ""; model.InvoiceBitcoinUrlQR = ""; } }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob, IPaymentMethod paymentMethod) { var paymentMethodId = paymentMethod.GetId(); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork <BTCPayNetwork>(model.CryptoCode); model.PaymentMethodName = GetPaymentMethodName(network); model.InvoiceBitcoinUrl = cryptoInfo.PaymentUrls?.BOLT11; model.InvoiceBitcoinUrlQR = $"lightning:{cryptoInfo.PaymentUrls?.BOLT11?.ToUpperInvariant()?.Substring("LIGHTNING:".Length)}"; model.PeerInfo = ((LightningLikePaymentMethodDetails)paymentMethod.GetPaymentMethodDetails()).NodeInfo; if (storeBlob.LightningAmountInSatoshi && model.CryptoCode == "BTC") { var satoshiCulture = new CultureInfo(CultureInfo.InvariantCulture.Name); satoshiCulture.NumberFormat.NumberGroupSeparator = " "; model.CryptoCode = "Sats"; model.BtcDue = Money.Parse(model.BtcDue).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.BtcPaid = Money.Parse(model.BtcPaid).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.OrderAmount = Money.Parse(model.OrderAmount).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.NetworkFee = new Money(model.NetworkFee, MoneyUnit.BTC).ToUnit(MoneyUnit.Satoshi); model.Rate = _currencyNameTable.DisplayFormatCurrency(paymentMethod.Rate / 100_000_000, model.InvoiceCurrency); } }
public InvoiceResponse Create(InvoiceViewModel invoice) { InvoiceResponse response = new InvoiceResponse(); using (SqliteConnection db = new SqliteConnection("Filename=SirmiumERPGFC.db")) { db.Open(); SqliteCommand insertCommand = db.CreateCommand(); insertCommand.CommandText = SqlCommandInsertPart; try { insertCommand = AddCreateParameters(insertCommand, invoice); insertCommand.ExecuteNonQuery(); } catch (SqliteException error) { MainWindow.ErrorMessage = error.Message; response.Success = false; response.Message = error.Message; return(response); } db.Close(); response.Success = true; return(response); } }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob) { var paymentMethodId = new PaymentMethodId(model.CryptoCode, PaymentTypes.LightningLike); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork <BTCPayNetwork>(model.CryptoCode); model.IsLightning = true; model.PaymentMethodName = GetPaymentMethodName(network); model.InvoiceBitcoinUrl = cryptoInfo.PaymentUrls.BOLT11; model.InvoiceBitcoinUrlQR = $"lightning:{cryptoInfo.PaymentUrls.BOLT11.ToUpperInvariant().Substring("LIGHTNING:".Length)}"; model.LightningAmountInSatoshi = storeBlob.LightningAmountInSatoshi; if (storeBlob.LightningAmountInSatoshi && model.CryptoCode == "BTC") { var satoshiCulture = new CultureInfo(CultureInfo.InvariantCulture.Name); satoshiCulture.NumberFormat.NumberGroupSeparator = " "; model.CryptoCode = "Sats"; model.BtcDue = Money.Parse(model.BtcDue).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.BtcPaid = Money.Parse(model.BtcPaid).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.OrderAmount = Money.Parse(model.OrderAmount).ToUnit(MoneyUnit.Satoshi).ToString("N0", satoshiCulture); model.NetworkFee = new Money(model.NetworkFee, MoneyUnit.BTC).ToUnit(MoneyUnit.Satoshi); } }
public override void PrepareInvoiceDto(InvoiceResponse invoiceResponse, InvoiceEntity invoiceEntity, InvoiceCryptoInfo invoiceCryptoInfo, PaymentMethodAccounting accounting, PaymentMethod info) { invoiceCryptoInfo.PaymentUrls = new InvoicePaymentUrls() { BOLT11 = $"lightning:{invoiceCryptoInfo.Address}" }; }
public InvoiceResponse Create(InvoiceViewModel invoice) { InvoiceResponse response = new InvoiceResponse(); try { //Backup items List <InvoiceItemViewModel> invoiceItems = invoice .InvoiceItems?.ToList() ?? new List <InvoiceItemViewModel>(); invoice.InvoiceItems = null; Invoice createdInvoice = unitOfWork.GetInvoiceRepository() .Create(invoice.ConvertToInvoice()); // Update items if (invoiceItems != null && invoiceItems.Count > 0) { foreach (InvoiceItemViewModel item in invoiceItems .Where(x => x.ItemStatus == ItemStatus.Added || x.ItemStatus == ItemStatus.Edited)?.ToList() ?? new List <InvoiceItemViewModel>()) { item.Invoice = new InvoiceViewModel() { Id = createdInvoice.Id }; item.ItemStatus = ItemStatus.Submited; var createdItem = unitOfWork.GetInvoiceItemRepository().Create(item.ConvertToInvoiceItem()); } foreach (InvoiceItemViewModel item in invoiceItems .Where(x => x.ItemStatus == ItemStatus.Deleted)?.ToList() ?? new List <InvoiceItemViewModel>()) { item.Invoice = new InvoiceViewModel() { Id = createdInvoice.Id }; unitOfWork.GetInvoiceItemRepository().Create(item.ConvertToInvoiceItem()); unitOfWork.GetInvoiceItemRepository().Delete(item.Identifier); } } unitOfWork.Save(); response.Invoice = createdInvoice.ConvertToInvoiceViewModel(); response.Success = true; } catch (Exception ex) { response.Invoice = new InvoiceViewModel(); response.Success = false; response.Message = ex.Message; } return(response); }
public void TestGetSingleInvoice() { Mock <IDatastore> mockDatastore = new Mock <IDatastore>(); mockDatastore.Setup(_invoiceExpectation).Returns(_jsonData); WhmcsApi instance = new WhmcsApi("User", "Pass", "Website", mockDatastore.Object); InvoiceResponse singleInvoice = instance.GetInvoice(218); Assert.NotNull(singleInvoice); }
public void TestSingleInvoiceItemAmount() { Mock <IDatastore> mockDatastore = new Mock <IDatastore>(); mockDatastore.Setup(_invoiceExpectation).Returns(_jsonData); WhmcsApi instance = new WhmcsApi("User", "Pass", "Website", mockDatastore.Object); InvoiceResponse singleInvoice = instance.GetInvoice(218); Assert.Equal("7.50", singleInvoice.Items.Item.SingleOrDefault().Amount); }
public async Task <JsonResult> Invoice(string cryptoCode, [FromBody] InvoiceCreationOption option) { var n = _networkProvider.GetByCryptoCode(cryptoCode); var invoice = await _invoiceRepository.GetNewInvoice(n, option); var resp = new InvoiceResponse { Invoice = invoice }; return(new JsonResult(resp, _repositoryProvider.GetSerializer(n).Options)); }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob, IPaymentMethod paymentMethod) { var paymentMethodId = paymentMethod.GetId(); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork <EthereumBTCPayNetwork>(model.CryptoCode); model.PaymentMethodName = GetPaymentMethodName(network); model.CryptoImage = GetCryptoImage(network); model.InvoiceBitcoinUrl = ""; model.InvoiceBitcoinUrlQR = cryptoInfo.Address ?? ""; }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse) { var paymentMethodId = new PaymentMethodId(model.CryptoCode, PaymentTypes.BTCLike); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork <BTCPayNetwork>(model.CryptoCode); model.IsLightning = false; model.PaymentMethodName = GetPaymentMethodName(network); model.InvoiceBitcoinUrl = cryptoInfo.PaymentUrls.BIP21; model.InvoiceBitcoinUrlQR = cryptoInfo.PaymentUrls.BIP21; }
public void OneTimeSetUp() { var bpService = appHost.Container.Resolve <BusinessPartnerService>(); starbucksBPResponse = bpService.Post(starbucksBP); microsoftBPResponse = bpService.Post(microsoftBP); var invoiceService = appHost.Container.Resolve <InvoiceService>(); softwareInvoice.CustomerId = starbucksBPResponse.Id; softwareInvoice.VendorId = microsoftBPResponse.Id; softwareInvoiceResponse = invoiceService.Post(softwareInvoice); }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob, IPaymentMethod paymentMethod) { var paymentMethodId = paymentMethod.GetId(); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork <BTCPayNetwork>(model.CryptoCode); model.ShowRecommendedFee = storeBlob.ShowRecommendedFee; model.FeeRate = ((BitcoinLikeOnChainPaymentMethod)paymentMethod.GetPaymentMethodDetails()).GetFeeRate(); model.PaymentMethodName = GetPaymentMethodName(network); var lightningFallback = ""; if (model.Activated && network.SupportLightning && storeBlob.OnChainWithLnInvoiceFallback) { var lightningInfo = invoiceResponse.CryptoInfo.FirstOrDefault(a => a.GetpaymentMethodId() == new PaymentMethodId(model.CryptoCode, PaymentTypes.LightningLike)); if (!string.IsNullOrEmpty(lightningInfo?.PaymentUrls?.BOLT11)) { lightningFallback = "&" + lightningInfo.PaymentUrls.BOLT11 .Replace("lightning:", "lightning=", StringComparison.OrdinalIgnoreCase) .ToUpperInvariant(); } } if (model.Activated) { model.InvoiceBitcoinUrl = (cryptoInfo.PaymentUrls?.BIP21 ?? "") + lightningFallback; model.InvoiceBitcoinUrlQR = (cryptoInfo.PaymentUrls?.BIP21 ?? "") + lightningFallback .Replace("LIGHTNING=", "lightning=", StringComparison.OrdinalIgnoreCase); } else { model.InvoiceBitcoinUrl = ""; model.InvoiceBitcoinUrlQR = ""; } // Most wallets still don't support GROESTLCOIN: schema, so we're leaving this for better days // Ref: https://github.com/btcpayserver/btcpayserver/pull/2060#issuecomment-723828348 //model.InvoiceBitcoinUrlQR = cryptoInfo.PaymentUrls.BIP21 // .Replace("groestlcoin:", "GROESTLCOIN:", StringComparison.OrdinalIgnoreCase) // We're leading the way in Bitcoin community with adding UPPERCASE Bech32 addresses in QR Code if (network.CryptoCode.Equals("BTC", StringComparison.InvariantCultureIgnoreCase) && _bech32Prefix.TryGetValue(model.CryptoCode, out var prefix) && model.BtcAddress.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { model.InvoiceBitcoinUrlQR = model.InvoiceBitcoinUrlQR.Replace( $"{network.NBitcoinNetwork.UriScheme}:{model.BtcAddress}", $"{network.NBitcoinNetwork.UriScheme}:{model.BtcAddress.ToUpperInvariant()}", StringComparison.OrdinalIgnoreCase ); } }
public async Task <IActionResult> Create([FromBody] InvoiceRequest invoiceRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = new InvoiceResponse() { ResponseResult = new ResponseResult(invoiceRequest.RequestHeader.RequestId) }; try { InvoiceRequestDTO dto = GetInvoiceRequestDtoFromRequest(invoiceRequest); result.Reference = new InvoiceReferenceResponse { InvoiceNumber = dto.Id, InvoiceDate = dto.InvoiceDate }; var command = new SubmitInvoiceCommand(dto, JsonConvert.SerializeObject(invoiceRequest), invoiceRequest.GetType().Name); try { var confirmationCode = await _mediator.Send(command); } catch (Exception ex) { throw new Exception(ex.Message); } } catch (Exception e) { result.ResponseResult.Errors = new List <ErrorDetail>() { new ErrorDetail() { ErrorCode = "-1", ErrorMessage = e.Message } }; return(BadRequest(result)); } return(Ok(result)); }
public async Task <IActionResult> GetInvoice([FromRoute] GetInvoiceRequest query) { GetInvoiceQueryResponse result = await _messageManager.SendCommand(new GetInvoiceQuery(query.Id)); if (result.Invoice is null) { return(NotFound("Not found")); } var response = new InvoiceResponse( new InvoiceDto(result.Invoice.Id, result.Invoice.Number, result.Invoice.CreationDate), StatusCodes.Status200OK); return(Ok(response)); }
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse, StoreBlob storeBlob) { var paymentMethodId = new PaymentMethodId(model.CryptoCode, PaymentType); var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId); var network = _networkProvider.GetNetwork <MoneroLikeSpecificBtcPayNetwork>(model.CryptoCode); model.IsLightning = false; model.PaymentMethodName = GetPaymentMethodName(network); model.CryptoImage = GetCryptoImage(network); model.InvoiceBitcoinUrl = MoneroPaymentType.Instance.GetPaymentLink(network, new MoneroLikeOnChainPaymentMethodDetails() { DepositAddress = cryptoInfo.Address }, cryptoInfo.Due, null); model.InvoiceBitcoinUrlQR = model.InvoiceBitcoinUrl; }
public Invoice CreateFromResponse(InvoiceResponse response) { var result = new Invoice { Id = response.Id, CreateAt = response.CreateAt, Name = response.Name, Amount = response.Amount, DueDate = response.DueDate, Category = new Category(), Contacts = new List <Contact>() }; return(result); }
public async Task <ActionResult <InvoiceResponse> > Post([FromBody] InvoiceResponse input, CancellationToken ct = default) { try { if (input == null) { return(BadRequest()); } return(StatusCode(201, await _chinookSupervisor.AddInvoiceAsync(input, ct))); } catch (Exception ex) { return(StatusCode(500, ex)); } }
public InvoiceResponse EntityToDTO() { ServerUrl = ServerUrl ?? ""; InvoiceResponse dto = new InvoiceResponse { Id = Id, OrderId = OrderId, PosData = PosData, CurrentTime = DateTimeOffset.UtcNow, InvoiceTime = InvoiceTime, ExpirationTime = ExpirationTime, BTCPrice = Money.Coins((decimal)(1.0 / Rate)).ToString(), Status = Status, Url = ServerUrl.WithTrailingSlash() + "invoice?id=" + Id, Currency = ProductInformation.Currency, Flags = new Flags() { Refundable = Refundable } }; Populate(ProductInformation, dto); Populate(BuyerInformation, dto); dto.ExRates = new Dictionary <string, double> { { ProductInformation.Currency, Rate } }; dto.PaymentUrls = new InvoicePaymentUrls() { BIP72 = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}&r={ServerUrl.WithTrailingSlash() + ($"i/{Id}")}", BIP72b = $"bitcoin:?r={ServerUrl.WithTrailingSlash() + ($"i/{Id}")}", BIP73 = ServerUrl.WithTrailingSlash() + ($"i/{Id}"), BIP21 = $"bitcoin:{DepositAddress}?amount={GetCryptoDue()}", }; dto.BitcoinAddress = DepositAddress.ToString(); dto.Token = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); //No idea what it is useful for dto.Guid = Guid.NewGuid().ToString(); var paid = Payments.Select(p => p.Output.Value).Sum(); dto.BTCPaid = paid.ToString(); dto.BTCDue = GetCryptoDue().ToString(); dto.ExceptionStatus = ExceptionStatus == null ? new JValue(false) : new JValue(ExceptionStatus); return(dto); }
public string GetInvoice([FromQuery] int invoiceId) { //Create response InvoiceResponse response = new InvoiceResponse(); try { //Get the current user string id = User.FindFirstValue(ClaimTypes.NameIdentifier); List <Invoice> invoices = new List <Invoice>(); //Try to find an invoice matching the user's id and the supplied invoice id Invoice invoice = _context.Invoice .Include(i => i.InvoiceProduct) .ThenInclude(ip => ip.Product) .Where(i => i.InvoiceId == invoiceId && i.UserId.Equals(id)) .FirstOrDefault(); //If invoice was found, add to the list in the response, otherwise set the error message if (invoice != null) { invoices.Add(invoice); response.Invoices = invoices; response.Success = true; } else { response.Success = false; response.ErrorMessage = "This invoice does not exist!"; } } catch (Exception e) { response.Success = false; response.ErrorMessage = e.Message; System.Diagnostics.Debug.WriteLine("ERROR: An error occurred in InvoiceController.cs\n" + e.Message); } //Serialize response and return return(JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); }
public async Task <ActionResult <InvoiceResponse> > GetInvoice(Guid orderCode) { var customerId = getUserMetaData().Id; var invoice = await invoiceService.GetInvoice(orderCode); if (invoice == null) { throw new WWSSException("Order not found", StatusCodes.Status404NotFound); } if (invoice.CustomerId != customerId) { throw new WWSSException("Resource is not available", StatusCodes.Status403Forbidden); } return(Ok(InvoiceResponse.Of(invoice))); }
public InvoiceResponse Create(InvoiceViewModel re) { InvoiceResponse response = new InvoiceResponse(); try { response = WpfApiHandler.SendToApi <InvoiceViewModel, InvoiceResponse>(re, "Create"); } catch (Exception ex) { response.Invoice = new InvoiceViewModel(); response.Success = false; response.Message = ex.Message; } return(response); }
public async Task <LightningInvoice> GetInvoice(string invoiceId, CancellationToken cancellation = default(CancellationToken)) { InvoiceResponse result = null; try { result = await _eclairClient.GetInvoice(invoiceId, cancellation); } catch (EclairClient.EclairApiException ex) when(ex.Error.Error == "Not found" || ex.Error.Error.Contains("Invalid hexadecimal", StringComparison.OrdinalIgnoreCase)) { return(null); } GetReceivedInfoResponse info = null; try { info = await _eclairClient.GetReceivedInfo(invoiceId, null, cancellation); } catch (EclairClient.EclairApiException) { } var parsed = BOLT11PaymentRequest.Parse(result.Serialized, _network); var lnInvoice = new LightningInvoice() { Id = result.PaymentHash, Amount = parsed.MinimumAmount, ExpiresAt = parsed.ExpiryDate, BOLT11 = result.Serialized }; if (DateTimeOffset.UtcNow >= parsed.ExpiryDate) { lnInvoice.Status = LightningInvoiceStatus.Expired; } if (info != null && info.Status.Type == "received") { lnInvoice.AmountReceived = info.Status.Amount; lnInvoice.Status = info.Status.Amount >= parsed.MinimumAmount ? LightningInvoiceStatus.Paid : LightningInvoiceStatus.Unpaid; lnInvoice.PaidAt = info.Status.ReceivedAt; } return(lnInvoice); }