Subversion Repositories SmartDukaan

Rev

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