Subversion Repositories SmartDukaan

Rev

Rev 5703 | Rev 5856 | 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
 
5684 mandeep.dh 288
        Warehouse shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId());
289
        PdfPTable invoiceTable = getTopInvoiceTable(order, shippingLocation.getTinNumber());
290
        PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
291
                                    "\nPIN " + warehouse.getPincode() + "\n\n");
292
 
3065 chandransh 293
        PdfPTable chargesTable = new PdfPTable(1);
294
        chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
295
        chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
5556 rajveer 296
        if(order.isLogisticsCod()){
3065 chandransh 297
            chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + order.getTotal_amount(), helveticaBold12));
5703 rajveer 298
            chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
3065 chandransh 299
        } else {
300
            chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
301
        }
302
 
303
        PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
304
        addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
305
        addressAndNoteTable.addCell(addressCell);
306
        addressAndNoteTable.addCell(chargesTable);
307
 
308
        table.addCell(logoTable);
2787 chandransh 309
        table.addCell(titleCell);
310
        table.addCell(dispatchTable);
311
        table.addCell(invoiceTable);
312
        table.addCell(new Phrase("If undelivered, return to:", helvetica10));
3065 chandransh 313
        table.addCell(addressAndNoteTable);
2787 chandransh 314
        return table;
315
    }
316
 
317
    private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
318
        String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
319
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
320
        ttfFontFactory.register(fontPath, "barcode");
321
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
322
        return barCodeFont;
323
    }
324
 
325
    private PdfPCell getLogoCell() {
326
        String logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
327
        PdfPCell logoCell;
328
        try {
329
            logoCell = new PdfPCell(Image.getInstance(logoPath), false);
330
        } catch (Exception e) {
331
            //Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
332
            logger.warn("Couldn't load the Saholic logo: ", e);
333
            logoCell = new PdfPCell(new Phrase("Saholic Logo"));
334
        }
335
        logoCell.setBorder(Rectangle.NO_BORDER);
336
        return logoCell;
337
    }
338
 
339
    private PdfPCell getTitleCell() {
340
        PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
341
        titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
342
        titleCell.setBorder(Rectangle.NO_BORDER);
343
        return titleCell;
344
    }
345
 
346
    private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
347
        PdfPTable providerInfoTable = new PdfPTable(1);
348
        providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
349
        PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
350
        providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
351
        providerNameCell.setBorder(Rectangle.NO_BORDER);
352
 
353
        PdfPCell awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
354
        awbNumberCell.setPaddingTop(20.0f);
355
        awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
356
        awbNumberCell.setBorder(Rectangle.NO_BORDER);
357
 
358
        providerInfoTable.addCell(providerNameCell);
359
        providerInfoTable.addCell(awbNumberCell);
5556 rajveer 360
        if(order.isLogisticsCod())
3065 chandransh 361
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.COD).getAccountNo(), helvetica8));
362
        else
363
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.PREPAID).getAccountNo(), helvetica8));
5585 mandeep.dh 364
        providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 365
        providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
366
        return providerInfoTable;
367
    }
368
 
2915 chandransh 369
    private PdfPTable getTopInvoiceTable(Order order, String tinNo){
2787 chandransh 370
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
371
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
372
 
373
        invoiceTable.addCell(getInvoiceTableHeader(6));
374
 
375
        invoiceTable.addCell(new Phrase("Order No", helvetica8));
376
        invoiceTable.addCell(new Phrase("Paymode", helvetica8));
377
        invoiceTable.addCell(new Phrase("Product Name", helvetica8));
378
        invoiceTable.addCell(new Phrase("Quantity", helvetica8));
379
        invoiceTable.addCell(new Phrase("Rate", helvetica8));
380
        invoiceTable.addCell(new Phrase("Amount", helvetica8));
381
        populateTopInvoiceTable(order, invoiceTable);
382
 
383
        invoiceTable.addCell(getTotalCell(4));      
384
        invoiceTable.addCell(getRupeesCell());
385
        invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()));
386
 
387
        PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
388
        tinCell.setColspan(6);
389
        tinCell.setPadding(2);
390
        invoiceTable.addCell(tinCell);
391
 
392
        return invoiceTable;
393
    }
394
 
395
    private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
396
        List<LineItem> lineitems = order.getLineitems();
397
        for (LineItem lineitem : lineitems) {
398
            invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
5556 rajveer 399
            if(order.isLogisticsCod())
3065 chandransh 400
                invoiceTable.addCell(new Phrase("COD", helvetica8));
401
            else
402
                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
2787 chandransh 403
 
404
            invoiceTable.addCell(getProductNameCell(lineitem, false));
405
 
406
            invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
407
 
408
            invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
409
 
410
            invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
411
        }
412
    }
413
 
2915 chandransh 414
    private PdfPCell getAddressCell(String address) {
415
        Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
2787 chandransh 416
        PdfPCell addressCell = new PdfPCell();
417
        addressCell.addElement(addressParagraph);
418
        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
419
        addressCell.setBorder(Rectangle.NO_BORDER);
420
        return addressCell;
421
    }
422
 
423
    private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
424
        PdfPTable taxTable = new PdfPTable(1);
5527 anupam.sin 425
        Phrase phrase = null;
2787 chandransh 426
        taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
427
        taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
428
 
5527 anupam.sin 429
        if (order.getOrderType().equals(OrderType.B2B)) {
430
            phrase = new Phrase("TAX INVOICE", helveticaBold12);
431
        } else {
432
            phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
433
        }
434
        PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
2787 chandransh 435
        retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
436
        retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
437
 
438
        Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
439
        PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
440
        sorlAddressCell.addElement(sorlAddress);
441
        sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
442
 
5556 rajveer 443
        PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
2787 chandransh 444
        PdfPTable orderDetails = getOrderDetails(order, provider);
445
 
446
        PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
447
        addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
448
        addrAndOrderDetailsTable.addCell(customerAddress);
449
        addrAndOrderDetailsTable.addCell(new Phrase(" "));
450
        addrAndOrderDetailsTable.addCell(orderDetails);
451
 
452
        boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
453
        PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
454
 
5527 anupam.sin 455
        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 456
        disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
457
        disclaimerCell.setBorder(Rectangle.NO_BORDER);
458
 
459
        taxTable.addCell(retailInvoiceTitleCell);
460
        taxTable.addCell(sorlAddress);
461
        taxTable.addCell(addrAndOrderDetailsTable);
462
        taxTable.addCell(invoiceTable);
463
        taxTable.addCell(disclaimerCell);
464
 
465
        return taxTable;
466
    }
467
 
5556 rajveer 468
    private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
2787 chandransh 469
        PdfPTable customerTable = new PdfPTable(1);
470
        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
5556 rajveer 471
        if(forInvoce || order.getPickupStoreId() == 0){
472
	        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
473
	        customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
474
	        customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
475
	        customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
476
	        if(destCode != null)
477
	            customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
478
	        else
479
	            customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
480
	        customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
481
        }else{
482
        	try {
483
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
484
	            PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
5757 rajveer 485
			    customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
5556 rajveer 486
		        customerTable.addCell(new Phrase(store.getLine1(), font));
487
		        customerTable.addCell(new Phrase(store.getLine2(), font));
488
		        customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
489
		        if(destCode != null)
490
		            customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
491
		        else
492
		            customerTable.addCell(new Phrase(store.getPin(), font));
493
		        customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
494
			} catch (TException e) {
495
				// TODO Auto-generated catch block
496
				e.printStackTrace();
497
			}
498
 
499
        }
500
 
5527 anupam.sin 501
        if(order.getOrderType().equals(OrderType.B2B)) {
502
            String tin = null;
503
            in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
504
            List<Attribute> attributes;
505
            try {
506
                attributes = tclient.getAllAttributesForOrderId(order.getId());
507
 
508
                for(Attribute attribute : attributes) {
509
                    if(attribute.getName().equals("tinNumber")) {
510
                        tin = attribute.getValue();
511
                    }
512
                }
513
                if (tin != null) {
514
                    customerTable.addCell(new Phrase("TIN :" + tin, font));
515
                }
516
 
517
            } catch (Exception e) {
518
                logger.error("Error while getting order attributes", e);
519
            }
520
        }
2787 chandransh 521
        if(showPaymentMode){
522
            customerTable.addCell(new Phrase(" ", font));
523
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
524
        }
525
        return customerTable;
526
    }
527
 
528
    private PdfPTable getOrderDetails(Order order, Provider provider){
529
        PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
530
        orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
531
 
532
        orderTable.addCell(new Phrase("Invoice No:", helvetica8));
533
        orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
534
 
535
        orderTable.addCell(new Phrase("Date:", helvetica8));
536
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
537
 
538
        orderTable.addCell(new Phrase(" "));
539
        orderTable.addCell(new Phrase(" "));
540
 
541
        orderTable.addCell(new Phrase("Order ID:", helvetica8));
542
        orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
543
 
544
        orderTable.addCell(new Phrase("Order Date:", helvetica8));
545
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
546
 
547
        orderTable.addCell(new Phrase("Courier:", helvetica8));
548
        orderTable.addCell(new Phrase(provider.getName(), helvetica8));
549
 
550
        orderTable.addCell(new Phrase("AWB No:", helvetica8));
551
        orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
552
 
553
        orderTable.addCell(new Phrase("AWB Date:", helvetica8));
5585 mandeep.dh 554
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 555
 
556
        return orderTable;
557
    }
558
 
559
    private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
560
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
561
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
562
 
563
        invoiceTable.addCell(getInvoiceTableHeader(5));
564
 
565
        invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
566
        invoiceTable.addCell(new Phrase("Description", helveticaBold8));
567
        invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
568
        invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
569
        invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
570
 
571
        double orderAmount = order.getTotal_amount();
4951 mandeep.dh 572
        double rate = getTaxRate(order.getLineitems().get(0).getUnit_price());
2787 chandransh 573
        double salesTax = (rate * orderAmount)/(100 + rate);
574
 
575
        populateBottomInvoiceTable(order, invoiceTable, rate);
576
 
577
        PdfPCell salesTaxCell = getPriceCell(salesTax);
578
 
579
        invoiceTable.addCell(getVATLabelCell(isVAT));
580
        invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
581
        invoiceTable.addCell(salesTaxCell);
582
 
583
        invoiceTable.addCell(getEmptyCell(5));
584
 
585
        invoiceTable.addCell(getTotalCell(3));
586
        invoiceTable.addCell(getRupeesCell());
587
        invoiceTable.addCell(getTotalAmountCell(orderAmount));
588
 
589
        invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
590
        invoiceTable.addCell(getAmountInWordsCell(orderAmount));
591
 
592
        invoiceTable.addCell(getEOECell(5));
593
 
594
        return invoiceTable;
595
    }
596
 
597
    private PdfPCell getInvoiceTableHeader(int colspan) {
598
        PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
599
        invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
600
        invoiceTableHeader.setColspan(colspan);
601
        invoiceTableHeader.setPaddingTop(10);
602
        return invoiceTableHeader;
603
    }
604
 
605
    private double getTaxRate(double orderAmount) {
606
        double rate;
607
        if(orderAmount <= salesTaxCutOff){
608
            rate = salesTaxLowRate;
609
        } else {
610
            rate = salesTaxHighRate;
611
        }
612
        return rate;
613
    }
614
 
615
    private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
616
        for (LineItem lineitem : order.getLineitems()) {
617
            invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
618
 
619
            invoiceTable.addCell(getProductNameCell(lineitem, true));
620
 
621
            invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
622
 
623
            double itemPrice = lineitem.getUnit_price();
624
            double showPrice = (100 * itemPrice)/(100 + rate);
625
            invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
626
 
627
            double totalPrice = lineitem.getTotal_price();
628
            showPrice = (100 * totalPrice)/(100 + rate);
629
            invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
630
        }
631
    }
632
 
633
    private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI) {
634
        String itemName = getItemDisplayName(lineitem, appendIMEI);
635
        PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
636
        productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
637
        return productNameCell;
638
    }
639
 
640
    private PdfPCell getPriceCell(double price) {
641
        PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
642
        totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
643
        return totalPriceCell;
644
    }
645
 
646
    private PdfPCell getVATLabelCell(boolean isVAT) {
647
        PdfPCell vatCell = null;
648
        if(isVAT){
649
            vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
650
        } else {
651
            vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
652
        }
653
        vatCell.setColspan(3);
654
        vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
655
        return vatCell;
656
    }
657
 
658
    private PdfPCell getEmptyCell(int colspan) {
659
        PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
660
        emptyCell.setColspan(colspan);
661
        return emptyCell;
662
    }
663
 
664
    private PdfPCell getTotalCell(int colspan) {
665
        PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
666
        totalCell.setColspan(colspan);
667
        totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
668
        return totalCell;
669
    }
670
 
671
    private PdfPCell getRupeesCell() {
672
        PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
673
        rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
674
        return rupeesCell;
675
    }
676
 
677
    private PdfPCell getTotalAmountCell(double orderAmount) {
678
        PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
679
        totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
680
        return totalAmountCell;
681
    }
682
 
683
    /**
684
     * This method uses ICU4J libraries to convert the given amount into words
685
     * of Indian locale.
686
     * 
687
     * @param orderAmount
688
     *            The amount to convert.
689
     * @return the string representation of the given amount.
690
     */
691
    private PdfPCell getAmountInWordsCell(double orderAmount) {
692
        RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
693
        StringBuilder amountInWords = new StringBuilder("Rs. ");
694
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
695
        amountInWords.append(" and ");
696
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
697
        amountInWords.append(" paise");
698
 
699
        PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
700
        amountInWordsCell.setColspan(4);
701
        return amountInWordsCell;
702
    }
703
 
704
    /**
705
     * Returns the item name to be displayed in the invoice table.
706
     * 
707
     * @param lineitem
708
     *            The line item whose name has to be displayed
709
     * @param appendIMEI
710
     *            Whether to attach the IMEI No. to the item name
711
     * @return The name to be displayed for the given line item.
712
     */
713
    private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
714
        StringBuffer itemName = new StringBuffer();
715
        if(lineitem.getBrand()!= null)
716
            itemName.append(lineitem.getBrand() + " ");
717
        if(lineitem.getModel_name() != null)
718
            itemName.append(lineitem.getModel_name() + " ");
719
        if(lineitem.getModel_number() != null )
720
            itemName.append(lineitem.getModel_number() + " ");
721
        if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
722
            itemName.append("("+lineitem.getColor()+")");
4659 mandeep.dh 723
        if(appendIMEI && lineitem.isSetSerial_number()){
724
            itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2787 chandransh 725
        }
726
 
727
        return itemName.toString();
728
    }
729
 
730
    /**
731
     * 
732
     * @param colspan
733
     * @return a PdfPCell containing the E&amp;OE text and spanning the given
734
     *         no. of columns
735
     */
736
    private PdfPCell getEOECell(int colspan) {
737
        PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
738
        eoeCell.setColspan(colspan);
739
        eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
740
        return eoeCell;
741
    }
742
 
4262 rajveer 743
    private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize){
744
        PdfPTable extraInfoTable = new PdfPTable(1);
745
        extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
746
        extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
747
 
748
        String fontPath = InvoiceGenerationService.class.getResource("/saholic.TTF").getPath();
749
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
750
        ttfFontFactory.register(fontPath, "barcode");
751
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
752
 
753
        PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
754
        extraInfoCell.setPaddingTop(20.0f);
755
        extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
756
        extraInfoCell.setBorder(Rectangle.NO_BORDER);
757
 
758
        extraInfoTable.addCell(extraInfoCell);
759
 
760
 
761
        return extraInfoTable;
762
    }
5527 anupam.sin 763
 
2787 chandransh 764
    public static void main(String[] args) throws IOException {
765
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
5527 anupam.sin 766
        long orderId = 148574;
4361 rajveer 767
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, false, false, 1);
2787 chandransh 768
        String userHome = System.getProperty("user.home");
769
        File f = new File(userHome + "/invoice-" + orderId + ".pdf");
770
        FileOutputStream fos = new FileOutputStream(f);
771
        baos.writeTo(fos);
772
        System.out.println("Invoice generated.");
773
    }
774
}