Subversion Repositories SmartDukaan

Rev

Rev 5556 | Rev 5684 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2787 chandransh 1
package in.shop2020.hotspot.dashbaord.server;
2
 
3
import in.shop2020.config.ConfigException;
3044 chandransh 4
import in.shop2020.logistics.DeliveryType;
2787 chandransh 5
import in.shop2020.logistics.LogisticsServiceException;
5527 anupam.sin 6
import in.shop2020.logistics.PickUpType;
5556 rajveer 7
import in.shop2020.logistics.PickupStore;
2787 chandransh 8
import in.shop2020.logistics.Provider;
9
import in.shop2020.model.v1.catalog.InventoryServiceException;
10
import in.shop2020.model.v1.catalog.Warehouse;
11
import in.shop2020.model.v1.catalog.InventoryService.Client;
5527 anupam.sin 12
import in.shop2020.model.v1.order.Attribute;
2787 chandransh 13
import in.shop2020.model.v1.order.LineItem;
14
import in.shop2020.model.v1.order.Order;
4361 rajveer 15
import in.shop2020.model.v1.order.OrderStatus;
5527 anupam.sin 16
import in.shop2020.model.v1.order.OrderType;
3132 rajveer 17
import in.shop2020.thrift.clients.CatalogClient;
18
import in.shop2020.thrift.clients.LogisticsClient;
19
import in.shop2020.thrift.clients.TransactionClient;
2787 chandransh 20
import in.shop2020.thrift.clients.config.ConfigClient;
21
 
22
import java.io.ByteArrayOutputStream;
23
import java.io.File;
24
import java.io.FileOutputStream;
25
import java.io.IOException;
26
import java.text.DateFormat;
27
import java.text.DecimalFormat;
4361 rajveer 28
import java.util.ArrayList;
4746 rajveer 29
import java.util.Calendar;
2787 chandransh 30
import java.util.Date;
31
import java.util.Enumeration;
4746 rajveer 32
import java.util.GregorianCalendar;
2787 chandransh 33
import java.util.List;
34
import java.util.Locale;
35
import java.util.Properties;
36
import java.util.ResourceBundle;
37
 
38
import javax.servlet.ServletException;
39
import javax.servlet.ServletOutputStream;
40
import javax.servlet.http.HttpServlet;
41
import javax.servlet.http.HttpServletRequest;
42
import javax.servlet.http.HttpServletResponse;
43
 
44
import org.apache.commons.lang.WordUtils;
45
import org.apache.thrift.TException;
46
import org.slf4j.Logger;
47
import org.slf4j.LoggerFactory;
48
 
49
import com.ibm.icu.text.RuleBasedNumberFormat;
50
 
51
import com.itextpdf.text.Document;
52
import com.itextpdf.text.Element;
53
import com.itextpdf.text.Font;
54
import com.itextpdf.text.FontFactory;
55
import com.itextpdf.text.FontFactoryImp;
56
import com.itextpdf.text.Image;
57
import com.itextpdf.text.Paragraph;
58
import com.itextpdf.text.Phrase;
59
import com.itextpdf.text.Rectangle;
60
import com.itextpdf.text.Font.FontFamily;
61
import com.itextpdf.text.pdf.BaseFont;
62
import com.itextpdf.text.pdf.PdfPCell;
63
import com.itextpdf.text.pdf.PdfPTable;
64
import com.itextpdf.text.pdf.PdfWriter;
65
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
66
 
67
@SuppressWarnings("serial")
68
public class InvoiceServlet extends HttpServlet {
69
 
70
    private static Logger logger = LoggerFactory.getLogger(InvoiceServlet.class);
71
 
72
    @Override
73
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
74
        long orderId = Long.parseLong(request.getParameter("id"));
4361 rajveer 75
        long warehouseId = Long.parseLong(request.getParameter("warehouse"));
2843 chandransh 76
        boolean withBill = false;
4361 rajveer 77
        boolean printAll = false;
2843 chandransh 78
        try {
79
            withBill = Boolean.parseBoolean(request.getParameter("withBill"));
80
        } catch(Exception e){
81
            logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
82
        }
4361 rajveer 83
        try {
84
        	printAll = Boolean.parseBoolean(request.getParameter("printAll"));
85
        } catch(Exception e){
86
            logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
87
        }
88
 
2787 chandransh 89
        logger.info("Printing invoice for order id: " + orderId);
90
 
91
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
4361 rajveer 92
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, withBill, printAll, warehouseId);
2787 chandransh 93
        response.setContentType("application/pdf");
94
        response.setHeader("Content-disposition", "inline; filename=invoice-"+orderId+".pdf" );
95
 
96
        ServletOutputStream sos;
97
        try {
98
            sos = response.getOutputStream();
99
            baos.writeTo(sos);
100
            sos.flush();
101
        } catch (IOException e) {
102
            logger.error("Encountered error while sending invoice response: ", e);
103
        }
104
    }
105
}
106
 
107
class InvoiceGenerationService {
108
 
109
    private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);
110
 
3132 rajveer 111
    private TransactionClient tsc = null;
112
    private CatalogClient csc = null;
113
    private LogisticsClient lsc = null;
2787 chandransh 114
 
115
    private static Locale indianLocale = new Locale("en", "IN");
116
    private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
117
 
118
    private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
119
    private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
120
    private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);
121
    private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
3065 chandransh 122
    private static final Font helvetica28 = FontFactory.getFont(FontFactory.HELVETICA, 28);
2787 chandransh 123
 
124
    private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
125
    private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
126
 
127
    private static final Properties properties = readProperties();
128
    private static final String ourAddress = properties.getProperty("sales_tax_address",
129
                    "Spice Online Retail Pvt. Ltd.\nKhasra No. 819, Block-K\nMahipalpur, New Delhi-110037\n");
130
    private static final String tinNo = properties.getProperty("sales_tax_tin", "07250399732");
131
 
132
    private static final String delhiPincodePrefix = "11";
133
 
134
    private static final double salesTaxLowRate = Double.parseDouble(properties.getProperty("sales_tax_low_rate", "5.0"));
135
    private static final double salesTaxHighRate = Double.parseDouble(properties.getProperty("sales_tax_high_rate", "12.5"));
136
    private static final double salesTaxCutOff = (Double.parseDouble(properties.getProperty("sales_tax_cutoff", "10000")) * (100 + salesTaxLowRate))/100;
137
 
138
    private static Properties readProperties(){
139
        ResourceBundle resource = ResourceBundle.getBundle(InvoiceGenerationService.class.getName());
140
        Properties props = new Properties();
141
 
142
        Enumeration<String> keys = resource.getKeys();
143
        while (keys.hasMoreElements()) {
144
            String key = keys.nextElement();
145
            props.put(key, resource.getString(key));
146
        }
147
        return props;
148
    }
149
 
150
    public InvoiceGenerationService() {
151
        try {
3132 rajveer 152
            tsc = new TransactionClient();
153
            csc = new CatalogClient();
154
            lsc = new LogisticsClient();
2787 chandransh 155
        } catch (Exception e) {
156
            logger.error("Error while instantiating thrift clients.", e);
157
        }
158
    }
159
 
4361 rajveer 160
    public ByteArrayOutputStream generateInvoice(long orderId, boolean withBill, boolean printAll, long warehouseId) {
2787 chandransh 161
        ByteArrayOutputStream baosPDF = null;
162
        in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
163
        Client iclient = csc.getClient();
164
        in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
165
 
4361 rajveer 166
 
2787 chandransh 167
        try {
168
            baosPDF = new ByteArrayOutputStream();
169
 
170
            Document document = new Document();
171
            PdfWriter.getInstance(document, baosPDF);
172
            document.addAuthor("shop2020");
4361 rajveer 173
            //document.addTitle("Invoice No: " + order.getInvoice_number());
2787 chandransh 174
            document.open();
4361 rajveer 175
 
176
            List<Order> orders = new ArrayList<Order>();
177
            if(printAll){
178
	            try {
4801 anupam.sin 179
	                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
180
	                statuses.add(OrderStatus.ACCEPTED);
181
	                orders = tclient.getAllOrders(statuses, 0, 0, warehouseId);
4361 rajveer 182
	            } catch (Exception e) {
183
	            	logger.error("Error while getting order information", e);
184
	                return baosPDF; 
185
				}
186
            }else{
187
            	orders.add(tclient.getOrder(orderId));	
188
            }
2787 chandransh 189
 
4361 rajveer 190
            for(Order order: orders){
191
            	Warehouse warehouse = null;
192
            	Provider provider = null;
193
            	String destCode = null;
194
            	int barcodeFontSize = 0;
195
            	try {
196
            		warehouse = iclient.getWarehouse(order.getWarehouse_id());
197
            		long providerId = order.getLogistics_provider_id();
198
            		provider = logisticsClient.getProvider(providerId);
5527 anupam.sin 199
            		if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
200
            			destCode = provider.getPickup().toString();
5387 rajveer 201
            		else
202
            			destCode = logisticsClient.getDestinationCode(providerId, order.getCustomer_pincode());
203
 
4361 rajveer 204
            		barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
205
            	} catch (InventoryServiceException ise) {
206
            		logger.error("Error while getting the warehouse information.", ise);
207
            		return baosPDF;
208
            	} catch (LogisticsServiceException lse) {
209
            		logger.error("Error while getting the provider information.", lse);
210
            		return baosPDF;
211
            	} catch (ConfigException ce) {
212
            		logger.error("Error while getting the fontsize for the given provider", ce);
213
            		return baosPDF;
214
            	} catch (TException te) {
215
            		logger.error("Error while getting some essential information from the services", te);
216
            		return baosPDF;
217
            	}
2787 chandransh 218
 
4361 rajveer 219
	            PdfPTable dispatchAdviceTable = getDispatchAdviceTable(order, warehouse, provider, barcodeFontSize, destCode, withBill);
220
	            dispatchAdviceTable.setSpacingAfter(10.0f);
221
	            dispatchAdviceTable.setWidthPercentage(90.0f);
222
 
223
	            document.add(dispatchAdviceTable);
224
	            if(withBill){
225
	                PdfPTable taxTable = getTaxCumRetailInvoiceTable(order, provider);
226
	                taxTable.setSpacingBefore(5.0f);
227
	                taxTable.setWidthPercentage(90.0f);
228
	                document.add(new DottedLineSeparator());
229
	                document.add(taxTable);
230
	            }else{
231
	            	PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16);
232
	            	extraInfoTable.setSpacingBefore(5.0f);
233
	            	extraInfoTable.setWidthPercentage(90.0f);
234
	                document.add(new DottedLineSeparator());
235
	                document.add(extraInfoTable);
236
	            }
237
	            document.newPage();
2843 chandransh 238
            }
2787 chandransh 239
            document.close();
240
            baosPDF.close();
4747 rajveer 241
         // Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
242
            if(withBill && !printAll){
243
            	Calendar cal = new GregorianCalendar();
244
            	cal.setTimeInMillis(orders.get(0).getBilling_timestamp());
245
            	int year = cal.get(Calendar.YEAR);
246
      		  	int month = cal.get(Calendar.MONTH);
247
      		  	int day = cal.get(Calendar.DAY_OF_MONTH);
248
      		  	String dirPath = "/SaholicInvoices" + File.separator + year + File.separator  + month + File.separator + day;
249
      		  	File dirFile = new File(dirPath);
250
      		  	if(!dirFile.exists()){
251
      		  		dirFile.mkdirs();	
252
      		  	}
253
      		  	File f = new File( dirPath + File.separator + orderId + ".pdf");
254
                FileOutputStream fos = new FileOutputStream(f);
255
                baosPDF.writeTo(fos);
256
            }
2787 chandransh 257
        } catch (Exception e) {
258
            logger.error("Error while generating Invoice: ", e);
259
        }
260
        return baosPDF;
261
    }
262
 
2915 chandransh 263
    private PdfPTable getDispatchAdviceTable(Order order, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill){
2787 chandransh 264
        Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
265
 
266
        PdfPTable table = new PdfPTable(1);
267
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
268
 
3065 chandransh 269
        PdfPTable logoTable = new PdfPTable(2);
270
        logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
271
        logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
272
        logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
273
        logoTable.addCell(getLogoCell());
5556 rajveer 274
        if(order.isLogisticsCod())
3065 chandransh 275
            logoTable.addCell(new Phrase("COD   ", helvetica28));
4550 rajveer 276
        else
277
        	logoTable.addCell(new Phrase("   ", helvetica28));
2787 chandransh 278
        PdfPCell titleCell = getTitleCell();
5556 rajveer 279
        PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false);
2787 chandransh 280
        PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);
281
 
282
        PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
283
        dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
284
        dispatchTable.addCell(customerTable);
285
        dispatchTable.addCell(new Phrase(" "));
286
        dispatchTable.addCell(providerInfoTable);
287
 
2915 chandransh 288
 
289
        PdfPTable invoiceTable = null;
290
        if(withBill)
291
            invoiceTable = getTopInvoiceTable(order, tinNo);
292
        else
293
            invoiceTable = getTopInvoiceTable(order, warehouse.getTinNumber());
3065 chandransh 294
 
2915 chandransh 295
        PdfPCell addressCell = null;
296
        if(withBill)
297
            addressCell = getAddressCell(ourAddress);
298
        else
299
            addressCell = getAddressCell(warehouse.getLocation() + "\nPIN " + warehouse.getPincode() + "\n\n");
2787 chandransh 300
 
3065 chandransh 301
        PdfPTable chargesTable = new PdfPTable(1);
302
        chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
303
        chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
5556 rajveer 304
        if(order.isLogisticsCod()){
3065 chandransh 305
            chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + order.getTotal_amount(), helveticaBold12));
4313 rajveer 306
            chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/ITG-111117"));
3065 chandransh 307
        } else {
308
            chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
309
        }
310
 
311
        PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
312
        addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
313
        addressAndNoteTable.addCell(addressCell);
314
        addressAndNoteTable.addCell(chargesTable);
315
 
316
        table.addCell(logoTable);
2787 chandransh 317
        table.addCell(titleCell);
318
        table.addCell(dispatchTable);
319
        table.addCell(invoiceTable);
320
        table.addCell(new Phrase("If undelivered, return to:", helvetica10));
3065 chandransh 321
        table.addCell(addressAndNoteTable);
2787 chandransh 322
        return table;
323
    }
324
 
325
    private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
326
        String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
327
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
328
        ttfFontFactory.register(fontPath, "barcode");
329
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
330
        return barCodeFont;
331
    }
332
 
333
    private PdfPCell getLogoCell() {
334
        String logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
335
        PdfPCell logoCell;
336
        try {
337
            logoCell = new PdfPCell(Image.getInstance(logoPath), false);
338
        } catch (Exception e) {
339
            //Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
340
            logger.warn("Couldn't load the Saholic logo: ", e);
341
            logoCell = new PdfPCell(new Phrase("Saholic Logo"));
342
        }
343
        logoCell.setBorder(Rectangle.NO_BORDER);
344
        return logoCell;
345
    }
346
 
347
    private PdfPCell getTitleCell() {
348
        PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
349
        titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
350
        titleCell.setBorder(Rectangle.NO_BORDER);
351
        return titleCell;
352
    }
353
 
354
    private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
355
        PdfPTable providerInfoTable = new PdfPTable(1);
356
        providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
357
        PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
358
        providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
359
        providerNameCell.setBorder(Rectangle.NO_BORDER);
360
 
361
        PdfPCell awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
362
        awbNumberCell.setPaddingTop(20.0f);
363
        awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
364
        awbNumberCell.setBorder(Rectangle.NO_BORDER);
365
 
366
        providerInfoTable.addCell(providerNameCell);
367
        providerInfoTable.addCell(awbNumberCell);
5556 rajveer 368
        if(order.isLogisticsCod())
3065 chandransh 369
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.COD).getAccountNo(), helvetica8));
370
        else
371
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.PREPAID).getAccountNo(), helvetica8));
5585 mandeep.dh 372
        providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 373
        providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
374
        return providerInfoTable;
375
    }
376
 
2915 chandransh 377
    private PdfPTable getTopInvoiceTable(Order order, String tinNo){
2787 chandransh 378
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
379
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
380
 
381
        invoiceTable.addCell(getInvoiceTableHeader(6));
382
 
383
        invoiceTable.addCell(new Phrase("Order No", helvetica8));
384
        invoiceTable.addCell(new Phrase("Paymode", helvetica8));
385
        invoiceTable.addCell(new Phrase("Product Name", helvetica8));
386
        invoiceTable.addCell(new Phrase("Quantity", helvetica8));
387
        invoiceTable.addCell(new Phrase("Rate", helvetica8));
388
        invoiceTable.addCell(new Phrase("Amount", helvetica8));
389
        populateTopInvoiceTable(order, invoiceTable);
390
 
391
        invoiceTable.addCell(getTotalCell(4));      
392
        invoiceTable.addCell(getRupeesCell());
393
        invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()));
394
 
395
        PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
396
        tinCell.setColspan(6);
397
        tinCell.setPadding(2);
398
        invoiceTable.addCell(tinCell);
399
 
400
        return invoiceTable;
401
    }
402
 
403
    private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
404
        List<LineItem> lineitems = order.getLineitems();
405
        for (LineItem lineitem : lineitems) {
406
            invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
5556 rajveer 407
            if(order.isLogisticsCod())
3065 chandransh 408
                invoiceTable.addCell(new Phrase("COD", helvetica8));
409
            else
410
                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
2787 chandransh 411
 
412
            invoiceTable.addCell(getProductNameCell(lineitem, false));
413
 
414
            invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
415
 
416
            invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
417
 
418
            invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
419
        }
420
    }
421
 
2915 chandransh 422
    private PdfPCell getAddressCell(String address) {
423
        Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
2787 chandransh 424
        PdfPCell addressCell = new PdfPCell();
425
        addressCell.addElement(addressParagraph);
426
        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
427
        addressCell.setBorder(Rectangle.NO_BORDER);
428
        return addressCell;
429
    }
430
 
431
    private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
432
        PdfPTable taxTable = new PdfPTable(1);
5527 anupam.sin 433
        Phrase phrase = null;
2787 chandransh 434
        taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
435
        taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
436
 
5527 anupam.sin 437
        if (order.getOrderType().equals(OrderType.B2B)) {
438
            phrase = new Phrase("TAX INVOICE", helveticaBold12);
439
        } else {
440
            phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
441
        }
442
        PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
2787 chandransh 443
        retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
444
        retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
445
 
446
        Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
447
        PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
448
        sorlAddressCell.addElement(sorlAddress);
449
        sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
450
 
5556 rajveer 451
        PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
2787 chandransh 452
        PdfPTable orderDetails = getOrderDetails(order, provider);
453
 
454
        PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
455
        addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
456
        addrAndOrderDetailsTable.addCell(customerAddress);
457
        addrAndOrderDetailsTable.addCell(new Phrase(" "));
458
        addrAndOrderDetailsTable.addCell(orderDetails);
459
 
460
        boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
461
        PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
462
 
5527 anupam.sin 463
        PdfPCell disclaimerCell = new PdfPCell(new Phrase("Goods once sold will not be taken back.\nAll disputes subject to Delhi Jurisdiction.\nThis is a Computer generated Invoice.", helvetica8));
2787 chandransh 464
        disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
465
        disclaimerCell.setBorder(Rectangle.NO_BORDER);
466
 
467
        taxTable.addCell(retailInvoiceTitleCell);
468
        taxTable.addCell(sorlAddress);
469
        taxTable.addCell(addrAndOrderDetailsTable);
470
        taxTable.addCell(invoiceTable);
471
        taxTable.addCell(disclaimerCell);
472
 
473
        return taxTable;
474
    }
475
 
5556 rajveer 476
    private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
2787 chandransh 477
        PdfPTable customerTable = new PdfPTable(1);
478
        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
5556 rajveer 479
        if(forInvoce || order.getPickupStoreId() == 0){
480
	        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
481
	        customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
482
	        customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
483
	        customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
484
	        if(destCode != null)
485
	            customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
486
	        else
487
	            customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
488
	        customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
489
        }else{
490
        	try {
491
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
492
	            PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
493
			    customerTable.addCell(new Phrase(store.getName(), font));
494
		        customerTable.addCell(new Phrase(store.getLine1(), font));
495
		        customerTable.addCell(new Phrase(store.getLine2(), font));
496
		        customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
497
		        if(destCode != null)
498
		            customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
499
		        else
500
		            customerTable.addCell(new Phrase(store.getPin(), font));
501
		        customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
502
			} catch (TException e) {
503
				// TODO Auto-generated catch block
504
				e.printStackTrace();
505
			}
506
 
507
        }
508
 
5527 anupam.sin 509
        if(order.getOrderType().equals(OrderType.B2B)) {
510
            String tin = null;
511
            in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
512
            List<Attribute> attributes;
513
            try {
514
                attributes = tclient.getAllAttributesForOrderId(order.getId());
515
 
516
                for(Attribute attribute : attributes) {
517
                    if(attribute.getName().equals("tinNumber")) {
518
                        tin = attribute.getValue();
519
                    }
520
                }
521
                if (tin != null) {
522
                    customerTable.addCell(new Phrase("TIN :" + tin, font));
523
                }
524
 
525
            } catch (Exception e) {
526
                logger.error("Error while getting order attributes", e);
527
            }
528
        }
2787 chandransh 529
        if(showPaymentMode){
530
            customerTable.addCell(new Phrase(" ", font));
531
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
532
        }
533
        return customerTable;
534
    }
535
 
536
    private PdfPTable getOrderDetails(Order order, Provider provider){
537
        PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
538
        orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
539
 
540
        orderTable.addCell(new Phrase("Invoice No:", helvetica8));
541
        orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
542
 
543
        orderTable.addCell(new Phrase("Date:", helvetica8));
544
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
545
 
546
        orderTable.addCell(new Phrase(" "));
547
        orderTable.addCell(new Phrase(" "));
548
 
549
        orderTable.addCell(new Phrase("Order ID:", helvetica8));
550
        orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
551
 
552
        orderTable.addCell(new Phrase("Order Date:", helvetica8));
553
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
554
 
555
        orderTable.addCell(new Phrase("Courier:", helvetica8));
556
        orderTable.addCell(new Phrase(provider.getName(), helvetica8));
557
 
558
        orderTable.addCell(new Phrase("AWB No:", helvetica8));
559
        orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
560
 
561
        orderTable.addCell(new Phrase("AWB Date:", helvetica8));
5585 mandeep.dh 562
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 563
 
564
        return orderTable;
565
    }
566
 
567
    private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
568
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
569
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
570
 
571
        invoiceTable.addCell(getInvoiceTableHeader(5));
572
 
573
        invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
574
        invoiceTable.addCell(new Phrase("Description", helveticaBold8));
575
        invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
576
        invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
577
        invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
578
 
579
        double orderAmount = order.getTotal_amount();
4951 mandeep.dh 580
        double rate = getTaxRate(order.getLineitems().get(0).getUnit_price());
2787 chandransh 581
        double salesTax = (rate * orderAmount)/(100 + rate);
582
 
583
        populateBottomInvoiceTable(order, invoiceTable, rate);
584
 
585
        PdfPCell salesTaxCell = getPriceCell(salesTax);
586
 
587
        invoiceTable.addCell(getVATLabelCell(isVAT));
588
        invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
589
        invoiceTable.addCell(salesTaxCell);
590
 
591
        invoiceTable.addCell(getEmptyCell(5));
592
 
593
        invoiceTable.addCell(getTotalCell(3));
594
        invoiceTable.addCell(getRupeesCell());
595
        invoiceTable.addCell(getTotalAmountCell(orderAmount));
596
 
597
        invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
598
        invoiceTable.addCell(getAmountInWordsCell(orderAmount));
599
 
600
        invoiceTable.addCell(getEOECell(5));
601
 
602
        return invoiceTable;
603
    }
604
 
605
    private PdfPCell getInvoiceTableHeader(int colspan) {
606
        PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
607
        invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
608
        invoiceTableHeader.setColspan(colspan);
609
        invoiceTableHeader.setPaddingTop(10);
610
        return invoiceTableHeader;
611
    }
612
 
613
    private double getTaxRate(double orderAmount) {
614
        double rate;
615
        if(orderAmount <= salesTaxCutOff){
616
            rate = salesTaxLowRate;
617
        } else {
618
            rate = salesTaxHighRate;
619
        }
620
        return rate;
621
    }
622
 
623
    private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
624
        for (LineItem lineitem : order.getLineitems()) {
625
            invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
626
 
627
            invoiceTable.addCell(getProductNameCell(lineitem, true));
628
 
629
            invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
630
 
631
            double itemPrice = lineitem.getUnit_price();
632
            double showPrice = (100 * itemPrice)/(100 + rate);
633
            invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
634
 
635
            double totalPrice = lineitem.getTotal_price();
636
            showPrice = (100 * totalPrice)/(100 + rate);
637
            invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
638
        }
639
    }
640
 
641
    private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI) {
642
        String itemName = getItemDisplayName(lineitem, appendIMEI);
643
        PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
644
        productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
645
        return productNameCell;
646
    }
647
 
648
    private PdfPCell getPriceCell(double price) {
649
        PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
650
        totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
651
        return totalPriceCell;
652
    }
653
 
654
    private PdfPCell getVATLabelCell(boolean isVAT) {
655
        PdfPCell vatCell = null;
656
        if(isVAT){
657
            vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
658
        } else {
659
            vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
660
        }
661
        vatCell.setColspan(3);
662
        vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
663
        return vatCell;
664
    }
665
 
666
    private PdfPCell getEmptyCell(int colspan) {
667
        PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
668
        emptyCell.setColspan(colspan);
669
        return emptyCell;
670
    }
671
 
672
    private PdfPCell getTotalCell(int colspan) {
673
        PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
674
        totalCell.setColspan(colspan);
675
        totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
676
        return totalCell;
677
    }
678
 
679
    private PdfPCell getRupeesCell() {
680
        PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
681
        rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
682
        return rupeesCell;
683
    }
684
 
685
    private PdfPCell getTotalAmountCell(double orderAmount) {
686
        PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
687
        totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
688
        return totalAmountCell;
689
    }
690
 
691
    /**
692
     * This method uses ICU4J libraries to convert the given amount into words
693
     * of Indian locale.
694
     * 
695
     * @param orderAmount
696
     *            The amount to convert.
697
     * @return the string representation of the given amount.
698
     */
699
    private PdfPCell getAmountInWordsCell(double orderAmount) {
700
        RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
701
        StringBuilder amountInWords = new StringBuilder("Rs. ");
702
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
703
        amountInWords.append(" and ");
704
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
705
        amountInWords.append(" paise");
706
 
707
        PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
708
        amountInWordsCell.setColspan(4);
709
        return amountInWordsCell;
710
    }
711
 
712
    /**
713
     * Returns the item name to be displayed in the invoice table.
714
     * 
715
     * @param lineitem
716
     *            The line item whose name has to be displayed
717
     * @param appendIMEI
718
     *            Whether to attach the IMEI No. to the item name
719
     * @return The name to be displayed for the given line item.
720
     */
721
    private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
722
        StringBuffer itemName = new StringBuffer();
723
        if(lineitem.getBrand()!= null)
724
            itemName.append(lineitem.getBrand() + " ");
725
        if(lineitem.getModel_name() != null)
726
            itemName.append(lineitem.getModel_name() + " ");
727
        if(lineitem.getModel_number() != null )
728
            itemName.append(lineitem.getModel_number() + " ");
729
        if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
730
            itemName.append("("+lineitem.getColor()+")");
4659 mandeep.dh 731
        if(appendIMEI && lineitem.isSetSerial_number()){
732
            itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2787 chandransh 733
        }
734
 
735
        return itemName.toString();
736
    }
737
 
738
    /**
739
     * 
740
     * @param colspan
741
     * @return a PdfPCell containing the E&amp;OE text and spanning the given
742
     *         no. of columns
743
     */
744
    private PdfPCell getEOECell(int colspan) {
745
        PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
746
        eoeCell.setColspan(colspan);
747
        eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
748
        return eoeCell;
749
    }
750
 
4262 rajveer 751
    private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize){
752
        PdfPTable extraInfoTable = new PdfPTable(1);
753
        extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
754
        extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
755
 
756
        String fontPath = InvoiceGenerationService.class.getResource("/saholic.TTF").getPath();
757
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
758
        ttfFontFactory.register(fontPath, "barcode");
759
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
760
 
761
        PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
762
        extraInfoCell.setPaddingTop(20.0f);
763
        extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
764
        extraInfoCell.setBorder(Rectangle.NO_BORDER);
765
 
766
        extraInfoTable.addCell(extraInfoCell);
767
 
768
 
769
        return extraInfoTable;
770
    }
5527 anupam.sin 771
 
2787 chandransh 772
    public static void main(String[] args) throws IOException {
773
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
5527 anupam.sin 774
        long orderId = 148574;
4361 rajveer 775
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, false, false, 1);
2787 chandransh 776
        String userHome = System.getProperty("user.home");
777
        File f = new File(userHome + "/invoice-" + orderId + ".pdf");
778
        FileOutputStream fos = new FileOutputStream(f);
779
        baos.writeTo(fos);
780
        System.out.println("Invoice generated.");
781
    }
782
}