Esempio n. 1
0
        public async Task <ApiResult <ReturnUpdate> > Update(UpdateBill bundle)
        {
            var json        = JsonConvert.SerializeObject(bundle);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            var url         = $"/api/Bill";
            var result      = await Update <ReturnUpdate>(url, httpContent);

            return(result);
        }
Esempio n. 2
0
        public CommunicationResponse UpdateBill([FromBody] UpdateBillRequest billRequest)
        {
            var response = new AddBillResponse();

            try
            {
                if (_userService.AuthenticateSession(Request.Headers["Authorization"].ToString()) == false)
                {
                    response.AddError("The authorization credentails were invalid", ErrorCode.SESSION_INVALID);
                    return(response);
                }

                ActiveUser user = _userService.GetUserInformationFromAuthHeader(Request.Headers["Authorization"].ToString());
                if (user.HouseId == 0)
                {
                    response.AddError("You must belong to a household to update bills", ErrorCode.USER_NOT_IN_HOUSEHOLD);
                    return(response);
                }
                UpdateBill bill = new UpdateBill
                {
                    Name          = billRequest.Name,
                    Id            = billRequest.Id,
                    Due           = billRequest.Due,
                    PeopleIds     = billRequest.PeopleIds,
                    TotalAmount   = billRequest.TotalAmount,
                    RecurringType = billRequest.RecurringType
                };
                var rowUpdated = _billRepository.UpdateBill(bill);

                if (rowUpdated == false)
                {
                    response.AddError("The given Bill Id does not correspond to an existing Bill");
                    return(response);
                }

                response.Notifications = new List <string>
                {
                    $"The bill '{billRequest.Name}' has been updated"
                };
            }
            catch (ErrorCodeException exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", billRequest, exception.Code);
            }
            catch (Exception exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", billRequest);
            }

            return(response);
        }
Esempio n. 3
0
        public async Task <IActionResult> Update([FromBody] UpdateBill bundle)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _billService.Update(bundle);

            if (!result.IsSuccessed)
            {
                return(BadRequest(result));
            }
            return(Ok(result));
        }
Esempio n. 4
0
        // 修改页面   订单查询按钮
        private void materialRaisedButton4_Click_1(object sender, EventArgs e)
        {
            MysqlManager manager = new MysqlManager();

            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入订单编号!");
            }
            else
            {
                BillPO bill = manager.getBillPObyBillid(textBox1.Text);
                if (bill == null)
                {
                    MessageBox.Show("订单编号输入有误,请重新输入!");
                }
                else
                {
                    UpdateBill updateBill = new UpdateBill(textBox1.Text);
                    updateBill.StartPosition = FormStartPosition.CenterParent;
                    updateBill.ShowDialog();
                }
            }
        }
Esempio n. 5
0
        public void GenerateNextMonthsBills(int houseId)
        {
            // Only works for first household
            var bills = _billRepository.GetAllBasicBillDetails(new Pagination
            {
                Page           = 0,
                ResultsPerPage = int.MaxValue
            }, houseId);

            var recurringBills = bills.Where(bill => bill.RecurringType == RecurringType.Monthly);

            foreach (var recurringBill in recurringBills)
            {
                if (recurringBill.FullDateDue > DateTime.Today)
                {
                    continue;
                }

                var billUpdateRequest = new UpdateBill
                {
                    Id            = recurringBill.Id,
                    RecurringType = RecurringType.None
                };
                _billRepository.UpdateBill(billUpdateRequest);

                var addBillRequest = new AddBill
                {
                    Due           = recurringBill.FullDateDue.AddMonths(1),
                    RecurringType = RecurringType.Monthly,
                    Name          = recurringBill.Name,
                    PeopleIds     = recurringBill.People.Select(person => person.Id).ToList(),
                    TotalAmount   = recurringBill.TotalAmount,
                    HouseId       = houseId
                };
                _billRepository.AddBill(addBillRequest);
            }
        }
Esempio n. 6
0
        public async Task <ApiResult <ReturnUpdate> > Update(UpdateBill bundle)
        {
            var bill = await _context.Bills.Include(x => x.BillDetails)
                       .FirstOrDefaultAsync(x => x.Id == bundle.IdBill);

            if (bill == null)
            {
                return(new ApiErrorResult <ReturnUpdate>("Không tồn tại hóa đơn"));
            }

            var billDetails = new List <BillDetail>();
            List <OrderDetail> listOrderDetails = new List <OrderDetail>();
            List <Material>    listMaterial     = new List <Material>();
            var    i     = 0;
            double total = 0;

            foreach (var item in bundle.IdMaterials)
            {
                double resultPrice = (bundle.EnterAmount[i] * bundle.Price[i]);
                double money       = 0;

                if (bundle.Discount[i] != 0)
                {
                    int percentComplete = (int)Math.Round((double)(resultPrice * bundle.Discount[i]) / 100);

                    money  = (resultPrice - percentComplete);
                    total += money;
                }
                else
                {
                    total += resultPrice;
                    money  = resultPrice;
                }

                // cập nhật số lượng: lấy số lượng nhập trừ số lượng hiện tại
                var bd        = bill.BillDetails.FirstOrDefault(x => x.IdMaterials == item);
                var howAmount = bundle.EnterAmount[i] - bd.Amount;

                var orderD = await _context.OrderDetails.FirstOrDefaultAsync(x => x.IdOrderPlan == bill.IdPlan &&
                                                                             x.IdMaterials == bundle.IdMaterials[i]);

                var amountNew = howAmount + orderD.EnterAmount;

                orderD.EnterAmount = amountNew;

                // cập nhật số lượng bên nguyên vật liệu
                var materials = await _context.Materials.Include(x => x.Packs)
                                .Where(x => x.Id == item).FirstOrDefaultAsync();

                var amountDefault    = materials.Packs.Where(x => x.Default == true).First();
                var materialsDefault = materials.Amount;
                if (amountDefault.Name == bd.Unit)
                {
                    materials.Amount = materialsDefault + howAmount;
                }
                else
                {
                    var amountPack = materials.Packs.Where(x => x.Name == bd.Unit).First();

                    var resultAmount = (long)(howAmount) * amountPack.Value;
                    materials.Amount = materialsDefault + resultAmount;
                }
                listMaterial.Add(materials);

                // cập nhật số lượng chi tiết đặt hàng
                if (amountNew >= orderD.Amount)
                {
                    orderD.Status = true;
                }
                else
                {
                    orderD.Status = false;
                }

                listOrderDetails.Add(orderD);

                bd.Price      = (decimal)bundle.Price[i];
                bd.Discount   = bundle.Discount[i];
                bd.Amount     = bundle.EnterAmount[i];
                bd.TotalPrice = (decimal)money;

                i++;
            }

            List <OrderDetail> listOrderDetailsCreate = new List <OrderDetail>();
            List <Material>    listMaterialCreate     = new List <Material>();
            List <BillDetail>  listBillDetailsCreate  = new List <BillDetail>();

            // khởi tạo thêm nguyên vật liệu vào hóa đơn
            if (bundle.EnterAmountCreate != null)
            {
                int y = 0;
                foreach (var create in bundle.EnterAmountCreate)
                {
                    if (create != 0)
                    {
                        double resultPrice = (bundle.EnterAmountCreate[y] * bundle.PriceCreate[y]);
                        double money       = 0;
                        if (bundle.Discount[i] != 0)
                        {
                            int percentComplete = (int)Math.Round((double)(resultPrice * bundle.DiscountCreate[y]) / 100);

                            money  = (resultPrice - percentComplete);
                            total += money;
                        }
                        else
                        {
                            total += resultPrice;
                            money  = resultPrice;
                        }

                        var billOr = new BillDetail()
                        {
                            IdBill      = bundle.IdBill,
                            Amount      = create,
                            Discount    = bundle.DiscountCreate[y],
                            Unit        = bundle.UnitCreate[y],
                            Price       = (decimal)bundle.PriceCreate[y],
                            TotalPrice  = (decimal)money,
                            IdMaterials = bundle.IdMaterialsCreate[y]
                        };
                        listBillDetailsCreate.Add(billOr);
                        // cập nhật số lượng chi tiết đặt hàng
                        var orderD = await _context.OrderDetails.FirstOrDefaultAsync(x => x.IdOrderPlan == bill.IdPlan);

                        var enterAmountNow = orderD.EnterAmount + bundle.EnterAmountCreate[y];
                        if (enterAmountNow >= orderD.Amount)
                        {
                            orderD.Status = true;
                        }
                        else
                        {
                            orderD.Status = false;
                        }
                        orderD.EnterAmount = enterAmountNow;
                        listOrderDetailsCreate.Add(orderD);

                        // cập nhật số lượng bên nguyên vật liệu

                        var materials = await _context.Materials.Include(x => x.Packs)
                                        .Where(x => x.Id == bundle.IdMaterialsCreate[y]).FirstOrDefaultAsync();

                        var amountDefault    = materials.Packs.Where(x => x.Default == true).First();
                        var materialsDefault = materials.Amount;
                        if (amountDefault.Name == bundle.UnitCreate[y])
                        {
                            materials.Amount = materialsDefault + create;
                        }
                        else
                        {
                            var amountPack = materials.Packs.Where(x => x.Name == bundle.UnitCreate[y]).First();

                            var resultAmount = (long)(create) * amountPack.Value;
                            materials.Amount = materialsDefault + resultAmount;
                        }
                        listMaterialCreate.Add(materials);
                    }
                    y++;
                }
            }
            //////////////

            if (bundle.Tax != 0)
            {
                int tax = (int)Math.Round((double)(total * bundle.Tax) / 100);
                total += tax;
            }

            // chuyển số thành chữ
            var convert = "";

            if (total != 0)
            {
                convert = this.NumberToText(total);
            }

            bill.IdSupplier     = bundle.IdSupliers;
            bill.PurchaseDate   = bundle.PurchaseDate;
            bill.Tax            = bundle.Tax;
            bill.AmountPaid     = Decimal.Parse(bundle.AmountPaid);
            bill.CodeBill       = bundle.CodeBill;
            bill.ConvertNumbers = convert;
            bill.TotalMoney     = (decimal)total;
            // cập nhật trạng thái
            var amountPaid = Double.Parse(bundle.AmountPaid);

            if (amountPaid == 0)
            {
                bill.PaymentStatus = PaymentStatus.Unpaid;
            }

            if (amountPaid > 0 && amountPaid < total)
            {
                bill.PaymentStatus = PaymentStatus.PartialPayment;
            }

            if (amountPaid >= total)
            {
                bill.PaymentStatus = PaymentStatus.Paid;
            }

            // Cập nhật hóa đơn và chi tiết hóa đơn
            _context.OrderDetails.UpdateRange(listOrderDetails);
            _context.Materials.UpdateRange(listMaterial);

            //Khởi tạo chi tiết hóa đơn
            _context.BillDetails.AddRange(listBillDetailsCreate);
            _context.OrderDetails.UpdateRange(listOrderDetailsCreate);
            _context.Materials.UpdateRange(listMaterialCreate);

            _context.Bills.Update(bill);
            await _context.SaveChangesAsync();

            // cập nhật trạng thái kế hoạch đặt hàng
            var check     = true;
            var orderPlan = await _context.OrderPlans.Include(x => x.OrderDetails)
                            .Where(x => x.Id == bill.IdPlan).FirstOrDefaultAsync();

            foreach (var item in orderPlan.OrderDetails)
            {
                if (!item.Status)
                {
                    check = false;
                    break;
                }
            }
            if (check)
            {
                orderPlan.Status = StatusOrderPlan.Accomplished;
            }
            else
            {
                orderPlan.Status = StatusOrderPlan.Unfinished;
            }
            _context.OrderPlans.Update(orderPlan);
            await _context.SaveChangesAsync();

            var countBills = await _context.BillDetails.Where(x => x.IdBill == bill.Id).ToListAsync();

            var delete = false;

            if (countBills == null)
            {
                delete = true;
            }
            else
            {
                foreach (var item in countBills)
                {
                    if (item.Amount != 0)
                    {
                        delete = false;
                        break;
                    }
                    else
                    {
                        delete = true;
                    }
                }
            }

            var pay = true;

            if (bill.PaymentStatus == PaymentStatus.Paid)
            {
                pay = false;
            }
            var result = new ReturnUpdate()
            {
                StatusOrder   = delete,
                PaymentStatus = pay,
                CodeBill      = bill.CodeBill,
                Id            = bill.Id
            };

            if (delete)
            {
                await this.DeleteNotMaterials(result.Id);
            }
            return(new ApiSuccessResult <ReturnUpdate>(result));
        }
Esempio n. 7
0
        public bool UpdateBill(UpdateBill billRequest)
        {
            NpgsqlConnection connection = new NpgsqlConnection(_connectionString);

            connection.Open();

            try
            {
                var setValues = new List <string>();

                if (billRequest.Name != null)
                {
                    setValues.Add($"\"Name\"='{billRequest.Name}'");
                }
                if (billRequest.TotalAmount != null)
                {
                    setValues.Add($"\"Amount\"={billRequest.TotalAmount}");
                }
                if (billRequest.Due != null)
                {
                    setValues.Add($"\"Due\"='{billRequest.Due}'");
                }
                if (billRequest.RecurringType != null)
                {
                    setValues.Add($"\"RecurringType\"={(int)billRequest.RecurringType}");
                }

                var              rowUpdated = false;
                NpgsqlCommand    command;
                Int64            billId = -1;
                NpgsqlDataReader reader;

                if (setValues.Count > 0)
                {
                    command = new NpgsqlCommand("UPDATE public.\"Bill\" " +
                                                $"SET {string.Join(", ", setValues)} " +
                                                $"WHERE \"Id\" = {billRequest.Id} " +
                                                "RETURNING \"Id\"", connection);
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        rowUpdated = true;
                        billId     = (Int64)reader[0];
                    }
                    reader.Close();
                }

                if (billRequest.PeopleIds == null || billRequest.PeopleIds.Count == 0)
                {
                    return(rowUpdated);
                }

                command = new NpgsqlCommand("DELETE FROM public.\"PeopleForBill\" " +
                                            $"WHERE \"BillId\" = {billRequest.Id}", connection);
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                }
                reader.Close();

                foreach (var peopleId in billRequest.PeopleIds)
                {
                    command = new NpgsqlCommand("INSERT INTO public.\"PeopleForBill\" (\"BillId\", \"PersonId\") " +
                                                $"VALUES ({billRequest.Id}, {peopleId})" +
                                                $"RETURNING \"Id\"", connection);
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        rowUpdated = true;
                    }
                    reader.Close();
                }

                return(rowUpdated);
            }
            catch (System.Exception exception)
            {
                throw new System.Exception($"An Error occured while updating the bill '{billRequest.Name}'", exception);
            }
            finally
            {
                connection.Close();
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> Update(UpdateBill bundle)
        {
            var result = await _billApiClient.Update(bundle);

            return(Ok(result));
        }