Beispiel #1
0
        public async Task <ApiResult <string> > CreateCustomerAsync(CustomerForCreationDto creationDto, string accountId)
        {
            try
            {
                var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                    .SingleOrDefaultAsync();

                if (checkEmployee == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, "Lỗi tài khoản đăng nhập"));
                }
                var sequenceNumber = await _context.Customers.CountAsync();

                var customerId = IdentifyGenerator.GenerateCustomerId(sequenceNumber + 1);
                var customer   = ObjectMapper.Mapper.Map <Data.Entities.Customer>(creationDto);
                customer.Id         = customerId;
                customer.EmployeeId = checkEmployee.Id;
                await _context.Customers.AddAsync(customer);

                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = customerId, Message = "Tạo mới khách hàng thành công"
                });
            }
            catch
            {
                return(new ApiResult <string>(HttpStatusCode.InternalServerError, "Có lỗi khi tạo khách hàng"));
            }
        }
Beispiel #2
0
        public async Task <ApiResult <string> > CreateSupplierAsync(SupplierForCreationDto creationDto, string accountId)
        {
            try
            {
                var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                    .SingleOrDefaultAsync();

                if (checkEmployee == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
                }
                var sequenceNumber = await _context.Suppliers.CountAsync();

                var generateId = IdentifyGenerator.GenerateSupplierId(sequenceNumber + 1);
                var supplier   = ObjectMapper.Mapper.Map <SupplierForCreationDto, Data.Entities.Supplier>(creationDto);
                supplier.Id         = generateId;
                supplier.EmployeeId = checkEmployee.Id;
                await _context.Suppliers.AddAsync(supplier);

                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = generateId, Message = "Tạo mới nhà cung cấp thành công"
                });
            }
            catch
            {
                _logger.LogInfo("Có lỗi khi thêm nhà cung cấp");
                return(new ApiResult <string>(HttpStatusCode.InternalServerError, $"Có lỗi khi tạo mới nhà cung cấp"));
            }
        }
Beispiel #3
0
        public async Task <ApiResult <string> > CreatePurchaseOrderAsync(string accountId, PurchaseOrderForCreationDto creationDto)
        {
            try
            {
                var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                    .SingleOrDefaultAsync();

                if (checkEmployee == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
                }
                var sequenceNumber = await _context.PurchaseOrders.CountAsync();

                var purchaseOrderId = IdentifyGenerator.GeneratePurchaseOrderId(sequenceNumber + 1);
                var purchaseOrder   = ObjectMapper.Mapper.Map <eQACoLTD.Data.Entities.PurchaseOrder>(creationDto);
                purchaseOrder.Id = purchaseOrderId;
                purchaseOrder.TransactionStatusId  = GlobalProperties.InventoryTransactionId;
                purchaseOrder.PaymentStatusId      = GlobalProperties.UnpaidPaymentId;
                purchaseOrder.DateCreated          = DateTime.Now;
                purchaseOrder.EmployeeId           = checkEmployee.Id;
                purchaseOrder.BrandId              = checkEmployee.BranchId;
                purchaseOrder.PurchaseOrderDetails = new List <Data.Entities.PurchaseOrderDetail>();
                decimal totalAmount = 0;
                foreach (var p in creationDto.ListProduct)
                {
                    var purchaseOrderDetails = ObjectMapper.Mapper.Map <PurchaseOrderDetail>(p);
                    purchaseOrderDetails.Id = Guid.NewGuid().ToString("D");
                    purchaseOrderDetails.PurchaseOrderId = purchaseOrderId;
                    purchaseOrder.PurchaseOrderDetails.Add(purchaseOrderDetails);
                    totalAmount += p.UnitPrice * p.Quantity;
                }
                if (string.IsNullOrEmpty(creationDto.DiscountType))
                {
                    purchaseOrder.DiscountType  = "$";
                    purchaseOrder.DiscountValue = 0;
                }
                purchaseOrder.TotalAmount = totalAmount - (creationDto.DiscountType == "$" ? creationDto.DiscountValue
                    : (totalAmount * creationDto.DiscountValue) / 100);
                await _context.PurchaseOrders.AddAsync(purchaseOrder);

                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = purchaseOrderId, Message = "Tạo mới phiếu nhập hàng thành công"
                });
            }
            catch
            {
                return(new ApiResult <string>(HttpStatusCode.InternalServerError)
                {
                    Message = "Có lỗi khi tạo phiếu nhập hàng"
                });
            }
        }
Beispiel #4
0
        public async Task <ApiResult <string> > PurchaseOrderPaymentAsync(string accountId, string purchaseOrderId,
                                                                          PurchaseOrderPaymentForCreationDto creationDto)
        {
            var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                .SingleOrDefaultAsync();

            if (checkEmployee == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
            }
            var checkPurchaseOrder = await _context.PurchaseOrders.FindAsync(purchaseOrderId);

            if (checkPurchaseOrder == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound));
            }
            if (checkEmployee.BranchId == checkPurchaseOrder.BrandId)
            {
                var sequenceNumber = await _context.PaymentVouchers.CountAsync();

                var paymentVoucherId = IdentifyGenerator.GeneratePaymentVoucherId(sequenceNumber + 1);
                var paymentVoucher   = ObjectMapper.Mapper.Map <PaymentVoucher>(creationDto);
                paymentVoucher.Id = paymentVoucherId;
                paymentVoucher.PurchaseOrderId = purchaseOrderId;
                paymentVoucher.DateCreated     = DateTime.Now;
                paymentVoucher.SupplierId      = checkPurchaseOrder.SupplierId;
                paymentVoucher.EmployeeId      = checkEmployee.Id;
                paymentVoucher.BranchId        = checkEmployee.BranchId;
                await _context.PaymentVouchers.AddAsync(paymentVoucher);

                var totalPayment = await(from pv in _context.PaymentVouchers
                                         where pv.PurchaseOrderId == purchaseOrderId
                                         select pv.Paid).SumAsync();
                if (totalPayment - checkPurchaseOrder.TotalAmount >= 0)
                {
                    checkPurchaseOrder.TransactionStatusId = GlobalProperties.FinishedTransactionId;
                    checkPurchaseOrder.PaymentStatusId     = GlobalProperties.PaidPaymentId;
                }
                else if (checkPurchaseOrder.TotalAmount - totalPayment > 0)
                {
                    checkPurchaseOrder.TransactionStatusId = GlobalProperties.TradingTransactionId;
                    checkPurchaseOrder.PaymentStatusId     = GlobalProperties.PartialPaymentId;
                }
                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = paymentVoucherId, Message = "Tạo phiếu chi cho đơn hàng thành công"
                });
            }
            return(new ApiResult <string>(HttpStatusCode.Forbidden, $"Tài khoản hiện tại không có quyền chỉnh sửa phiếu chi tại chi nhánh này"));
        }
    public void IdentifyGeneratorTest()
    {
        var set = new HashSet <string>();

        for (int i = 1; i <= 1000000; i++)
        {
            var id = IdentifyGenerator.WebHash();
            if (!set.Add(id))
            {
                Assert.Fail("IdentifyGenerator duplicate found");
            }
        }
    }
Beispiel #6
0
        public async Task <ApiResult <string> > CreateProductAsync(ProductForCreationDto creationDto)
        {
            try
            {
                var sequenceNumber = await _context.Products.CountAsync();

                var productId = IdentifyGenerator.GenerateProductId(sequenceNumber + 1);
                var product   = ObjectMapper.Mapper.Map <Data.Entities.Product>(creationDto);
                product.Id = productId;
                await _context.Products.AddAsync(product);

                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = productId, Message = "Tạo mới sản phẩm thành công"
                });
            }
            catch
            {
                return(new ApiResult <string>(HttpStatusCode.InternalServerError, $"Có lỗi khi thêm sản phẩm"));
            }
        }
Beispiel #7
0
        public async Task <ApiResult <string> > CreateReceiptVoucherAsync(ReceiptVoucherForCreationDto creationDto, string accountId)
        {
            var employee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                           .SingleOrDefaultAsync();

            if (employee == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
            }
            if (!string.IsNullOrEmpty(creationDto.CustomerId) && !string.IsNullOrEmpty(creationDto.SupplierId))
            {
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Một phiếu thu chỉ thuộc về một đối tượng."));
            }
            if (string.IsNullOrEmpty(creationDto.CustomerId) && string.IsNullOrEmpty(creationDto.SupplierId))
            {
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Phiếu thu phải thuộc về một đối tượng"));
            }
            if (!string.IsNullOrEmpty(creationDto.CustomerId))
            {
                var checkCustomer = await _context.Customers.Where(x => x.Id == creationDto.CustomerId)
                                    .SingleOrDefaultAsync();

                if (checkCustomer == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy khách hàng có mã: {creationDto.CustomerId}"));
                }
            }
            else
            {
                var checkSupplier = await _context.Suppliers.Where(x => x.Id == creationDto.SupplierId)
                                    .SingleOrDefaultAsync();

                if (checkSupplier == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy nhà cung cấp có mã: {creationDto.SupplierId}"));
                }
            }
            if (creationDto.Received <= 0)
            {
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Số tiền thu phải là một số dương"));
            }
            var sequenceNumber = await _context.ReceiptVouchers.CountAsync();

            var receiptVoucherId = IdentifyGenerator.GenerateReceiptVoucherId(sequenceNumber + 1);
            var receiptVoucher   = new ReceiptVoucher()
            {
                Description     = creationDto.Description,
                Id              = receiptVoucherId,
                Received        = creationDto.Received,
                BranchId        = employee.BranchId,
                CustomerId      = string.IsNullOrEmpty(creationDto.CustomerId)?null:creationDto.CustomerId,
                DateCreated     = DateTime.Now,
                EmployeeId      = employee.Id,
                IsDelete        = false,
                PaymentMethodId = creationDto.PaymentMethodId,
                ReceivedDate    = creationDto.ReceivedDate,
                SupplierId      = string.IsNullOrEmpty(creationDto.SupplierId)?null:creationDto.SupplierId
            };
            await _context.ReceiptVouchers.AddAsync(receiptVoucher);

            await _context.SaveChangesAsync();

            return(new ApiResult <string>(HttpStatusCode.OK)
            {
                ResultObj = receiptVoucherId,
                Message = "Tạo phiếu thu thành công"
            });
        }
Beispiel #8
0
        public async Task <ApiResult <string> > OrderReceiveAsync(string accountId, string orderId, OrderPaymenForCreationDto creationDto)
        {
            var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                .SingleOrDefaultAsync();

            if (checkEmployee == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
            }
            var checkOrder = await _context.Orders.FindAsync(orderId);

            if (checkOrder == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, ($"Không tìm thấy đơn hàng có mã: {orderId}")));
            }
            if (checkOrder.TransactionStatusId != GlobalProperties.FinishedTransactionId &&
                checkOrder.TransactionStatusId != GlobalProperties.WaitingTransactionId &&
                checkOrder.TransactionStatusId != GlobalProperties.CancelTransactionId)
            {
                if (checkEmployee.BranchId == checkOrder.BranchId)
                {
                    var receiptVoucher = ObjectMapper.Mapper.Map <ReceiptVoucher>(creationDto);
                    var sequenceNumber = await _context.ReceiptVouchers.CountAsync();

                    var receiptVoucherId = IdentifyGenerator.GenerateReceiptVoucherId(sequenceNumber + 1);
                    receiptVoucher.Id          = receiptVoucherId;
                    receiptVoucher.OrderId     = checkOrder.Id;
                    receiptVoucher.DateCreated = DateTime.Now;
                    receiptVoucher.CustomerId  = checkOrder.CustomerId;
                    receiptVoucher.IsDelete    = false;
                    receiptVoucher.BranchId    = checkOrder.BranchId;
                    receiptVoucher.EmployeeId  = checkEmployee.Id;
                    await _context.ReceiptVouchers.AddAsync(receiptVoucher);

                    await _context.SaveChangesAsync();

                    var totalPaid = await(from rv in _context.ReceiptVouchers
                                          where rv.OrderId == checkOrder.Id
                                          select rv.Received).SumAsync();
                    var checkExportStock = await _context.GoodsDeliveryNotes.Where(x => x.OrderId == checkOrder.Id)
                                           .SingleOrDefaultAsync();

                    if (totalPaid == checkOrder.TotalAmount)
                    {
                        if (checkExportStock != null)
                        {
                            checkOrder.TransactionStatusId = GlobalProperties.FinishedTransactionId;
                        }
                        checkOrder.PaymentStatusId = GlobalProperties.PaidPaymentId;
                    }
                    else if (totalPaid < checkOrder.TotalAmount)
                    {
                        checkOrder.PaymentStatusId = GlobalProperties.PartialPaymentId;
                    }
                    else
                    {
                        return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Giá trị thanh toán lớn hơn giá trị đơn hàng"));
                    }
                    await _context.SaveChangesAsync();

                    return(new ApiResult <string>(HttpStatusCode.OK)
                    {
                        ResultObj = receiptVoucherId, Message = "Đã tạo phiếu thu cho đơn hàng"
                    });
                }
                return(new ApiResult <string>(HttpStatusCode.Forbidden, $"Tài khoản đăng nhập hiện tại không có quyền chỉnh sửa phiếu thu tại chi nhánh này"));
            }
            return(new ApiResult <string>(HttpStatusCode.BadRequest, "Chỉ được tạo phiếu thu cho đơn hàng đang trọng trạng thái giao dịch."));
        }
Beispiel #9
0
        public async Task <ApiResult <string> > CreateEmployeeAsync(EmployeeForCreationDto creationDto)
        {
            try
            {
                if (creationDto != null)
                {
                    var checkRole = await _roleManager.FindByIdAsync(creationDto.DefaultRoleId.ToString("D"));

                    if (checkRole == null)
                    {
                        _logger.LogError($"Mã quyền {creationDto.DefaultRoleId} không tồn tại");
                        return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Mã quyền {creationDto.DefaultRoleId} không tồn tại"));
                    }
                    var checkEmail = await _userManager.FindByEmailAsync(creationDto.Email);

                    if (checkEmail != null)
                    {
                        return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Email: {creationDto.Email} đã được sử dụng"));
                    }
                    var countNumber = await _context.Employees.CountAsync();

                    var generateId = IdentifyGenerator.GenerateEmployeeId(countNumber + 1);
                    var employee   = ObjectMapper.Mapper.Map <EmployeeForCreationDto, Data.Entities.Employee>(creationDto);
                    employee.Id       = generateId;
                    employee.IsDelete = false;
                    await _context.Employees.AddAsync(employee);

                    await _context.SaveChangesAsync();

                    var newAccount = new AppUser(generateId.ToLower())
                    {
                        PhoneNumber = creationDto.PhoneNumber,
                        Email       = creationDto.Email
                    };
                    var result = await _userManager.CreateAsync(newAccount, _configuration["DefaultPassword"]);

                    if (!result.Succeeded)
                    {
                        _logger.LogError("Có lỗi khi tạo tài khoản cho nhân viên");
                        return(new ApiResult <string>(HttpStatusCode.InternalServerError,
                                                      "Có lỗi khi tạo tài khoản cho nhân viên"));
                    }

                    var createdEmployee = await _context.Employees.Where(x => x.Id == generateId).SingleOrDefaultAsync();

                    if (createdEmployee != null)
                    {
                        var createdAccount = await _userManager.FindByNameAsync(newAccount.UserName);

                        createdEmployee.AppuserId = createdAccount.Id;
                        await _context.SaveChangesAsync();

                        await _userManager.AddToRoleAsync(createdAccount, checkRole.Name);

                        return(new ApiResult <string>()
                        {
                            Code = HttpStatusCode.OK,
                            ResultObj = generateId,
                            Message = "Tạo mới nhân viên thành công"
                        });
                    }
                    _logger.LogError($"Nhân viên có mã {generateId} chưa được tạo.");
                    return(new ApiResult <string>(HttpStatusCode.InternalServerError, $"Nhân viên có mã {generateId} chưa được tạo."));
                }
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Employee is null"));
            }
            catch (Exception e)
            {
                _logger.LogError($"Có lỗi khi tạo nhân viên, lỗi: {e.Message}");
                return(new ApiResult <string>(HttpStatusCode.InternalServerError, "Có lỗi khi tạo tài khoản cho nhân viên"));
            }
        }
Beispiel #10
0
        public async Task <ApiResult <string> > CreateOrderAsync(OrderForCreationDto creationDto, string accountId)
        {
            try
            {
                var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId).SingleOrDefaultAsync();

                if (checkEmployee == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound,
                                                  "Lỗi tài khoản đăng nhập."));
                }
                if (string.IsNullOrEmpty(checkEmployee.BranchId))
                {
                    return(new ApiResult <string>(HttpStatusCode.BadRequest,
                                                  $"Tài khoản hiện tại không thuộc chi nhánh nào"));
                }
                var sequenceNumber = await _context.Orders.CountAsync();

                var orderId     = IdentifyGenerator.GenerateOrderId(sequenceNumber + 1);
                var order       = ObjectMapper.Mapper.Map <Data.Entities.Order>(creationDto);
                var orderDetail = ObjectMapper.Mapper.Map <IEnumerable <OrderDetail> >(creationDto.ListOrderDetail);
                if (string.IsNullOrEmpty(creationDto.CustomerId))
                {
                    order.CustomerId   = null;
                    order.CustomerName = "Khách lẻ";
                }
                decimal totalAmount       = 0;
                int     checkIfAllService = 0;
                foreach (var od in orderDetail)
                {
                    od.Id        = Guid.NewGuid().ToString("D");
                    od.OrderId   = orderId;
                    totalAmount += od.Quantity * od.UnitPrice;
                    if (string.IsNullOrEmpty(od.ProductId))
                    {
                        od.ProductId = null;
                        checkIfAllService++;
                    }
                }
                order.Id = orderId;
                if (checkIfAllService == creationDto.ListOrderDetail.Count())
                {
                    order.TransactionStatusId = GlobalProperties.TradingTransactionId;
                }
                else
                {
                    order.TransactionStatusId = GlobalProperties.InventoryTransactionId;
                }
                order.PaymentStatusId = GlobalProperties.UnpaidPaymentId;
                order.DateCreated     = DateTime.Now;
                order.BranchId        = checkEmployee.BranchId;
                order.EmployeeId      = checkEmployee.Id;
                if (string.IsNullOrEmpty(order.DiscountType))
                {
                    order.DiscountType  = "$";
                    order.DiscountValue = 0;
                }
                order.TotalAmount  = totalAmount - (order.DiscountType == "%" ? totalAmount * order.DiscountValue / 100 : order.DiscountValue);
                order.OrderDetails = orderDetail.ToList();
                await _context.Orders.AddAsync(order);

                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = orderId, Message = "Tạo mới đơn hàng thành công"
                });
            }
            catch
            {
                return(new ApiResult <string>(HttpStatusCode.InternalServerError, "Có lỗi khi tạo đơn hàng"));
            }
        }
Beispiel #11
0
        public async Task <ApiResult <string> > CreateOrderForUnknownUser(CartDto cartDto)
        {
            var sequenceNumber = await _context.Orders.CountAsync();

            var orderId     = IdentifyGenerator.GenerateOrderId(sequenceNumber + 1);
            var orderDetail = new List <OrderDetail>();

            foreach (var item in cartDto.ListProduct)
            {
                var result = await GetProductPrice(item.ProductId);

                orderDetail.Add(new OrderDetail()
                {
                    Id        = Guid.NewGuid().ToString("D"),
                    Quantity  = item.Quantity,
                    OrderId   = orderId,
                    ProductId = item.ProductId,
                    UnitPrice = result.Item1
                });
            }
            var order = new Data.Entities.Order()
            {
                Id = orderId,
                CustomerAddress     = cartDto.Address,
                CustomerName        = cartDto.CustomerName,
                CustomerPhone       = cartDto.PhoneNumber,
                DateCreated         = DateTime.Now,
                TransactionStatusId = GlobalProperties.WaitingTransactionId,
                PaymentStatusId     = GlobalProperties.UnpaidPaymentId,
                TotalAmount         = orderDetail.Select(x => x.Quantity * x.UnitPrice).Sum(),
                DiscountValue       = 0,
                DiscountType        = "$",
                OrderDetails        = orderDetail
            };
            await _context.Orders.AddAsync(order);

            await _context.SaveChangesAsync();

            var content =
                $"Cảm ơn quý khách: {order.CustomerName} đã mua hàng tại Máy tính Quang Anh. Đơn hàng của quý khách gồm các sản phẩm: ";

            foreach (var item in order.OrderDetails)
            {
                var product = await _context.Products.Where(x => x.Id == item.ProductId).SingleOrDefaultAsync();

                content += $"{product.Name} (Đơn giá: {item.UnitPrice} đồng, Số lượng: {item.Quantity} cái), ";
            }
            content +=
                $"để công ty có thể đóng gói và gửi hàng cho quý khách theo địa chỉ:{order.CustomerAddress}, quý khách vui lòng chuyển khoản trước 10% giá trị tổng đơn hàng: {(order.TotalAmount.ToString("#,##0"))} đồng, " +
                $"tức: {(order.TotalAmount * 10 / 100).ToString("#,##0")} đồng vào Số tài khoản: 0123456789101112, Chủ sở hữu: Hoàng Kim Quang, Ngân hàng Vietcombank với nội dung như sau: \"Chuyen tien dat coc 10% cho don hang ma so: {order.Id}\" " +
                $".Mong quý khách hãy để ý điện thoại để có thể nhận được thông tin đơn vận chuyển từ nhà vận chuyển, xin cảm ơn quý khách!";
            var sendTestEmail = new Message(new string[] { cartDto.Email }, "Xác nhận đơn hàng Máy tính Quang Anh", content, null);

            try
            {
                await _emailSender.SendEmailAsync(sendTestEmail);
            }
            catch
            {
                return(new ApiResult <string>(HttpStatusCode.OK, $"Tạo đơn hàng thành công")
                {
                    ResultObj = orderId
                });
            }
            return(new ApiResult <string>(HttpStatusCode.OK, $"Tạo đơn hàng thành công")
            {
                ResultObj = orderId
            });
        }
Beispiel #12
0
        public async Task <ApiResult <string> > ExportOrderAsync(string accountId, string orderId, ExportOrderDto orderDto)
        {
            try
            {
                var checkOrder = await _context.Orders.FindAsync(orderId);

                if (checkOrder == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, ($"Không tìm thấy đơn hàng có mã: {orderId}")));
                }
                var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                    .SingleOrDefaultAsync();

                if (checkEmployee == null)
                {
                    return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
                }
                if (checkOrder.BranchId == checkEmployee.BranchId)
                {
                    var goodsDeliveryNote = ObjectMapper.Mapper.Map <GoodsDeliveryNote>(orderDto);
                    var sequenceNumber    = await _context.GoodsDeliveryNotes.CountAsync();

                    var goodsDeliveryNoteId = IdentifyGenerator.GenerateGoodsDeliveryNoteId(sequenceNumber + 1);
                    goodsDeliveryNote.Id         = goodsDeliveryNoteId;
                    goodsDeliveryNote.OrderId    = orderId;
                    goodsDeliveryNote.EmployeeId = checkEmployee.Id;
                    var goodsDeliveryNoteDetails = await(from od in _context.OrderDetails
                                                         where od.OrderId == checkOrder.Id && od.ProductId != null
                                                         select new GoodsDeliveryNoteDetail()
                    {
                        Id = Guid.NewGuid().ToString("D"),
                        GoodsDeliveryNoteId = goodsDeliveryNoteId,
                        ProductId           = od.ProductId,
                        Quantity            = od.Quantity,
                        UnitPrice           = od.UnitPrice
                    }).ToListAsync();
                    foreach (var g in goodsDeliveryNoteDetails)
                    {
                        var prod = await _context.Stocks.Where(x => x.ProductId == g.ProductId && x.WarehouseId == orderDto.WarehouseId).
                                   SingleOrDefaultAsync();

                        if (prod == null)
                        {
                            return(new ApiResult <string>(HttpStatusCode.NotFound, $"Sản phẩm không có trong kho"));
                        }
                        prod.RealQuantity -= g.Quantity;
                        prod.AbleToSale   -= g.Quantity;
                        if (checkOrder.PaymentStatusId == GlobalProperties.PaidPaymentId)
                        {
                            checkOrder.TransactionStatusId = GlobalProperties.FinishedTransactionId;
                        }
                        else
                        {
                            checkOrder.TransactionStatusId = GlobalProperties.TradingTransactionId;
                        }
                    }
                    goodsDeliveryNote.GoodsDeliveryNoteDetails = goodsDeliveryNoteDetails;
                    await _context.GoodsDeliveryNotes.AddAsync(goodsDeliveryNote);

                    await _context.SaveChangesAsync();

                    return(new ApiResult <string>(HttpStatusCode.OK)
                    {
                        ResultObj = goodsDeliveryNoteId, Message = "Xuất kho cho đơn hàng thành công"
                    });
                }
                return(new ApiResult <string>(HttpStatusCode.Forbidden, ($"Tài khoản hiện tại không được phép tạo phiếu xuất kho cho chi nhánh này")));
            }
            catch
            {
                return(new ApiResult <string>(HttpStatusCode.InternalServerError, "Có lỗi khi tạo phiếu xuất kho"));
            }
        }
Beispiel #13
0
        public async Task <ApiResult <string> > ImportPurchaseOrderAsync(string accountId, string purchaseOrderId, ImportPurchaseOrderDto orderDto)
        {
            var checkPurchaseOrder = await _context.PurchaseOrders.FindAsync(purchaseOrderId);

            if (checkPurchaseOrder == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound));
            }
            var checkEmployee = await _context.Employees.Where(x => x.AppuserId.ToString() == accountId)
                                .SingleOrDefaultAsync();

            if (checkEmployee == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Lỗi tài khoản đăng nhập"));
            }
            if (checkEmployee.BranchId == checkPurchaseOrder.BrandId)
            {
                var sequencyNumber = await _context.GoodReceivedNotes.CountAsync();

                var goodsReceivedId      = IdentifyGenerator.GenerateGoodsReceivedNoteId(sequencyNumber + 1);
                var goodsReceivedNote    = ObjectMapper.Mapper.Map <GoodsReceivedNote>(orderDto);
                var purchaseOrderDetails = await(from pod in _context.PurchaseOrderDetails
                                                 where pod.PurchaseOrderId == purchaseOrderId
                                                 select new GoodsReceivedNoteDetail()
                {
                    Id = Guid.NewGuid().ToString("D"),
                    GoodsReceivedNoteId = goodsReceivedId,
                    ProductId           = pod.ProductId,
                    Quantity            = pod.Quantity,
                    UnitPrice           = pod.UnitPrice
                }).ToListAsync();
                goodsReceivedNote.Id         = goodsReceivedId;
                goodsReceivedNote.EmployeeId = checkEmployee.Id;
                goodsReceivedNote.GoodsReceivedNoteDetails = purchaseOrderDetails;
                goodsReceivedNote.PurchaseOrderId          = purchaseOrderId;
                foreach (var p in goodsReceivedNote.GoodsReceivedNoteDetails)
                {
                    p.Id = Guid.NewGuid().ToString("D");
                    p.GoodsReceivedNoteId = goodsReceivedId;
                    var productInStock = await _context.Stocks.Where(x => x.ProductId == p.ProductId &&
                                                                     x.WarehouseId == orderDto.WarehouseId).SingleOrDefaultAsync();

                    if (productInStock == null)
                    {
                        await _context.Stocks.AddAsync(new Data.Entities.Stock()
                        {
                            AbleToSale   = p.Quantity,
                            ProductId    = p.ProductId,
                            RealQuantity = p.Quantity,
                            WarehouseId  = orderDto.WarehouseId
                        });
                    }
                    else
                    {
                        productInStock.RealQuantity += p.Quantity;
                        productInStock.AbleToSale   += p.Quantity;
                    }
                }
                await _context.GoodReceivedNotes.AddAsync(goodsReceivedNote);

                checkPurchaseOrder.TransactionStatusId = GlobalProperties.TradingTransactionId;
                await _context.SaveChangesAsync();

                return(new ApiResult <string>(HttpStatusCode.OK)
                {
                    ResultObj = goodsReceivedId, Message = "Nhập kho cho phiếu nhập hàng thành công"
                });
            }
            return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Tài khoản hiện tại không được phép tạo phiếu nhập cho chi nhánh này"));
        }
Beispiel #14
0
        public async Task <ApiResult <string> > CreateOrderFromCartAsync(string customerId)
        {
            var checkCustomerAccount = await _context.AppUsers.Where(x => x.Id.ToString() == customerId).SingleOrDefaultAsync();

            if (checkCustomerAccount == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy tài khoản"));
            }
            var checkCustomer = await _context.Customers.Where(x => x.AppUserId == checkCustomerAccount.Id).SingleOrDefaultAsync();

            if (checkCustomer == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy khách hàng"));
            }
            var carts = await _context.Carts.Where(x => x.AppUserId == checkCustomerAccount.Id).ToListAsync();

            if (carts == null || carts.Count == 0)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Giỏ hàng của khách hàng đang trống"));
            }
            if (string.IsNullOrEmpty(checkCustomer.Name) || string.IsNullOrEmpty(checkCustomer.PhoneNumber) ||
                string.IsNullOrEmpty(checkCustomer.Address))
            {
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Hãy cập nhập thông tin cá nhân trước khi đặt hàng"));
            }
            var sequenceNumber = await _context.Orders.CountAsync();

            var orderId      = IdentifyGenerator.GenerateOrderId(sequenceNumber + 1);
            var orderDetails = new List <OrderDetail>();

            foreach (var cart in carts)
            {
                orderDetails.Add(new OrderDetail()
                {
                    Id        = Guid.NewGuid().ToString("D"),
                    OrderId   = orderId,
                    ProductId = cart.ProductId,
                    Quantity  = cart.Quantity,
                    UnitPrice = await GetProductPrice(cart.ProductId)
                });
            }
            var order = new Data.Entities.Order()
            {
                Id                  = orderId,
                CustomerId          = checkCustomer.Id,
                TransactionStatusId = GlobalProperties.WaitingTransactionId,
                PaymentStatusId     = GlobalProperties.UnpaidPaymentId,
                TotalAmount         = orderDetails.Sum(x => x.Quantity * x.UnitPrice),
                DateCreated         = DateTime.Now,
                OrderDetails        = orderDetails
            };
            await _context.Orders.AddAsync(order);

            _context.RemoveRange(carts);
            await _context.SaveChangesAsync();

            return(new ApiResult <string>(HttpStatusCode.OK)
            {
                ResultObj = orderId,
                Message = "Đã tạo đơn hàng"
            });
        }