Exemplo n.º 1
0
        public async Task <IActionResult> Create([FromBody] CreateInvoiceReq req)
        {
            var entry = req.toEntity(HttpContext.UserId().Value);
            await repo.Create(entry);

            return(Created($"/api/entrys/${entry.Id}", entry));
        }
Exemplo n.º 2
0
        public void AddInvoice(InvoiceForCreationDto invoice, List <SelectingProductForSellDto> products)
        {
            // 1. add custom?
            var phoneNumber = invoice.PhoneNumber;

            // check if it's existing?
            var customer   = _customerRepository.GetCustomByPhoneNumber(phoneNumber);
            var customerId = -1;

            if (customer == null)
            {
                customer = new Customer {
                    Name = invoice.CustomerName, PhoneNumber = phoneNumber, CreationTime = DateTime.Now, AccumulatedPoint = invoice.Price / 100000
                };
                if (customer.AccumulatedPoint >= _customerLevelRepository.GetCustomerLevelByName("Hạng Vàng").PointLevel)
                {
                    customer.CustomerLevelId = 3;
                }
                else if (customer.AccumulatedPoint >= _customerLevelRepository.GetCustomerLevelByName("Hạng Bạc").PointLevel)
                {
                    customer.CustomerLevelId = 2;
                }
                else
                {
                    customer.CustomerLevelId = 1;
                }
                var storedCustomer = _customerRepository.Create(customer);
                customerId = storedCustomer.Id;
            }
            else
            {
                customerId = customer.Id;
            }

            // 2. add invoice
            var storedInvoice = _invoiceRepository.Create(new Invoice
            {
                CustomerId   = customerId,
                UserId       = Session.CurrentUser.Id,
                CreationTime = DateTime.Now,
                Total        = invoice.Total,
                Discount     = invoice.Discount,
                Price        = invoice.Price
            });;

            // 3. add invoice's products and decrease no. each product
            foreach (var product in products)
            {
                var invoiceProduct = new InvoiceProduct
                {
                    ProductId = product.Id,
                    Number    = product.SelectedNumber,
                    InvoiceId = storedInvoice.Id
                };

                _invoiceProductRepository.Create(invoiceProduct);
                _productRepository.UpdateNumberById(product.Id, product.SelectedNumber);
            }
        }
        public void Create_should_return_an_invoice()
        {
            // Arrange
            var instance = new Invoice("1001", Guid.Empty.ToString(), DateTimeOffset.Now.Date, DateTimeOffset.Now.Date,
                                       new InvoiceCustomer("Customer 1001", new List <string>()), new List <InvoiceLine>());

            // Act
            var response = testSubject.Create(instance);

            // Assert
            Assert.NotNull(response);
        }
        public void Create_Success_ReturnEntity()
        {
            // Arrange
            var repository = new InvoiceRepository();
            var input      = GenerateInput();

            // Act
            var result = repository.Create(input);

            // Assert
            Assert.That(CompareProperties(input, result));
        }
        public void Get_Success_ReturnEntity()
        {
            // Arrange
            var repository = new InvoiceRepository();
            var input      = repository.Create(GenerateInput());

            // Act
            var result = repository.Get(input.Id);

            // Assert
            Assert.IsInstanceOf <Invoice>(result);
        }
        public void Delete_Success_ReturnNull()
        {
            // Arrange
            var repository = new InvoiceRepository();
            var input      = repository.Create(GenerateInput());

            // Act
            repository.Delete(input.Id);
            var result = repository.Get(input.Id);

            // Assert
            Assert.IsNull(result);
        }
        public void Update_Success_ReturnTrue()
        {
            // Arrange
            var repository = new InvoiceRepository();
            var input      = repository.Create(GenerateInput());

            var inputForUpdate = GenerateInput(id: input.Id);

            // Act
            var result = repository.Update(inputForUpdate);

            // Assert
            Assert.IsTrue(result);
        }
Exemplo n.º 8
0
 public static Invoice Create(
     UserModel user            = null, int?entityId = null, EntityType entityType = EntityType.Project,
     CurrencyType currencyType = CurrencyType.BitCoin, InvoiceStatus status = InvoiceStatus.Created
     )
 {
     return(InvoiceRepository.Create(
                user ?? UserFaker.Create(),
                entityId ?? ProjectFaker.Create().id,
                entityType,
                0.001M * Rand.SmallInt(),
                currencyType,
                status,
                CurrencyWalletFaker.Create(currencyType)
                ));
 }
Exemplo n.º 9
0
        public void Create_DataCorrect_GotInvoice()
        {
            var user   = UserFaker.Create();
            var result = InvoiceRepository.Create(
                user,
                Rand.Int(),
                EntityType.Project,
                0.0001M * Rand.SmallInt(),
                CurrencyType.BitCoin,
                InvoiceStatus.Created,
                CurrencyWalletFaker.Create(CurrencyType.BitCoin)
                );

            Assert.NotNull(result);
            Assert.AreEqual(user.id, result.User().id);
        }
Exemplo n.º 10
0
        public void TestAggregateChange()
        {
            var repo    = new InvoiceRepository();
            var invoice = repo.Create();

            Assert.IsTrue(invoice.GetEntityState() == EntityState.New);
            Assert.IsFalse(invoice.ChangeTracker.GetIsChanged());
            Assert.IsFalse(invoice.ChangeTracker.GetIsChangedDeep());

            var line = invoice.CreateNewLine();

            line.Quantity  = 1;
            line.ProductId = 1;

            invoice.OnPersisted();

            Assert.IsTrue(invoice.GetEntityState() == EntityState.Existing);
            Assert.IsFalse(invoice.ChangeTracker.GetIsChangedDeep());
        }
Exemplo n.º 11
0
        public void DomainSerializerTest()
        {
            var serializer         = new DomainSerializer();
            var customerRepository = new CustomerRepository();


            var customer = customerRepository.CreateNew(0, "No");

            customer.MainAddress = new Address("1", "1", null, null, new Phone("!23", 1), null);
            customer.OtherAddresses.AddRange(new[] {
                new Address("2", "2", null, null, new Phone("9123", 1), null),
                new Address("3", "3", null, null, new Phone("123123", 1), null),
            });

            var serializedCustomer = serializer.Serialize(customer);

            var customerCopy = serializer.Deserialize <Customer>(serializedCustomer);

            Assert.IsTrue(ObjectComparer.Default.DeepEquals(customer, customerCopy));

            var invoiceRepository = new InvoiceRepository();

            var invoice = invoiceRepository.Create();
            var line    = invoice.CreateNewLine();

            line.Quantity  = 0.5m;
            line.ProductId = 1;
            line.SetKey(1);

            line           = invoice.CreateNewLine();
            line.Quantity  = 0.7m;
            line.ProductId = 2;
            line.SetKey(2);

            var serializedInvoice = serializer.Serialize(invoice);

            var invoiceCopy = serializer.Deserialize <Invoice>(serializedInvoice);

            Assert.IsTrue(ObjectComparer.Default.DeepEquals(invoice, invoiceCopy));
        }
Exemplo n.º 12
0
 public void Create(Invoice entity)
 {
     _repository.Create(entity);
 }
Exemplo n.º 13
0
        public InvoiceController()
        {
            Post("/api/v1/invoice/new", _ => {
                var me = DL.Model.User.User.Find(CurrentRequest.UserId);

                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "entity_guid", "entity_type", "amount", "currency_type" }),
                    new ShouldBeCorrectEnumValue("entity_type", typeof(EntityType)),
                    new ShouldBeCorrectEnumValue("currency_type", typeof(CurrencyType)),
                    new EntityShouldExist(),
                    new UserActiveInvoicesLimit(me, InvoiceConfig.UserActiveInvoicesLimit),
                }, true);
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var entityType = (EntityType)GetRequestEnum("entity_type", typeof(EntityType));

                var currencyType = (CurrencyType)GetRequestEnum("currency_type", typeof(CurrencyType));

                var wallet = CurrencyWalletRepository.FindRandom(currencyType);

                var invoice = InvoiceRepository.Create(
                    me,
                    EntityUtils.GetEntityId(GetRequestStr("entity_guid"), entityType),
                    entityType,
                    (decimal)Request.Query["amount"],
                    currencyType,
                    InvoiceStatus.Created,
                    wallet
                    );

                return(HttpResponse.Item(
                           "invoice", new InvoiceTransformer().Transform(invoice), HttpStatusCode.Created
                           ));
            });

            Get("/api/v1/me/invoice/get", _ => {
                var me = UserRepository.Find(CurrentRequest.UserId);

                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "invoice_guid" }),
                    new ExistsInTable("invoice_guid", "invoices", "guid"),
                    new StringShouldBeSameInDb(
                        "invoice_guid", "invoices", "guid", "user_id", me.id.ToString()
                        )
                }, true);
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                return(HttpResponse.Item("invoice", new InvoiceTransformer().Transform(
                                             InvoiceRepository.FindByGuid(GetRequestStr("invoice_guid"))
                                             )));
            });

            Get("/api/v1/me/invoices/finished", _ => {
                var me = UserRepository.Find(CurrentRequest.UserId);

                var invoices = DL.Model.Funding.Invoice.GetForUserByStatuses(me, new [] {
                    InvoiceStatus.Confirmed, InvoiceStatus.Failed, InvoiceStatus.Done
                });

                return(HttpResponse.Item("invoices", new InvoiceTransformer().Many(invoices)));
            });

            Get("/api/v1/me/invoices/active", _ => {
                var me = UserRepository.Find(CurrentRequest.UserId);

                var invoices = DL.Model.Funding.Invoice.GetActiveForUser(me, 25);

                return(HttpResponse.Item("invoices", new InvoiceTransformer().Many(invoices)));
            });

            Patch("/api/v1/me/invoice/status/update", _ => {
                var me = UserRepository.Find(CurrentRequest.UserId);

                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "invoice_guid", "status" }),
                    new ExistsInTable("invoice_guid", "invoices", "guid"),
                    new ShouldBeCorrectEnumValue("status", typeof(InvoiceStatus)),
                    new StringShouldBeSameInDb(
                        "invoice_guid", "invoices", "guid", "user_id", me.id.ToString()
                        )
                }, true);
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var newStatus = (InvoiceStatus)GetRequestEnum("status", typeof(InvoiceStatus));

                var invoice = InvoiceRepository.FindByGuid(GetRequestStr("invoice_guid"));

                if (invoice.status != InvoiceStatus.Created)
                {
                    return(HttpResponse.Error(new HttpError(HttpStatusCode.Forbidden, "Cannot update invoice with this status")));
                }

                var availableStatuses = new[] { InvoiceStatus.Failed, InvoiceStatus.RequiresConfirmation };

                if (!availableStatuses.Contains(newStatus))
                {
                    return(HttpResponse.Error(new HttpError(HttpStatusCode.Forbidden, "This status is not allowed")));
                }

                InvoiceRepository.UpdateStatus(invoice, newStatus);

                return(HttpResponse.Item("invoice", new InvoiceTransformer().Transform(invoice.Refresh())));
            });
        }