Subversion Repositories SmartDukaan

Rev

Rev 6746 | Rev 6912 | 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);
394
 
395
        invoiceTable.addCell(getTotalCell(4));      
396
        invoiceTable.addCell(getRupeesCell());
6318 rajveer 397
        invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()-order.getGvAmount()));
2787 chandransh 398
 
399
        PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
400
        tinCell.setColspan(6);
401
        tinCell.setPadding(2);
402
        invoiceTable.addCell(tinCell);
403
 
404
        return invoiceTable;
405
    }
406
 
407
    private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
408
        List<LineItem> lineitems = order.getLineitems();
409
        for (LineItem lineitem : lineitems) {
410
            invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
5908 anupam.sin 411
            if(order.getPickupStoreId() > 0 && order.isCod() == true)
5856 anupam.sin 412
                invoiceTable.addCell(new Phrase("In-Store", helvetica8));
413
            else if (order.isCod())
414
                invoiceTable.addCell(new Phrase("COD", helvetica8));
415
            else
416
                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
417
            /*
5556 rajveer 418
            if(order.isLogisticsCod())
3065 chandransh 419
                invoiceTable.addCell(new Phrase("COD", helvetica8));
420
            else
421
                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
5856 anupam.sin 422
            */
2787 chandransh 423
            invoiceTable.addCell(getProductNameCell(lineitem, false));
424
 
425
            invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
426
 
6331 rajveer 427
            invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
2787 chandransh 428
 
6331 rajveer 429
            invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
2787 chandransh 430
        }
431
    }
432
 
2915 chandransh 433
    private PdfPCell getAddressCell(String address) {
434
        Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
2787 chandransh 435
        PdfPCell addressCell = new PdfPCell();
436
        addressCell.addElement(addressParagraph);
437
        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
438
        addressCell.setBorder(Rectangle.NO_BORDER);
439
        return addressCell;
440
    }
441
 
442
    private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
443
        PdfPTable taxTable = new PdfPTable(1);
5527 anupam.sin 444
        Phrase phrase = null;
2787 chandransh 445
        taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
446
        taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
447
 
5527 anupam.sin 448
        if (order.getOrderType().equals(OrderType.B2B)) {
449
            phrase = new Phrase("TAX INVOICE", helveticaBold12);
450
        } else {
451
            phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
452
        }
453
        PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
2787 chandransh 454
        retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
455
        retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
456
 
457
        Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
458
        PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
459
        sorlAddressCell.addElement(sorlAddress);
460
        sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
461
 
5556 rajveer 462
        PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
2787 chandransh 463
        PdfPTable orderDetails = getOrderDetails(order, provider);
464
 
465
        PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
466
        addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
467
        addrAndOrderDetailsTable.addCell(customerAddress);
468
        addrAndOrderDetailsTable.addCell(new Phrase(" "));
469
        addrAndOrderDetailsTable.addCell(orderDetails);
470
 
471
        boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
472
        PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
473
 
5527 anupam.sin 474
        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 475
        disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
476
        disclaimerCell.setBorder(Rectangle.NO_BORDER);
477
 
478
        taxTable.addCell(retailInvoiceTitleCell);
479
        taxTable.addCell(sorlAddress);
480
        taxTable.addCell(addrAndOrderDetailsTable);
481
        taxTable.addCell(invoiceTable);
482
        taxTable.addCell(disclaimerCell);
483
 
484
        return taxTable;
485
    }
486
 
5556 rajveer 487
    private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
2787 chandransh 488
        PdfPTable customerTable = new PdfPTable(1);
489
        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
5556 rajveer 490
        if(forInvoce || order.getPickupStoreId() == 0){
491
	        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
492
	        customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
493
	        customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
494
	        customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
495
	        if(destCode != null)
496
	            customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
497
	        else
498
	            customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
499
	        customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
500
        }else{
501
        	try {
502
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
503
	            PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
5757 rajveer 504
			    customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
5556 rajveer 505
		        customerTable.addCell(new Phrase(store.getLine1(), font));
506
		        customerTable.addCell(new Phrase(store.getLine2(), font));
507
		        customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
508
		        if(destCode != null)
509
		            customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
510
		        else
511
		            customerTable.addCell(new Phrase(store.getPin(), font));
512
		        customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
513
			} catch (TException e) {
514
				// TODO Auto-generated catch block
515
				e.printStackTrace();
516
			}
517
 
518
        }
519
 
5527 anupam.sin 520
        if(order.getOrderType().equals(OrderType.B2B)) {
521
            String tin = null;
522
            in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
523
            List<Attribute> attributes;
524
            try {
525
                attributes = tclient.getAllAttributesForOrderId(order.getId());
526
 
527
                for(Attribute attribute : attributes) {
528
                    if(attribute.getName().equals("tinNumber")) {
529
                        tin = attribute.getValue();
530
                    }
531
                }
532
                if (tin != null) {
533
                    customerTable.addCell(new Phrase("TIN :" + tin, font));
534
                }
535
 
536
            } catch (Exception e) {
537
                logger.error("Error while getting order attributes", e);
538
            }
539
        }
5856 anupam.sin 540
        /*
2787 chandransh 541
        if(showPaymentMode){
542
            customerTable.addCell(new Phrase(" ", font));
543
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 544
        }*/
2787 chandransh 545
        return customerTable;
546
    }
547
 
548
    private PdfPTable getOrderDetails(Order order, Provider provider){
549
        PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
550
        orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
551
 
552
        orderTable.addCell(new Phrase("Invoice No:", helvetica8));
553
        orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
554
 
555
        orderTable.addCell(new Phrase("Date:", helvetica8));
556
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
557
 
558
        orderTable.addCell(new Phrase(" "));
559
        orderTable.addCell(new Phrase(" "));
560
 
561
        orderTable.addCell(new Phrase("Order ID:", helvetica8));
562
        orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
563
 
564
        orderTable.addCell(new Phrase("Order Date:", helvetica8));
565
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
566
 
567
        orderTable.addCell(new Phrase("Courier:", helvetica8));
568
        orderTable.addCell(new Phrase(provider.getName(), helvetica8));
569
 
570
        orderTable.addCell(new Phrase("AWB No:", helvetica8));
571
        orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
572
 
573
        orderTable.addCell(new Phrase("AWB Date:", helvetica8));
5585 mandeep.dh 574
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 575
 
576
        return orderTable;
577
    }
578
 
579
    private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
580
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
581
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
582
 
583
        invoiceTable.addCell(getInvoiceTableHeader(5));
584
 
585
        invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
586
        invoiceTable.addCell(new Phrase("Description", helveticaBold8));
587
        invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
588
        invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
589
        invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
6039 amit.gupta 590
        LineItem lineItem = order.getLineitems().get(0);
2787 chandransh 591
        double orderAmount = order.getTotal_amount();
6039 amit.gupta 592
        double rate = lineItem.getVatRate();
2787 chandransh 593
        double salesTax = (rate * orderAmount)/(100 + rate);
594
 
595
        populateBottomInvoiceTable(order, invoiceTable, rate);
596
 
597
        PdfPCell salesTaxCell = getPriceCell(salesTax);
598
 
599
        invoiceTable.addCell(getVATLabelCell(isVAT));
600
        invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
601
        invoiceTable.addCell(salesTaxCell);
602
 
603
        invoiceTable.addCell(getEmptyCell(5));
604
 
605
        invoiceTable.addCell(getTotalCell(3));
606
        invoiceTable.addCell(getRupeesCell());
607
        invoiceTable.addCell(getTotalAmountCell(orderAmount));
608
 
609
        invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
610
        invoiceTable.addCell(getAmountInWordsCell(orderAmount));
611
 
612
        invoiceTable.addCell(getEOECell(5));
613
 
614
        return invoiceTable;
615
    }
616
 
617
    private PdfPCell getInvoiceTableHeader(int colspan) {
618
        PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
619
        invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
620
        invoiceTableHeader.setColspan(colspan);
621
        invoiceTableHeader.setPaddingTop(10);
622
        return invoiceTableHeader;
623
    }
624
 
625
    private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
626
        for (LineItem lineitem : order.getLineitems()) {
627
            invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
628
 
629
            invoiceTable.addCell(getProductNameCell(lineitem, true));
630
 
631
            invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
632
 
633
            double itemPrice = lineitem.getUnit_price();
634
            double showPrice = (100 * itemPrice)/(100 + rate);
635
            invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
636
 
637
            double totalPrice = lineitem.getTotal_price();
638
            showPrice = (100 * totalPrice)/(100 + rate);
639
            invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
640
        }
641
    }
642
 
643
    private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI) {
644
        String itemName = getItemDisplayName(lineitem, appendIMEI);
645
        PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
646
        productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
647
        return productNameCell;
648
    }
649
 
650
    private PdfPCell getPriceCell(double price) {
651
        PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
652
        totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
653
        return totalPriceCell;
654
    }
655
 
656
    private PdfPCell getVATLabelCell(boolean isVAT) {
657
        PdfPCell vatCell = null;
658
        if(isVAT){
659
            vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
660
        } else {
661
            vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
662
        }
663
        vatCell.setColspan(3);
664
        vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
665
        return vatCell;
666
    }
667
 
668
    private PdfPCell getEmptyCell(int colspan) {
669
        PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
670
        emptyCell.setColspan(colspan);
671
        return emptyCell;
672
    }
673
 
674
    private PdfPCell getTotalCell(int colspan) {
675
        PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
676
        totalCell.setColspan(colspan);
677
        totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
678
        return totalCell;
679
    }
680
 
681
    private PdfPCell getRupeesCell() {
682
        PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
683
        rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
684
        return rupeesCell;
685
    }
686
 
687
    private PdfPCell getTotalAmountCell(double orderAmount) {
688
        PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
689
        totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
690
        return totalAmountCell;
691
    }
692
 
693
    /**
694
     * This method uses ICU4J libraries to convert the given amount into words
695
     * of Indian locale.
696
     * 
697
     * @param orderAmount
698
     *            The amount to convert.
699
     * @return the string representation of the given amount.
700
     */
701
    private PdfPCell getAmountInWordsCell(double orderAmount) {
702
        RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
703
        StringBuilder amountInWords = new StringBuilder("Rs. ");
704
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
705
        amountInWords.append(" and ");
706
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
707
        amountInWords.append(" paise");
708
 
709
        PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
710
        amountInWordsCell.setColspan(4);
711
        return amountInWordsCell;
712
    }
713
 
714
    /**
715
     * Returns the item name to be displayed in the invoice table.
716
     * 
717
     * @param lineitem
718
     *            The line item whose name has to be displayed
719
     * @param appendIMEI
720
     *            Whether to attach the IMEI No. to the item name
721
     * @return The name to be displayed for the given line item.
722
     */
723
    private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
724
        StringBuffer itemName = new StringBuffer();
725
        if(lineitem.getBrand()!= null)
726
            itemName.append(lineitem.getBrand() + " ");
727
        if(lineitem.getModel_name() != null)
728
            itemName.append(lineitem.getModel_name() + " ");
729
        if(lineitem.getModel_number() != null )
730
            itemName.append(lineitem.getModel_number() + " ");
731
        if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
732
            itemName.append("("+lineitem.getColor()+")");
4659 mandeep.dh 733
        if(appendIMEI && lineitem.isSetSerial_number()){
734
            itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2787 chandransh 735
        }
736
 
737
        return itemName.toString();
738
    }
739
 
740
    /**
741
     * 
742
     * @param colspan
743
     * @return a PdfPCell containing the E&amp;OE text and spanning the given
744
     *         no. of columns
745
     */
746
    private PdfPCell getEOECell(int colspan) {
747
        PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
748
        eoeCell.setColspan(colspan);
749
        eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
750
        return eoeCell;
751
    }
752
 
6746 rajveer 753
    private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
4262 rajveer 754
        PdfPTable extraInfoTable = new PdfPTable(1);
755
        extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
756
        extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
757
 
6331 rajveer 758
        String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
4262 rajveer 759
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
760
        ttfFontFactory.register(fontPath, "barcode");
761
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
762
 
6746 rajveer 763
        PdfPCell extraInfoCell;
764
        if(billingType == BillingType.EXTERNAL){
765
        	extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
766
        }else{
6750 rajveer 767
        	extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
6746 rajveer 768
        }
769
 
4262 rajveer 770
        extraInfoCell.setPaddingTop(20.0f);
771
        extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
772
        extraInfoCell.setBorder(Rectangle.NO_BORDER);
773
 
774
        extraInfoTable.addCell(extraInfoCell);
775
 
776
 
777
        return extraInfoTable;
778
    }
6750 rajveer 779
 
780
    private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
781
        PdfPTable extraInfoTable = new PdfPTable(1);
782
        extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
783
        extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
784
 
785
        String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
786
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
787
        ttfFontFactory.register(fontPath, "barcode");
788
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
789
 
790
        PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
791
 
792
        extraInfoCell.setPaddingTop(20.0f);
793
        extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
794
        extraInfoCell.setBorder(Rectangle.NO_BORDER);
795
 
796
        extraInfoTable.addCell(extraInfoCell);
797
 
798
        return extraInfoTable;
799
    }
5527 anupam.sin 800
 
2787 chandransh 801
    public static void main(String[] args) throws IOException {
802
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
5527 anupam.sin 803
        long orderId = 148574;
4361 rajveer 804
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, false, false, 1);
2787 chandransh 805
        String userHome = System.getProperty("user.home");
806
        File f = new File(userHome + "/invoice-" + orderId + ".pdf");
807
        FileOutputStream fos = new FileOutputStream(f);
808
        baos.writeTo(fos);
809
        System.out.println("Invoice generated.");
810
    }
811
}