public async Task GIVEN_valid_command_WHEN_Handle_THEN_creates_a_draft_invoice_for_the_customer()
        {
            var command = _fixture
                          .Build <InvoiceCustomerCommand>()
                          .With(_ => _.InvoiceLines, new [] {
                new InvoiceLine {
                    Quantity     = 5,
                    PricePerUnit = 2,
                    TotalAmount  = 10
                }
            })
                          .Create();

            await _sut.Handle(command);

            var state = new InvoiceState {
                Id           = command.Id,
                Date         = command.Date,
                Description  = command.Description,
                CustomerId   = command.CustomerId,
                TotalAmount  = command.TotalAmount,
                InvoiceLines = command.InvoiceLines.Select(_ => new Domain.Invoices.State.InvoiceLine {
                    Quantity     = _.Quantity,
                    TotalAmount  = _.TotalAmount,
                    PricePerUnit = _.PricePerUnit
                }).ToArray(),
                Status = InvoiceStatus.Draft
            };

            A.CallTo(() => _invoiceRepository.Upsert(A <Invoice> .That.HasState(state))).MustHaveHappened();
        }
Esempio n. 2
0
 /// <summary>改变发票状态
 /// </summary>
 /// <param name="saleFilialeId"></param>
 /// <param name="invoiceId"></param>
 /// <param name="invoiceState"></param>
 /// <param name="flag">true 更新订单表的发票状态和发票表的发票状态,false 只更新发票表的发票状态</param>
 /// <param name="clew"></param>
 public static void SetInvoiceState(Guid saleFilialeId, Guid invoiceId, InvoiceState invoiceState, Boolean flag, String clew)
 {
     using (var client = ClientProxy.CreateB2CWcfClient(saleFilialeId))
     {
         client.Instance.SetInvoiceState(Guid.NewGuid(), invoiceId, (Int32)invoiceState, flag, clew);
     }
 }
Esempio n. 3
0
        public async Task <IActionResult> CancelUnpaidPendingInvoice(string id, bool redirect = true)
        {
            var result = await _PaymentRequestService.GetPaymentRequest(id, GetUserId());

            if (result == null)
            {
                return(NotFound());
            }

            var invoices = result.Invoices.Where(requestInvoice =>
                                                 requestInvoice.Status.Equals(InvoiceState.ToString(InvoiceStatus.New),
                                                                              StringComparison.InvariantCulture) && !requestInvoice.Payments.Any());

            if (!invoices.Any())
            {
                return(BadRequest("No unpaid pending invoice to cancel"));
            }

            foreach (var invoice in invoices)
            {
                await _InvoiceRepository.UpdatePaidInvoiceToInvalid(invoice.Id);

                _EventAggregator.Publish(new InvoiceEvent(await _InvoiceRepository.GetInvoice(invoice.Id), 1008,
                                                          InvoiceEvent.MarkedInvalid));
            }

            if (redirect)
            {
                TempData[WellKnownTempData.SuccessMessage] = "Payment cancelled";
                return(RedirectToAction(nameof(ViewPaymentRequest), new { Id = id }));
            }

            return(Ok("Payment cancelled"));
        }
Esempio n. 4
0
 /// <summary>
 /// 设置发票状态
 /// </summary>
 /// <param name="invoiceIdList">发票编号列表</param>
 /// <param name="invoiceState">发票状态</param>
 /// <param name="cancelPersonel">作废申请人</param>
 /// zal 2016-12-27
 public bool BatchSetInvoiceState(List <Guid> invoiceIdList, InvoiceState invoiceState, string cancelPersonel)
 {
     if (invoiceIdList.Count > 0)
     {
         return(_invoiceDao.BatchSetInvoiceState(invoiceIdList, invoiceState, cancelPersonel));
     }
     return(false);
 }
Esempio n. 5
0
 /// <summary>
 /// 设置发票状态
 /// </summary>
 /// <param name="invoiceId">发票编号</param>
 /// <param name="invoiceState">发票状态</param>
 /// <param name="cancelPersonel">作废申请人</param>
 public bool UpdateSetInvoiceState(Guid invoiceId, InvoiceState invoiceState, string cancelPersonel)
 {
     if (invoiceId != Guid.Empty)
     {
         return(_invoiceDao.UpdateSetInvoiceState(invoiceId, invoiceState, cancelPersonel));
     }
     return(false);
 }
Esempio n. 6
0
 bool CanRefund(InvoiceState invoiceState)
 {
     return(invoiceState.Status == InvoiceStatus.Confirmed ||
            invoiceState.Status == InvoiceStatus.Complete ||
            ((invoiceState.Status == InvoiceStatus.Expired || invoiceState.Status == InvoiceStatus.Invalid) &&
             (invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidLate ||
              invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidOver ||
              invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)));
 }
Esempio n. 7
0
 /// <summary>
 /// 根据条件查找发票(分页)
 /// </summary>
 /// <param name="startTime">开始时间</param>
 /// <param name="endTime">结束时间</param>
 /// <param name="isOrderComplete"></param>
 /// <param name="orderNo"> </param>
 /// <param name="invoiceName"> </param>
 /// <param name="invoiceNo"> </param>
 /// <param name="address"> </param>
 /// <param name="invoiceContent"> </param>
 /// <param name="invoiceState">发票状态</param>
 /// <param name="isNeedManual">是否需要手动打印发票</param>
 /// <param name="warehouseId"> </param>
 /// <param name="permissionFilialeId"> </param>
 /// <param name="permissionBranchId"> </param>
 /// <param name="permissionPositionId"> </param>
 /// <param name="invoiceType"></param>
 /// <param name="saleFilialeid"></param>
 /// <param name="pageSize"></param>
 /// <param name="recordCount"></param>
 /// <param name="cancelPersonel"></param>
 /// <param name="pageIndex"></param>
 /// <returns></returns>
 public IList <InvoiceInfo> GetInvoiceListByPage(DateTime startTime, DateTime endTime, bool isOrderComplete,
                                                 string orderNo, string invoiceName, string invoiceNo, string address, string invoiceContent,
                                                 InvoiceState invoiceState, bool isNeedManual, Guid warehouseId, Guid permissionFilialeId,
                                                 Guid permissionBranchId, Guid permissionPositionId, int invoiceType, Guid saleFilialeid, string cancelPersonel, int pageIndex,
                                                 int pageSize, out int recordCount)
 {
     return(_invoiceDao.GetInvoiceListByPage(startTime, endTime, isOrderComplete, orderNo, invoiceName, invoiceNo, address, invoiceContent, invoiceState, isNeedManual, warehouseId,
                                             permissionFilialeId, permissionBranchId, permissionPositionId, invoiceType, saleFilialeid, cancelPersonel, pageIndex, pageSize, out recordCount));
 }
Esempio n. 8
0
        public async Task CanCancelPaymentWhenPossible()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");

                var paymentRequestController = user.GetController <PaymentRequestController>();


                Assert.IsType <NotFoundResult>(await
                                               paymentRequestController.CancelUnpaidPendingInvoice(Guid.NewGuid().ToString(), false));


                var request = new UpdatePaymentRequestViewModel()
                {
                    Title       = "original juice",
                    Currency    = "BTC",
                    Amount      = 1,
                    StoreId     = user.StoreId,
                    Description = "description"
                };
                var response = Assert
                               .IsType <RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result)
                               .RouteValues.First();

                var paymentRequestId = response.Value.ToString();

                var invoiceId = Assert
                                .IsType <OkObjectResult>(await paymentRequestController.PayPaymentRequest(paymentRequestId, false)).Value
                                .ToString();

                var actionResult = Assert
                                   .IsType <RedirectToActionResult>(await paymentRequestController.PayPaymentRequest(response.Value.ToString()));

                Assert.Equal("Checkout", actionResult.ActionName);
                Assert.Equal("Invoice", actionResult.ControllerName);
                Assert.Contains(actionResult.RouteValues, pair => pair.Key == "Id" && pair.Value.ToString() == invoiceId);

                var invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);
                Assert.Equal(InvoiceState.ToString(InvoiceStatus.New), invoice.Status);
                Assert.IsType <OkObjectResult>(await
                                               paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId, false));

                invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);
                Assert.Equal(InvoiceState.ToString(InvoiceStatus.Invalid), invoice.Status);


                Assert.IsType <BadRequestObjectResult>(await
                                                       paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId, false));
            }
        }
        public bool CheckCompatibility(InvoiceState invoiceState)
        {
            switch (invoiceState)
            {
            case InvoiceState.NotPaid:
                return(true);

            default:
                return(false);
            }
        }
Esempio n. 10
0
 private string GetInvoiceCode(InvoiceState isInvoiceState, InvoiceType itInvoiceType)
 {
     try
     {
         return(pDAL.ExecuteScalar("SELECT ISNULL(CAST(MAX(SUBSTRING(InvoiceCode, 9, 4)) AS Int),0) + 1 InvoiceID FROM m_Invoice WHERE SolarDate = '" + pSCL.GetSolarDate('/') + "' AND FK_InvoiceTypeCode = " + (int)itInvoiceType + "AND FK_InvoiceStateCode = " + (int)isInvoiceState).ToString().PadLeft(4, '0'));
     }
     catch
     {
         return(String.Empty);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// 修改发票状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult Change(int id, InvoiceState state)
        {
            var cid = Core.InvoiceManager.Change(id, state);

            if (cid > 0)
            {
                return(Core.ContractManager.UpdateState(cid) ? SuccessJsonResult() : ErrorJsonResult("更新合同发票开具情况失败!"));
            }
            else
            {
                return(ErrorJsonResult("修改发票状态失败!"));
            }
        }
Esempio n. 12
0
        public int Change(int id, InvoiceState state)
        {
            using (var db = GetDbContext())
            {
                var invoice = db.Invoices.Find(id);
                if (invoice == null)
                {
                    return(-1);
                }

                invoice.State = state;
                db.SaveChanges();
                return(invoice.CID);
            }
        }
Esempio n. 13
0
 public OutgoingInvoice(long primaryId, long secondaryId, int orderId, long clientIdentifier,
                        string targetPurse, decimal amount, string description, byte expirationPeriod, InvoiceState state, DateTime creationTime,
                        DateTime updateTime)
 {
     PrimaryId        = primaryId;
     SecondaryId      = secondaryId;
     OrderId          = orderId;
     ClientIdentifier = clientIdentifier;
     TargetPurse      = targetPurse ?? throw new ArgumentNullException(nameof(targetPurse));
     Amount           = amount;
     Description      = description ?? throw new ArgumentNullException(nameof(description));
     ExpirationPeriod = expirationPeriod;
     State            = state;
     CreationTime     = creationTime;
     UpdateTime       = updateTime;
 }
Esempio n. 14
0
 public int Improve(int id, DateTime fillTime, string number, string remark, InvoiceState state)
 {
     using (var db = GetDbContext())
     {
         var invoice = db.Invoices.Find(id);
         if (invoice == null)
         {
             return(-1);
         }
         invoice.FillTime = fillTime;
         invoice.Number   = number;
         invoice.Remark   = remark;
         invoice.State    = state;
         db.SaveChanges();
         return(invoice.CID);
     }
 }
        public InvoiceModel(RequestType type, String value)
        {
            Type = type;
            if (type == RequestType.PDF)
            {
                pathPdfSource = value;
            }
            else
            {
                sourceXmlText = value;
            }

            state             = InvoiceState.added;
            CreatedDate       = DateTime.Now;
            CustomerSendState = CustomerSendState.noSended;
            CustomerAction    = CustomerAction.noAction;
        }
Esempio n. 16
0
 /// <summary>
 ///   下单发票信息
 /// </summary>
 /// <param name="invoiceState">开票方式</param>
 /// <param name="invoiceType">
 ///   发票类型
 ///   <para>当 <paramref name="invoiceType"/> 为 <see cref="InvoiceType.VAT"/>
 ///   增值税专用发票时,开票方式 <paramref name="invoiceState"/> 只支持
 ///   <see cref="InvoiceState.Centralized"/> 集中开票)</para>
 /// </param>
 /// <param name="selectedInvoiceTitle">发票类型</param>
 /// <param name="invoiceContent">发票内容</param>
 /// <param name="invoicePhone">收票人电话</param>
 /// <param name="regCompanyName">专票资质公司名称</param>
 /// <param name="regCode">专票资质纳税人识别号</param>
 /// <param name="companyName">
 ///   发票抬头
 ///   <para>如果 <paramref name="selectedInvoiceTitle"/> 为
 ///   <see cref="InvoiceTitle.Company"/> 时此字段必须</para>
 /// </param>
 public OrderInvoice(
     InvoiceState invoiceState, InvoiceType invoiceType,
     InvoiceTitle selectedInvoiceTitle, InvoiceContent invoiceContent,
     string invoicePhone, string regCompanyName, string regCode,
     string companyName = default)
 {
     this.KV = new Dictionary <string, string>
     {
         { "invoiceState", ((int)invoiceState).ToString() },
         { "invoiceType", ((int)invoiceType).ToString() },
         { "selectedInvoiceTitle", ((int)selectedInvoiceTitle).ToString() },
         { "invoiceContent", ((int)invoiceContent).ToString() },
         { "companyName", companyName },
         { "invoicePhone", invoicePhone },
         { "regCompanyName", regCompanyName },
         { "regCode", regCode },
     };
 }
Esempio n. 17
0
        private async Task <InvoiceEntity[]> GetInvoicesForApp(AppData appData, DateTime?startDate = null)
        {
            var invoices = await _InvoiceRepository.GetInvoices(new InvoiceQuery()
            {
                StoreId = new[] { appData.StoreData.Id },
                OrderId = appData.TagAllInvoices ? null : new[] { GetCrowdfundOrderId(appData.Id) },
                Status  = new string[] {
                    InvoiceState.ToString(InvoiceStatus.New),
                    InvoiceState.ToString(InvoiceStatus.Paid),
                    InvoiceState.ToString(InvoiceStatus.Confirmed),
                    InvoiceState.ToString(InvoiceStatus.Complete)
                },
                StartDate = startDate
            });

            // Old invoices may have invoices which were not tagged
            invoices = invoices.Where(inv => inv.Version < InvoiceEntity.InternalTagSupport_Version ||
                                      inv.InternalTags.Contains(GetAppInternalTag(appData.Id))).ToArray();
            return(invoices);
        }
Esempio n. 18
0
 public String GenerateInvoiceCode(InvoiceState isInvoiceState, InvoiceType itInvoiceType)
 {
     try
     {
         string strNNNN = GetInvoiceCode(isInvoiceState, itInvoiceType);
         if (strNNNN == string.Empty)
         {
             return(string.Empty);
         }
         string strRRR         = ((int)itInvoiceType).ToString() + ((int)isInvoiceState).ToString().PadLeft(2, '0');
         string strYY          = pBFL.GetSolarDate().Trim().Substring(2, 2).Trim();
         string strDDD         = pBFL.GetSolarDayOfYear().ToString().PadLeft(3, '0');
         String strInvoiceCode = strYY + strDDD + strRRR + strNNNN;
         return(strInvoiceCode);
     }
     catch
     {
         return(String.Empty);
     }
 }
Esempio n. 19
0
        internal override void Fill(WmXmlPackage wmXmlPackage)
        {
            if (null == wmXmlPackage)
            {
                throw new ArgumentNullException(nameof(wmXmlPackage));
            }

            Id          = wmXmlPackage.SelectUInt32("invoice/@id");
            Ts          = wmXmlPackage.SelectUInt32("invoice/@ts");
            OrderId     = wmXmlPackage.SelectUInt32("invoice/orderid");
            SourceWmId  = wmXmlPackage.SelectWmId("invoice/customerwmid");
            TargetPurse = wmXmlPackage.SelectPurse("invoice/storepurse");
            Amount      = wmXmlPackage.SelectAmount("invoice/amount");
            Description = (Description)wmXmlPackage.SelectString("invoice/desc");
            Address     = (Description)wmXmlPackage.SelectString("invoice/address");
            Period      = wmXmlPackage.SelectUInt8("invoice/period");
            Expiration  = wmXmlPackage.SelectUInt8("invoice/expiration");
            State       = (InvoiceState)wmXmlPackage.SelectInt32("invoice/state");
            CreateTime  = wmXmlPackage.SelectWmDateTime("invoice/datecrt");
            UpdateTime  = wmXmlPackage.SelectWmDateTime("invoice/dateupd");
        }
Esempio n. 20
0
        // https://github.com/harvesthq/api/blob/master/Sections/Invoices.md

        /// <summary>
        /// Retrieve a list of invoices from the authenticated account. Makes a GET request to the Invoices resource.
        /// </summary>
        /// <param name="page">The page to retrieve (1-based)</param>
        /// <param name="from">The earliest date of invoices to retrieve</param>
        /// <param name="to">The latest date of invoices to retrieve</param>
        /// <param name="updatedSince">The earliest update date of invoices to retrieve</param>
        /// <param name="status">The status of invoices to retrieve</param>
        /// <param name="clientId">The client ID of invoices to retrieve</param>
        public IList<Invoice> ListInvoices(int page = 1, DateTime? from = null, DateTime? to = null, DateTime? updatedSince = null, InvoiceState? status = null, long? clientId = null)
        {
            var request = Request("invoices");

            if (page > 1)
                request.AddParameter("page", page);

            if (from != null)
                request.AddParameter("from", from.Value.ToString("yyyyMMdd"));
            if (to != null)
                request.AddParameter("to", to.Value.ToString("yyyyMMdd"));

            if (updatedSince != null)
                request.AddParameter("updated_since", updatedSince.Value.ToString("yyyy-MM-dd HH:mm"));

            if (status != null)
                request.AddParameter("status", status.Value.ToString().ToLower());

            if (clientId != null)
                request.AddParameter("client", clientId.Value);

            return Execute<List<Invoice>>(request);
        }
Esempio n. 21
0
 /// <summary>更新B2C发票状态
 /// </summary>
 /// <param name="saleFilialeId">销售公司ID</param>
 /// <param name="invoiceId">发票ID</param>
 /// <param name="invoiceState">发票状态</param>
 /// <param name="flag">true 更新订单表的发票状态和发票表的发票状态,false 只更新发票表的发票状态</param>
 /// <param name="clew">备注</param>
 internal void SyncSetInvoiceState(Guid saleFilialeId, Guid invoiceId, InvoiceState invoiceState, Boolean flag, String clew)
 {
     InvoiceSao.SetInvoiceState(saleFilialeId, invoiceId, invoiceState, flag, clew);
 }
Esempio n. 22
0
        async Task Notify(InvoiceEntity invoice, InvoiceEvent invoiceEvent, bool extendedNotification, bool sendMail)
        {
            var dto          = invoice.EntityToDTO();
            var notification = new InvoicePaymentNotificationEventWrapper()
            {
                Data = new InvoicePaymentNotification()
                {
                    Id              = dto.Id,
                    Currency        = dto.Currency,
                    CurrentTime     = dto.CurrentTime,
                    ExceptionStatus = dto.ExceptionStatus,
                    ExpirationTime  = dto.ExpirationTime,
                    InvoiceTime     = dto.InvoiceTime,
                    PosData         = dto.PosData,
                    Price           = dto.Price,
                    Status          = dto.Status,
                    BuyerFields     = invoice.RefundMail == null ? null : new Newtonsoft.Json.Linq.JObject()
                    {
                        new JProperty("buyerEmail", invoice.RefundMail)
                    },
                    PaymentSubtotals = dto.PaymentSubtotals,
                    PaymentTotals    = dto.PaymentTotals,
                    AmountPaid       = dto.AmountPaid,
                    ExchangeRates    = dto.ExchangeRates,
                    OrderId          = dto.OrderId
                },
                Event = new InvoicePaymentNotificationEvent()
                {
                    Code = (int)invoiceEvent.EventCode,
                    Name = invoiceEvent.Name
                },
                ExtendedNotification = extendedNotification,
                NotificationURL      = invoice.NotificationURL?.AbsoluteUri
            };

            // For lightning network payments, paid, confirmed and completed come all at once.
            // So despite the event is "paid" or "confirmed" the Status of the invoice is technically complete
            // This confuse loggers who think their endpoint get duplicated events
            // So here, we just override the status expressed by the notification
            if (invoiceEvent.Name == InvoiceEvent.Confirmed)
            {
                notification.Data.Status = InvoiceState.ToString(InvoiceStatusLegacy.Confirmed);
            }
            if (invoiceEvent.Name == InvoiceEvent.PaidInFull)
            {
                notification.Data.Status = InvoiceState.ToString(InvoiceStatusLegacy.Paid);
            }
            //////////////////

            // We keep backward compatibility with bitpay by passing BTC info to the notification
            // we don't pass other info, as it is a bad idea to use IPN data for logic processing (can be faked)
            var btcCryptoInfo = dto.CryptoInfo.FirstOrDefault(c => c.GetpaymentMethodId() == new PaymentMethodId("BTC", Payments.PaymentTypes.BTCLike) && !string.IsNullOrEmpty(c.Address));

            if (btcCryptoInfo != null)
            {
#pragma warning disable CS0618
                notification.Data.Rate     = dto.Rate;
                notification.Data.Url      = dto.Url;
                notification.Data.BTCDue   = dto.BTCDue;
                notification.Data.BTCPaid  = dto.BTCPaid;
                notification.Data.BTCPrice = dto.BTCPrice;
#pragma warning restore CS0618
            }

            if (sendMail && !String.IsNullOrEmpty(invoice.NotificationEmail))
            {
                var json  = NBitcoin.JsonConverters.Serializer.ToString(notification);
                var store = await _StoreRepository.FindStore(invoice.StoreId);

                var storeName = store.StoreName ?? "BTCPay Server";
                var emailBody = $"Store: {storeName}<br>" +
                                $"Invoice ID: {notification.Data.Id}<br>" +
                                $"Status: {notification.Data.Status}<br>" +
                                $"Amount: {notification.Data.Price} {notification.Data.Currency}<br>" +
                                $"<br><details><summary>Details</summary><pre>{json}</pre></details>";

                (await _EmailSenderFactory.GetEmailSender(invoice.StoreId)).SendEmail(
                    invoice.NotificationEmail,
                    $"{storeName} Invoice Notification - ${invoice.StoreId}",
                    emailBody);
            }

            if (invoice.NotificationURL != null)
            {
                _Queue.Enqueue(invoice.Id, (cancellationToken) => NotifyHttp(new ScheduledJob()
                {
                    TryCount = 0, Notification = notification
                }, cancellationToken));
            }
        }
Esempio n. 23
0
 /// <summary>
 /// 根据条件查找发票
 /// </summary>
 /// <param name="startTime">开始时间</param>
 /// <param name="endTime">结束时间</param>
 /// <param name="isOrderComplete"></param>
 /// <param name="orderNo"></param>
 /// <param name="invoiceName"></param>
 /// <param name="invoiceNo"></param>
 /// <param name="address"></param>
 /// <param name="invoiceContent"></param>
 /// <param name="invoiceState">发票状态</param>
 /// <param name="isNeedManual">是否需要手动打印发票</param>
 /// <param name="warehouseIds"></param>
 /// <param name="invoiceType"></param>
 /// <param name="saleFilialeId"></param>
 /// <param name="cancelPersonnel"></param>
 /// <returns></returns>
 public IList <InvoiceInfo> GetInvoiceList(DateTime startTime, DateTime endTime, bool isOrderComplete, string orderNo, string invoiceName, string invoiceNo, string address, string invoiceContent, InvoiceState invoiceState, bool isNeedManual, IEnumerable <Guid> warehouseIds, int invoiceType, Guid saleFilialeId, string cancelPersonnel)
 {
     return(_invoiceDao.GetInvoiceList(startTime, endTime, isOrderComplete, orderNo, invoiceName, invoiceNo, address, invoiceContent, invoiceState, isNeedManual, warehouseIds, invoiceType, saleFilialeId, cancelPersonnel));
 }
Esempio n. 24
0
        public ActionResult ImproveInvoice(int id, DateTime fillTime, string number, string remark, InvoiceState state)
        {
            var cid = Core.InvoiceManager.Improve(id, fillTime, number, remark, state);

            if (cid > 0)
            {
                return(Core.ContractManager.UpdateState(cid) ? SuccessJsonResult() : ErrorJsonResult("更新合同发票开具情况失败!"));
            }
            else
            {
                return(ErrorJsonResult("补充信息失败!"));
            }
        }
Esempio n. 25
0
        public async Task CanCancelPaymentWhenPossible()
        {
            using var tester = CreateServerTester();
            await tester.StartAsync();

            var user = tester.NewAccount();

            user.GrantAccess();
            user.RegisterDerivationScheme("BTC");

            var paymentRequestController = user.GetController <UIPaymentRequestController>();

            Assert.IsType <NotFoundResult>(await
                                           paymentRequestController.CancelUnpaidPendingInvoice(Guid.NewGuid().ToString(), false));

            var request = new UpdatePaymentRequestViewModel()
            {
                Title       = "original juice",
                Currency    = "BTC",
                Amount      = 1,
                StoreId     = user.StoreId,
                Description = "description"
            };
            var response = Assert
                           .IsType <RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result)
                           .RouteValues.Last();
            var invoiceId = response.Value.ToString();
            await paymentRequestController.PayPaymentRequest(invoiceId, false);

            Assert.IsType <BadRequestObjectResult>(await
                                                   paymentRequestController.CancelUnpaidPendingInvoice(invoiceId, false));

            request.AllowCustomPaymentAmounts = true;

            response = Assert
                       .IsType <RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result)
                       .RouteValues.Last();

            var paymentRequestId = response.Value.ToString();

            invoiceId = Assert
                        .IsType <OkObjectResult>(await paymentRequestController.PayPaymentRequest(paymentRequestId, false))
                        .Value
                        .ToString();

            var actionResult = Assert
                               .IsType <RedirectToActionResult>(
                await paymentRequestController.PayPaymentRequest(response.Value.ToString()));

            Assert.Equal("Checkout", actionResult.ActionName);
            Assert.Equal("UIInvoice", actionResult.ControllerName);
            Assert.Contains(actionResult.RouteValues,
                            pair => pair.Key == "Id" && pair.Value.ToString() == invoiceId);

            var invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);

            Assert.Equal(InvoiceState.ToString(InvoiceStatusLegacy.New), invoice.Status);
            Assert.IsType <OkObjectResult>(await
                                           paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId, false));

            invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);
            Assert.Equal(InvoiceState.ToString(InvoiceStatusLegacy.Invalid), invoice.Status);

            Assert.IsType <BadRequestObjectResult>(await
                                                   paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId, false));

            invoiceId = Assert
                        .IsType <OkObjectResult>(await paymentRequestController.PayPaymentRequest(paymentRequestId, false))
                        .Value
                        .ToString();

            await user.BitPay.GetInvoiceAsync(invoiceId, Facade.Merchant);

            //a hack to generate invoices for the payment request is to manually create an invoice with an order id that matches:
            user.BitPay.CreateInvoice(new Invoice(1, "USD")
            {
                OrderId = PaymentRequestRepository.GetOrderIdForPaymentRequest(paymentRequestId)
            });
            //shouldn't crash
            await paymentRequestController.ViewPaymentRequest(paymentRequestId);

            await paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId);
        }
Esempio n. 26
0
        void Notify(InvoiceEntity invoice, InvoiceEvent invoiceEvent, bool extendedNotification)
        {
            var dto          = invoice.EntityToDTO(_NetworkProvider);
            var notification = new InvoicePaymentNotificationEventWrapper()
            {
                Data = new InvoicePaymentNotification()
                {
                    Id              = dto.Id,
                    Currency        = dto.Currency,
                    CurrentTime     = dto.CurrentTime,
                    ExceptionStatus = dto.ExceptionStatus,
                    ExpirationTime  = dto.ExpirationTime,
                    InvoiceTime     = dto.InvoiceTime,
                    PosData         = dto.PosData,
                    Price           = dto.Price,
                    Status          = dto.Status,
                    BuyerFields     = invoice.RefundMail == null ? null : new Newtonsoft.Json.Linq.JObject()
                    {
                        new JProperty("buyerEmail", invoice.RefundMail)
                    },
                    PaymentSubtotals = dto.PaymentSubtotals,
                    PaymentTotals    = dto.PaymentTotals,
                    AmountPaid       = dto.AmountPaid,
                    ExchangeRates    = dto.ExchangeRates,
                },
                Event = new InvoicePaymentNotificationEvent()
                {
                    Code = invoiceEvent.EventCode,
                    Name = invoiceEvent.Name
                },
                ExtendedNotification = extendedNotification,
                NotificationURL      = invoice.NotificationURL
            };

            // For lightning network payments, paid, confirmed and completed come all at once.
            // So despite the event is "paid" or "confirmed" the Status of the invoice is technically complete
            // This confuse loggers who think their endpoint get duplicated events
            // So here, we just override the status expressed by the notification
            if (invoiceEvent.Name == InvoiceEvent.Confirmed)
            {
                notification.Data.Status = InvoiceState.ToString(InvoiceStatus.Confirmed);
            }
            if (invoiceEvent.Name == InvoiceEvent.PaidInFull)
            {
                notification.Data.Status = InvoiceState.ToString(InvoiceStatus.Paid);
            }
            //////////////////

            // We keep backward compatibility with bitpay by passing BTC info to the notification
            // we don't pass other info, as it is a bad idea to use IPN data for logic processing (can be faked)
            var btcCryptoInfo = dto.CryptoInfo.FirstOrDefault(c => c.GetpaymentMethodId() == new PaymentMethodId("BTC", Payments.PaymentTypes.BTCLike));

            if (btcCryptoInfo != null)
            {
#pragma warning disable CS0618
                notification.Data.Rate     = dto.Rate;
                notification.Data.Url      = dto.Url;
                notification.Data.BTCDue   = dto.BTCDue;
                notification.Data.BTCPaid  = dto.BTCPaid;
                notification.Data.BTCPrice = dto.BTCPrice;
#pragma warning restore CS0618
            }

            CancellationTokenSource cts = new CancellationTokenSource(10000);

            if (!String.IsNullOrEmpty(invoice.NotificationEmail))
            {
                var emailBody = NBitcoin.JsonConverters.Serializer.ToString(notification);

                _EmailSenderFactory.GetEmailSender(invoice.StoreId).SendEmail(
                    invoice.NotificationEmail,
                    $"BtcPayServer Invoice Notification - ${invoice.StoreId}",
                    emailBody);
            }
            if (string.IsNullOrEmpty(invoice.NotificationURL) || !Uri.IsWellFormedUriString(invoice.NotificationURL, UriKind.Absolute))
            {
                return;
            }
            var invoiceStr = NBitcoin.JsonConverters.Serializer.ToString(new ScheduledJob()
            {
                TryCount = 0, Notification = notification
            });
            if (!string.IsNullOrEmpty(invoice.NotificationURL))
            {
                _JobClient.Schedule(() => NotifyHttp(invoiceStr), TimeSpan.Zero);
            }
        }
        public async Task <IActionResult> CancelUnpaidPendingInvoice(string id, bool redirect = true)
        {
            var result = await _PaymentRequestService.GetPaymentRequest(id, GetUserId());

            if (result == null)
            {
                return(NotFound());
            }

            var invoice = result.Invoices.SingleOrDefault(requestInvoice =>
                                                          requestInvoice.Status.Equals(InvoiceState.ToString(InvoiceStatus.New), StringComparison.InvariantCulture) && !requestInvoice.Payments.Any());

            if (invoice == null)
            {
                return(BadRequest("No hay factura pendiente de pagar para cancelar"));
            }

            await _InvoiceRepository.UpdatePaidInvoiceToInvalid(invoice.Id);

            _EventAggregator.Publish(new InvoiceEvent(await _InvoiceRepository.GetInvoice(invoice.Id), 1008, InvoiceEvent.MarkedInvalid));

            if (redirect)
            {
                return(RedirectToAction(nameof(ViewPaymentRequest), new
                {
                    Id = id,
                    StatusMessage = "Pago cancelado"
                }));
            }

            return(Ok("Pago cancelado"));
        }
Esempio n. 28
0
        public FunctionResult <InvoiceInfo> PublishAndSignInvoice(string stt_rec, string ma_ct, System.Collections.Hashtable htOverrireDmct)
        {
            FunctionResult <InvoiceInfo> result = new FunctionResult <InvoiceInfo>();

            result.Status = ResultCode.Error;
            result.Data   = new InvoiceInfo();
            Guid      logId = Guid.Empty;
            Stopwatch sw    = new Stopwatch();
            Stopwatch sw2   = new Stopwatch();


            string log_content = "";

            try
            {
                sw.Start();
                logId = CreateLog(ma_ct, stt_rec, (int)PublishType.Publish);



                SqlCommand cmd    = new SqlCommand("Select * from dmct where ma_ct='" + ma_ct + "'");
                DataSet    dsDmct = StartupBase.SysObj.ExcuteReader(cmd);
                if (dsDmct.Tables[0].Rows.Count > 0)
                {
                    string ph  = dsDmct.Tables[0].Rows[0]["v_phdbf"].ToString();
                    string ct  = dsDmct.Tables[0].Rows[0]["v_ctdbf"].ToString();
                    string mph = dsDmct.Tables[0].Rows[0]["m_phdbf"].ToString();
                    string mct = dsDmct.Tables[0].Rows[0]["m_ctdbf"].ToString();
                    cmd = new SqlCommand("Select * FROM " + ph + " Where stt_rec=@stt_rec");
                    cmd.Parameters.Add(new SqlParameter("@stt_rec", stt_rec));
                    DataSet dsPH = StartupBase.SysObj.ExcuteReader(cmd);

                    cmd = new SqlCommand("Select * FROM " + ct + " Where stt_rec=@stt_rec");
                    cmd.Parameters.Add(new SqlParameter("@stt_rec", stt_rec));
                    DataSet dsCt = StartupBase.SysObj.ExcuteReader(cmd);

                    string ma_qs0 = dsPH.Tables[0].Rows[0]["ma_qs"].ToString();

                    DataTable tblDmqs = Utils.GetQuyenHddtInfo(ma_qs0, 0);
                    if (tblDmqs.Rows.Count == 0)
                    {
                        throw new Exception("Không tìm thấy quyển khai báo sử dụng hóa đơn điện tử cho quyển chứng từ " + ma_qs0);
                    }

                    if (tblDmqs.Rows[0]["ma_qs_ax"].ToString().Trim() == "")
                    {
                        throw new Exception(string.Format("Quyển chứng từ [{0}] chưa được gán mã quyển HĐĐT", tblDmqs.Rows[0]["ma_qs"]));
                    }

                    DataTable tblQHddt = Utils.GetQuyenHddtInfo(tblDmqs.Rows[0]["ma_qs_ax"].ToString(), 1);
                    if (tblQHddt.Rows.Count == 0)
                    {
                        throw new Exception("Không tìm thấy  khai báo quyển chứng từ có mã " + tblDmqs.Rows[0]["ma_qs_ax"].ToString());
                    }

                    DataRow dmKhRow = Utils.SelectDmkhInfo(dsPH.Tables[0].Rows[0]["ma_kh"].ToString());
                    if (dmKhRow["e_mail"].ToString().Trim() == "")
                    {
                        throw new Exception("Khách hàng mã " + dsPH.Tables[0].Rows[0]["ma_kh"].ToString() + " chưa được khai báo email để sử dụng hóa đơn điện tử");
                    }
                    string email_cus = dmKhRow["e_mail"].ToString().Trim();
                    string ma_qs     = tblQHddt.Rows[0]["ma_qs"].ToString();
                    string pattern   = tblQHddt.Rows[0]["kh_mau_hd"].ToString().Trim();
                    string serial    = tblQHddt.Rows[0]["so_seri"].ToString().Trim();
                    string transform = tblQHddt.Rows[0]["transform"].ToString().Trim();
                    result.Data.MaQs_Luu  = ma_qs0;
                    result.Data.MaQs_Hddt = ma_qs;
                    result.Data.Transform = transform;

                    //Kiểm tra xem hóa đơn đã được post trước đó chưa


                    ResponeBaseGenneric <CheckInvoiceStateData> rsCheck = checkInvoiceState(stt_rec);
                    InvoiceState state = rsCheck.Data.GetInvState(stt_rec);
                    if (state == InvoiceState.NotExist)
                    {
                        Hashtable htJson = new Hashtable();


                        string xmlContent = ConvertDataToXMLInvoice(dsPH.Tables[0], dsCt.Tables[0], ma_ct, (int)PublishType.Publish);

                        htJson.Add("XmlData", xmlContent);
                        htJson.Add("Pattern", pattern);
                        htJson.Add("Serial", serial);
                        htJson.Add("IkeyEmail", new KeyValuePair <string, string>(stt_rec, email_cus));
                        string json = Newtonsoft.Json.JsonConvert.SerializeObject(htJson);



                        string use_client_cert = FrmConfig.GetConfig(FrmConfig.KEY_USE_CLIENT_CERT);
                        string respone         = "";

                        if (use_client_cert != "true")
                        {
                            sw2.Start();
                            log_content += Environment.NewLine + "Phát hành trực tiếp hóa đơn điện tử";
                            UpdateLogField(logId, new string[] { "request", "end_point" }, new object[] { json, "api/publish/importAndPublishInvoice" });
                            respone = Post2Server("api/publish/importAndPublishInvoice", SMethod.POST, json);
                            sw2.Stop();
                            UpdateLogField(logId, new string[] { "respone" }, new object[] { respone });
                            Hashtable htResult = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(respone);
                            string    status   = htResult["Status"].ToString();
                            string    message  = htResult["Message"].ToString();
                            if (status == "2")
                            {
                                result.Status      = ResultCode.Success;
                                result.Message     = message;
                                result.ResponeData = Encoding.UTF8.GetBytes(respone);
                                Hashtable htInvoiceInfo = htResult["Data"] as Hashtable;

                                result.Data.Pattern = htInvoiceInfo["Pattern"].ToString();
                                result.Data.Serial  = htInvoiceInfo["Serial"].ToString();

                                Hashtable htKeyInvoiceNo = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htInvoiceInfo["KeyInvoiceNo"].ToString());
                                if (result.Data.Transform != "")
                                {
                                    result.Data.InvoiceNo = string.Format(result.Data.Transform, int.Parse(htKeyInvoiceNo[stt_rec].ToString()));
                                }
                                else
                                {
                                    result.Data.InvoiceNo = htKeyInvoiceNo[stt_rec].ToString();
                                }
                            }
                            else
                            {
                                result.Status  = ResultCode.Error;
                                result.Message = message;
                            }
                        }
                        else
                        {
                            sw2.Start();
                            log_content += Environment.NewLine + "Phát hành 2 bước hóa đơn điện tử";
                            //Ký số 2 bước
                            //Bước 1.
                            //Tạo hóa đơn tạm api/publish/externalGetDigestForImportation
                            //Chọn CKS
                            X509Certificate2 signCert   = null;
                            string           certString = GetCertString(out signCert);
                            htJson.Add("CertString", certString);
                            json         = Newtonsoft.Json.JsonConvert.SerializeObject(htJson);
                            log_content += Environment.NewLine + "1. Tạo hóa đơn tạm";
                            log_content += Environment.NewLine + "==>JSon:" + json;
                            respone      = Post2Server("api/publish/externalGetDigestForImportation", SMethod.POST, json);
                            log_content += Environment.NewLine + "==>Respone:" + respone;

                            //Xử lý kết quả trả về

                            Hashtable htResult = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(respone);
                            if (htResult.ContainsKey("Status") && htResult["Status"].ToString() == "2")
                            {
                                //Tạo hóa đơn thành công
                                //Bước 2. Ký số hóa đơn và phát hành
                                Hashtable htData = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htResult["Data"].ToString());
                                //Lấy digest value

                                Hashtable hDigestData = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htData["DigestData"].ToString());

                                Hashtable             htData2Post2 = new Hashtable();
                                IDictionaryEnumerator ie           = hDigestData.GetEnumerator();
                                while (ie.MoveNext())
                                {
                                    string sDigestData = hDigestData[ie.Key].ToString();
                                    string signHash    = SignHash(signCert, sDigestData);
                                    htData2Post2.Add(ie.Key, signHash);
                                }


                                Hashtable htData2Post = new Hashtable();
                                htData2Post.Add("Pattern", htData["Pattern"]);
                                htData2Post.Add("Serial", htData["Serial"]);



                                htData2Post.Add("Signature", htData2Post2);
                                log_content += Environment.NewLine + "2. Phát hành hóa đơn tạm";
                                json         = Newtonsoft.Json.JsonConvert.SerializeObject(htData2Post);
                                log_content += Environment.NewLine + "==>JSon:" + json;

                                respone      = Post2Server("api/publish/externalWrapAndLaunchImportation", SMethod.POST, json);
                                log_content += Environment.NewLine + "==>Respone:" + respone;

                                htResult = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(respone);
                                if (htResult.ContainsKey("Status") && htResult["Status"].ToString() == "2")
                                {
                                    result.Status      = ResultCode.Success;
                                    result.Message     = "";
                                    result.ResponeData = Encoding.UTF8.GetBytes(respone);
                                    Hashtable htInvoiceInfo = htInvoiceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htResult["Data"].ToString());
                                    result.Data.Pattern     = htInvoiceInfo["Pattern"].ToString();
                                    result.Data.Serial      = htInvoiceInfo["Serial"].ToString();
                                    result.Data.InvoiceDate = (DateTime)dsPH.Tables[0].Rows[0]["ngay_ct"];
                                    Hashtable htKeyInvoiceNo = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htInvoiceInfo["KeyInvoiceNo"].ToString());
                                    if (result.Data.Transform != "")
                                    {
                                        result.Data.InvoiceNo = string.Format(result.Data.Transform, int.Parse(htKeyInvoiceNo[stt_rec].ToString()));
                                    }
                                    else
                                    {
                                        result.Data.InvoiceNo = htKeyInvoiceNo[stt_rec].ToString();
                                    }
                                }
                                else
                                {
                                    //Lỗi
                                    result.Status  = ResultCode.Error;
                                    result.Message = htResult["Message"].ToString();
                                }
                            }
                            else
                            {
                                result.Status  = ResultCode.Error;
                                result.Message = htResult["Message"].ToString();
                            }

                            sw2.Stop();
                        }

                        UpdateLogField(logId, new string[] { "status_code" }, new object[] { result.Status.ToString() });
                    }
                    else
                    {
                        switch (state)
                        {
                        case InvoiceState.NaN:
                            throw new Exception("Lỗi khi tra cứu trạng thái hóa đơn");

                        case InvoiceState.Published:
                            if (MessageBox.Show("Hóa đơn hiện tại đã được phát hành. Bạn có muốn cập nhật lại trạng thái hóa đơn?", "Cảnh báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                result.Status = ResultCode.Success;
                                ResponeBaseGenneric <ViewInvoiceData> rsViewInv = GetViewInvoice(stt_rec, rsCheck.Data.Pattern);
                                //   result.Data = new InvoiceInfo();
                                result.Data.InvState = rsViewInv.Data.InvState;
                                if (result.Data.Transform != "")
                                {
                                    result.Data.InvoiceNo = string.Format(result.Data.Transform, int.Parse(rsViewInv.Data.No));
                                }
                                else
                                {
                                    result.Data.InvoiceNo = rsViewInv.Data.No;
                                }


                                result.Data.InvoiceDate = DateTime.ParseExact(rsViewInv.Data.ArisingDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                                result.Data.Serial      = rsViewInv.Data.Serial;
                            }
                            break;

                        default:
                            throw new Exception("Trạng thái hóa đơn hiện tại không cho phép cập nhật:" + InvStateDescription[state]);
                        }
                    }
                }
                else
                {
                    throw new Exception("Không tìm thấy mã chứng từ " + ma_ct);
                }
            }
            catch (Exception ex)
            {
                result.Status  = ResultCode.Exception;
                result.Message = ex.ToString();
                log_content   += ex.ToString();
            }
            finally
            {
                sw.Stop();
                sw2.Stop();
                try
                {
                    UpdateLogField(logId, new string[] { "duration", "duration_publish", "log_content", "status_code" }, new object[] { sw.Elapsed.Seconds, sw2.Elapsed.Seconds, log_content, result.Status.ToString() });
                }
                catch
                {
                }
            }
            return(result);
        }
Esempio n. 29
0
        private void mainFunction(Order order)
        {
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": POST Request received. OrderId: " + order.OrderID.Value.ToString());
            }

            //write data in DB
            MySqlConnection con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"insert into shopdb.controller(OrderID,CustomerName,CustomerAddress,CustomerEmail,ArticleId,Quantity,Price,OrderSize,OrderWeight) values('" + order.OrderID + "','" + order.CustomerName + "','" + order.CustomerAddress + "','" + order.CustomerEMail + "','" + order.ArticleID + "','" + order.Quantity + "','" + order.Price + "','" + order.OrderSize + "','" + order.OrderWeight + "');";
            MySqlCommand command = new MySqlCommand(Query, con);

            command.ExecuteReader();
            con.Close();

            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - initial Request");
            }

            //new Invoice Request
            InvoiceRequest invRequest = new InvoiceRequest(order.OrderID, order.Price, order.CustomerName, order.CustomerAddress);

            httpMachine.Invoicepost(invRequest);
            System.Threading.Thread.Sleep(1000);
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Sent POST to Invoice API. OrderId: " + order.OrderID.Value.ToString());
            }

            //warten, bis der Invoice Request abgeschlossen ist
            InvoiceState invState = httpMachine.Invoiceget(order.OrderID.Value);

            while (!invState.PaymentState.Equals("completed"))
            {
                using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Invoice not paid yet, waiting 5 Seconds. OrderId: " + order.OrderID.Value.ToString());
                }
                System.Threading.Thread.Sleep(5000);
                invState = httpMachine.Invoiceget(order.OrderID.Value);
            }
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Invoice paid");
            }

            //DB schreiben
            con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"update controller set PaymentState = 1 where OrderId = " + order.OrderID.Value.ToString());
            MySqlCommand command2 = new MySqlCommand(Query, con);

            command2.ExecuteReader();
            con.Close();
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - InvoiceState");
            }

            //new Inventory Request
            InventoryRequest ivtRequest = new InventoryRequest(order.OrderID, order.ArticleID, order.Quantity);

            httpMachine.Inventorypost(ivtRequest);
            System.Threading.Thread.Sleep(1000);
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Sent POST to Inventory API. OrderId: " + order.OrderID.Value.ToString());
            }

            //warten, bis der Inventory Request abgeschlossen ist
            InventoryState ivtState = httpMachine.Inventoryget(order.OrderID.Value);

            while (!ivtState.InventoryStateProperty.Equals("completed"))
            {
                using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Inventory not yet commissioned, waiting 5 Seconds. OrderId: " + order.OrderID.Value.ToString());
                }
                System.Threading.Thread.Sleep(5000);
                ivtState = httpMachine.Inventoryget(order.OrderID.Value);
            }
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Inventory commissioned");
            }

            //DB schreiben
            con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"update controller set InventoryState = 1 where OrderId = " + order.OrderID.Value.ToString());
            MySqlCommand command3 = new MySqlCommand(Query, con);

            command3.ExecuteReader();
            con.Close();
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - InventoryState");
            }

            //new Shipment Request
            ShipmentRequest shpRequest = new ShipmentRequest(order.OrderID, order.OrderSize, order.OrderWeight, order.CustomerName, order.CustomerAddress, order.CustomerEMail);

            httpMachine.Shipmentpost(shpRequest);
            System.Threading.Thread.Sleep(1000);
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Sent POST to Shipment API. OrderId: " + order.OrderID.Value.ToString());
            }

            //warten, bis der Shipment Request abgeschlossen ist
            ShipmentState shpState = httpMachine.Shipmentget(order.OrderID.Value);

            while (!shpState.Status.Equals("Delivered"))
            {
                using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Shipment not completed, waiting 5 Seconds. OrderId: " + order.OrderID.Value.ToString());
                }
                System.Threading.Thread.Sleep(5000);
                shpState = httpMachine.Shipmentget(order.OrderID.Value);
            }
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Shipment completed");
            }

            //DB schreiben
            con = new MySqlConnection("server=localhost; user id = root; database = shopdb; password ="******"update controller set ShipmentState = 1 where OrderId = " + order.OrderID.Value.ToString());
            MySqlCommand command4 = new MySqlCommand(Query, con);

            command4.ExecuteReader();
            con.Close();
            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Database Updated - ShipmentState");
            }

            using (StreamWriter sw = new StreamWriter(@"C:\temp\ShopStantly.log", true))
            {
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": _________________");
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": Request completed");
                sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + ": _________________");
            }
        }
        private async Task <IActionResult> ComputeSweepRequests(SweepFundsViewModel viewModel)
        {
            var invoices = await _invoiceRepository.GetInvoices(new InvoiceQuery()
            {
                StoreId = new[] { StoreData.Id },
                Status  = new[] { InvoiceState.ToString(InvoiceStatusLegacy.Complete) },
            });

            var invoicesWithPayment = invoices.Select(entity => (
                                                          entity,
                                                          entity.GetSupportedPaymentMethod <EthereumSupportedPaymentMethod>(),
                                                          entity.GetPayments()
                                                          .Where(paymentEntity => paymentEntity.Accounted &&
                                                                 paymentEntity.Network is EthereumBTCPayNetwork ethN &&
                                                                 ethN.ChainId == viewModel.ChainId)
                                                          .Select(paymentEntity => (paymentEntity,
                                                                                    paymentEntity.GetCryptoPaymentData() as EthereumLikePaymentData))
                                                          .Where(tuple =>
                                                                 tuple.Item2 != null && string.IsNullOrEmpty(tuple.Item2.SweepingTransaction) &&
                                                                 tuple.Item2.XPub == viewModel.XPub)))
                                      .Where(tuple => tuple.Item3.Any());

            if (!invoicesWithPayment.Any())
            {
                TempData.SetStatusMessageModel(new StatusMessageModel()
                {
                    Message = $"Nothing found to sweep", Severity = StatusMessageModel.StatusSeverity.Error
                });

                return(RedirectToAction("GetStoreEthereumLikePaymentMethods", new { storeId = StoreData.Id }));
            }

            //need construct list address with ERC tokens and list address with ETH token
            var payments = invoicesWithPayment.SelectMany(tuple => tuple.Item3.Select(valueTuple =>
                                                                                      (InvoiceId: tuple.entity.Id, PaymentEntity: valueTuple.paymentEntity, PaymentData: valueTuple.Item2)));

            var groupedByAddress = payments.GroupBy(tuple => tuple.PaymentData.Address);

            var networks = _btcPayNetworkProvider.GetAll().OfType <EthereumBTCPayNetwork>()
                           .Where(network => network.ChainId == viewModel.ChainId);
            var mainNetwork = networks.SingleOrDefault(network => !(network is ERC20BTCPayNetwork));
            var pmi         = new PaymentMethodId(mainNetwork.CryptoCode, EthereumPaymentType.Instance);

            //need send ETH to addresses even erc, make sure they not monitored in invoices
            var ethInvoices =
                await _invoiceRepository.GetInvoicesFromAddresses(groupedByAddress
                                                                  .Select(tuples => $"{tuples.Key}#{pmi}").ToArray());

            var pendingInvoices = await _invoiceRepository.GetPendingInvoices();

            var pendingEthInvoices = ethInvoices.Where(entity => (pendingInvoices).Contains(entity.Id))
                                     .Select(entity => (entity, entity.GetPaymentMethod(pmi))).Select(tuple => (tuple.entity, tuple.Item2,
                                                                                                                tuple.Item2.GetPaymentMethodDetails() as EthereumLikeOnChainPaymentMethodDetails))
                                     .ToDictionary(tuple => tuple.Item3.DepositAddress);

            var requests = new List <SweepRequest>();

            foreach (IGrouping <string, (string InvoiceId, PaymentEntity PaymentEntity, EthereumLikePaymentData
                                         PaymentData)> grouping in groupedByAddress)
            {
                var request = new SweepRequest();
                request.Address = grouping.Key;
                request.Index   = grouping.First().PaymentData.AccountIndex;
                if (pendingEthInvoices.TryGetValue(grouping.Key, out var conflict))
                {
                    request.UnableToSweepBecauseOfActiveInvoiceWithNativeCurrency = conflict.entity.Id;
                }

                foreach ((string InvoiceId, PaymentEntity PaymentEntity, EthereumLikePaymentData PaymentData)valueTuple
                         in grouping)
                {
                    var network = valueTuple.PaymentEntity.Network as EthereumBTCPayNetwork;

                    var sweepRequestItem = new SweepRequestItem();
                    sweepRequestItem.CryptoCode = network.CryptoCode;
                    sweepRequestItem.InvoiceId  = valueTuple.InvoiceId;
                    sweepRequestItem.Sweep      =
                        string.IsNullOrEmpty(request.UnableToSweepBecauseOfActiveInvoiceWithNativeCurrency);
                    if (network is ERC20BTCPayNetwork erc20BTCPayNetwork)
                    {
                        request.Tokens.Add(sweepRequestItem);
                    }
                    else
                    {
                        request.Native = sweepRequestItem;
                    }
                }

                requests.Add(request);
            }

            viewModel.SweepRequests = requests;

            return(await CheckIfCanSweepNow(viewModel, "", false));
        }
Esempio n. 31
0
 public InvoiceStatus(InvoiceState status, IEnumerable <InvoiceValidationResult> validationResults)
 {
     Status            = status;
     ValidationResults = validationResults;
 }