Subversion Repositories SmartDukaan

Rev

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