com.carser.viamais.entity.Transaction.java Source code

Java tutorial

Introduction

Here is the source code for com.carser.viamais.entity.Transaction.java

Source

package com.carser.viamais.entity;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import com.carser.viamais.util.StringUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", length = 50)
public abstract class Transaction extends BaseEntity {

    private static final long serialVersionUID = 9395924029538580L;

    protected static PdfReader reader;

    protected static PdfStamper stamper;

    protected static AcroFields form;

    protected static NumberFormat formatter;

    protected static Locale brazilLocale;

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;

    @NotNull(message = "Data de venda no informada")
    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private final Date transactionDate = new Date();

    @Column(insertable = false, nullable = false, updatable = false)
    private String type;

    private Long km;

    @ManyToOne
    private Seller seller;

    private BigDecimal deposit;

    @Temporal(TemporalType.TIMESTAMP)
    private Date deliveryDate;

    @ManyToOne(optional = false)
    @NotNull(message = "Cliente no informado")
    private Customer customer;

    @ManyToOne(optional = false)
    @NotNull(message = "Veculo no informado")
    private Car car;

    private String advertiser;

    private String observation;

    @Column(nullable = false)
    @NotNull(message = "Valor no informado")
    private BigDecimal price;

    public void generateReceipt(final OutputStream os, final String template)
            throws IOException, DocumentException {
        reader = new PdfReader(this.getClass().getResourceAsStream("/receipts/" + template));
        stamper = new PdfStamper(reader, os);
        form = stamper.getAcroFields();
        brazilLocale = new Locale("pt", "BR");
        formatter = NumberFormat.getCurrencyInstance(brazilLocale);
        // Customer data
        Customer customer = getCustomer();
        form.setField("CUSTOMER_NAME", customer.getName().toUpperCase());
        form.setField("CUSTOMER_CPF", StringUtil.formatCPF(customer.getCpf()));
        form.setField("CUSTOMER_RG", customer.getRg().toUpperCase());
        // Addres data
        Address address = customer.getAddresses().get(0);
        StringBuilder addressDescription = new StringBuilder();
        addressDescription.append(address.getStreet());
        addressDescription.append(", " + address.getNumber());
        if (address.getComplement() != null) {
            addressDescription.append(", " + address.getComplement());
        }
        form.setField("CUSTOMER_ADDRESS", addressDescription.toString().toUpperCase());
        form.setField("CUSTOMER_DISTRICT", address.getDistrict().toUpperCase());
        form.setField("CUSTOMER_CEP", address.getCep());
        form.setField("CUSTOMER_CITY", address.getCity().toUpperCase());
        form.setField("CUSTOMER_STATE", address.getState().toUpperCase());
        List<Phone> phones = customer.getPhones();
        for (Phone phone : phones) {
            String phoneNumber = StringUtil.formatPhone(Long.valueOf(phone.getPrefix() + "" + phone.getNumber()));
            switch (phone.getType()) {
            case "Celular":
                form.setField("CUSTOMER_CELLPHONE", phoneNumber);
                break;
            case "Residencial":
                form.setField("CUSTOMER_PHONE", phoneNumber);
                break;
            case "Comercial":
                form.setField("CUSTOMER_COMPHONE", phoneNumber);
                break;
            default:
                break;
            }
        }
        // Car data
        Car car = getCar();
        form.setField("CAR_MANUFACTURER", car.getModel().getManufacturer().getName().toUpperCase());
        form.setField("CAR_MODEL", car.getModel().getName().toUpperCase());
        form.setField("CAR_YEAR", car.getYearOfManufacture() + "/" + car.getYearOfModel());
        form.setField("CAR_COLOR", car.getColor().toUpperCase());
        form.setField("CAR_PLATE", car.getLicensePlate().toUpperCase());
        form.setField("CAR_CHASSI", car.getChassi().toUpperCase());
        form.setField("CAR_RENAVAM", car.getRenavam().toUpperCase());
        // Transaction data
        form.setField("CAR_DEPOSIT",
                formatter.format(getDeposit()) + " (" + StringUtil.formatCurrency(getDeposit()) + ")");
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.LONG, brazilLocale);
        form.setField("CAR_VALUE",
                formatter.format(getPrice()) + " (" + StringUtil.formatCurrency(getPrice()) + ")");
        form.setField("DATE", dateFormatter.format(new Date()));
        DateFormat deliveryDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, brazilLocale);
        DateFormat deliveryTimeFormatter = DateFormat.getTimeInstance(DateFormat.SHORT, brazilLocale);
        if (getDeliveryDate() != null) {
            form.setField("DELIVERY_DATE", deliveryDateFormatter.format(getDeliveryDate()) + " "
                    + deliveryTimeFormatter.format(getDeliveryDate()));
        }
        if (getKm() != null) {
            form.setField("DELIVERY_KM", getKm().toString());
        }

    }

    public void setType(String type) {
        this.type = type;
    }

    public Seller getSeller() {
        return seller;
    }

    public void setSeller(Seller seller) {
        this.seller = seller;
    }

    public String getAdvertiser() {
        return advertiser;
    }

    public Car getCar() {
        return car;
    }

    public Date getTransactionDate() {
        return transactionDate;
    }

    public Customer getCustomer() {
        return customer;
    }

    public Date getDeliveryDate() {
        return deliveryDate;
    }

    public BigDecimal getDeposit() {
        return deposit;
    }

    public Long getId() {
        return id;
    }

    public Long getKm() {
        return km;
    }

    public String getObservation() {
        return observation;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public String getType() {
        if (this instanceof Purchase) {
            return "purchase";
        } else if (this instanceof Sale) {
            return "sale";
        }
        return null;
    }

    @JsonIgnore
    public boolean isClosed() {
        return km != null && deliveryDate != null;
    }

    public void setAdvertiser(final String advertiser) {
        this.advertiser = advertiser;
    }

    public void setCar(final Car car) {
        this.car = car;
    }

    public void setCustomer(final Customer customer) {
        this.customer = customer;
    }

    public void setDeliveryDate(final Date deliveryDate) {
        this.deliveryDate = deliveryDate;
    }

    public void setDeposit(final BigDecimal deposit) {
        this.deposit = deposit;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public void setKm(final Long km) {
        this.km = km;
    }

    public void setObservation(final String observation) {
        this.observation = observation;
    }

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