By GokiSoft.com| 17:23 29/10/2021|
Java Advanced

[Assignment] >> Quản lý bán hàng + java console

Viết chương trình sau :

- Triển khai lớp đối tường sau

1. Danh mục sản phầm -> gồm các thuộc tính sau : mã danh mục, tên danh mục

- tạo hàm tạo và các bộ getter/setter cho chương trình

- Viết hàm nhập dữ liệu và hiển thị dữ liệu cho danh mục

2. Sản phẩm -> gồm các thuộc tính : mã sản phẩm, mã danh mục, tên sp, giá, ngày nhập, ngày bán, hạn sử dụng, mô tả sản phẩm.

- tạo hàm tạo và các bộ getter/setter cho chương trình

- Viết hàm nhập dữ liệu và hiển thị dữ liệu cho danh mục

Viết menu chương trình sau

1. Nhập thông tin danh mục

2. Nhập thông tin sản phẩm 

3. In ra danh sách các sản phẩm đã bán

4. In ra danh sách sản phầm còn tồn kho

5. In ra danh sách sản phẩm đã quá hạn sử dụng (lấy giờ hiện tại của hệ thống để kiểm tra với HSD của sản phẩm)

6. In ra danh sách sản phẩm sắp hết hạn sử dụng (lấy giờ hiện tại của hệ thống và kiểm tra vs HSD, nếu giờ hiện tại <= HSD và giờ hiện tại >= HSD - 7 ngày thì in  kết quả ra)

7. Tìm kiếm >>> nhập tên sản phẩm -> in ra tất cả các sản phẩm có tên nhập vào và số sản phẩm.

Ví dụ : 

-Tìm kiếm : A

Kết quả :

Sản phẩm: A, price : 100$, ngày nhập : xx-xx-xxxx, ngày bán : xx-xx-xxxx, HSD : xx-xx-xxxx

Sản phẩm: A, price : 100$, ngày nhập : xx-xx-xxxx, ngày bán : xx-xx-xxxx, HSD : xx-xx-xxxx

Sản phẩm: A, price : 100$, ngày nhập : xx-xx-xxxx, ngày bán : xx-xx-xxxx, HSD : xx-xx-xxxx

Số lượng : 3

8. Lưu vào file (danh mục sẽ được lưu vào file category.dat, sản phẩm đã bán vào sell.dat, hết hạn sử dụng vào file : expire.dat, sản phẩm còn lại vào product.dat)

9. Đọc dữ liệu từ file và lưu ra chương trình.

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Do Trung Duc [T2008A]
Do Trung Duc

2021-03-28 05:05:26



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex.test4;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author TrungDuc
 */
public class Product implements Serializable{

    public String MaSanPham;
    public String MaDanhMuc;
    public String TenSanPham;
    public float Giaban;
    public Date NgayNhap;
    public Date NgayBan;
    public Date HanSuDung;
    public String MotaSanPham;

    public Product() {
    }

    public Product(String MaSanPham, String MaDanhMuc, String TenSanPham, float Giaban, Date NgayNhap, Date NgayBan, Date HanSuDung, String MotaSanPham) {
        this.MaSanPham = MaSanPham;
        this.MaDanhMuc = MaDanhMuc;
        this.TenSanPham = TenSanPham;
        this.Giaban = Giaban;
        this.NgayNhap = NgayNhap;
        this.NgayBan = NgayBan;
        this.HanSuDung = HanSuDung;
        this.MotaSanPham = MotaSanPham;
    }

    public String getMaSanPham() {
        return MaSanPham;
    }

    public void setMaSanPham(String MaSanPham) {
        this.MaSanPham = MaSanPham;
    }

    public String getMaDanhMuc() {
        return MaDanhMuc;
    }

    public void setMaDanhMuc(String MaDanhMuc) {
        this.MaDanhMuc = MaDanhMuc;
    }

    public String getTenSanPham() {
        return TenSanPham;
    }

    public void setTenSanPham(String TenSanPham) {
        this.TenSanPham = TenSanPham;
    }

    public float getGiaban() {
        return Giaban;
    }

    public void setGiaban(float Giaban) {
        this.Giaban = Giaban;
    }

    public Date getNgayNhap() {
        return NgayNhap;
    }

    public void setNgayNhap(Date NgayNhap) {
        this.NgayNhap = NgayNhap;
    }

    public Date getNgayBan() {
        return NgayBan;
    }

    public void setNgayBan(Date NgayBan) {
        this.NgayBan = NgayBan;
    }

    public Date getHanSuDung() {
        return HanSuDung;
    }

    public void setHanSuDung(Date HanSuDung) {
        this.HanSuDung = HanSuDung;
    }

    public String getMotaSanPham() {
        return MotaSanPham;
    }

    public void setMotaSanPham(String MotaSanPham) {
        this.MotaSanPham = MotaSanPham;
    }

    @Override
    public String toString() {
        return "Product{" + "MaSanPham=" + MaSanPham + ", MaDanhMuc=" + MaDanhMuc + ", TenSanPham=" + TenSanPham + ", Giaban=" + Giaban + ", NgayNhap=" + NgayNhap + ", NgayBan=" + NgayBan + ", HanSuDung=" + HanSuDung + ", MotaSanPham=" + MotaSanPham + '}';
    }

    public void NhapDuLieu() {
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Scanner scan = new Scanner(System.in);

        System.out.println("Nhap Ma San Pham: ");
        MaSanPham = scan.nextLine();

        System.out.println("Nhap Ma Danh Muc: ");
        MaDanhMuc = scan.nextLine();

        System.out.println("Nhap Ten San Pham: ");
        TenSanPham = scan.nextLine();

        System.out.println("Nhap Gia ban San Pham: ");
        Giaban = Float.parseFloat(scan.nextLine());

        System.out.println("Nhap Ngay nhap San Pham: ");
        String ngaynhapString = scan.nextLine();
        if (ngaynhapString.equals("")) {
            NgayNhap = null;
        } else {

            try {
                NgayNhap = format.parse(ngaynhapString);
            } catch (ParseException ex) {
                Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        System.out.println("Nhap Ngay Ban San Pham: ");
        String ngaybanString = scan.nextLine();

        if (ngaybanString.equals("")) {
            NgayBan = null;
        } else {
            try {
                NgayBan = format.parse(ngaybanString);
            } catch (ParseException ex) {
                Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Nhap Han Su Dung San Pham: ");
        String HSDString = scan.nextLine();

        if (HSDString.equals("")) {
            HanSuDung = null;
        } else {
            try {
                HanSuDung = format.parse(HSDString);
            } catch (ParseException ex) {
                Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Nhap mo ta san pham: ");
        MotaSanPham = scan.nextLine();
    }

    public void HienThi() {
        System.out.println(this);
    }

}



Do Trung Duc [T2008A]
Do Trung Duc

2021-03-28 05:05:14



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex.test4;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author TrungDuc
 */
public class Category implements Serializable{

    public String MaDanhMuc;
    public String TenDanhMuc;

    public Category() {
    }

    public Category(String MaDanhMuc, String TenDanhMuc) {
        this.MaDanhMuc = MaDanhMuc;
        this.TenDanhMuc = TenDanhMuc;
    }

    public String getMaDanhMuc() {
        return MaDanhMuc;
    }

    public void setMaDanhMuc(String MaDanhMuc) {
        this.MaDanhMuc = MaDanhMuc;
    }

    public String getTenDanhMuc() {
        return TenDanhMuc;
    }

    public void setTenDanhMuc(String TenDanhMuc) {
        this.TenDanhMuc = TenDanhMuc;
    }

    @Override
    public String toString() {
        return "Category{" + "MaDanhMuc=" + MaDanhMuc + ", TenDanhMuc=" + TenDanhMuc + '}';
    }

    public void Hienthi() {
        System.out.println(this);
    }

    public void nhapDuLieu() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap ten danh muc");
        TenDanhMuc = scan.nextLine();
        System.out.println("Nhap ma danh muc");
        MaDanhMuc = scan.nextLine();

    }

}



Do Trung Duc [T2008A]
Do Trung Duc

2021-03-28 05:05:02



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex.test4;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author TrungDuc
 */
public class Main {

    static List<Category> categoryList = new ArrayList<>();
    static List<Product> productList = new ArrayList<>();
    static Date dateSystem = new Date();

    public static void main(String[] agrs) {
        Scanner scan = new Scanner(System.in);
        int choose;
        do {
            Menu();
            choose = Integer.parseInt(scan.nextLine());

            switch (choose) {
                case 1:
                    NhapThongTinDanhMuc();
                    break;

                case 2:
                    NhapThongTinSanPham();
                    break;

                case 3:
                    InSanPhamDaBan();
                    break;

                case 4:
                    InSanPhamTonKho();
                    break;

                case 5:
                    InSanPhamQuaHan();
                    break;

                case 6:
                    InSanPhamSapHetHan();
                    break;

                case 7:
                    TimKiem();
                    break;

                case 8:
                    LuuFile();
                    break;

                case 9:
                    DocFile();
                    break;
                default:
                    System.err.println("Nhap choose sai!!!");
                    break;
            }

        } while (choose != 9);

    }

    static void Menu() {
        System.out.println("1. Nhập thông tin danh mục");
        System.out.println("2. Nhập thông tin sản phẩm ");
        System.out.println("3. In ra danh sách các sản phẩm đã bán");
        System.out.println("4. In ra danh sách sản phầm còn tồn kho");
        System.out.println("5. In ra danh sách sản phẩm đã quá hạn sử dụng ");
        System.out.println("6. In ra danh sách sản phẩm sắp hết hạn sử dụng");
        System.out.println("7.Tìm kiếm ");
        System.out.println("8. Lưu vào file");
        System.out.println("9. Đọc dữ liệu từ file và lưu ra chương trình");
        System.out.println("Chon: ");
    }

    private static void NhapThongTinDanhMuc() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap so luong danh muc muon them: ");
        int num = Integer.parseInt(scan.nextLine());

        for (int i = 0; i < num; i++) {
            System.out.format("Nhap danh muc thu %d", i + 1);
            Category category = new Category();
            category.nhapDuLieu();
            categoryList.add(category);
        }
    }

    private static void NhapThongTinSanPham() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap so luong san pham muon them: ");
        int num = Integer.parseInt(scan.nextLine());
        for (int i = 0; i < num; i++) {
            System.out.format("Nhap san pham thu %d", i + 1);
            Product product = new Product();
            product.NhapDuLieu();
            productList.add(product);
        }
    }

    private static void InSanPhamDaBan() {
        for (Product product : productList) {
            if (product.getNgayBan() != null) {
                product.HienThi();
            }
        }

    }

    private static void InSanPhamTonKho() {
        for (Product product : productList) {
            if (product.getNgayBan() == null) {
                product.HienThi();
            }
        }
    }

    private static void InSanPhamQuaHan() {
        for (Product product : productList) {
            if (product.getHanSuDung().before(dateSystem)) {
                product.HienThi();
            }
        }

    }

    private static void InSanPhamSapHetHan() {

        for (Product product : productList) {
            Date HanSuDung = product.getHanSuDung();
            Calendar c = Calendar.getInstance();
            c.setTime(HanSuDung);
            c.add(Calendar.DATE, 7);
            Date HanSuDungPlus = c.getTime();

            int compare1 = HanSuDungPlus.compareTo(dateSystem);
            int compare2 = (product.getHanSuDung()).compareTo(dateSystem);
            if (compare1 > 0 && compare2 < 0) {
                product.HienThi();
            }
        }
    }

    private static void TimKiem() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nhap ten san pham can tim");
        String name = scan.nextLine();
        int count = 0;
        for (Product product : productList) {
            if (product.getTenSanPham().equalsIgnoreCase(name)) {
                count += 1;
                product.HienThi();
            }
        }
        System.out.println("So luong san pham:" + count);

    }

    private static void LuuFile() {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = new FileOutputStream("category.dat");
            oos = new ObjectOutputStream(fos);
            for (Category category : categoryList) {
                oos.writeObject(category);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        FileOutputStream fos_sell = null;
        ObjectOutputStream oos_sell = null;

        try {
            fos_sell = new FileOutputStream("sell.dat");
            oos_sell = new ObjectOutputStream(fos_sell);
            for (Product product : productList) {
                if (product.NgayBan != null) {
                    oos_sell.writeObject(product);
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        FileOutputStream fos_expire = null;
        ObjectOutputStream oos_expire = null;

        try {
            fos_expire = new FileOutputStream("expire.dat");
            oos_expire = new ObjectOutputStream(fos_expire);
            for (Product product : productList) {
                int compare = product.HanSuDung.compareTo(dateSystem);
                if (compare > 0) {
                    oos_expire.writeObject(product);
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        FileOutputStream fos_other = null;
        ObjectOutputStream oos_other = null;
        try {
            fos_other = new FileOutputStream("product.dat");
            oos_other = new ObjectOutputStream(fos_other);
            for (Product product : productList) {
                int compare1 = product.HanSuDung.compareTo(dateSystem);
                int compare2 = (product.getHanSuDung()).compareTo(dateSystem);
                if ((compare1 > 0 && compare2 < 0) || (product.NgayBan != null)) {
                    continue;
                }
                oos_other.writeObject(product);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private static void DocFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        try {

            fis = new FileInputStream("category.dat");
            ois = new ObjectInputStream(fis);
            while (true) {
                Category category = (Category) ois.readObject();
                if (category != null) {
                    categoryList.add(category);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        FileInputStream fis_sell = null;
        ObjectInputStream ois_sell = null;

        try {

            fis_sell = new FileInputStream("sell.dat");
            ois_sell = new ObjectInputStream(fis_sell);
            while (true) {
                Product product = (Product) ois_sell.readObject();
                if (product != null) {
                    productList.add(product);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        FileInputStream fis_expire = null;
        ObjectInputStream ois_expire = null;

        try {

            fis_expire = new FileInputStream("expire.dat");
            ois_expire = new ObjectInputStream(fis_expire);
            while (true) {
                Product product = (Product) ois_expire.readObject();
                if (product != null) {
                    productList.add(product);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        FileInputStream fis_other = null;
        ObjectInputStream ois_other = null;

        try {

            fis_other = new FileInputStream("product.dat");
            ois_other = new ObjectInputStream(fis_other);
            while (true) {
                Product product = (Product) ois_other.readObject();
                if (product != null) {
                    productList.add(product);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}



vuong huu phu [T2008A]
vuong huu phu

2021-03-27 15:31:25



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication50;

import java.util.Scanner;

/**
 *
 * @author Admin
 */
public class Product_portfolio {
    int Ma_danh_muc;
    String Ten_danh_muc; 

    public Product_portfolio() {
    }

    public Product_portfolio(int Ma_danh_muc, String Ten_danh_muc) {
        this.Ma_danh_muc = Ma_danh_muc;
        this.Ten_danh_muc = Ten_danh_muc;
    }

    public int getMa_danh_muc() {
        return Ma_danh_muc;
    }

    public void setMa_danh_muc(int Ma_danh_muc) {
        this.Ma_danh_muc = Ma_danh_muc;
    }

    public String getTen_danh_muc() {
        return Ten_danh_muc;
    }

    public void setTen_danh_muc(String Ten_danh_muc) {
        this.Ten_danh_muc = Ten_danh_muc;
    }

    @Override
    public String toString() {
        return "Ma_danh_muc=" + Ma_danh_muc + ", Ten_danh_muc=" + Ten_danh_muc;
    }
    public void Nhap(){
        Scanner sc = new  Scanner(System.in);
        System.out.println("Nhap ma danh muc");
        Ma_danh_muc = Integer.parseInt(sc.nextLine());
        System.out.println("Nhap ten danh muc");
        Ten_danh_muc = sc.nextLine();
    }
    public void hienthi(){
        System.out.println(toString());
    }
    public String hienthi1(){
      return "Ma danh muc: "+Ma_danh_muc+":: Ten danh muc: "+Ten_danh_muc;
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication50;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Admin
 */
public class Test {

    static ArrayList<Product> Productlist = new ArrayList<>();
    static ArrayList<Product_portfolio> Product_portfoliolist = new ArrayList<>();
    static ArrayList<Product> Sanpham_hethansd = new ArrayList<>();
    static ArrayList<Product> San_pham_da_ban = new ArrayList<>();
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int lc;
        do {
            menu();
            System.out.println("Nhap su lua chon");
            lc = Integer.parseInt(sc.nextLine());
            switch (lc) {
                case 1:
                    nhap_danh_muc_sp();
                    break;
                case 2:
                    nhap_sp();
                    break;
                case 3:
                    ds_san_pham_ban();
                    break;
                case 4:
                    ds_san_pham_ton_kho();
                    break;
                case 5:
                    ds_sp_qua_han();
                    break;
                case 6:
                    San_shh();
                    break;
                case 7:
                    Tim_kiem();
                    break;
                case 8:
                    luu_file();
                    break;
                case 9:
                    Hienthifile();
                    break;
                default:
                    System.out.println("Nhap lai");
            }
        } while (lc < 10);
    }

    public static void menu() {
        System.out.println("1 Nhap thong tin danh muc");
        System.out.println("2 Nhap thong tin san pham");
        System.out.println("3 In ra cac san pham da ban");
        System.out.println("4 In ra danh sach san pham ton kho");
        System.out.println("5 In ra danh sach san pham qua han");
        System.out.println("6 In ra danh sach san pham sap het han");
        System.out.println("7 Tim kiem san pham");
        System.out.println("8 Luu vao file");
        System.out.println("9 doc du lieu trong file va in ra ");
    }

    private static void nhap_danh_muc_sp() {
        int n;
        System.out.println("So luong danh muc ");
        n = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < n; i++) {
            Product_portfolio p = new Product_portfolio();
            p.Nhap();
            Product_portfoliolist.add(p);
        }
    }

    private static void nhap_sp() {
        if (Product_portfoliolist.size() < 0) {
            System.out.println("chua co danh muc san pham nao!!");
        } else {
            System.out.println("======== danh muc san pham ========");
            for (int i = 0; i < Product_portfoliolist.size(); i++) {
                System.out.println(i + 1 + ":  " + Product_portfoliolist.get(i).hienthi1());
            }
            System.out.println("======== Nhap san pham ===========");
            int n;
            System.out.println("Nhap so luong san pham can them");
            n = Integer.parseInt(sc.nextLine());
            for (int i = 0; i < n; i++) {
                Product product = new Product();
                product.Nhap();
                Productlist.add(product);
            }
        }
    }

    private static void ds_san_pham_ban() {
        System.out.println("Danh sach san pham da ban:");
        Productlist.stream().filter((product) -> (product.getLc() == 1)).forEachOrdered((product) -> {
            product.hienthi();
        });
    }

    private static void ds_san_pham_ton_kho() {
        System.out.println("Danh sach san pham ton kho:");
        Productlist.stream().filter((product) -> (product.getLc() != 1)).forEachOrdered((product) -> product.hienthitonkho());
    }

    private static void ds_sp_qua_han() {
        long millis = System.currentTimeMillis();
        java.sql.Date today = new java.sql.Date(millis);
        Productlist.stream().filter((product) -> (product.getHan_sd().before(today) && product.getLc() == 1)).forEachOrdered((product) -> {
            product.hienthi();
        });
    }

    private static void Tim_kiem() {
        int k = 0;
        System.out.println("Nhap ten can tim kiem!!");
        String tkiem = sc.nextLine();
        k = Productlist.stream().filter((product) -> (product.getTen_san_pham().equalsIgnoreCase(tkiem))).map((product) -> {
            product.hienthi();
            return product;
        }).map((_item) -> 1).reduce(k, Integer::sum);
        if (k != 0) {
            System.out.println("Khong co san pham nao !!");
        } else {
            System.out.println("Co " + k + " san pham!!");
        }
    }

    private static void San_shh() {
        long millis = System.currentTimeMillis();
        Date date = new Date(millis);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -7);
        java.util.Date gioi_han = cal.getTime();
        Productlist.stream().filter((product) -> (gioi_han.after(product.getHan_sd()))).forEachOrdered((product) -> {
            product.hienthi();
        });
    }

    private static void luu_file() {
        long millis = System.currentTimeMillis();
        java.sql.Date today = new java.sql.Date(millis);
// danh mục sẽ được lưu vào file category.dat
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream("category.dat");
            oos = new ObjectOutputStream(fos);
            for (Product_portfolio pr : Product_portfoliolist) {
                oos.writeObject(pr);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }

        for (Product product : Productlist) {
            if (product.getLc() == 1) {
                //  sản phẩm đã bán vào sell.dat  
                FileOutputStream fos1 = null;
                ObjectOutputStream oos1 = null;

                try {
                    fos = new FileOutputStream("sell.dat");
                    oos = new ObjectOutputStream(fos);
                    oos1.writeObject(product);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (product.getHan_sd().before(today) && product.getLc() == 2) {
// hết hạn sử dụng vào file : expire.dat,
                FileOutputStream fos1 = null;
                ObjectOutputStream oos1 = null;
                try {
                    fos1 = new FileOutputStream("expire.dat");
                    oos1 = new ObjectOutputStream(fos);
                    oos1.writeObject(product);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }

            } else {
                // product.dat     
                FileOutputStream fos1 = null;
                ObjectOutputStream oos1 = null;
                try {
                    fos1 = new FileOutputStream("product.dat");
                    oos1 = new ObjectOutputStream(fos);
                    oos1.writeObject(product);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }

    private static void Hienthifile() {
        System.out.println("Danh sach danh muc san pham!!");
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream("category.dat");
            ois = new ObjectInputStream(fis);
            while (true) {
                Object obj = ois.readObject();
                if (obj != null) {
                    Product_portfoliolist.add((Product_portfolio) obj);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        System.out.println();
        System.out.println("Danh sach san pham het han");
        FileInputStream fis1 = null;
        ObjectInputStream ois1 = null;
        try {
            fis = new FileInputStream("expire.dat");
            ois = new ObjectInputStream(fis);
            while (true) {
                Object obj = ois1.readObject();
                if (obj != null) {
                    Sanpham_hethansd.add((Product) obj);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis1 != null) {
                try {
                    fis1.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois1 != null) {
                try {
                    ois1.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        System.out.println();
        System.out.println("Danh sach san pham da ban");
        FileInputStream fis2 = null;
        ObjectInputStream ois2 = null;
        try {
            fis2 = new FileInputStream("sell.dat");
            ois2 = new ObjectInputStream(fis);
            while (true) {
                Object obj = ois2.readObject();
                if (obj != null) {
                    San_pham_da_ban.add((Product) obj);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis2 != null) {
                try {
                    fis2.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois2 != null) {
                try {
                    ois2.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        System.out.println();
        System.out.println("Danh sach san pham con trong kho");
        FileInputStream fis3 = null;
        ObjectInputStream ois3 = null;
        try {
            fis3 = new FileInputStream("product.dat");
            ois3 = new ObjectInputStream(fis);
            while (true) {
                Object obj = ois3.readObject();
                if (obj != null) {
                    Productlist.add((Product) obj);
                } else {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis3 != null) {
                try {
                    fis3.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (ois3 != null) {
                try {
                    ois3.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication50;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Admin
 */
public class Product {
    int Ma_san_pham,Ma_danh_muc,lc;
    String Ten_san_pham,Mo_ta;
    double Gia_ban;
String Ngnhap,Ngayban,Hansd;
Date Ngay_nhap,Ngay_ban,Han_sd;
    public Product() {
    }

    public Product(int Ma_san_pham, int Ma_danh_muc, int lc, String Ten_san_pham, String Mo_ta, double Gia_ban, String Ngnhap, String Ngayban, String Hansd, Date Ngay_nhap, Date Ngay_ban, Date Han_sd) {
        this.Ma_san_pham = Ma_san_pham;
        this.Ma_danh_muc = Ma_danh_muc;
        this.lc = lc;
        this.Ten_san_pham = Ten_san_pham;
        this.Mo_ta = Mo_ta;
        this.Gia_ban = Gia_ban;
        this.Ngnhap = Ngnhap;
        this.Ngayban = Ngayban;
        this.Hansd = Hansd;
        this.Ngay_nhap = Ngay_nhap;
        this.Ngay_ban = Ngay_ban;
        this.Han_sd = Han_sd;
    }

    public int getMa_san_pham() {
        return Ma_san_pham;
    }

    public void setMa_san_pham(int Ma_san_pham) {
        this.Ma_san_pham = Ma_san_pham;
    }

    public int getMa_danh_muc() {
        return Ma_danh_muc;
    }

    public void setMa_danh_muc(int Ma_danh_muc) {
        this.Ma_danh_muc = Ma_danh_muc;
    }

    public int getLc() {
        return lc;
    }

    public void setLc(int lc) {
        this.lc = lc;
    }

    public String getTen_san_pham() {
        return Ten_san_pham;
    }

    public void setTen_san_pham(String Ten_san_pham) {
        this.Ten_san_pham = Ten_san_pham;
    }

    public String getMo_ta() {
        return Mo_ta;
    }

    public void setMo_ta(String Mo_ta) {
        this.Mo_ta = Mo_ta;
    }

    public double getGia_ban() {
        return Gia_ban;
    }

    public void setGia_ban(double Gia_ban) {
        this.Gia_ban = Gia_ban;
    }

    public String getNgnhap() {
        return Ngnhap;
    }

    public void setNgnhap(String Ngnhap) {
        this.Ngnhap = Ngnhap;
    }

    public String getNgayban() {
        return Ngayban;
    }

    public void setNgayban(String Ngayban) {
        this.Ngayban = Ngayban;
    }

    public String getHansd() {
        return Hansd;
    }

    public void setHansd(String Hansd) {
        this.Hansd = Hansd;
    }

    public Date getNgay_nhap() {
        return Ngay_nhap;
    }

    public void setNgay_nhap(Date Ngay_nhap) {
        this.Ngay_nhap = Ngay_nhap;
    }

    public Date getNgay_ban() {
        return Ngay_ban;
    }

    public void setNgay_ban(Date Ngay_ban) {
        this.Ngay_ban = Ngay_ban;
    }

    public Date getHan_sd() {
        return Han_sd;
    }

    public void setHan_sd(Date Han_sd) {
        this.Han_sd = Han_sd;
    }

    public void Nhap(){
    Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ma san pham");
        Ma_san_pham = Integer.parseInt(sc.nextLine());
        System.out.println("Nhap ma danh muc");
        Ma_danh_muc = Integer.parseInt(sc.nextLine());
        System.out.println("Nhap ten san pham");
        Ten_san_pham = sc.nextLine();
        System.out.println("Nhap gia ban");
        Gia_ban= Double.parseDouble(sc.nextLine());
        System.out.println("Nhap ngay nhap hang");
        Ngnhap = sc.nextLine();
        SimpleDateFormat format = new SimpleDateFormat("dd/mm/yy");
        try {
            Ngay_nhap = format.parse(Ngnhap);
        } catch (ParseException ex) {
            Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Nhap Ngay ban");
        System.out.println("");
        System.out.println("Ban co nhap ngay ban khong");
        System.out.println("1 co:");
        System.out.println("2 khong:");
        System.out.println("Nhap su lua chon");
        lc = Integer.parseInt(sc.nextLine());
        switch(lc){
        case 1:
            System.out.println("Nhap ngay ban:");
             Ngayban = sc.nextLine();
        SimpleDateFormat format1 = new SimpleDateFormat("dd/mm/yy");
        if (Ngayban != null) {
         try {
            Ngay_ban= format1.parse(Ngayban);
                    } catch (ParseException ex) {
            Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
        }   
            break;
        }
       case 2:
           break;
        }
        System.out.println("Nhap han su dung");
        Hansd = sc.nextLine();
        SimpleDateFormat format2 = new SimpleDateFormat("dd/mm/yy");
        try {
            Han_sd = format2.parse(Hansd);
        } catch (ParseException ex) {
            Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Nhap mo ta san pham");
        Mo_ta = sc.nextLine();
    }
    public void hienthi(){
        System.out.println(this);
    }
    public void hienthitonkho(){
        System.out.println(tonkho());
    }

    @Override
    public String toString() {
        return "Ma_san_pham=" + Ma_san_pham + ", Ma_danh_muc=" + Ma_danh_muc + ", Ten_san_pham=" + Ten_san_pham + ", Ngay_nhap=" + Ngay_nhap + ", Ngay_ban=" + Ngay_ban + ", Han_sd=" + Han_sd + ", Mo_ta=" + Mo_ta + ", Gia_ban=" + Gia_ban ;
    }
     public String tonkho() {
        return "Ma_san_pham=" + Ma_san_pham + ", Ma_danh_muc=" + Ma_danh_muc + ", Ten_san_pham=" + Ten_san_pham + ", Ngay_nhap=" + Ngay_nhap +", Han_sd=" + Han_sd + ", Mo_ta=" + Mo_ta + ", Gia_ban=" + Gia_ban ;
    }
}



trung [C1907L]
trung

2020-05-31 08:56:39



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pkQuanLyBanHang;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author prdox
 */
public class Category implements Serializable{
    String categoryName, categoryCode;

    public void input() {
        Scanner inp = new Scanner(System.in);
        System.out.println("Input category code");
        categoryCode = inp.nextLine();
        System.out.println("Input category name");
        categoryName = inp.nextLine();
    }

    @Override
    public String toString() {
        return "Category{" + "categoryName=" + categoryName + ", categoryCode=" + categoryCode + '}';
    }
    
    public void output() {
        System.out.println(this);
    }
    
    public Category() {
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryCode() {
        return categoryCode;
    }

    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pkQuanLyBanHang;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

/**
 *
 * @author prdox
 */
public class Product implements Serializable{
    String productName,categoryCode,productCode;
    Float price;
    Date importDate,sellDate,expiryDate;
    String description;
    
    public boolean isSold() {
        return (sellDate != null);
    }
    
    public boolean isExpire() {
        Date today = new Date();
        return (expiryDate.before(today));
    }
    
    public boolean isSoonExpire() {
        Date today = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(today);
        cal.add(Calendar.DATE, 7);
        Date todayPlus7 = cal.getTime();
        return (expiryDate.after(today) && expiryDate.before(todayPlus7));
    }

    public void input() {
        Scanner inp = new Scanner(System.in);
        while (true) {
            System.out.println("Input category code");
            if (isExistCategory(categoryCode = inp.nextLine())) break;
            System.out.println("Category does not exist, choose from the list below:");
            DataMgr.getInstance().getListCategory().forEach((cate) -> {
                System.out.println(cate.getCategoryCode());
            });
        }
        
        System.out.println("Input product code");
        productCode = inp.nextLine();
        System.out.println("Input product name");
        productName = inp.nextLine();
        System.out.println("Input price");
        price = Float.parseFloat(inp.nextLine());
        System.out.println("Input description");
        description = inp.nextLine();
        
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        while (true) {            
            try {
                System.out.println("Input import date");
                importDate = sdf.parse(inp.nextLine());
                break;
            } catch (ParseException ex) {
                System.out.println("Please input in this format (dd/mm/yyyy)");
            }
        }
        
        while (true) {            
            try {
                System.out.println("Input expiry date");
                String inpStr = inp.nextLine();
                if (!inpStr.equals("")){
                    expiryDate = sdf.parse(inpStr);
                }
                break;
            } catch (ParseException ex) {
                System.out.println("Please input in this format (dd/mm/yyyy)");
            }
        }
        
        while (true) {            
            try {
                System.out.println("Input sell date");
                String inpStr = inp.nextLine();
                if (!inpStr.equals("")){
                    sellDate = sdf.parse(inpStr);
                }
                break;
            } catch (ParseException ex) {
                System.out.println("Please input in this format (dd/mm/yyyy)");
            }
        }
    }

    @Override
    public String toString() {
        return "Product{" + "productName=" + productName + ", categoryCode=" + categoryCode + ", productCode=" + productCode + ", price=" + price + ", importDate=" + importDate + ", sellDate=" + sellDate + ", expiryDate=" + expiryDate + ", description=" + description + '}';
    }
    
    public void output() {
        System.out.println(this);
    }
    
    private boolean isExistCategory(String inpCate) {
        return DataMgr.getInstance().getListCategory().stream().
                anyMatch((category) -> (inpCate.
                        equalsIgnoreCase(category.getCategoryCode())));
    }
    
    public Product() {
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getCategoryCode() {
        return categoryCode;
    }

    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }

    public String getProductCode() {
        return productCode;
    }

    public void setProductCode(String productCode) {
        this.productCode = productCode;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public Date getImportDate() {
        return importDate;
    }

    public void setImportDate(Date importDate) {
        this.importDate = importDate;
    }

    public Date getSellDate() {
        return sellDate;
    }

    public void setSellDate(Date sellDate) {
        this.sellDate = sellDate;
    }

    public Date getExpiryDate() {
        return expiryDate;
    }

    public void setExpiryDate(Date expiryDate) {
        this.expiryDate = expiryDate;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    
    
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pkQuanLyBanHang;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 * @author prdox
 */
public class DataMgr {
    List<Category> listCategory = null;
    List<Product> listProduct = null;
    private static DataMgr instance;

    public DataMgr() {
        listCategory = new ArrayList<>();
        listProduct = new ArrayList<>();
    }
    
    public static synchronized DataMgr getInstance() {
        if (instance == null) {
            instance = new DataMgr();
        }
        return instance;
    }

    public List<Product> getSoldProducts() {
        if (instance == null || instance.getListProduct() == null) return null;
        List<Product> soldProducts = new ArrayList<>();
        instance.getListProduct().stream().
                filter((product) -> product.isSold()).
                forEachOrdered((product) -> {
                    soldProducts.add(product);
                });
        return soldProducts;
    }
    
    public List<Product> getExpiryProducts() {
        if (instance == null || instance.getListProduct() == null) return null;
        List<Product> expiryProducts = new ArrayList<>();
        Date today = new Date();
        instance.getListProduct().stream().
                filter((product) -> (product.isExpire())).
                forEachOrdered((product) -> {
                    expiryProducts.add(product);
                });
        return expiryProducts;
    }
    
    public List<Product> getSoonExpiryProducts() {
        if (instance == null || instance.getListProduct() == null) return null;
        List<Product> soonExpiryProducts = new ArrayList<>();
        Date today = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(today);
        cal.add(Calendar.DATE, 7);
        Date todayPlus7 = cal.getTime();
        DataMgr.getInstance().getListProduct().stream().
            filter((product) -> (product.isSoonExpire())).
                forEachOrdered(soonExpiryProducts::add);
        return soonExpiryProducts;
    }
    
    public List<Product> getRemainsProducts() {
        if (instance == null || instance.getListProduct() == null) return null;
        List<Product> remains = new ArrayList<>();
        instance.getListProduct().stream().filter((prod) -> (!prod.
                isExpire() && !prod.isSold())).forEachOrdered((prod) -> {
            remains.add(prod);
        });
        return remains;
    }
    
    public List<Category> getListCategory() {
        return listCategory;
    }

    public List<Product> getListProduct() {
        return listProduct;
    }

    public void setListCategory(List<Category> listCategory) {
        this.listCategory = listCategory;
    }

    public void setListProduct(List<Product> listProduct) {
        this.listProduct = listProduct;
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pkQuanLyBanHang;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author prdox
 */
interface MapMethod {

    void process();
}

public class Main {

    static Scanner inp = new Scanner(System.in);

    public static void main(String[] args) {
        int choice;
        do {
            try {
                showMenu();
                choice = Integer.parseInt(inp.nextLine());
                getMap()[choice - 1].process();
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Invalid input ...");
                choice = 0; //reset choice
            }
        } while (choice != 10);
    }

    private static void showMenu() {
        System.out.println("1. Nhập thông tin danh mục");
        System.out.println("2. Nhập thông tin sản phẩm ");
        System.out.println("3. In ra danh sách các sản phẩm đã bán");
        System.out.println("4. In ra danh sách sản phầm còn tồn kho");
        System.out.println("5. In ra danh sách sản phẩm đã quá hạn sử dụng");
        System.out.println("6. In ra danh sách sản phẩm sắp hết hạn sử dụng");
        System.out.println("7. Tìm kiếm ");
        System.out.println("8. Luu -> file");
        System.out.println("9. Doc du lieu tu file");
        System.out.println("10. Quit");
    }

    private static MapMethod[] getMap() {
        MapMethod map[] = {
            Main::inputCategory,
            Main::inputProduct,
            Main::outputSoldProducts,
            Main::outputInstock,
            Main::outputExpiryProduct,
            Main::outputSoonExpiryProduct,
            Main::searchProduct,
            Main::outputToFile,
            Main::getDataFromFile,
            Main::quitProgram
        };
        return map;
    }

    private static void quitProgram() {
        System.out.println("Bye bye ...");
    }

    private static void inputCategory() {
        do {
            Category newCate = new Category();
            newCate.input();
            DataMgr.getInstance().getListCategory().add(newCate);
            System.out.println("Input new category (y/n) ?");
        } while (inp.nextLine().equalsIgnoreCase("y"));
    }

    private static void inputProduct() {
        if (DataMgr.getInstance().getListCategory() == null) {
            System.out.println("Please input category first");
            return;
        }

        do {
            Product newProd = new Product();
            newProd.input();
            DataMgr.getInstance().getListProduct().add(newProd);
            System.out.println("Input new product (y/n) ?");
        } while (inp.nextLine().equalsIgnoreCase("y"));
    }

    private static void outputSoldProducts() {
        if (DataMgr.getInstance().getSoldProducts() == null) {
            System.out.println("No product available");
            return;
        }

        System.out.println("List sold product : ");
        DataMgr.getInstance().getSoldProducts().forEach((prod) -> {
            prod.output();
        });
    }

    private static void outputInstock() {
        if (DataMgr.getInstance().getListProduct() == null) {
            System.out.println("No product available");
            return;
        }

        DataMgr.getInstance().getListProduct().stream().
                filter((product) -> (product.getSellDate() != null)).
                forEachOrdered((product) -> {
                    product.output();
                });
    }

    private static void outputExpiryProduct() {
        if (DataMgr.getInstance().getExpiryProducts() == null) {
            System.out.println("No product available");
            return;
        }

        System.out.println("List expiry product : ");
        DataMgr.getInstance().getExpiryProducts().forEach((prod) -> {
            prod.output();
        });
    }

    private static void outputSoonExpiryProduct() {
        if (DataMgr.getInstance().getSoonExpiryProducts() == null) {
            System.out.println("No product available");
            return;
        }

        System.out.println("List soon to expiry product : ");
        DataMgr.getInstance().getSoonExpiryProducts().forEach((prod) -> {
            prod.output();
        });
    }

    private static void searchProduct() {
        if (DataMgr.getInstance().getListProduct() == null) {
            System.out.println("No product available");
            return;
        }

        System.out.println("Input product name to search");
        String searchProd = inp.nextLine();
        int total = 0;
        for (Product prod : DataMgr.getInstance().getListProduct()) {
            if (prod.getProductName().equalsIgnoreCase(searchProd)) {
                total++;
                prod.output();
            }
        }
        System.out.println("Total: " + total);
    }

    private static void outputToFile() {
        saveList(DataMgr.getInstance().getListCategory(), "category.dat");
        saveList(DataMgr.getInstance().getSoldProducts(), "sell.dat");
        saveList(DataMgr.getInstance().getExpiryProducts(), "expire.dat");
        saveList(DataMgr.getInstance().getRemainsProducts(), "product.dat");
    }

    private static void getDataFromFile() {
        DataMgr.getInstance().setListCategory(readFile("category.dat"));
        List listProd = new ArrayList<>();
        listProd.addAll(readFile("sell.dat"));
        listProd.addAll(readFile("expire.dat"));
        listProd.addAll(readFile("product.dat"));
        DataMgr.getInstance().setListProduct(listProd);
    }

    private static List readFile(String fileName) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        List returnList = new ArrayList<>();
        try {
            fis = new FileInputStream(fileName);
            ois = new ObjectInputStream(fis);
            Object obj = null;
            while (true) {
                try {
                    returnList.add(ois.readObject());
                } catch (EOFException e) {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return returnList;
    }

    private static void saveList(List list, String fileName) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(fileName);
            oos = new ObjectOutputStream(fos);
            for (Object obj : list) {
                oos.writeObject(obj);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}



Nguyễn Hoàng Anh [C1907L]
Nguyễn Hoàng Anh

2020-05-31 08:15:16



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang_javaadvanced;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import static java.time.temporal.TemporalQueries.localDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Redmibook 14
 */
public class main {

    public static void menu() {
        System.out.println("1.Nhập thông tin danh mục");
        System.out.println("2. Nhập thông tin sản phẩm ");
        System.out.println("3. Thay đổi trạng thái sản phẩm ");
        System.out.println("4. In ra danh sách các sản phẩm đã bán");
        System.out.println("5. In ra danh sách sản phầm còn tồn kho");
        System.out.println("6. In ra danh sách sản phẩm đã quá hạn sử dụng");
        System.out.println("7. In ra danh sách sản phẩm sắp hết hạn sử dụng");
        System.out.println("8. Tìm kiếm ");
        System.out.println("9. Lưu vào file ");
        System.out.println("10. Đọc dữ liệu từ file và lưu ra chương trình");
        System.out.println("11. Exit");
        System.out.println("Choose :");

    }

    public static void inputCate(ArrayList<Category> listCategory) {
        Category category = new Category();
        category.input();
        listCategory.add(category);
    }

    public static void inputProduct(ArrayList<Product> listProduct, ArrayList<Category> listCategory) {
        Scanner input = new Scanner(System.in);
        System.out.println("-------Category-------");
        for (int i = 0; i < listCategory.size(); i++) {
            listCategory.get(i).display();
        }
        System.out.println("----------||----------");
        System.out.println("Input category code :");
        String cateCode = input.nextLine();
        int i;
        Boolean flag = true;
        for (i = 0; i < listCategory.size(); i++) {
            if (cateCode.equals(listCategory.get(i).CategoryCode)) {

                break;
            }
        }
        if (i == listCategory.size()) {
            System.out.println("Wrong category code!");
            flag = false;
        }
        if (flag == true) {
            System.out.println("Input product code : ");
            String productCode = input.nextLine();
            int j;
            for (j = 0; j < listProduct.size(); j++) {
                if (listProduct.get(j).ProductCode.equals(productCode)) {
                    System.out.println("Code existed!");
                    break;
                }
            }
            if (j == listProduct.size()) {
                Product product = new Product();
                product.input(cateCode, productCode);
                listProduct.add(product);
            }
        }

    }

    public static void changeStatus(ArrayList<Product> listProduct) {
        Scanner input = new Scanner(System.in);
        System.out.println("----Product----");
        for (int i = 0; i < listProduct.size(); i++) {
            listProduct.get(i).display();
        }
        System.out.println("------||------");
        System.out.println("Input product code :");
        String productCode = input.nextLine();

        for (int i = 0; i < listProduct.size(); i++) {
            if (productCode.equals(listProduct.get(i).ProductCode)) {
                listProduct.get(i).status();

            }
        }
    }

    public static void showSoldProduct(ArrayList<Product> listProduct) {
        System.out.println("Sold product :");
        for (int i = 0; i < listProduct.size(); i++) {
            if (listProduct.get(i).DateSale != null) {
                listProduct.get(i).display();

            }
        }
    }

    public static void showInStockProduct(ArrayList<Product> listProduct) {
        System.out.println("Instock product :");
        for (int i = 0; i < listProduct.size(); i++) {
            if (listProduct.get(i).DateSale == null) {
                listProduct.get(i).display();

            }
        }
    }

    public static void showExpriedProduct(ArrayList<Product> listProduct) {
        System.out.println("Expried product :");
        LocalDate localDate = LocalDate.now();
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        for (int i = 0; i < listProduct.size(); i++) {
            System.out.println(listProduct.get(i).DateExpired);
            System.out.println(date);
            if (listProduct.get(i).DateExpired.compareTo(date) < 0) {
                listProduct.get(i).display();

            }
        }
    }

    public static void almostExpriedProduct(ArrayList<Product> listProduct) {
        System.out.println("Almost expried product :");
        LocalDate localDate2 = LocalDate.now();
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        Date date2 = Date.from(localDate2.atStartOfDay(ZoneId.systemDefault()).toInstant());
        c1.setTime(date2);
        c1.add(Calendar.MONTH, 1);
        Long currentTime = c1.getTime().getTime() / (24 * 3600 * 1000);
        for (int i = 0; i < listProduct.size(); i++) {
            c2.setTime(listProduct.get(i).DateExpired);
            Long expiredTime = c2.getTime().getTime() / (24 * 3600 * 1000);
            if (currentTime <= expiredTime && currentTime >= expiredTime - 7) {

                listProduct.get(i).display();
            }
        }
    }

    public static void findProductByName(ArrayList<Product> listProduct) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input product name :");
        String productName = input.nextLine();
        for (int i = 0; i < listProduct.size(); i++) {
            if (listProduct.get(i).ProductName.contains(productName)) {
                listProduct.get(i).display();
            }
        }
    }

    public static void saveToFile(ArrayList<Product> listProduct, ArrayList<Category> listCategory) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        File fileCategory = new File("category.dat");
        File fileSell = new File("sell.dat");
        File fileExpried = new File("expried.dat");
        File fileProduct = new File("product.dat");
        {
            try {
                fos = new FileOutputStream(fileCategory);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(listCategory);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        {
            try {
                fos = new FileOutputStream(fileSell);
                oos = new ObjectOutputStream(fos);
                ArrayList<Product> productSold = new ArrayList();
                for (int i = 0; i < listCategory.size(); i++) {
                    if (listProduct.get(i).DateSale != null) {
                        productSold.add(listProduct.get(i));

                    }
                }
                oos.writeObject(productSold);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        {
            try {
                fos = new FileOutputStream(fileProduct);
                oos = new ObjectOutputStream(fos);
                ArrayList<Product> Product = new ArrayList();
                LocalDate localDate2 = LocalDate.now();
                Calendar c1 = Calendar.getInstance();
                Calendar c2 = Calendar.getInstance();
                Date date2 = Date.from(localDate2.atStartOfDay(ZoneId.systemDefault()).toInstant());
                c1.setTime(date2);
                c1.add(Calendar.MONTH, 1);
                Long currentTime = c1.getTime().getTime() / (24 * 3600 * 1000);
                for (int i = 0; i < listProduct.size(); i++) {
                    c2.setTime(listProduct.get(i).DateExpired);
                    Long expiredTime = c2.getTime().getTime() / (24 * 3600 * 1000);
                    if ((currentTime <= expiredTime && currentTime >= expiredTime
                            - 7) && listProduct.get(i).DateSale == null) {
                        Product.add(listProduct.get(i));
                    }
                }
                oos.writeObject(Product);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        {
            try {
                fos = new FileOutputStream(fileExpried);
                oos = new ObjectOutputStream(fos);
                ArrayList<Product> productExpried = new ArrayList();
                LocalDate localDate2 = LocalDate.now();
                Calendar c1 = Calendar.getInstance();
                Calendar c2 = Calendar.getInstance();
                Date date2 = Date.from(localDate2.atStartOfDay(ZoneId.systemDefault()).toInstant());
                c1.setTime(date2);
                c1.add(Calendar.MONTH, 1);
                Long currentTime = c1.getTime().getTime() / (24 * 3600 * 1000);
                for (int i = 0; i < listProduct.size(); i++) {
                    c2.setTime(listProduct.get(i).DateExpired);
                    Long expiredTime = c2.getTime().getTime() / (24 * 3600 * 1000);
                    if (currentTime <= expiredTime && currentTime >= expiredTime - 7) {
                        productExpried.add(listProduct.get(i));
                    }
                }
                oos.writeObject(productExpried);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        System.err.println("Ok!");

    }

    public static void readFile(ArrayList<Category> listCategory, ArrayList<Product> listProduct) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        try {
            fis = new FileInputStream("category.dat");
            ois = new ObjectInputStream(fis);
            ArrayList<Category> tempListCategory = (ArrayList<Category>) ois.readObject();
            for (int i = 0; i < tempListCategory.size(); i++) {
                listCategory.add(tempListCategory.get(i));
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            fis = new FileInputStream("sell.dat");
            ois = new ObjectInputStream(fis);
            ArrayList<Product> tempListProduct = (ArrayList<Product>) ois.readObject();
            for (int i = 0; i < tempListProduct.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < listProduct.size(); j++) {
                    if (tempListProduct.get(i).ProductCode.equals(listProduct.get(j).ProductCode)) {
                        flag = false;
                    }
                }
                if (flag == true) {
                    listProduct.add(tempListProduct.get(i));
                }

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            fis = new FileInputStream("expried.dat");
            ois = new ObjectInputStream(fis);
            ArrayList<Product> tempListProduct = (ArrayList<Product>) ois.readObject();
            for (int i = 0; i < tempListProduct.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < listProduct.size(); j++) {
                    if (tempListProduct.get(i).ProductCode.equals(listProduct.get(j).ProductCode)) {
                        flag = false;
                    }
                }
                if (flag == true) {
                    listProduct.add(tempListProduct.get(i));
                }

            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            fis = new FileInputStream("product.dat");
            ois = new ObjectInputStream(fis);
            ArrayList<Product> tempListProduct = (ArrayList<Product>) ois.readObject();
            for (int i = 0; i < tempListProduct.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < listProduct.size(); j++) {
                    if (tempListProduct.get(i).ProductCode.equals(listProduct.get(j).ProductCode)) {
                        flag = false;
                    }
                }
                if (flag == true) {
                    listProduct.add(tempListProduct.get(i));
                }

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ArrayList<Category> listCategory = new ArrayList();
        ArrayList<Product> listProduct = new ArrayList();
        while (true) {
            menu();
            int choice = Integer.parseInt(input.nextLine());
            switch (choice) {
                case 1:
                    inputCate(listCategory);
                    break;
                case 2:
                    inputProduct(listProduct, listCategory);
                    break;
                case 3:
                    changeStatus(listProduct);
                    break;
                case 4:
                    showSoldProduct(listProduct);
                    break;
                case 5:
                    showInStockProduct(listProduct);
                    break;
                case 6:
                    showExpriedProduct(listProduct);
                    break;
                case 7:
                    almostExpriedProduct(listProduct);
                    break;
                case 8:
                    findProductByName(listProduct);
                    break;
                case 9:
                    saveToFile(listProduct, listCategory);
                    break;
                case 10:
                    readFile(listCategory, listProduct);
                    break;
                case 11:
                    return;

            }
        }

    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang_javaadvanced;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Redmibook 14
 */
public class Product implements Serializable{

    String ProductCode, CategoryCode, ProductName, Describe;
    float Price;
    Date DateAdded, DateSale, DateExpired;

    public void setDescribe(String Describe) {
        this.Describe = Describe;
    }

    public String getDescribe() {
        return Describe;
    }

    public String getProductCode() {
        return ProductCode;
    }

    public String getCategoryCode() {
        return CategoryCode;
    }

    public String getProductName() {
        return ProductName;
    }

    public float getPrice() {
        return Price;
    }

    public Date getDateAdded() {
        return DateAdded;
    }

    public Date getDateSale() {
        return DateSale;
    }

    public Date getDateExpired() {
        return DateExpired;
    }

    public void setProductCode(String ProductCode) {
        this.ProductCode = ProductCode;
    }

    public void setCategoryCode(String CategoryCode) {
        this.CategoryCode = CategoryCode;
    }

    public void setProductName(String ProductName) {
        this.ProductName = ProductName;
    }

    public void setPrice(float Price) {
        this.Price = Price;
    }

    public void setDateAdded(Date DateAdded) {
        this.DateAdded = DateAdded;
    }

    public void setDateSale(Date DateSale) {
        this.DateSale = DateSale;
    }

    public void setDateExpired(Date DateExpired) {
        this.DateExpired = DateExpired;
    }

    public void input(String CategoryCode,String ProductCode) {
        Scanner input = new Scanner(System.in);
        this.CategoryCode = CategoryCode;
       
        this.ProductCode = ProductCode;

        System.out.println("Input product name : ");
        ProductName = input.nextLine();
        System.out.println("Input added date : ");
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            DateAdded = sdf.parse(input.nextLine());
        } catch (ParseException ex) {
            Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Input date expried : ");
        try {
            DateExpired = sdf.parse(input.nextLine());
        } catch (ParseException ex) {
            Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
        }

        DateSale = null;
    }

    public void status() {
        Scanner input = new Scanner(System.in);
        System.out.println("Input product status : ");
        System.out.println("1.Sold ");
        System.out.println("2.Instock ");
        int choice = Integer.parseInt(input.nextLine());
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        switch (choice) {
            case 1:
                System.out.println("Input date sale : ");
                try {
                    DateSale = sdf.parse(input.nextLine());
                } catch (ParseException ex) {
                    Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            default:
                DateSale = null;
                break;
        }

    }

    public void display() {
        System.out.println(toString());
    }

    @Override
    public String toString() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String DataSale = this.DateSale != null ? sdf.format(DateAdded) : "Instock";

        return "Product{" + "ProductCode=" + ProductCode + ", CategoryCode=" + CategoryCode + ", ProductName=" + ProductName + ", Price=" + Price + ", DateAdded=" + sdf.format(DateAdded) + ", DateSale=" + DataSale + ", DateExpired=" + sdf.format(DateExpired) + '}';
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang_javaadvanced;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Redmibook 14
 */
public class Category implements Serializable{

    String CategoryCode, CategoyName;

    public String getCategoryCode() {
        return CategoryCode;
    }

    public String getCategoyName() {
        return CategoyName;
    }

    public Category() {
    }

    public Category(String CategoryCode, String CategoyName) {
        this.CategoryCode = CategoryCode;
        this.CategoyName = CategoyName;
    }

    public void input() {
        Scanner input = new Scanner(System.in);
        System.out.println("Input Category Code : ");
        CategoryCode = input.nextLine();
        System.out.println("Input Category Name : ");
        CategoyName = input.nextLine();
    }

    public void display() {
        System.out.println(toString());
    }

    @Override
    public String toString() {
        return "CategoryCode=" + CategoryCode + ", CategoyName=" + CategoyName;
    }

}



Ngô Quang Huy [C1907L]
Ngô Quang Huy

2020-05-30 09:59:47



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package May29FilePractice;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class Main {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        List<Category> listCategory = new ArrayList<>();
        List<Product> listProduct = new ArrayList<>();
        List<Product> listProductSell = new ArrayList<>();
        List<Product> listProductExpired = new ArrayList<>();
        for(;;){
            Date now = new Date(System.currentTimeMillis());
            showMenu();
            System.out.print("Choose: ");
            int choose = Integer.parseInt(input.nextLine());
            switch(choose){
                case 1:
                    for(;;){
                        Category category = new Category();
                        category.input();
                        listCategory.add(category);
                        System.out.println("Continue? y/n");
                        String dk = input.nextLine();
                        if("n".equalsIgnoreCase(dk)){
                            break;
                        }
                    }
                    break;
                case 2:
                    for(;;){
                        Product product = new Product();
                        product.input();
                        if(product.SellDate.compareTo(now)<0){
                            listProductSell.add(product);
                        }else if(product.ExpiredDate.compareTo(now)<0){
                            listProductExpired.add(product);
                        }else{
                            listProduct.add(product);
                        }
                        System.out.println("Continue? y/n");
                        String dk = input.nextLine();
                        if("n".equalsIgnoreCase(dk)){
                            break;
                        }
                    }
                    break;
                case 3:
                    for (Product product : listProductSell) {
                        product.output();
                    }
                    break;
                case 4:
                    for (Product product : listProduct) {
                        product.output();
                    }
                    break;
                case 5:
                    for (Product product : listProductExpired) {
                        product.output();
                    }
                    break;
                case 6:
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(now);
                    cal.add(Calendar.DAY_OF_YEAR, 7);
                    for (Product product : listProduct) {
                        if(product.ExpiredDate.compareTo(cal.getTime())<0){
                            product.output();
                        }
                    }
                    break;
                case 7:
                    int count = 0;
                    System.out.print("Find product Name: ");
                    String search = input.nextLine();
                    for (Product product : listProductExpired) {
                        if(product.Name.equals(search)){
                            product.output();
                            count++;
                        }
                    }
                    for (Product product : listProduct) {
                        if(product.Name.equals(search)){
                            product.output();
                            count++;
                        }
                    }
                    for (Product product : listProductSell) {
                        if(product.Name.equals(search)){
                            product.output();
                            count++;
                        }
                    }
                    if(count==0){
                        System.out.println("Not Found");
                    }else{
                        System.out.println(" - Quantity: "+count);
                    }
                    break;
                case 8:
                    FileOutputStream fosCategory = null;
                    ObjectOutputStream oosCategory = null;
                    FileOutputStream fosSell = null;
                    FileOutputStream fosExpired = null;
                    FileOutputStream fosProduct = null;
                    ObjectOutputStream oosSell = null;
                    ObjectOutputStream oosExpired = null;
                    ObjectOutputStream oosProduct = null;
                    try {
                        fosCategory = new FileOutputStream("category.dat");
                        oosCategory = new ObjectOutputStream(fosCategory);
                        oosCategory.writeObject(listCategory);
                        fosSell = new FileOutputStream("sell.dat");
                        oosSell = new ObjectOutputStream(fosSell);
                        oosSell.writeObject(listProductSell);
                        fosExpired = new FileOutputStream("expire.dat");
                        oosExpired = new ObjectOutputStream(fosExpired);
                        oosExpired.writeObject(listProductExpired);
                        fosProduct = new FileOutputStream("product.dat");
                        oosProduct = new ObjectOutputStream(fosProduct);
                        oosProduct.writeObject(listProduct);
                        
                        
                        System.out.println("\t-----Successfully save");
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } finally{
                        if( fosCategory!=null){
                            try {
                                fosCategory.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( fosSell!=null){
                            try {
                                fosSell.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( fosExpired!=null){
                            try {
                                fosExpired.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( fosProduct!=null){
                            try {
                                fosProduct.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( oosCategory!=null){
                            try {
                                oosCategory.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( oosSell!=null){
                            try {
                                oosSell.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( oosExpired!=null){
                            try {
                                oosExpired.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if( oosProduct!=null){
                            try {
                                oosProduct.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                    break;
                case 9:
                    FileInputStream fisCategory = null;
                    FileInputStream fisSell = null;
                    FileInputStream fisExpired = null;
                    FileInputStream fisProduct = null;
                    ObjectInputStream oisCategory = null;
                    ObjectInputStream oisSell = null;
                    ObjectInputStream oisExpired = null;
                    ObjectInputStream oisProduct = null;
                    try {
                        fisSell = new FileInputStream("sell.dat");
                        oisSell = new ObjectInputStream(fisSell);
                        fisCategory = new FileInputStream("category.dat");
                        oisCategory = new ObjectInputStream(fisCategory);
                        fisExpired = new FileInputStream("expire.dat");
                        oisExpired = new ObjectInputStream(fisExpired);
                        fisProduct = new FileInputStream("product.dat");
                        oisProduct = new ObjectInputStream(fisProduct);
                        
                        listCategory = (List<Category>) oisCategory.readObject();
                        listProduct = (List<Product>) oisProduct.readObject();
                        listProductExpired = (List<Product>) oisExpired.readObject();
                        listProductSell = (List<Product>) oisSell.readObject();
                        
                        System.out.println("\t-----Successfully Read");

                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } finally{
                        if(fisCategory!= null){
                            try {
                                fisCategory.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(fisSell!= null){
                            try {
                                fisSell.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(fisExpired!= null){
                            try {
                                fisExpired.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(fisProduct!= null){
                            try {
                                fisProduct.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(oisCategory!= null){
                            try {
                                oisCategory.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(oisSell!= null){
                            try {
                                oisSell.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(oisExpired!= null){
                            try {
                                oisExpired.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        if(oisProduct!= null){
                            try {
                                oisProduct.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                    break;
                default:
                    System.exit(0);
                    break;
            }
        }
    }
    
    static void showMenu(){
        System.out.println("1. Insert Category");
        System.out.println("2. Insert Product");
        System.out.println("3. Show Sold Product");
        System.out.println("4. Show Product in Storage");
        System.out.println("5. Show Expired Product");
        System.out.println("6. Show Product close to Expired");
        System.out.println("7. Find Product");
        System.out.println("8. Save to file");
        System.out.println("9. Read from file");
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package May29FilePractice;

import java.io.Serializable;
import java.util.Scanner;

/**
 *
 * @author Administrator
 */
public class Category implements Serializable{
    String CatCode,CatName;

    public Category() {
    }

    public Category(String CatCode, String CatName) {
        this.CatCode = CatCode;
        this.CatName = CatName;
    }

    public String getCatCode() {
        return CatCode;
    }

    public void setCatCode(String CatCode) {
        this.CatCode = CatCode;
    }

    public String getCatName() {
        return CatName;
    }

    public void setCatName(String CatName) {
        this.CatName = CatName;
    }
    
    public void input(){
        Scanner input = new Scanner(System.in);
        System.out.print("Insert Category Code: ");
        CatCode = input.nextLine();
        System.out.print("Insert Category Name: ");
        CatName = input.nextLine();
    }

    @Override
    public String toString() {
        return "Category{" + "CatCode=" + CatCode + ", CatName=" + CatName + '}';
    }
    
    public void output(){
        System.out.println(toString());
    }
    
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package May29FilePractice;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class Product implements Serializable{
    String Code,Category,Name,Description;
    Date ImportDate,SellDate,ExpiredDate;
    float Price;

    public Product() {
    }

    public Product(String Code, String Category, String Name, String Description, Date ImportDate, Date SellDate, Date ExpiredDate, float Price) {
        this.Code = Code;
        this.Category = Category;
        this.Name = Name;
        this.Description = Description;
        this.ImportDate = ImportDate;
        this.SellDate = SellDate;
        this.ExpiredDate = ExpiredDate;
        this.Price = Price;
    }

    public String getCode() {
        return Code;
    }

    public void setCode(String Code) {
        this.Code = Code;
    }

    public String getCategory() {
        return Category;
    }

    public void setCategory(String Category) {
        this.Category = Category;
    }

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String Description) {
        this.Description = Description;
    }

    public Date getImportDate() {
        return ImportDate;
    }

    public void setImportDate(Date ImportDate) {
        this.ImportDate = ImportDate;
    }

    public Date getSellDate() {
        return SellDate;
    }

    public void setSellDate(Date SellDate) {
        this.SellDate = SellDate;
    }

    public Date getExpiredDate() {
        return ExpiredDate;
    }

    public void setExpiredDate(Date ExpiredDate) {
        this.ExpiredDate = ExpiredDate;
    }

    public float getPrice() {
        return Price;
    }

    public void setPrice(float Price) {
        this.Price = Price;
    }
    
    
    public void input(){
        Scanner input = new Scanner(System.in);
        System.out.print("Insert Product Code: ");
        Code = input.nextLine();
        System.out.print("Insert Product Category: ");
        Category = input.nextLine();
        System.out.print("Insert Product Name: ");
        Name = input.nextLine();
        System.out.print("Insert Product Price: ");
        Price = Float.parseFloat(input.nextLine());
        for(;;){
            System.out.print("Insert Product Import Date: ");
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            try {
                ImportDate = df.parse(input.nextLine());
                break;
            } catch (ParseException ex) {
                Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for(;;){
            System.out.print("Insert Product Sell Date: ");
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            try {
                SellDate = df.parse(input.nextLine());
                break;
            } catch (ParseException ex) {
                Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for(;;){
            System.out.print("Insert Product Expired Date: ");
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            try {
                ExpiredDate = df.parse(input.nextLine());
                break;
            } catch (ParseException ex) {
                Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.print("Insert Product Description: ");
        Description = input.nextLine();
    }
    
    public void output(){
        System.out.println("Product: "+Name+", Price :"+Price+", Import Date: "+ImportDate+", Sell Date: "+SellDate+", Expired Date: "+ExpiredDate);
    }
}



Luong Dinh Dai [T1907A]
Luong Dinh Dai

2020-04-10 17:52:09



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang;

import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author FATE STORE
 */
public class DanhMucSanPham {

    private String maDanhmuc, tenDanhmuc;

    public DanhMucSanPham() {
    }

    public DanhMucSanPham(String maDanhmuc, String tenDanhmuc) {
        this.maDanhmuc = maDanhmuc;
        this.tenDanhmuc = tenDanhmuc;
    }

    public String getMaDanhmuc() {
        return maDanhmuc;
    }

    public void setMaDanhmuc(String maDanhmuc) {
        this.maDanhmuc = maDanhmuc;
    }

    public String getTenDanhmuc() {
        return tenDanhmuc;
    }

    public void setTenDanhmuc(String tenDanhmuc) {
        this.tenDanhmuc = tenDanhmuc;
    }

    public void input() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ma danh muc");
        maDanhmuc = sc.nextLine();
        System.out.println("Nhap ten danh muc");
        tenDanhmuc = sc.nextLine();
        lstDanhmuc.add(this);
    }
     String formatLine() {
        return maDanhmuc + "," + tenDanhmuc + "\n";
    }
     
     void getLine(String line) {
        line = line.trim();
        String[] data = line.split(",");
        if (data.length < 2) {
            System.out.println("Data error");
            return;
        }
        this.maDanhmuc = data[0];
        this.tenDanhmuc = data[1];
    }

    @Override
    public String toString() {
        return "DanhMucSanPham{" + "maDanhmuc=" + maDanhmuc + ", tenDanhmuc=" + tenDanhmuc + '}';
    }
     public void display(){
         System.out.println(toString());
     }
     ArrayList<DanhMucSanPham> lstDanhmuc;

    public DanhMucSanPham(ArrayList<DanhMucSanPham> lstDanhmuc) {
        this.lstDanhmuc = lstDanhmuc;
    }
     
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang;

import java.util.Scanner;

/**
 *
 * @author FATE STORE
 */
public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        Manage manage = new Manage();
        Scanner sc = new Scanner(System.in);
        int sw;
        do {
            main.menu();
            sw = sc.nextInt();
            sc.nextLine();
            switch (sw) {
                case 1:
                    manage.nhapDanhmuc();
                    break;
                case 2:
                    manage.nhapSanpham();
                    break;
                case 3:
                    manage.spDaBan();
                    break;
                case 4:
                    manage.spTonkho();
                    break;
                case 5:
                    manage.dsSpHetHan();
                    break;
                case 6:   
                    manage.sanphamSapHSD();
                    break;
                case 7:
                    manage.timkiem();
                    break;
                case 8:
                    manage.saveFileSpdaban();
                    manage.saveFileSpconlai();
                    manage.SaveFileListHetHSd();
                    manage.saveFileDanhmuc();
                    break;
                case 9:
                    manage.readFileListHetHSd();
                    manage.readFileSpconlai();
                    manage.readFileSpBan();
                    manage.readFileDanhmuc();
                    break;
                default:
                    break;
            }
        } while (sw != 0);
    }

    public void menu() {
        System.out.print("**********************************\n1: Nhap thong tin danh muc:\n2: Nhap thong tin san pham:\n3: In ra cac san pham da ban:\n4: In ra danh sach san pham ton kho:\n5: In ra san pham qua han su dung:\n6: In ra san pham sap het han su dung:\n7: Tim kiem theo ten SP:\n8: Luu vao file:\n9: Doc du lieu tu file:\nLua Chon: ");
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author FATE STORE
 */
public class Manage {

    List<DanhMucSanPham> lstDanhmuc;
    List<SanPham> lstSp;
    List<SanPham> lstBan;
    List<SanPham> lstTonkho;
    List<SanPham> lstHethan;
    List<SanPham> lstChuaban;
    List<SanPham> lstSaphethsd;
    Scanner sc = new Scanner(System.in);

    public Manage() {
        lstDanhmuc = new ArrayList<>();
        lstSp = new ArrayList<>();
        lstBan = new ArrayList<>();
        lstTonkho = new ArrayList<>();
        lstHethan = new ArrayList<>();
        lstChuaban = new ArrayList<>();
        lstSaphethsd = new ArrayList<>();
    }

    public void nhapDanhmuc() {
        System.out.println("Nhap N danh muc: ");
        int n = sc.nextInt();
        sc.nextLine();
        for (int i = 0; i < n; i++) {
            DanhMucSanPham Danhmuc = new DanhMucSanPham();
            Danhmuc.input();
            lstDanhmuc.add(Danhmuc);
        }
        for (DanhMucSanPham lstDanhMuc : lstDanhmuc) {
            lstDanhMuc.display();
        }

    }

    public void nhapSanpham() {
        System.out.println("Nhap N san pham: ");
        int n = sc.nextInt();
        sc.nextLine();
        for (int i = 0; i < n; i++) {
            SanPham sp = new SanPham();
            sp.inputSp(lstDanhmuc);
            lstSp.add(sp);
        }
        System.out.println("cac san pham da nhap: ");
        for (SanPham sp : lstSp) {
            sp.display();
        }
    }

    public void spDaBan() {

        for (SanPham sanpham : lstSp) {
            if (!"".equals(sanpham.getNgayban())) {
                lstBan.add(sanpham);
            }
        }
        System.out.println("san pham da ban: ");
        for (int i = 0; i < lstBan.size(); i++) {
            lstBan.get(i).display();
        }

    }

    public void spTonkho() {
        System.out.println("Danh sách sản phẩm tồn kho:");
        for (SanPham sanpham : lstSp) {
            if ("".equals(sanpham.getNgayban())) {
                lstTonkho.add(sanpham);
                sanpham.display();
            }
        }
    }

    public int checkHsd(String d1) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        int detDiff = 0;
        boolean check = false;
        try {
            Date curent = new Date();
            String nowDate = sdf.format(curent);
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(nowDate);

            detDiff = (int) (date2.getTime() - date1.getTime());
            detDiff = detDiff / (24 * 60 * 60 * 1000);
        } catch (ParseException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        return detDiff;
    }

    public void dsSpHetHan() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        for (int i = 0; i < lstTonkho.size(); i++) {
            if (checkHsd(lstTonkho.get(i).getHsd()) > 0) {
                lstHethan.add(lstTonkho.get(i));
            } else {
                lstChuaban.add(lstTonkho.get(i));
            }
        }
        System.out.println("Danh sach cac san pham het han: ");
        for (SanPham sanpham : lstHethan) {
            sanpham.display();
        }
    }

    public void sanphamSapHSD() {
        int count = 0;
        for (SanPham sanpham : lstChuaban) {
            if (checkHsd(sanpham.getHsd()) < 0 && checkHsd(sanpham.getHsd()) >= -7) {
                count++;
                lstSaphethsd.add(sanpham);
            }
        }
        if (count != 0) {

            System.out.println("San pham sap het han: ");
            for (SanPham sanpham : lstSaphethsd) {
                sanpham.display();
            }
        } else {
            System.out.println("khong co san pham sap het han: ");
        }
    }

    public void timkiem() {
        int count = 0;
        System.out.println("Nhap ten san pham can tim: ");
        String ten = sc.nextLine();
        System.out.println("Ket qua: " + ten);
        for (int i = 0; i < lstSp.size(); i++) {
            if (ten.equalsIgnoreCase(lstSp.get(i).getTensp())) {
                lstSp.get(i).display();
                count++;
            }
        }
        System.out.println("So luong: " + count);
    }

    public void saveFileSpdaban() {
        String url = "C:\\Java\\src\\QuanLyBanHang\\sell.dat";
        saveFile(url, lstBan);
    }

    private void saveFile(String url, List<SanPham> listobject) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(url);
            bos = new BufferedOutputStream(fos);

            for (SanPham listobject1 : listobject) {
                String line = listobject1.formatLine();
                byte[] b;
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public void readFile(String url, List<SanPham> listSp) {
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            reader = new FileReader(url);
            bufferedReader = new BufferedReader(reader);

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                SanPham sp = new SanPham();
                sp.getLine(line);
                listSp.add(sp);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
    public void readFileListHetHSd() {
        lstHethan.clear();
        String url = "C:\\Java\\src\\QuanLyBanHang\\expire.dat";
        readFile(url, lstHethan);
        System.out.println("Danh sach san pham het han su dung: ");
        for (SanPham sanpham : lstHethan) {
            sanpham.display();
        }
    }
     public void readFileSpBan() {
        lstBan.clear();
        String url = "D:\\baitapjava\\JavaNangCao\\src\\QuanLiBanHang\\sell.dat";
        readFile(url, lstBan);
        System.out.println("Danh sach sp da ban");
        for (SanPham sanpham : lstBan) {
            sanpham.display();
        }
    }

    public void saveFileSpconlai() {
        String url = "C:\\Java\\src\\QuanLyBanHang\\product.dat";
        saveFile(url, lstChuaban);
    }
    public void SaveFileListHetHSd() {
        String url = "C:\\Java\\src\\QuanLyBanHang\\expire.dat";
        saveFile(url, lstHethan);
    }


    public void readFileSpconlai() {
        lstChuaban.clear();
        String url = "C:\\Java\\src\\QuanLyBanHang\\product.dat";
        saveFile(url, lstChuaban);
        System.out.println("Danh sach sp con lai: ");
        for (SanPham sanpham : lstChuaban) {
            sanpham.display();
        }
    }
    public void saveFileDanhmuc() {
        String url = "C:\\Java\\src\\QuanLyBanHang\\category.dat";
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(url);
            bos = new BufferedOutputStream(fos);

            for (DanhMucSanPham danhmuc : lstDanhmuc) {
                String line = danhmuc.formatLine();
                byte[] b;
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void readFileDanhmuc() {
        lstDanhmuc.clear();
        String url = "C:\\Java\\src\\QuanLyBanHang\\category.dat";
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            reader = new FileReader(url);
            bufferedReader = new BufferedReader(reader);

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                DanhMucSanPham danhmuc = new DanhMucSanPham();
                danhmuc.getLine(line);
                lstDanhmuc.add(danhmuc);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("Danh sach danh muc san pham");
        for (DanhMucSanPham danhmuc : lstDanhmuc) {
            danhmuc.display();
        }
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlybanhang;

import java.util.List;
import java.util.Scanner;

/**
 *
 * @author FATE STORE
 */
public class SanPham {

    private String masp, madanhmuc, tensp, gia, ngaynhap, ngayban, hsd, mota;

    public SanPham() {
    }

    public SanPham(String masp, String madanhmuc, String tensp, String gia, String ngaynhap, String ngayban, String hsd, String mota) {
        this.masp = masp;
        this.madanhmuc = madanhmuc;
        this.tensp = tensp;
        this.gia = gia;
        this.ngaynhap = ngaynhap;
        this.ngayban = ngayban;
        this.hsd = hsd;
        this.mota = mota;
    }

    public String getMasp() {
        return masp;
    }

    public void setMasp(String masp) {
        this.masp = masp;
    }

    public String getMadanhmuc() {
        return madanhmuc;
    }

    public void setMadanhmuc(String madanhmuc) {
        this.madanhmuc = madanhmuc;
    }

    public String getTensp() {
        return tensp;
    }

    public void setTensp(String tensp) {
        this.tensp = tensp;
    }

    public String getGia() {
        return gia;
    }

    public void setGia(String gia) {
        this.gia = gia;
    }

    public String getNgaynhap() {
        return ngaynhap;
    }

    public void setNgaynhap(String ngaynhap) {
        this.ngaynhap = ngaynhap;
    }

    public String getNgayban() {
        return ngayban;
    }

    public void setNgayban(String ngayban) {
        this.ngayban = ngayban;
    }

    public String getHsd() {
        return hsd;
    }

    public void setHsd(String hsd) {
        this.hsd = hsd;
    }

    public String getMota() {
        return mota;
    }

    public void setMota(String mota) {
        this.mota = mota;
    }

    @Override
    public String toString() {
        return "SanPham{" + "masp=" + masp + ", madanhmuc=" + madanhmuc + ", tensp=" + tensp + ", gia=" + gia + ", ngaynhap=" + ngaynhap + ", ngayban=" + ngayban + ", hsd=" + hsd + ", mota=" + mota + '}';
    }

    public void display() {
        System.out.println(toString());
    }

    public void inputSp(List<DanhMucSanPham> danhmuc) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ma san pham: ");
        masp = sc.nextLine();
        while (true) {
            System.out.println("Nhap ma danh muc: ");
            madanhmuc = sc.nextLine();
            boolean check = false;
            for (DanhMucSanPham Danhmuc : danhmuc) {
                if (Danhmuc.getMaDanhmuc().equalsIgnoreCase(madanhmuc)) {
                    check = true;
                    break;
                }
            }
            if (check) {
                break;
            } else {
                System.err.println("Ma danh muc khong ton tai: ");
            }
        }
        System.out.println("Nhap ten san pham: ");
        tensp = sc.nextLine();
        System.out.println("Nhap gia san pham: ");
        gia = sc.nextLine();
        System.out.println("Nhap ngay nhap san pham(dd-MM-yyyy): ");
        ngaynhap = sc.nextLine();
        System.out.println("Nhap ngay ban san pham(dd-MM-yyyy): ");
        ngayban = sc.nextLine();
        System.out.println("Nhap han su dung(dd-MM-yyyy: )");
        hsd = sc.nextLine();
        System.out.println("Nhap mo ta san pham: ");
        mota = sc.nextLine();

    }

    public String formatLine() {
        return masp + "," + madanhmuc + "," + tensp + "," + gia + "," + ngaynhap + "," + ngayban + "," + hsd + "," + mota + "\n";
    }

    void getLine(String line) {
        line = line.trim();
        String[] data = line.split(",");
        if (data.length < 8) {
            System.out.println("Data error");
            return;
        }
        this.masp = data[0];
        this.madanhmuc = data[1];
        this.tensp = data[2];
        this.gia = data[3];
        this.ngaynhap = data[4];
        this.ngayban = data[5];
        this.hsd = data[6];
        this.mota = data[7];
    }

}



Lê Minh Bắc [T1907A]
Lê Minh Bắc

2020-04-09 15:52:36



package QuanLiBanHang;

/**
 *
 * @author lemin
 */
import java.util.Scanner;

public class DanhMucSP {

    String idDanhMuc, nameDanhMuc;

    public DanhMucSP() {
    }

    public DanhMucSP(String idDanhMuc, String nameDanhMuc) {
        this.idDanhMuc = idDanhMuc;
        this.nameDanhMuc = nameDanhMuc;
    }

    public void setIdDanhMuc(String idDanhMuc) {
        this.idDanhMuc = idDanhMuc;
    }

    public void setNameDanhMuc(String nameDanhMuc) {
        this.nameDanhMuc = nameDanhMuc;
    }

    public String getIdDanhMuc() {
        return idDanhMuc;
    }

    public String getNameDanhMuc() {
        return nameDanhMuc;
    }

    @Override
    public String toString() {
        return "DanhMucSP{" + "idDanhMuc=" + idDanhMuc + ", nameDanhMuc=" + nameDanhMuc + '}';
    }

    public void display() {
        System.out.println(toString());
    }

    public void inputDM() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ma danh muc");
        idDanhMuc = sc.nextLine();
        System.out.println("Nhap ten danh muc");
        nameDanhMuc = sc.nextLine();
    }

    String formatLine() {
        return idDanhMuc + "," + nameDanhMuc + "\n";
    }

    void getLine(String line) {
        line = line.trim();
        String[] data = line.split(",");
        if (data.length < 2) {
            System.out.println("Data error");
            return;
        }
        this.idDanhMuc = data[0];
        this.nameDanhMuc = data[1];
    }
}



package QuanLiBanHang;

import java.util.List;
import java.util.Scanner;

/**
 *
 * @author lemin
 */
public class SanPham {

    String idSp, maDanhMuc;
    String nameSp, price;
    String inputdate, outputdate, hsd, mota;

    public SanPham() {
    }

    public SanPham(String idSp, String maDanhMuc, String nameSp, String price, String inputdate, String outputdate, String hsd, String mota) {
        this.idSp = idSp;
        this.maDanhMuc = maDanhMuc;
        this.nameSp = nameSp;
        this.price = price;
        this.inputdate = inputdate;
        this.outputdate = outputdate;
        this.hsd = hsd;
        this.mota = mota;
    }

    public void inputSp(List<DanhMucSP> dm) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhap ma san pham");
        idSp = sc.nextLine();
        while (true) {
            System.out.println("Nhap ma danh muc");
            maDanhMuc = sc.nextLine();
            boolean check = false;
            for (DanhMucSP dm1 : dm) {
                if (dm1.getIdDanhMuc().equalsIgnoreCase(maDanhMuc)) {
                    check = true;
                    break;
                }
            }
            if (check) {
                break;
            } else {
                System.err.println("Ma danh muc khong ton tai");
            }
        }
        //trường hợp nhập dữ liệu vào 100% là đúng
        System.out.println("Nhap ten san pham: ");
        nameSp = sc.nextLine();
        System.out.println("Nhap gia san pham");
        price = sc.nextLine();
        
        System.out.println("Nhap ngay nhap san pham(dd-MM-yyyy)");
        inputdate = sc.nextLine();
        // nếu chưa bán đc thì nhập để rỗng
        System.out.println("Nhap ngay ban san pham(dd-MM-yyyy)");
        outputdate = sc.nextLine();
        System.out.println("Nhap han su dung(dd-MM-yyyy)");
        hsd = sc.nextLine();
        System.out.println("Nhap mo ta san pham");
        mota = sc.nextLine();

    }

    public String getIdSp() {
        return idSp;
    }

    public void setIdSp(String idSp) {
        this.idSp = idSp;
    }

    public String getMaDanhMuc() {
        return maDanhMuc;
    }

    public void setMaDanhMuc(String maDanhMuc) {
        this.maDanhMuc = maDanhMuc;
    }

    public String getNameSp() {
        return nameSp;
    }

    public void setNameSp(String nameSp) {
        this.nameSp = nameSp;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getInputdate() {
        return inputdate;
    }

    public void setInputdate(String inputdate) {
        this.inputdate = inputdate;
    }

    public String getOutputdate() {
        return outputdate;
    }

    public void setOutputdate(String outputdate) {
        this.outputdate = outputdate;
    }

    public String getHsd() {
        return hsd;
    }

    public void setHsd(String hsd) {
        this.hsd = hsd;
    }

    public String getMota() {
        return mota;
    }

    public void setMota(String mota) {
        this.mota = mota;
    }

    @Override
    public String toString() {
        return "SanPham{" + "idSp=" + idSp + ", maDanhMuc=" + maDanhMuc + ", nameSp=" + nameSp + ", price=" + price + ", inputdate=" + inputdate + ", outputdate=" + outputdate + ", hsd=" + hsd + ", mota=" + mota + '}';
    }

    public void displaySq() {
        System.out.println(toString());
    }

    public String formatLine() {
        return idSp + "," + maDanhMuc + "," + nameSp + "," + price + "," + inputdate + "," + outputdate + "," + hsd + "," + mota + "\n";
    }

    void getLine(String line) {
        line = line.trim();
        String[] data = line.split(",");
        if (data.length < 8) {
            System.out.println("Data error");
            return;
        }
        this.idSp = data[0];
        this.maDanhMuc = data[1];
        this.nameSp = data[2];
        this.price = data[3];
        this.inputdate = data[4];
        this.outputdate = data[5];
        this.hsd = data[6];
        this.mota = data[7];
    }
}



package QuanLiBanHang;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author lemin
 */
public class Manage {

    private static Scanner sc = new Scanner(System.in);
    List<DanhMucSP> listDanhMuc;
    List<SanPham> listSp;
    List<SanPham> listSell;
    List<SanPham> listTonkho;
    List<SanPham> listHetHSD;
    List<SanPham> listSpConLai;// la nhung sp chưa bán dc và chưa hết hạn
    List<SanPham> listSpSapHSD;

    public Manage() {
        listDanhMuc = new ArrayList<>();
        listSp = new ArrayList<>();
        listSell = new ArrayList<>();
        listTonkho = new ArrayList<>();
        listHetHSD = new ArrayList<>();
        listSpConLai = new ArrayList<>();
        listSpSapHSD = new ArrayList<>();
    }

    public void nhapDm() {
        System.out.println("Nhap N danh muc muốn nhập:");
        int n = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < n; i++) {
            DanhMucSP dm = new DanhMucSP();
            dm.inputDM();
            listDanhMuc.add(dm);
        }
        for (DanhMucSP listDanhMuc1 : listDanhMuc) {
            listDanhMuc1.display();
        }

    }

    public void inputSanpham() {
        System.out.println("Nhap N san pham muốn thêm vào :");
        int n = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < n; i++) {
            SanPham sp = new SanPham();
            sp.inputSp(listDanhMuc);
            listSp.add(sp);
        }
        System.out.println("danh sach cac san pham da nhap");
        for (SanPham sp : listSp) {
            sp.displaySq();
        }
    }

    //ds cac san pham da ban
    public void spSell() {

        for (SanPham sanpham1 : listSp) {
            if (!"".equals(sanpham1.getOutputdate())) {
                listSell.add(sanpham1);
            }
        }
        System.out.println("Danh sách sản phẩm đã bán:");
        for (int i = 0; i < listSell.size(); i++) {
            listSell.get(i).displaySq();
        }

    }

    //ds san pham ton kho
    public void spTonkho() {
        System.out.println("Danh sách sản phẩm tồn kho:");
        for (SanPham sanpham1 : listSp) {
            if ("".equals(sanpham1.getOutputdate())) {
                listTonkho.add(sanpham1);
                sanpham1.displaySq();
            }
        }
    }

    public int checkHsd(String d1) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        int detDiff = 0;
        boolean check = false;
        try {
            // String ngay = "2020-04-01";
            Date curent = new Date();
            String nowDate = sdf.format(curent);
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(nowDate);

            detDiff = (int) (date2.getTime() - date1.getTime());
            detDiff = detDiff / (24 * 60 * 60 * 1000);
            // System.out.println("Date khoangcach: " + detDiff);

        } catch (ParseException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        return detDiff;
    }

    //danh sach san pham da qua han su dung
    //chỉ check những thằng chưa bán dc để kiểm tra xem hét hạn chưa
    public void dsSpHetHan() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        for (int i = 0; i < listTonkho.size(); i++) {
            if (checkHsd(listTonkho.get(i).getHsd()) > 0) {
                listHetHSD.add(listTonkho.get(i));
            } else {
                //thằng nào chưa hết hạn ném vào danh sách sp còn lại chưa bán chưa hết hạn
                listSpConLai.add(listTonkho.get(i));
            }
        }
        System.out.println("Danh sach cac san pham het han:");
        for (SanPham sp : listHetHSD) {
            sp.displaySq();
        }
    }

    //tim danh sach san pham sap het hạn.check ngày hiện tại  so vs ngày sử dụng <=7 thì cho vào ds sắp hét hạn
    public void sanphamSapHSD() {
// ti sua lai
        int count = 0;
        for (SanPham sp : listSpConLai) {
            if (checkHsd(sp.getHsd()) < 0 && checkHsd(sp.getHsd())>= -7 ) {
                count++;
                listSpSapHSD.add(sp);
            }
        }
        if (count != 0) {

            System.out.println("Danh sách sản phẩm sắp hết hạn sử dụng");
            for (SanPham sp1 : listSpSapHSD) {
                sp1.displaySq();
            }
        } else {
            System.out.println("Không có sản phẩm nào sắp hết hạn sử dụng");
        }
    }

    // tim kiem >> nhap ten san pham
    public void findSp() {
        int count = 0;
        System.out.println("Nhap ten san pham can tim: ");
        String findName = sc.nextLine();
        System.out.println("Ket qua: " + findName);
        for (int i = 0; i < listSp.size(); i++) {
            if (findName.equalsIgnoreCase(listSp.get(i).getNameSp())) {
                listSp.get(i).displaySq();
                count++;
            }
        }
        System.out.println("So luong: " + count);
    }

    // luu du lieu xuong file
    public void SaveFilelistSpdaban() {
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\sell.dat";
        saveFile(url, listSell);
    }

    public void readFileSpSell() {
        listSell.clear();
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\sell.dat";
        readFile(url, listSell);
        System.out.println("Danh sach sp da ban");
        for (SanPham sp : listSell) {
            sp.displaySq();
        }
    }

    public void SaveFileListHetHSd() {
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHangg\\expire.dat";
        saveFile(url, listHetHSD);
    }

    public void readFileListHetHSd() {
        listHetHSD.clear();
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\expire.dat";
        readFile(url, listHetHSD);
        System.out.println("Danh sach san pham het han su dung");
        for (SanPham sp : listHetHSD) {
            sp.displaySq();
        }
    }

    //luu xuong file list ds san pham con lai:cac sp chưa bán và chưa hêt hạn
    public void saveFileSpconlai() {
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\product.dat";
        saveFile(url, listSpConLai);
    }

    public void readFileSpconlai() {
        listSpConLai.clear();
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\product.dat";
        saveFile(url, listSpConLai);
        System.out.println("Danh sach sp con lai:");
        for (SanPham sp : listSpConLai) {
            sp.displaySq();
        }
    }

    public void saveFile(String url, List<SanPham> listobject) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(url);
            bos = new BufferedOutputStream(fos);

            for (SanPham listobject1 : listobject) {
                String line = listobject1.formatLine();
                byte[] b;
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    //doc data tu file va hien thi len chuong trinh
    public void readFile(String url, List<SanPham> listSp) {
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            reader = new FileReader(url);
            bufferedReader = new BufferedReader(reader);

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                SanPham sp = new SanPham();
                sp.getLine(line);
                listSp.add(sp);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    // luu file danh muc
    public void saveFileDm() {
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\category.dat";
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(url);
            bos = new BufferedOutputStream(fos);

            for (DanhMucSP dm : listDanhMuc) {
                String line = dm.formatLine();
                byte[] b;
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void readFileDm() {
        listDanhMuc.clear();
        String url = "C:\\Users\\lemin\\OneDrive\\Documents\\NetBeansProjects\\Java2\\src\\QuanLiBanHang\\category.dat";
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            reader = new FileReader(url);
            bufferedReader = new BufferedReader(reader);

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                DanhMucSP dm = new DanhMucSP();
                dm.getLine(line);
                listDanhMuc.add(dm);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("Danh sach danh muc san pham");
        for (DanhMucSP listDanhMuc1 : listDanhMuc) {
            listDanhMuc1.display();
        }
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package QuanLiBanHang;

import java.util.Scanner;

/**
 *
 * @author Thien Phu
 */
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Manage manage = new Manage();

        int choose;
        do {
            showmenu();
            choose = Integer.parseInt(sc.nextLine());
            switch (choose) {
                case 1:
                    manage.nhapDm();
                    break;
                case 2:
                    manage.inputSanpham();
                    break;
                case 3:
                    manage.spSell();
                    break;
                case 4:
                    manage.spTonkho();
                    break;
                case 5:
                    manage.dsSpHetHan();
                    break;
                case 6:
                    manage.sanphamSapHSD();
                    break;
                case 7:
                    manage.findSp();
                    break;
                case 8:
                    manage.SaveFilelistSpdaban();
                    manage.SaveFileListHetHSd();
                    manage.saveFileSpconlai();
                    manage.saveFileDm();
                    break;
                case 9:
                    manage.readFileSpSell();
                    manage.readFileListHetHSd();
                    manage.readFileSpconlai();
                    manage.readFileDm();
                    break;
                case 0:
                    System.out.println("Thoat thanh cong");
                    break;
                default:
                    System.out.println("Nhap lai di");
                    break;
            }
        } while (choose != 0);

    }

    static void showmenu() {
        System.out.println("1: Nhap thong tin danh muc");
        System.out.println("2: Nhap thong tin san pham");
        System.out.println("3: In danh sach cac san pham da ban");
        System.out.println("4: In danh sach cac san pham con ton tai trong kho");
        System.out.println("5: In danh sach cac san pham da qua han su dung");
        System.out.println("6: In ra danh sach cac san pham sap het han su dung");
        System.out.println("7: Tim kiem san pham");
        System.out.println("8 Luu du lieu vao file");
        System.out.println("9: Doc du lieu tu file va  luu ra chuong trinh");
        System.out.println("0: Thoat");
        System.out.println("Chooose: ");
    }
}




Đường Thanh Bình [T1907A]
Đường Thanh Bình

2020-04-08 13:14:21



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Assignment1;
import java.util.Scanner;
/**
 *
 * @author Administrator
 */
public class Main {
     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Manager manager = new Manager();

        int choose;
        do {
            showmenu();
            choose = Integer.parseInt(sc.nextLine());
            switch (choose) {
                case 1:
                    System.out.println("Hay nhap thong tin danh muc");
                    manager.importCategory();
                    break;
                case 2:
                    System.out.println("Hay nhap thong tin san pham");
                    manager.inputProduct();
                    break;
                case 3:
                    System.out.println("In ra danh sach casc san pham da ban ");
                    manager.Sell();
                    break;
                case 4:
                    System.out.println("In ra danh sach sasn pham con ton kho");
                    manager.Inventory();
                    break;
                case 5:
                    System.out.println("In ra danh sach san pham da qua han su dung");
                    manager.Rest();
                    break;
                case 6:
                    System.out.println("In ra ds casc san pham sap het han su dung");
                    manager.AlmostEndDate();
                    break;
                case 7:
                    System.out.println("TIM KIEM");
                    manager.SearchProduct();
                    break;
                case 8:
                    System.out.println("Da luu file thanh cong");
                    manager.SaveFileListSell();
                    manager.SaveFileListEndDate();
                    manager.saveFileRest();
                    manager.saveFileCategory();
                    break;
                case 9:
                    System.out.println("Da doc file hoan tat");
                    manager.readFileListSell();
                    manager.readFileListEndDate();
                    manager.readFileRest();
                    manager.readFileCategory();
                    break;
                case 10:
                    System.out.println("PP");
                    break;
                default:
                    System.out.println("Nhap lai di ban ei");
                    
            }
        } while (choose != 0);

    }

    static void showmenu() {
        System.out.println("1 : Nhap thong tin danh muc");
        System.out.println("2 : Nhap thong tin san pham");
        System.out.println("3 : In danh sach cac san pham da ban");
        System.out.println("4 : In danh sach cac san pham con ton tai trong kho");
        System.out.println("5 : In danh sach cac san pham da qua han su dung");
        System.out.println("6 : In ra danh sach cac san pham sap het han su dung");
        System.out.println("7 : Tim kiem san pham");
        System.out.println("8 : Luu du lieu vao file");
        System.out.println("9 : Doc du lieu tu file va  luu ra chuong trinh");
        System.out.println("10 : Thoat");
        System.out.println("Chooose: ");
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Assignment1;
import java.util.List;
import java.util.Scanner;
/**
 *
 * @author Administrator
 */
public class Product {
    String IdPro, maDanhMuc, price;
    String NamePro, inputDate, outputDate, dateEnd, describe;

    public Product() {
    }

    public Product(String IdPro, String maDanhMuc, String price, String NamePro, String inputDate, String outputDate, String dateEnd, String describe) {
        this.IdPro = IdPro;
        this.maDanhMuc = maDanhMuc;
        this.price = price;
        this.NamePro = NamePro;
        this.inputDate = inputDate;
        this.outputDate = outputDate;
        this.dateEnd = dateEnd;
        this.describe = describe;
    }

    public String getIdPro() {
        return IdPro;
    }

    public void setIdPro(String IdPro) {
        this.IdPro = IdPro;
    }

    public String getMaDanhMuc() {
        return maDanhMuc;
    }

    public void setMaDanhMuc(String maDanhMuc) {
        this.maDanhMuc = maDanhMuc;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getNamePro() {
        return NamePro;
    }

    public void setNamePro(String NamePro) {
        this.NamePro = NamePro;
    }

    public String getInputDate() {
        return inputDate;
    }

    public void setInputDate(String inputDate) {
        this.inputDate = inputDate;
    }

    public String getOutputDate() {
        return outputDate;
    }

    public void setOutputDate(String outputDate) {
        this.outputDate = outputDate;
    }

    public String getDateEnd() {
        return dateEnd;
    }

    public void setDateEnd(String dateEnd) {
        this.dateEnd = dateEnd;
    }

    public String getDescribe() {
        return describe;
    }

    public void setDescribe(String describe) {
        this.describe = describe;
    }

    @Override
    public String toString() {
        return "Product{" + "IdPro=" + IdPro + ", maDanhMuc=" + maDanhMuc + ", price=" + price + ", NamePro=" + NamePro + ", inputDate=" + inputDate + ", outputDate=" + outputDate + ", dateEnd=" + dateEnd + ", describe=" + describe + '}';
    }

    public void inputProduct(List<Category> Category) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Moi ban nhap ma san pham : ");
        IdPro = scan.nextLine();
        while (true) {
            System.out.println("Moi ban nhap ma danh muc : ");
            maDanhMuc = scan.nextLine();
            boolean check = false;
            for (Category Category1 : Category) {
                if (Category1.getIdCate().equalsIgnoreCase(maDanhMuc)) {
                    check = true;
                    break;
                }
            }
            if (check) {
                break;
            } else {
                System.err.println("Ma danh muc nay khong ton tai !!!");
            }
        }
        System.out.println("Moi ban nhap gia san pham : ");
        NamePro = scan.nextLine();
        System.out.println("Moi ban nhap gia san pham : ");
        price = scan.nextLine();
        System.out.println(" Ngay nhap san pham : ");
        inputDate = scan.nextLine();
        System.out.println("Nhap ngay ban san pham :");
        outputDate = scan.nextLine();
        System.out.println("Nhap han su dung:");
        dateEnd = scan.nextLine();
        System.out.println("Nhap mo ta san pham : ");
        describe = scan.nextLine();
    }

    public void displayProduct() {
        System.out.println(toString());
    }

    public String formatLine() {
        return IdPro + "," + maDanhMuc + "," + NamePro + "," + price + "," + inputDate + "," + outputDate + "," + dateEnd + "," + describe + "\n";
    }

    void getLine(String line) {
        line = line.trim();
        String[] data = line.split(",");
        if (data.length < 8) {
            System.out.println("Data error");
            return;
        }
        this.IdPro = data[0];
        this.maDanhMuc = data[1];
        this.NamePro = data[2];
        this.price = data[3];
        this.inputDate = data[4];
        this.outputDate = data[5];
        this.dateEnd = data[6];
        this.describe = data[7];
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Assignment1;

import java.util.Scanner;

/**
 *
 * @author Administrator
 */
public class Category {
    String IdCate, NameCate;

    public Category() {
    }

    public Category(String IdCate, String NameCate) {
        this.IdCate = IdCate;
        this.NameCate = NameCate;
    }

    public String getIdCate() {
        return IdCate;
    }

    public void setIdCate(String IdCate) {
        this.IdCate = IdCate;
    }

    public String getNameCate() {
        return NameCate;
    }

    public void setNameCate(String NameCate) {
        this.NameCate = NameCate;
    }

    @Override
    public String toString() {
        return "Category{" + "IdCate=" + IdCate + ", NameCate=" + NameCate + '}';
    }

    public void display() {
        System.out.println(toString());
    }

    public void inputCategory() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Moi ban nhap ma danh muc : ");
        IdCate = scan.nextLine();
        System.out.println("Moi ban nhap ten danh muc : ");
        NameCate = scan.nextLine();
    }

    String formatLine() {
        return IdCate + "," + NameCate + "\n";
    }

    void getLine(String line) {
        line = line.trim();
        String[] data = line.split(",");
        if (data.length < 2) {
            System.out.println("Data error");
            return;
        }
        this.IdCate = data[0];
        this.NameCate = data[1];
    }
}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Assignment1;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Administrator
 */
public class Manager {
    Scanner scan = new Scanner(System.in);
    List<Category> listCate = new ArrayList<>();
    List<Product> listPro = new ArrayList<>();
    List<Product> listSell = new ArrayList<>();
    List<Product> listInventory = new ArrayList<>();
    List<Product> listEndDate = new ArrayList<>();
    List<Product> listRest = new ArrayList<>();
    List<Product> listAlmostEndDate = new ArrayList<>();

    public Manager() {
      
    }

    public void importCategory() {
        System.out.println("Nhap N danh muc muon nhap :");
        int n = Integer.parseInt(scan.nextLine());
        
       
        for (int i = 0; i < n; i++) {
            Category category = new Category();
            category.inputCategory();
            listCate.add(category);
        }
        listCate.forEach((listCate1) -> {
            listCate1.display();
        });

    }

    public void inputProduct() {
        System.out.println("Nhap N san pham muon them : ");
        int n = Integer.parseInt(scan.nextLine());
        for (int i = 0; i < n; i++) {
            Product product = new Product();
            product.inputProduct(listCate);
            listPro.add(product);
        }
        System.out.println("danh sach cac san pham da nhap");
        listPro.forEach((product) -> {
            product.displayProduct();
        });
    }

   
    public void Sell() {

        listPro.stream().filter((product1) -> (!"".equals(product1.getOutputDate()))).forEachOrdered((product1) -> {
            listSell.add(product1);
        });
        System.out.println("Danh sach san pham da ban :");
        for (int i = 0; i < listSell.size(); i++) {
            listSell.get(i).displayProduct();
        }

    }

   
    public void Inventory() {
        System.out.println("Danh sach san pham ton kho : ");
        listPro.stream().filter((product1) -> ("".equals(product1.getOutputDate()))).map((product1) -> {
            listInventory.add(product1);
            return product1;
        }).forEachOrdered((product1) -> {
            product1.displayProduct();
        });
    }

    public int EndDate(String d1) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            int detDiff = 0;
            boolean check = false;
            
            Date curent = new Date();
            String nowDate = sdf.format(curent);
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(nowDate);

            detDiff = (int) (date2.getTime() - date1.getTime());
            detDiff = detDiff / (24 * 60 * 60 * 1000);     
        } catch (ParseException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
         return 0;
    }



    public void Rest() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        for (int i = 0; i < listRest.size(); i++) {
            if (EndDate(listRest.get(i).getDateEnd()) > 0) {
                listEndDate.add(listRest.get(i));
            } else {
                listRest.add(listInventory.get(i));
            }
        }
        System.out.println("Danh sach cac san pham het han:");
        listEndDate.forEach((product) -> {
            product.displayProduct();
        });
    }

    
    public void AlmostEndDate() {
        int count = 0;
        for (Product product : listRest) {
            if (EndDate(product.getDateEnd()) <= 7) {
                count++;
                listAlmostEndDate.add(product);
            }
        }
        if (count != 0) {

            System.out.println("Danh sach san pham sap het han su dung : ");
            listAlmostEndDate.forEach((product) -> {
                product.displayProduct();
            });
        } else {
            System.out.println("Khong co san pham nao sap het HSD !!!");
        }
    }

  //search
    public void SearchProduct() {
        int count = 0;
        System.out.println("Nhap ten san pham can tim : ");
        String findName = scan.nextLine();
        System.out.println("Ket qua: " + findName);
        for (int i = 0; i < listPro.size(); i++) {
            if (findName.equalsIgnoreCase(listPro.get(i).getNamePro())) {
                listPro.get(i).displayProduct();
                count++;
            }
        }
        System.out.println("So luong la : " + count);
    }

    // save file
    public void SaveFileListSell() {
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\sell.dat";
        saveFile(url, listSell);
    }

    public void readFileListSell() {
        listSell.clear();
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\sell.dat";
        readFile(url, listSell);
        System.out.println("Danh sach sp da ban");
        listSell.forEach((product) -> {
            product.displayProduct();
        });
    }

    public void SaveFileListEndDate() {
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\expire.dat";
        saveFile(url, listEndDate);
    }

    public void readFileListEndDate() {
        listEndDate.clear();
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\expire.dat";
        readFile(url, listEndDate);
        System.out.println("Danh sach san pham het han su dung");
        listEndDate.forEach((product) -> {
            product.displayProduct();
        });
    }

    
    public void saveFileRest() {
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\product.dat";
        saveFile(url, listRest);
    }

    public void readFileRest() {
        listRest.clear();
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\product.dat";
        saveFile(url, listRest);
        System.out.println("Danh sach sp con lai:");
        listRest.forEach((product) -> {
            product.displayProduct();
        });
    }

    public void saveFile(String url, List<Product> listobject) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(url);
            bos = new BufferedOutputStream(fos);

            for ( Product listobject1 : listobject) {
                String line = listobject1.formatLine();
                byte[] b;
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    
    public void readFile(String url, List<Product> listPro) {
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            reader = new FileReader(url);
            bufferedReader = new BufferedReader(reader);

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                Product product = new Product();
                product.getLine(line);
                listPro.add(product);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    // luu file danh muc
    public void saveFileCategory() {
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\category.dat";
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(url);
            bos = new BufferedOutputStream(fos);

            for (Category category : listCate) {
                String line = category.formatLine();
                byte[] b;
                b = line.getBytes("utf8");
                bos.write(b);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void readFileCategory() {
        listCate.clear();
        String url = "C:\\Users\\Admin\\Documents\\NetBeensProjects\\FPTAPTECH\\QuanLiBanHang\\category.dat";
        FileReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            reader = new FileReader(url);
            bufferedReader = new BufferedReader(reader);

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                Category category = new Category();
               category.getLine(line);
                listCate.add(category);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("Danh sach danh muc san pham");
        listCate.forEach((cate1) -> {
            cate1.display();
        });
    }

    void importCategory() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}