コード例 #1
0
        public Task <Result <Guid> > Add(CreateInvoiceModel model, UserSurvey userSurvey = null)
        => Result <Guid> .TryAsync(async() =>
        {
            var user = (await _membershipServiceApi.SystemUserApiService.Get(
                            new MembershipService.ApiClient.Models.BaseModel {
                Id = model.UserId
            })).Data;
            if (user == null)
            {
                return(Result <Guid> .Failed(Error.WithCode(ErrorCodes.NotFound)));
            }

            var invoice = new Invoice
            {
                Id          = Guid.NewGuid(), Amount = model.Amount + model.Amount * 5 / 100,
                TaxAmount   = model.Amount * 5 / 100, CreationDate = DateTime.Now,
                UserId      = model.UserId, Enabled = model.Enabled,
                Description = model.Description, Title = model.Title, Status = (byte)model.Status
            };

            if (userSurvey != null)
            {
                invoice.UserSurvey.Add(userSurvey);
            }

            _repository.Add(invoice);
            await _repository.CommitAsync();

            if (userSurvey == null)
            {
                _coreSmtpClient.SendInvoiceReady(user.Email, user.Firstname + " " + user.Lastname);
            }
            return(Result <Guid> .Successful(invoice.Id));
        });
コード例 #2
0
        public async Task <IActionResult> CreateInvoice(CreateInvoiceModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Stores = await GetStores(GetUserId(), model.StoreId);

                return(View(model));
            }
            var store = await _StoreRepository.FindStore(model.StoreId, GetUserId());

            if (string.IsNullOrEmpty(store.DerivationStrategy))
            {
                StatusMessage = "Error: You need to configure the derivation scheme in order to create an invoice";
                return(RedirectToAction(nameof(StoresController.UpdateStore), "Stores", new
                {
                    storeId = store.Id
                }));
            }
            var result = await CreateInvoiceCore(new Invoice()
            {
                Price    = model.Amount.Value,
                Currency = "USD",
                PosData  = model.PosData,
                OrderId  = model.OrderId,
                //RedirectURL = redirect + "redirect",
                NotificationURL   = model.NotificationUrl,
                ItemDesc          = model.ItemDesc,
                FullNotifications = true,
                BuyerEmail        = model.BuyerEmail,
            }, store, HttpContext.Request.GetAbsoluteRoot());

            StatusMessage = $"Invoice {result.Data.Id} just created!";
            return(RedirectToAction(nameof(ListInvoices)));
        }
コード例 #3
0
 public ActionResult DraftProformaInvoice(CreateInvoiceModel model)
 {
     try
     {
         var roleId         = Common.GetRoleId(User.Identity.Name);
         var loggedinuser   = User.Identity.Name;
         var loggedinuserid = Common.GetUserid(loggedinuser);
         var servicetype    = Common.getservicetype();
         var invoicetype    = Common.getinvoicetype();
         ViewBag.typeofservice = servicetype;
         ViewBag.TypeofInvoice = invoicetype;
         //if (roleId != 1)
         //    return RedirectToAction("Index", "Home");
         ProjectService _ps            = new ProjectService();
         var            InvoiceDraftID = _ps.DraftInvoice(model, loggedinuserid);
         if (InvoiceDraftID > 0)
         {
             ViewBag.succMsg = "Proforma Invoice has been saved as draft";
         }
         else
         {
             ViewBag.errMsg = "Something went wrong please contact administrator";
         }
         return(View("CreateProformaInvoice", model));
     }
     catch (Exception ex)
     {
         return(View());
     }
 }
コード例 #4
0
        public static CreateInvoiceModel Sanitize(this CreateInvoiceModel model)
        {
            model.ClientEmail = model.ClientEmail.SanitizeEmail();
            model.ClientName  = model.ClientName.Sanitize();

            return(model);
        }
コード例 #5
0
        public RequestResponse <CreateInvoiceModel> GetInvoice(Guid invoiceId)
        {
            if (invoiceId == Guid.Empty)
            {
                return new RequestResponse <CreateInvoiceModel> {
                           Success = false, Data = null, Message = "Invalid invoice Id"
                }
            }
            ;

            var selectedInvoice = _invoiceRepository.Get(invoiceId);

            if (selectedInvoice == null)
            {
                return new RequestResponse <CreateInvoiceModel> {
                           Success = false, Data = null, Message = "Selected Invoice couldn't be found"
                }
            }
            ;

            var mappedInvoice = new CreateInvoiceModel {
                Id = selectedInvoice.Id, Amount = selectedInvoice.Amount, CreationDate = selectedInvoice.CreationDate, Description = selectedInvoice.Description, DueDate = selectedInvoice.DueDate, InvoiceState = (int)selectedInvoice.State, InvoiceType = (int)selectedInvoice.Type
            };

            return(new RequestResponse <CreateInvoiceModel> {
                Success = true, Data = new List <CreateInvoiceModel> {
                    mappedInvoice
                }, Message = "Selected successfully"
            });
        }
 public static void ValidateDueDate(this CreateInvoiceModel model)
 {
     // https://docs.microsoft.com/en-us/rest/api/storageservices/Understanding-the-Table-Service-Data-Model?redirectedfrom=MSDN#property-types
     if (model.DueDate <= DateTime.UtcNow)
     {
         throw new InvoiceDueDateException();
     }
 }
コード例 #7
0
        public async Task <CreateInvoiceResponseModel> UpdateUBL(CreateInvoiceModel model)
        {
            var reponseModel = await flurlClient.Request($"/v1/outboxinvoice")
                               .PutJsonAsync(model)
                               .ReceiveJson <CreateInvoiceResponseModel>();

            return(reponseModel);
        }
コード例 #8
0
        public async Task <IActionResult> CreateInvoice(CreateInvoiceModel model, CancellationToken cancellationToken)
        {
            var stores = await _StoreRepository.GetStoresByUserId(GetUserId());

            model.Stores = new SelectList(stores, nameof(StoreData.Id), nameof(StoreData.StoreName), model.StoreId);
            model.AvailablePaymentMethods = GetPaymentMethodsSelectList();
            var store = HttpContext.GetStoreData();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            StatusMessage = null;
            if (store.GetSupportedPaymentMethods(_NetworkProvider).Count() == 0)
            {
                ModelState.AddModelError(nameof(model.StoreId), "You need to configure the derivation scheme in order to create an invoice");
                return(View(model));
            }


            if (StatusMessage != null)
            {
                return(RedirectToAction(nameof(StoresController.UpdateStore), "Stores", new
                {
                    storeId = store.Id
                }));
            }

            try
            {
                var result = await CreateInvoiceCore(new CreateInvoiceRequest()
                {
                    Price    = model.Amount.Value,
                    Currency = model.Currency,
                    PosData  = model.PosData,
                    OrderId  = model.OrderId,
                    //RedirectURL = redirect + "redirect",
                    NotificationEmail = model.NotificationEmail,
                    NotificationURL   = model.NotificationUrl,
                    ItemDesc          = model.ItemDesc,
                    FullNotifications = true,
                    BuyerEmail        = model.BuyerEmail,
                    SupportedTransactionCurrencies = model.SupportedTransactionCurrencies?.ToDictionary(s => s, s => new InvoiceSupportedTransactionCurrency()
                    {
                        Enabled = true
                    })
                }, store, HttpContext.Request.GetAbsoluteRoot(), cancellationToken : cancellationToken);

                StatusMessage = $"Invoice {result.Data.Id} just created!";
                return(RedirectToAction(nameof(ListInvoices)));
            }
            catch (BitpayHttpException ex)
            {
                ModelState.TryAddModelError(nameof(model.Currency), $"Error: {ex.Message}");
                return(View(model));
            }
        }
コード例 #9
0
        public static CreateInvoiceModel Sanitize(this CreateInvoiceModel model)
        {
            var context = Mapper.Map <CreateInvoiceModel>(model);

            context.ClientEmail = context.ClientEmail?.SanitizeEmail();
            context.ClientName  = context.ClientName?.Sanitize();

            return(context);
        }
コード例 #10
0
        public async Task <IActionResult> CreateInvoice(CreateInvoiceModel model)
        {
            model.Stores = await GetStores(GetUserId(), model.StoreId);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var store = await _StoreRepository.FindStore(model.StoreId, GetUserId());

            StatusMessage = null;
            if (store.Role != StoreRoles.Owner)
            {
                ModelState.AddModelError(nameof(model.StoreId), "You need to be owner of this store to create an invoice");
                return(View(model));
            }

            if (store.GetSupportedPaymentMethods(_NetworkProvider).Count() == 0)
            {
                ModelState.AddModelError(nameof(model.StoreId), "You need to configure the derivation scheme in order to create an invoice");
                return(View(model));
            }

            if (StatusMessage != null)
            {
                return(RedirectToAction(nameof(StoresController.UpdateStore), "Stores", new
                {
                    storeId = store.Id
                }));
            }

            try
            {
                var result = await CreateInvoiceCore(new Invoice()
                {
                    Price    = model.Amount.Value,
                    Currency = model.Currency,
                    PosData  = model.PosData,
                    OrderId  = model.OrderId,
                    //RedirectURL = redirect + "redirect",
                    NotificationURL   = model.NotificationUrl,
                    ItemDesc          = model.ItemDesc,
                    FullNotifications = true,
                    BuyerEmail        = model.BuyerEmail,
                }, store, HttpContext.Request.GetAbsoluteRoot());

                StatusMessage = $"Invoice {result.Data.Id} just created!";
                return(RedirectToAction(nameof(ListInvoices)));
            }
            catch (RateUnavailableException)
            {
                ModelState.TryAddModelError(nameof(model.Currency), "Unsupported currency");
                return(View(model));
            }
        }
コード例 #11
0
        public async Task <IActionResult> Create([FromBody] CreateInvoiceModel model)
        {
            var user = await _userManager.GetUserAsync(User);

            var team = await _dbContext.Teams.FirstOrDefaultAsync(t => t.Slug == TeamSlug);

            // validate model
            if (!ModelState.IsValid)
            {
                return(new JsonResult(new
                {
                    success = false,
                    errorMessage = "Errors found in request",
                    modelState = ModelState
                }));
            }

            IReadOnlyList <Invoice> invoices;

            try
            {
                invoices = await _invoiceService.CreateInvoices(model, team);
            }
            catch (ArgumentException ex)
            {
                ModelState.AddModelError(ex.ParamName, ex.Message);
                return(new JsonResult(new
                {
                    success = false,
                    errorMessage = "Errors found in request",
                    modelState = ModelState
                }));
            }

            // record action on invoices
            foreach (var invoice in invoices)
            {
                var action = new History()
                {
                    Type           = HistoryActionTypes.InvoiceCreated.TypeCode,
                    ActionDateTime = DateTime.UtcNow,
                    Actor          = user.Name,
                };
                invoice.History.Add(action);
            }

            await _dbContext.SaveChangesAsync();

            return(new JsonResult(new
            {
                success = true,
                ids = invoices.Select(i => i.Id),
            }));
        }
コード例 #12
0
        public async Task <IActionResult> Create([FromBody] CreateInvoiceModel model)
        {
            var team = await GetAuthorizedTeam();

            // validate model
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new
                {
                    success = false,
                    errorMessage = "Errors found in request",
                    modelState = ModelState
                }));
            }

            // create invoices
            IReadOnlyList <Invoice> invoices;

            try
            {
                invoices = await _invoiceService.CreateInvoices(model, team);
            }
            catch (ArgumentException ex)
            {
                ModelState.AddModelError(ex.ParamName, ex.Message);
                return(new BadRequestObjectResult(new
                {
                    success = false,
                    errorMessage = "Errors found in request",
                    modelState = ModelState
                }));
            }

            // record action on invoices
            foreach (var invoice in invoices)
            {
                var action = new History()
                {
                    Type           = HistoryActionTypes.InvoiceCreated.TypeCode,
                    ActionDateTime = DateTime.UtcNow,
                };
                invoice.History.Add(action);
            }

            await _dbContext.SaveChangesAsync();

            return(new JsonResult(new CreateInvoiceResult
            {
                Success = true,
                Ids = invoices.Select(i => i.Id).ToArray(),
            }));
        }
コード例 #13
0
 public Invoice CreateNewInvoice(CreateInvoiceModel model)
 {
     try
     {
         var newInvoice = _invoiceRepository.CreateNewInvoice(model.InvoiceName);
         return(newInvoice);
     }
     catch (Exception)
     {
         // TODO: Log the exception
         return(null);
     }
 }
コード例 #14
0
        public async Task <IActionResult> PostUBL()
        {
            //Önceden oluşturulmuş Fatura UBL'i okuyarak, servisin istediği önceden ziplenmiş base64 formata çeviriyorum..
            var    ubl        = new Api.Invoice.Models.Invoice21.InvoiceType();
            string path       = Path.Combine(Environment.CurrentDirectory, "Static");
            var    invoiceXml = await System.IO.File.ReadAllTextAsync(Path.Combine(path, "Invoice.xml"), Encoding.UTF8);

            var    plainTextBytes = System.Text.Encoding.UTF8.GetBytes(invoiceXml);
            string base64         = string.Empty;

            var helper = new Helper();

            using (var stream = new MemoryStream(plainTextBytes))
            {
                var serializer = new XmlSerializer(typeof(Api.Invoice.Models.Invoice21.InvoiceType));
                ubl = (Api.Invoice.Models.Invoice21.InvoiceType)(serializer.Deserialize(stream) as Api.Invoice.Models.Invoice21.InvoiceType);
            }

            using (var stream = new MemoryStream())
            {
                var writer        = new XmlTextWriter(stream, Encoding.UTF8);
                var xmlSerializer = new XmlSerializer(typeof(Api.Invoice.Models.Invoice21.InvoiceType));
                xmlSerializer.Serialize(writer, ubl, XmlNamespaceHelper.InvoiceNamespaces);
                writer.Flush();
                stream.Seek((long)0, SeekOrigin.Begin);

                var zipFile = helper.ZipFileToByte(stream, ubl.UUID.Value.ToString() + ".xml");
                base64 = Convert.ToBase64String(zipFile);
            }

            var byteFile  = Convert.FromBase64String(base64);
            var unZipFile = helper.UnzipFile(byteFile);

            CreateInvoiceModel model = new CreateInvoiceModel()
            {
                InvoiceZip = base64,
                // Status = (int)InvoiceStatus.Draft,  //Taslak fatura
                Status = (int)InvoiceStatus.Queued,  //Direkt gönderilmesi için
                CheckLocalReferenceId = false,
                Prefix             = "",
                UseManualInvoiceId = true,
                TargetAlias        = "urn:mail:[email protected]",
                // AppType = 1 // e-Fatura
                AppType = 2 // e-Arşiv
            };

            var data = await _outboxInvoiceClient.PostUBL(model);

            return(Ok(data));
        }
コード例 #15
0
 public ActionResult CreateProformaInvoice(CreateInvoiceModel model)
 {
     try
     {
         var roleId         = Common.GetRoleId(User.Identity.Name);
         var loggedinuser   = User.Identity.Name;
         var loggedinuserid = Common.GetUserid(loggedinuser);
         var servicetype    = Common.getservicetype();
         var invoicetype    = Common.getinvoicetype();
         ViewBag.typeofservice = servicetype;
         ViewBag.TypeofInvoice = invoicetype;
         if (model.TaxableValue <= 0)
         {
             ViewBag.errMsg = "Proforma Invoice Cannot be generated. No balance available for raising Invoice";
             return(View(model));
         }
         //if (roleId != 1 && roleId != 2)
         //    return RedirectToAction("Index", "Home");
         ProjectService _ps       = new ProjectService();
         var            InvoiceID = _ps.CreateProformaInvoice(model, loggedinuserid);
         if (InvoiceID == -4)
         {
             ViewBag.errMsg = "Proforma Invoice Cannot be generated as the Taxable value has exceeded the balance available for raising Invoice. Please enter correct value and try again.";
             return(View(model));
         }
         if (InvoiceID > 0)
         {
             var InvoiceNumber = Common.getproformainvoicenumber(InvoiceID);
             ViewBag.succMsg = "Proforma Invoice has been created successfully with Invoice Number - " + InvoiceNumber + ".";
         }
         else if (InvoiceID == -2)
         {
             var InvoiceId     = Convert.ToInt32(model.InvoiceId);
             var InvoiceNumber = Common.getproformainvoicenumber(InvoiceId);
             ViewBag.succMsg = "Proforma Invoice with Invoice number - " + InvoiceNumber + " has been updated successfully.";
         }
         else
         {
             ViewBag.errMsg = "Something went wrong please contact administrator";
         }
         return(View(model));
     }
     catch (Exception ex)
     {
         return(View());
     }
 }
コード例 #16
0
        public async Task <IActionResult> CreateAsync([FromBody] CreateInvoiceModel model)
        {
            try
            {
                model.ValidateDueDate();

                Invoice invoice = await _invoiceService.CreateDraftAsync(Mapper.Map <Invoice>(model));

                return(Ok(Mapper.Map <InvoiceModel>(invoice)));
            }
            catch (InvoiceDueDateException ex)
            {
                _log.WarningWithDetails(ex.Message, model.Sanitize());

                return(BadRequest(ErrorResponse.Create(ex.Message)));
            }
        }
コード例 #17
0
        public IActionResult Create([FromBody] CreateInvoiceModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            var createdInvoice = _manager.CreateNewInvoice(model);

            if (createdInvoice != null)
            {
                //return Created(nameof(GetById), createdInvoice);
                // TODO: Make a getbyid action
                return(Created("test", createdInvoice));
            }

            return(StatusCode(500));
        }
コード例 #18
0
        public async Task <Invoice> CreateAsync(CreateInvoiceModel model, bool draft)
        {
            model.PaymentAssetId = _lykkeAssetsResolver.GetInvoiceCreationPair(model.SettlementAssetId);

            InvoiceModel invoice;

            try
            {
                if (draft)
                {
                    invoice = await _payInvoiceClient.CreateDraftInvoiceAsync(model);
                }
                else
                {
                    invoice = await _payInvoiceClient.CreateInvoiceAsync(model);
                }
            }
            catch (ErrorResponseException ex)
            {
                _log.ErrorWithDetails(ex, new { model = model.Sanitize(), draft });

                throw new InvalidOperationException(ex.Message);
            }

            Asset settlementAsset = await _lykkeAssetsResolver.TryGetAssetAsync(invoice.SettlementAssetId);

            return(new Invoice
            {
                Id = invoice.Id,
                Number = invoice.Number,
                ClientEmail = invoice.ClientEmail,
                ClientName = invoice.ClientName,
                Amount = invoice.Amount,
                DueDate = invoice.DueDate,
                Status = invoice.Status,
                SettlementAsset = settlementAsset,
                CreatedDate = invoice.CreatedDate,
                Note = invoice.Note
            });
        }
コード例 #19
0
        public ActionResult PickDraftProformaInvoice(int DraftId = 0)
        {
            try
            {
                var roleId      = Common.GetRoleId(User.Identity.Name);
                var servicetype = Common.getservicetype();
                var invoicetype = Common.getinvoicetype();
                ViewBag.typeofservice = servicetype;
                ViewBag.TypeofInvoice = invoicetype;
                //if (roleId != 1 && roleId != 2)
                //    return RedirectToAction("Index", "Home");
                CreateInvoiceModel model = new CreateInvoiceModel();
                ProjectService     _ps   = new ProjectService();
                model = _ps.GetProformaInvoiceDraftDetails(DraftId);

                return(View("CreateProformaInvoice", model));
            }
            catch (Exception ex)
            {
                return(View());
            }
        }
コード例 #20
0
        public ActionResult CreateInvoice(CreateInvoiceModel createInvoice)
        {
            var invoice = new JeebApi(signature).IssueInvoice(new IssueInvoiceRequest()
            {
                AllowReject     = false,
                OrderNo         = createInvoice.OrderNo,
                CallBackUrl     = $"{baseUrl}jeeb/callback",
                NotificationUrl = $"{baseUrl}jeeb/notification",
                RequestAmount   = createInvoice.RequestAmount,
            });

            _paymentsRepo.Add(new Payment()
            {
                Token       = invoice.Token,
                IsConfirmed = false,
                ReferenceNo = invoice.ReferenceNo,
            });

            return(View(new CreateInvoiceViewModel {
                Token = invoice.Token
            }));
        }
コード例 #21
0
 public ActionResult CreateProformaInvoice(int pId = 0)
 {
     try
     {
         if (pId == 0)
         {
             return(RedirectToAction("Dashboard", "Home"));
         }
         var loggedinuser     = User.Identity.Name;
         var user             = Common.getUserIdAndRole(loggedinuser);
         int logged_in_userid = user.Item1;
         int user_role        = user.Item2;
         var servicetype      = Common.getservicetype();
         var invoicetype      = Common.getinvoicetype();
         ViewBag.typeofservice = servicetype;
         ViewBag.TypeofInvoice = invoicetype;
         //if (user_role != 7 && user_role != 8)
         //{
         //    return RedirectToAction("Dashboard", "Home");
         //}
         CreateInvoiceModel model = new CreateInvoiceModel();
         ProjectService     _ps   = new ProjectService();
         model = _ps.GetDetailsforProformaInvoice(pId);
         if (model.AvailableBalance <= 0)
         {
             ViewBag.errMsg = "No balance available for raising Invoice";
         }
         if (model.TaxableValue <= 0)
         {
             ViewBag.errMsg = "No balance available for raising Invoice for this financial year";
         }
         return(View(model));
     }
     catch (Exception ex)
     {
         return(View());
     }
 }
コード例 #22
0
 public ActionResult EditProformaInvoice(int InvoiceId = 0)
 {
     try
     {
         var roleId      = Common.GetRoleId(User.Identity.Name);
         var servicetype = Common.getservicetype();
         var invoicetype = Common.getinvoicetype();
         ViewBag.typeofservice = servicetype;
         ViewBag.TypeofInvoice = invoicetype;
         CreateInvoiceModel model = new CreateInvoiceModel();
         ProjectService     _ps   = new ProjectService();
         model = _ps.GetProformaInvoiceDetails(InvoiceId);
         if (model.InvoiceId == null)
         {
             ViewBag.errMsg = "Proforma Invoice approved or not available for edit.";
         }
         return(View("CreateProformaInvoice", model));
     }
     catch (Exception ex)
     {
         return(View());
     }
 }
コード例 #23
0
        public RequestResponse <object> CreateInvoice(CreateInvoiceModel invoiceToCreate)
        {
            if (invoiceToCreate == null)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Invalid invoice data"
                }
            }
            ;
            if (invoiceToCreate.Amount <= 0)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Invoice amount must be greater than 0"
                }
            }
            ;
            if (invoiceToCreate.CreationDate == default(DateTime))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please enter Creation date"
                }
            }
            ;
            if (invoiceToCreate.DueDate == default(DateTime))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please enter Due Date"
                }
            }
            ;
            if (string.IsNullOrEmpty(invoiceToCreate.Description) || invoiceToCreate.Description.Length > 200)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Invoice description length must be 200 characters maximum"
                }
            }
            ;
            if (!Enum.IsDefined(typeof(InvoiceState), invoiceToCreate.InvoiceState))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please select a valid Invoice State"
                }
            }
            ;
            if (!Enum.IsDefined(typeof(InvoiceType), invoiceToCreate.InvoiceType))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please select a valid invoice type"
                }
            }
            ;
            if (invoiceToCreate.CreationDate > invoiceToCreate.DueDate)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Due Date must be greater than Creation Date"
                }
            }
            ;
            var mappedInvoice = new Invoice {
                Amount = invoiceToCreate.Amount, CreationDate = invoiceToCreate.CreationDate, Description = invoiceToCreate.Description, DueDate = invoiceToCreate.DueDate, State = (InvoiceState)invoiceToCreate.InvoiceState, Type = (InvoiceType)invoiceToCreate.InvoiceType
            };

            var createdInvoice = _invoiceRepository.Create(mappedInvoice);

            if (createdInvoice == null)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "An error occured. Please try again later"
                }
            }
            ;

            return(new RequestResponse <object> {
                Success = true, Data = null, Message = "Created successfully"
            });
        }
コード例 #24
0
        public async Task CanCreateInvoiceDraft()
        {
            var createCustomerModel = new CreateCustomerModel
            {
                Name = "CreateInvoiceDraftTestCustomer"
            };

            var customer = await Client.Value.CreateCustomer(createCustomerModel);

            var invoice = new CreateInvoiceModel
            {
                Date     = "2020-03-03",
                Customer = new Customer
                {
                    CustomerNumber = customer.CustomerNumber
                },
                Layout = new Layout
                {
                    LayoutNumber = 14
                },
                References = new References
                {
                    Other = "MRR-75"
                },
                PaymentTerms = new PaymentTerms
                {
                    PaymentTermsNumber = 1
                },

                Lines = new List <Line>
                {
                    new Line()
                    {
                        Product = new Product
                        {
                            ProductNumber = "1"
                        },
                        Quantity = 1,
                        Unit     = new Unit
                        {
                            UnitNumber = 1
                        },
                        DiscountPercentage = 0,
                        UnitNetPrice       = 200
                    }
                },
                Recipient = new Recipient
                {
                    Name    = "Morten",
                    VatZone = new VatZone
                    {
                        VatZoneNumber = 1
                    }
                }
            };

            var response = await Client.Value.CreateInvoice(invoice);

            await Client.Value.DeleteInvoiceDraft(response.DraftInvoiceNumber);

            await Client.Value.DeleteCustomer(customer.CustomerNumber);
        }
コード例 #25
0
        public async Task <IActionResult> CreateInvoice(CreateInvoiceModel model, CancellationToken cancellationToken)
        {
            var stores = await _StoreRepository.GetStoresByUserId(GetUserId());

            model.Stores = new SelectList(stores, nameof(StoreData.Id), nameof(StoreData.StoreName), model.StoreId);

            var paymentMethods = new SelectList(_NetworkProvider.GetAll().SelectMany(network => new[]
            {
                new PaymentMethodId(network.CryptoCode, PaymentTypes.BTCLike),
                new PaymentMethodId(network.CryptoCode, PaymentTypes.LightningLike)
            }).Select(id => new SelectListItem(id.ToString(true), id.ToString(false))),
                                                nameof(SelectListItem.Value),
                                                nameof(SelectListItem.Text));

            model.AvailablePaymentMethods = paymentMethods;

            var store = stores.FirstOrDefault(s => s.Id == model.StoreId);

            if (store == null)
            {
                ModelState.AddModelError(nameof(model.StoreId), "Tienda no encontrada");
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            StatusMessage = null;
            if (!store.HasClaim(Policies.CanCreateInvoice.Key))
            {
                ModelState.AddModelError(nameof(model.StoreId), "Necesitas ser propietario de esta tienda para crear una factura");
                return(View(model));
            }

            if (store.GetSupportedPaymentMethods(_NetworkProvider).Count() == 0)
            {
                ModelState.AddModelError(nameof(model.StoreId), "Es necesario configurar el esquema de derivación para crear una factura");
                return(View(model));
            }


            if (StatusMessage != null)
            {
                return(RedirectToAction(nameof(StoresController.UpdateStore), "Stores", new
                {
                    storeId = store.Id
                }));
            }

            try
            {
                var result = await CreateInvoiceCore(new CreateInvoiceRequest()
                {
                    Price    = model.Amount.Value,
                    Currency = model.Currency,
                    PosData  = model.PosData,
                    OrderId  = model.OrderId,
                    //RedirectURL = redirect + "redirect",
                    NotificationEmail = model.NotificationEmail,
                    NotificationURL   = model.NotificationUrl,
                    ItemDesc          = model.ItemDesc,
                    FullNotifications = true,
                    BuyerEmail        = model.BuyerEmail,
                    SupportedTransactionCurrencies = model.SupportedTransactionCurrencies?.ToDictionary(s => s, s => new InvoiceSupportedTransactionCurrency()
                    {
                        Enabled = true
                    })
                }, store, HttpContext.Request.GetAbsoluteRoot(), cancellationToken : cancellationToken);

                StatusMessage = $"Factura {result.Data.Id} creada!";
                return(RedirectToAction(nameof(ListInvoices)));
            }
            catch (BitpayHttpException ex)
            {
                ModelState.TryAddModelError(nameof(model.Currency), $"Error: {ex.Message}");
                return(View(model));
            }
        }
コード例 #26
0
 public async Task <CreateInvoiceResponseModel> PostUBL(CreateInvoiceModel model)
 {
     return(await flurlClient.Request($"/v1/outboxinvoice")
            .PostJsonAsync(model)
            .ReceiveJson <CreateInvoiceResponseModel>());
 }
コード例 #27
0
ファイル: InvoiceService.cs プロジェクト: ucdavis/payments
        public async Task <IReadOnlyList <Invoice> > CreateInvoices(CreateInvoiceModel model, Team team)
        {
            // find account
            var account = await _dbContext.FinancialAccounts
                          .FirstOrDefaultAsync(a => a.Team.Id == team.Id && a.Id == model.AccountId);

            if (account == null)
            {
                throw new ArgumentException("Account Id not found for this team.", nameof(model.AccountId));
            }

            if (!account.IsActive)
            {
                throw new ArgumentException("Account is inactive.", nameof(model.AccountId));
            }

            // find coupon
            Coupon coupon = null;

            if (model.CouponId > 0)
            {
                coupon = await _dbContext.Coupons
                         .FirstOrDefaultAsync(c => c.Team.Id == team.Id && c.Id == model.CouponId);
            }

            // manage multiple customer scenario
            var invoices = new List <Invoice>();

            foreach (var customer in model.Customers)
            {
                // create new object, track it
                var invoice = new Invoice
                {
                    DraftCount      = 1,
                    Account         = account,
                    Coupon          = coupon,
                    Team            = team,
                    ManualDiscount  = model.ManualDiscount,
                    TaxPercent      = model.TaxPercent,
                    DueDate         = model.DueDate,
                    CustomerAddress = customer.Address,
                    CustomerEmail   = customer.Email,
                    CustomerName    = customer.Name,
                    CustomerCompany = customer.Company,
                    Memo            = model.Memo,
                    Status          = Invoice.StatusCodes.Draft,
                    Sent            = false,
                };

                // add line items
                var items = model.Items.Select(i => new LineItem()
                {
                    Amount      = i.Amount,
                    Description = i.Description,
                    Quantity    = i.Quantity,
                    TaxExempt   = i.TaxExempt,
                    Total       = i.Quantity * i.Amount,
                });
                invoice.Items = items.ToList();

                // add attachments
                var attachments = model.Attachments.Where(a => !string.IsNullOrWhiteSpace(a.Identifier)).Select(a => new InvoiceAttachment()
                {
                    Identifier  = a.Identifier,
                    FileName    = a.FileName,
                    ContentType = a.ContentType,
                    Size        = a.Size,
                });
                invoice.Attachments = attachments.ToList();

                // start tracking for db
                invoice.UpdateCalculatedValues();
                _dbContext.Invoices.Add(invoice);

                invoices.Add(invoice);
            }

            return(invoices);
        }
コード例 #28
0
        public RequestResponse <object> UpdateInvoice(CreateInvoiceModel invoiceToEdit)
        {
            if (invoiceToEdit == null || invoiceToEdit.Id == Guid.Empty)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Invalid invoice data"
                }
            }
            ;
            if (invoiceToEdit.Amount <= 0)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Invoice amount must be greater than 0"
                }
            }
            ;
            if (invoiceToEdit.CreationDate == default(DateTime))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please enter Creation date"
                }
            }
            ;
            if (invoiceToEdit.DueDate == default(DateTime))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please enter Due Date"
                }
            }
            ;
            if (string.IsNullOrEmpty(invoiceToEdit.Description) || invoiceToEdit.Description.Length > 200)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Invoice description length must be 200 characters maximum"
                }
            }
            ;
            if (!Enum.IsDefined(typeof(InvoiceState), invoiceToEdit.InvoiceState))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please select a valid Invoice State"
                }
            }
            ;
            if (!Enum.IsDefined(typeof(InvoiceType), invoiceToEdit.InvoiceType))
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Please select a valid invoice type"
                }
            }
            ;
            if (invoiceToEdit.CreationDate > invoiceToEdit.DueDate)
            {
                return new RequestResponse <object> {
                           Success = false, Data = null, Message = "Due Date must be greater than Creation Date"
                }
            }
            ;
            var mappedInvoice = new Invoice {
                Id = invoiceToEdit.Id, Amount = invoiceToEdit.Amount, CreationDate = invoiceToEdit.CreationDate, Description = invoiceToEdit.Description, DueDate = invoiceToEdit.DueDate, State = (InvoiceState)invoiceToEdit.InvoiceState, Type = (InvoiceType)invoiceToEdit.InvoiceType
            };

            mappedInvoice.ModifiedDate = DateTime.Now;
            _invoiceRepository.Update(mappedInvoice);


            return(new RequestResponse <object> {
                Success = true, Data = null, Message = "Created successfully"
            });
        }
    }
}
コード例 #29
0
        public async Task <IActionResult> CreateInvoice(CreateInvoiceModel model)
        {
            var stores = await _StoreRepository.GetStoresByUserId(GetUserId());

            model.Stores = new SelectList(stores, nameof(StoreData.Id), nameof(StoreData.StoreName), model.StoreId);
            var store = stores.FirstOrDefault(s => s.Id == model.StoreId);

            if (store == null)
            {
                ModelState.AddModelError(nameof(model.StoreId), "Store not found");
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            StatusMessage = null;
            if (!store.HasClaim(Policies.CanCreateInvoice.Key))
            {
                ModelState.AddModelError(nameof(model.StoreId), "You need to be owner of this store to create an invoice");
                return(View(model));
            }

            if (store.GetSupportedPaymentMethods(_NetworkProvider).Count() == 0)
            {
                ModelState.AddModelError(nameof(model.StoreId), "You need to configure the derivation scheme in order to create an invoice");
                return(View(model));
            }

            if (StatusMessage != null)
            {
                return(RedirectToAction(nameof(StoresController.UpdateStore), "Stores", new
                {
                    storeId = store.Id
                }));
            }

            try
            {
                var result = await CreateInvoiceCore(new Invoice()
                {
                    Price    = model.Amount.Value,
                    Currency = model.Currency,
                    PosData  = model.PosData,
                    OrderId  = model.OrderId,
                    //RedirectURL = redirect + "redirect",
                    NotificationEmail = model.NotificationEmail,
                    NotificationURL   = model.NotificationUrl,
                    ItemDesc          = model.ItemDesc,
                    FullNotifications = true,
                    BuyerEmail        = model.BuyerEmail,
                }, store, HttpContext.Request.GetAbsoluteRoot());

                StatusMessage = $"Invoice {result.Data.Id} just created!";
                return(RedirectToAction(nameof(ListInvoices)));
            }
            catch (BitpayHttpException ex)
            {
                ModelState.TryAddModelError(nameof(model.Currency), $"Error: {ex.Message}");
                return(View(model));
            }
        }
コード例 #30
0
 public RequestResponse <object> Update(CreateInvoiceModel invoiceToUpdate)
 {
     return(_invoiceService.UpdateInvoice(invoiceToUpdate));
 }