Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
104 ashish 1
'''
2
Created on 29-Mar-2010
3
 
2536 chandransh 4
@author: Chandranshu
104 ashish 5
'''
2536 chandransh 6
 
7
import sys
8
import os
9
import datetime 
10
import time
11
from datetime import date
12
from textwrap import dedent
1262 varun.gupt 13
from string import Template
14
 
2536 chandransh 15
from sqlalchemy.sql.expression import and_, or_, desc
16
from sqlalchemy.sql import func
17
 
18
from elixir import *
19
 
20
from reportlab.pdfgen.canvas import Canvas
21
from reportlab.rl_config import defaultPageSize
22
from reportlab.lib.units import inch
2747 chandransh 23
from shop2020.clients.PaymentClient import PaymentClient
2819 chandransh 24
from shop2020.thriftpy.warehouse.ttypes import PurchaseOrder, LineItem as POLineItem
2536 chandransh 25
 
2687 chandransh 26
from shop2020.model.v1.order.impl.model.ReturnOrder import ReturnOrder
104 ashish 27
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem,\
2783 chandransh 28
    Alerts, Order, BatchNoGenerator, InvoiceIDGenerator
104 ashish 29
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as T_Transaction,\
690 chandransh 30
    TransactionServiceException, TransactionStatus, OrderStatus
855 rajveer 31
from shop2020.utils.Utils import to_py_date, to_java_date
483 rajveer 32
from shop2020.model.v1 import order
743 rajveer 33
from shop2020.clients.LogisticsClient import LogisticsClient
871 chandransh 34
from shop2020.clients.InventoryClient import InventoryClient
1262 varun.gupt 35
from shop2020.clients.UserClient import UserClient
1351 varun.gupt 36
from shop2020.clients.HelperClient import HelperClient
2536 chandransh 37
from shop2020.utils.EmailAttachmentSender import mail, get_attachment_part
2819 chandransh 38
from shop2020.clients.WarehouseClient import WarehouseClient
104 ashish 39
 
2819 chandransh 40
PAGE_HEIGHT=defaultPageSize[1]
41
PAGE_WIDTH=defaultPageSize[0]
42
 
104 ashish 43
def get_new_transaction():
44
    transaction = Transaction()
45
    transaction.createdOn = datetime.datetime.now()
738 chandransh 46
    transaction.status = TransactionStatus.INIT
104 ashish 47
    transaction.status_message = "New transaction"
483 rajveer 48
    return transaction
49
 
50
def create_order(t_order):
51
    order = Order()
52
    if t_order.warehouse_id:
53
        order.warehouse_id = t_order.warehouse_id
509 rajveer 54
    if t_order.logistics_provider_id:    
483 rajveer 55
        order.logistics_provider_id = t_order.logistics_provider_id
56
        order.airwaybill_no = t_order.airwaybill_no
57
        order.tracking_id = t_order.tracking_id
58
    if t_order.expected_delivery_time:    
59
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
60
    if t_order.customer_id:    
61
        order.customer_id = t_order.customer_id
62
        order.customer_name = t_order.customer_name
860 rajveer 63
        order.customer_city = t_order.customer_city
64
        order.customer_state = t_order.customer_state
483 rajveer 65
        order.customer_mobilenumber = t_order.customer_mobilenumber
66
        order.customer_pincode = t_order.customer_pincode
738 chandransh 67
        order.customer_address1 = t_order.customer_address1
68
        order.customer_address2 = t_order.customer_address2
483 rajveer 69
        order.customer_email = t_order.customer_email
70
    #new status and status description to be added    
716 rajveer 71
    order.status = t_order.status  
483 rajveer 72
    order.statusDescription = t_order.statusDescription
73
    order.total_amount = t_order.total_amount
74
    order.total_weight = t_order.total_weight
75
    if t_order.created_timestamp:
76
        order.created_timestamp = to_py_date(t_order.created_timestamp)
77
    else:
685 chandransh 78
        order.created_timestamp = datetime.datetime.now()
483 rajveer 79
    return order
80
 
81
def create_transaction(t_transaction):
82
    t_orders = t_transaction.orders
83
    if not t_orders:
84
        raise TransactionServiceException(101, "Orders missing from the transaction")
85
    transaction = get_new_transaction()
86
    transaction.customer_id = t_transaction.customer_id 
87
    transaction.shopping_cart_id = t_transaction.shoppingCartid
2219 varun.gupt 88
    transaction.coupon_code = t_transaction.coupon_code
2815 vikas 89
    transaction.session_source = t_transaction.sessionSource
90
    transaction.session_start_time = to_py_date(t_transaction.sessionStartTime)
483 rajveer 91
 
92
    for t_order in t_orders:
93
        order = create_order(t_order)
94
        order.transaction = transaction 
95
        for line_item in t_order.lineitems:
96
            litem = LineItem()
716 rajveer 97
            litem.item_id = line_item.item_id
963 chandransh 98
            litem.productGroup = line_item.productGroup
483 rajveer 99
            litem.brand = line_item.brand
100
            if line_item.model_number:
101
                litem.model_number = line_item.model_number
102
            if line_item.model_name:    
103
                litem.model_name = line_item.model_name
908 chandransh 104
            if line_item.color:
105
                litem.color = line_item.color
483 rajveer 106
            if line_item.extra_info:
107
                litem.extra_info = line_item.extra_info
108
            litem.quantity = line_item.quantity
109
            litem.unit_price = line_item.unit_price
110
            litem.unit_weight = line_item.unit_weight
111
            litem.total_price = line_item.total_price
112
            litem.total_weight = line_item.total_weight
1262 varun.gupt 113
            litem.transfer_price = line_item.transfer_price
1976 varun.gupt 114
 
483 rajveer 115
            """
116
            if line_item.addedOn:
117
                litem.added_on = to_py_date(line_item.addedOn)
118
            else:
119
                litem.added_on = datetime.datetime.now()
120
            """
121
            litem.order = order
122
    session.commit()
123
    return transaction.id
124
 
125
def get_transaction(transaction_id):
126
    transaction = Transaction.get_by(id=transaction_id)
127
    if not transaction:
128
        raise TransactionServiceException(108, "no such transaction")
129
 
130
    return transaction
131
 
132
def get_transactions_for_customer(customer_id, from_date, to_date, status):
133
    if not customer_id:
134
        raise TransactionServiceException(101, "bad customer id")
135
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 136
    if status is not None:
483 rajveer 137
        query = query.filter(Transaction.status == status)
138
    if from_date:
139
        query = query.filter(Transaction.createdOn >from_date)
140
    if to_date:
141
        query = query.filter(Transaction.createdOn < to_date)
142
    return query.all()
143
 
144
def get_transactions_for_shopping_cart_id(shopping_cart_id):
145
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
146
    return transactions
147
 
148
def get_transaction_status(transaction_id):
149
    if not transaction_id:
150
        raise TransactionServiceException(101, "bad transaction id")
151
 
152
    transaction = get_transaction(transaction_id)
153
 
154
    return transaction.status
155
 
156
def change_transaction_status(transaction_id, new_status, description):
157
    transaction = get_transaction(transaction_id)
158
    transaction.status = new_status
159
    transaction.status_message = description
690 chandransh 160
    if new_status == TransactionStatus.FAILED:
161
        for order in transaction.orders:
162
            order.status = OrderStatus.PAYMENT_FAILED
2339 chandransh 163
            order.statusDescription = "Payment Failed"
690 chandransh 164
    elif new_status == TransactionStatus.IN_PROCESS:
165
        for order in transaction.orders:
166
            order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1219 chandransh 167
            order.statusDescription = "Submitted to warehouse"
743 rajveer 168
            #After we got payment success, we will set logistics info also 
169
            logistics_client = LogisticsClient().get_client()
170
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 171
            item_id = order.lineitems[0].item_id
172
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id)
743 rajveer 173
 
1730 ankur.sing 174
            current_time = datetime.datetime.now()
175
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
176
 
743 rajveer 177
            order.warehouse_id = logistics_info.warehouseId
178
            order.logistics_provider_id = logistics_info.providerId
179
            order.airwaybill_no = logistics_info.airway_billno
180
            order.tracking_id = order.airwaybill_no
1730 ankur.sing 181
            order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
871 chandransh 182
 
183
            catalog_client = InventoryClient().get_client()
184
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, order.lineitems[0].quantity)
1351 varun.gupt 185
 
1341 chandransh 186
            item_pricing = catalog_client.getItemPricing(item_id, order.warehouse_id)
187
            order.lineitems[0].transfer_price = item_pricing.transferPrice
1262 varun.gupt 188
 
483 rajveer 189
    session.commit()
190
    return True
191
 
1730 ankur.sing 192
def adjust_delivery_time(order_time, delivery_days):
193
    order_date = order_time.date()
194
 
195
    delivery_date = order_date + datetime.timedelta(days = delivery_days)
196
    final_delivery_date = delivery_date
197
 
198
    time_format = "%Y-%m-%d %H:%M:%S.%f"
199
    t = time.strptime(str(order_time), time_format)
200
    midnightTime = datetime.datetime(*t[:3])
201
    fromDate = to_java_date(midnightTime)
202
    toDate = -1L
203
 
204
    logistics_client = LogisticsClient().get_client()
205
    holiday_dates = logistics_client.getHolidays(fromDate, toDate)
206
    holiday_dates = [(to_py_date(h_date)).date() for h_date in holiday_dates]
207
 
208
    while order_date <= final_delivery_date:
209
        if order_date.weekday() == 6 or is_holiday(holiday_dates, order_date):
210
            delivery_days = delivery_days + 1
211
            final_delivery_date = final_delivery_date + datetime.timedelta(days = 1)
212
        order_date = order_date + datetime.timedelta(days = 1)
213
    return delivery_days
214
 
215
 
216
 
217
def is_holiday(holidays, date):
218
    try:
219
        holidays.index(date)
220
        return 1
221
    except:
222
        return 0
223
 
1398 varun.gupt 224
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 225
    transaction = get_transaction(transaction_id)
226
 
227
    html_header = """
228
<html>
229
<body>
230
<div>
231
    <p>
232
        Hello,<br /><br />
1742 rajveer 233
        Thanks for placing order with us. Following are the details of your order:
1262 varun.gupt 234
    </p>
235
    <div>
236
        Order Date: $order_date
1569 varun.gupt 237
    </div>
1262 varun.gupt 238
    <div>
239
        <table>
1569 varun.gupt 240
        <tr><td colspan="5"><hr /></td></tr>
241
        <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
242
        <tr><td colspan="5"><hr /></td></tr>
1262 varun.gupt 243
        <tr>
2050 varun.gupt 244
            <th width="100">Order No.</th>
245
            <th>Product</th>
246
            <th width="100">Quantity</th>
247
            <th width="100">Unit Price</th>
248
            <th width="100">Amount</th>
1262 varun.gupt 249
        </tr>
250
    """
1398 varun.gupt 251
    user_email = ""
1262 varun.gupt 252
    total_amount = 0.0
253
    html_table = ""
1569 varun.gupt 254
    order_date = datetime.datetime.now()
1262 varun.gupt 255
 
256
    for order in transaction.orders:
257
        order_date = order.created_timestamp
1398 varun.gupt 258
        user_email = order.customer_email
1569 varun.gupt 259
        html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
1262 varun.gupt 260
 
261
        for lineitem in order.lineitems:
2050 varun.gupt 262
            lineitem_total_price = round(lineitem.total_price, 2)
263
 
1276 chandransh 264
            html_tr += "<td>" + str(lineitem) + "</td>"
2050 varun.gupt 265
            html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
266
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
267
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
268
            total_amount += lineitem_total_price
1262 varun.gupt 269
            html_table += html_tr
2050 varun.gupt 270
 
1262 varun.gupt 271
    html_footer = """
272
        <tr><td colspan=5>&nbsp;</td></tr>
1565 varun.gupt 273
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 274
        <tr>
275
            <td colspan=4>Total Amount</td>
2050 varun.gupt 276
            <td> Rs. $total_amount</td>
1262 varun.gupt 277
        </tr>
1569 varun.gupt 278
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 279
        </table>
1569 varun.gupt 280
    </div>
1262 varun.gupt 281
    <p>
282
        Best Wishes,<br />
283
        Saholic Team
284
    </p>
285
</div>
286
</body>
287
</html>
288
    """
1398 varun.gupt 289
 
1569 varun.gupt 290
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 291
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
292
 
1262 varun.gupt 293
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date))
2050 varun.gupt 294
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount))
1262 varun.gupt 295
 
1351 varun.gupt 296
    try:
297
        helper_client = HelperClient().get_client()
1398 varun.gupt 298
        helper_client.saveUserEmailForSending(user_email, "", "Saholic - Order Details", email_header + html_table + email_footer, str(transaction_id), "TransactionInfo")
1351 varun.gupt 299
        return True
300
    except Exception as e:
301
        print e
302
        return False
1262 varun.gupt 303
 
483 rajveer 304
def get_order(order_id):
305
    order = Order.get_by(id=order_id)
306
    if not order:
307
        raise TransactionServiceException(108, "no such order")
308
 
309
    return order
310
 
311
def get_orders_for_customer(customer_id, from_date, to_date, status):
312
    if not customer_id:
313
        raise TransactionServiceException(101, "bad customer id")
314
    query = Order.query.filter(Order.customer_id == customer_id)
315
    if status:
316
        query = query.filter(Order.status == status)
317
    if from_date:
318
        query = query.filter(Order.created_timestamp >from_date)
319
    if to_date:
320
        query = query.filter(Order.created_timestamp < to_date)
321
    return query.all()
322
 
1528 ankur.sing 323
def get_order_for_customer(order_id, customer_id):
324
    if not customer_id:
325
        raise TransactionServiceException(101, "bad customer id")
326
    order = get_order(order_id)
327
    if order.customer_id != customer_id:
328
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
329
    return order
330
 
483 rajveer 331
def get_all_orders(status, from_date, to_date, warehouse_id):
332
    if not warehouse_id:
333
        raise TransactionServiceException(101, "bad warehouse id")
334
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
335
    if status:
336
        query = query.filter(Order.status == status)
337
    if from_date:
338
        query = query.filter(Order.created_timestamp >from_date)
339
    if to_date:
340
        query = query.filter(Order.created_timestamp < to_date)
341
    return query.all()
342
 
1382 varun.gupt 343
def get_returnable_orders_for_customer(customer_id, limit = None):
344
    if not customer_id:
345
        raise TransactionServiceException(101, "bad customer id")
346
 
347
    query = Order.query.filter(Order.customer_id == customer_id)
348
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
349
    query = query.filter(Order.status != OrderStatus.REJECTED)
350
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
351
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
352
    orders = query.all()
353
    order_ids = [order.id for order in orders]
354
    return order_ids
355
 
356
def get_cancellable_orders_for_customer(customer_id, limit = None):
357
    if not customer_id:
358
        raise TransactionServiceException(101, "bad customer id")
359
 
360
    query = Order.query.filter(Order.customer_id == customer_id)
361
    query = query.filter(Order.status != OrderStatus.REJECTED)
1483 varun.gupt 362
    query = query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING)
1382 varun.gupt 363
    query = query.filter(Order.status < OrderStatus.BILLED)
364
    orders = query.all()
365
    return [order.id for order in orders]
366
 
995 varun.gupt 367
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
368
    if not warehouse_id:
369
        raise TransactionServiceException(101, "bad warehouse id")
370
 
371
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
372
 
373
    if status:
374
        query = query.filter(Order.status == status)
375
 
376
    if start_billing_date:
377
        query = query.filter(Order.billing_timestamp >= start_billing_date)
378
 
379
    if end_billing_date:
380
        query = query.filter(Order.billing_timestamp <= end_billing_date)
381
 
382
    return query.all()
383
 
1528 ankur.sing 384
def get_orders_for_transaction(transaction_id, customer_id):
385
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
386
 
1208 chandransh 387
    if not orders:
388
        raise TransactionServiceException(101, "No order for the transaction")
389
    return orders
390
 
1405 ankur.sing 391
def get_undelivered_orders(provider_id, warehouse_id):
392
    query = Order.query
393
    if provider_id != -1:
394
        query = query.filter_by(Order.logistics_provider_id == provider_id)
395
    if warehouse_id != -1:
396
        query = query.filter(Order.warehouse_id == warehouse_id)
397
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
398
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 399
    #Get last midnight time instead of current time as courier company would have sent the 
400
    #delivery records updated at least till midnight and not by the current time.
401
    time_format = "%Y-%m-%d %H:%M:%S.%f"
402
    t = time.strptime(str(datetime.datetime.now()), time_format)
403
    midnightTime = datetime.datetime(*t[:3])
404
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 405
    orders = query.all()
406
    return orders
407
 
1208 chandransh 408
def get_line_items_for_order(order_id):
409
    query = LineItem.query.filter(LineItem.order_id == order_id)
410
    return query.all()
411
 
483 rajveer 412
def change_order_status(self, orderId, status, description):
413
    order = get_order(orderId)
414
    order.status = status
415
    order.statusDescription = description
416
    session.commit()
417
    return True
418
 
921 rajveer 419
def accept_order(self, orderId):
420
    order = get_order(orderId)
421
    order.status = OrderStatus.ACCEPTED
422
    order.statusDescription = "Order Accepted"
423
    order.accepted_timestamp = datetime.datetime.now()
424
    session.commit()
425
    return True
426
 
427
def bill_order(self, orderId):
428
    order = get_order(orderId)
429
    order.status = OrderStatus.BILLED
430
    order.statusDescription = "Order Billed"
431
    order.billing_timestamp = datetime.datetime.now()
432
    session.commit()
1208 chandransh 433
    return True
921 rajveer 434
 
1149 chandransh 435
def add_billing_details(orderId, invoice_number, billed_by):
494 rajveer 436
    order = Order.get_by(id=orderId)
437
    if not order:
2783 chandransh 438
        raise TransactionServiceException(101, "No order found for the given order id:" + str(orderId))
494 rajveer 439
    order.invoice_number = invoice_number
440
    order.billed_by = billed_by
441
    session.commit()
442
    return True
759 chandransh 443
 
2783 chandransh 444
def add_jacket_number(self, orderId, jacket_number, imei_number, item_number, billed_by):
445
    if jacket_number is None or jacket_number <= 0:
446
        raise TransactionServiceException(110, "Invalid jacket number")
447
 
448
    if item_number is None or item_number.strip() == "":
449
        raise TransactionServiceException(110, "Invalid item number")
450
 
451
    if billed_by is None or billed_by.strip() == "":
452
        raise TransactionServiceException(110, "Invalid Biller")
453
 
1149 chandransh 454
    order = Order.get_by(id=orderId)
455
    if not order:
2783 chandransh 456
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
457
 
458
    lineitem = order.lineitems[0]
459
    if lineitem.productGroup == "Handsets" and imei_number <= 0:
460
        raise TransactionServiceException(110, "No IMEI number supplied for a handset.")
461
 
462
    order.jacket_number = jacket_number
463
    order.invoice_number = get_next_invoice_number()
464
    order.billed_by = billed_by
465
    order.status = OrderStatus.BILLED
466
    order.statusDescription = "Order Billed"
467
    order.billing_timestamp = datetime.datetime.now()
468
 
469
    lineitem.item_number = item_number
470
    if imei_number > 0:
471
        lineitem.imei_number = str(imei_number)
472
 
1149 chandransh 473
    session.commit()
474
    return True
475
 
1220 chandransh 476
def batch_orders(warehouseId):
477
    if not warehouseId:
478
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 479
 
480
    batchno_generator = BatchNoGenerator()
481
    session.commit()
1220 chandransh 482
    query = Order.query.filter_by(warehouse_id=warehouseId)
483
    query = query.filter_by(status=OrderStatus.SUBMITTED_FOR_PROCESSING)
484
    query = query.order_by(Order.created_timestamp)
485
    pending_orders = query.all()
1225 chandransh 486
 
1220 chandransh 487
    serial_no = 1
488
    for order in pending_orders:
1276 chandransh 489
        order.batchNo = batchno_generator.id
1220 chandransh 490
        order.serialNo = serial_no
491
        serial_no += 1
492
    session.commit() 
493
    pending_orders = query.all()
494
    return pending_orders
495
 
496
def order_outofstock(orderId):
1911 chandransh 497
    '''
498
    Mark order as out of stock
499
    '''
1220 chandransh 500
    order = get_order(orderId)
501
    order.status = OrderStatus.INVENTORY_LOW
502
    order.statusDescription = "Low Inventory"
503
    order.outofstock_timestamp = datetime.datetime.now()
504
    session.commit()
505
    return True
506
 
759 chandransh 507
def mark_orders_as_manifested(warehouse_id, provider_id):
508
    try:
986 chandransh 509
        current_timestamp = datetime.datetime.now()
852 chandransh 510
        orders = Order.query.filter_by(warehouse_id = warehouse_id, logistics_provider_id = provider_id, status = OrderStatus.BILLED).all()
759 chandransh 511
        for order in orders:
512
            order.status = OrderStatus.SHIPPED_FROM_WH
987 chandransh 513
            order.statusDescription = "Order shipped from warehouse"
986 chandransh 514
            order.shipping_timestamp = current_timestamp
759 chandransh 515
        session.commit()
516
        return True
517
    except:
518
        return False
1113 chandransh 519
 
520
def mark_orders_as_picked_up(provider_id, pickup_details):
521
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 522
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 523
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 524
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
525
            continue
1113 chandransh 526
        order.status = OrderStatus.SHIPPED_TO_LOGST
527
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 528
        order.pickup_timestamp = pickup_timestamp
1113 chandransh 529
    session.commit()
1217 chandransh 530
 
1132 chandransh 531
    current_time = datetime.datetime.now()
532
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1246 chandransh 533
    from_datetime = to_datetime - datetime.timedelta(2)
1132 chandransh 534
    orders_not_picked_up = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.SHIPPED_FROM_WH).filter(Order.shipping_timestamp >= from_datetime).filter(Order.shipping_timestamp <= to_datetime).all()
1113 chandransh 535
    return orders_not_picked_up
536
 
1132 chandransh 537
def mark_orders_as_delivered(provider_id, delivered_orders):
538
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 539
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 540
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1911 chandransh 541
            continue
542
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1132 chandransh 543
        order.status = OrderStatus.DELIVERY_SUCCESS
544
        order.statusDescription = "Order delivered"
545
        order.delivery_timestamp, order.receiver = detail.split('|')
546
    session.commit()
547
 
1135 chandransh 548
def mark_orders_as_failed(provider_id, returned_orders):
549
    for awb, detail in returned_orders.iteritems():
550
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 551
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
552
            continue
553
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
554
        order.status = OrderStatus.SALES_RETURN_IN_TRANSIT
1135 chandransh 555
        order.delivery_timestamp, reason = detail.split('|')
556
        order.statusDescription = "Order Returned to Origin:" + reason
1911 chandransh 557
    session.commit()
1135 chandransh 558
 
1246 chandransh 559
def update_non_delivery_reason(provider_id, undelivered_orders):
560
    for awb, reason in undelivered_orders.iteritems():
561
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
562
        if order == None:
2684 chandransh 563
            continue
564
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 565
        order.statusDescription = reason
566
    session.commit()
567
 
483 rajveer 568
def get_alerts(order_id, all):
569
    query = Alerts.query.filter_by(order_id=order_id)
570
    if not all:
571
        query = query.filter_by(valid=True)
572
    return query.all()
573
 
574
def set_alert(order_id, unset, type, comment):
575
    #get existing alert
576
    if unset:
577
        query = Alerts.query.filter_by(order_id=order_id)
578
        query = query.filter_by(type=type)
579
        alerts = query.all()
580
        for alert in alerts:
581
            if alert.valid:
582
                alert.valid = False
583
                alert.comment = comment
584
                alert.time_unset = datetime.datetime.now()
585
    else:
586
        alert = Alerts()
587
        alert.order_id = order_id
588
        alert.valid = True
589
        alert.type = type
590
        alert.comment = comment
591
        alert.time_set = datetime.datetime.now()
766 rajveer 592
    session.commit()    
593
 
1596 ankur.sing 594
def get_valid_order_count():
595
    return Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).count()
596
 
1627 ankur.sing 597
def get_cust_count_with_successful_txn():
598
    return session.query(Order.customer_id).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).distinct().count()
599
 
1730 ankur.sing 600
def get_valid_orders_amount_range():
1627 ankur.sing 601
    orders = Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).all()
602
    order_amounts = [o.total_amount for o in orders]
1730 ankur.sing 603
    return [min(order_amounts), max(order_amounts)]
1627 ankur.sing 604
 
1886 ankur.sing 605
def get_valid_orders(limit):
606
    query = Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING)
607
    query = query.order_by(desc(Order.created_timestamp))
608
    if limit > 0:
609
        query = query.limit(limit)
610
    elif limit < 0:
611
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
612
    return query.all()
613
 
2783 chandransh 614
def get_next_invoice_number():
615
    entity_id = InvoiceIDGenerator.query.with_lockmode("update").one()
616
    invoice_number = entity_id.id + 1
617
    entity_id.id = invoice_number
618
    session.commit()
619
    return invoice_number
620
 
2536 chandransh 621
def toggle_doa_flag(order_id):
622
    order = get_order(order_id)
623
    if(order.doaFlag):
624
        order.doaFlag = False
625
    else:
626
        order.doaFlag = True
627
    session.commit()
628
    return order.doaFlag
629
 
630
def request_pickup_number(order_id):
631
    order = get_order(order_id)
632
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_PICKUP_REQUESTED:
633
        return False
634
    from_user = 'cnc.center@shop2020.in'
635
    from_pwd = '5h0p2o2o'
636
 
637
    subject = "Pickup request"
638
    try:
639
        catalog_client = InventoryClient().get_client()
640
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
641
 
642
        logistics_client = LogisticsClient().get_client()
643
        provider = logistics_client.getProvider(order.logistics_provider_id)
644
        to_addr = provider.email
645
        raw_message = '''
646
        Dear Sir/Madam,
647
 
2559 chandransh 648
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 649
 
650
        Pickup CODE: %(provider_code)s
651
        Total Weight: %(order_weight)s kg
652
 
2559 chandransh 653
        Pickup Address:
2536 chandransh 654
 
655
        %(customer_address)s
656
 
657
        Delivery Address:
658
 
659
        %(warehouse_executive)s
660
        %(warehouse_address)s
661
        PIN %(warehouse_pin)s
662
        Phone: %(warehouse_phone)s
663
 
664
        Thanks and Regards
665
        Anand Sinha
666
        '''
2559 chandransh 667
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
668
                                          'provider_code' : provider.accountNo,
2536 chandransh 669
                                          'order_weight' : str(order.total_weight),
670
                                          'customer_address' : __get_order_address(order),
671
                                          'warehouse_executive' : 'Parmod Kumar',
672
                                          'warehouse_address' : warehouse.location,
673
                                          'warehouse_pin' : warehouse.pincode,
674
                                          'warehouse_phone': '9971573026'}
675
        mail(from_user, from_pwd, to_addr, subject, message)
676
        order.status = OrderStatus.DOA_PICKUP_REQUESTED
677
        order.statusDescription = "Pick up requested for DOA"
678
        session.commit()
679
        return True
680
    except Exception as e:
681
        print sys.exc_info()[0]
682
        return False
683
 
684
def authorize_pickup(order_id, pickup_number):
685
    order = get_order(order_id)
686
    if order.status != OrderStatus.DOA_PICKUP_REQUESTED:
687
        return False
688
    from_user = 'help@shop2020.in'
689
    from_pwd = '5h0p2o2o'
690
    subject = 'Pickup details'
691
    filename = "/tmp/" +  str(order.id) +".pdf" 
692
    try:
693
        catalog_client = InventoryClient().get_client()
694
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
695
 
696
        logistics_client = LogisticsClient().get_client()
697
        provider = logistics_client.getProvider(order.logistics_provider_id)
698
        provider_name = provider.name
699
 
700
        to_addr = order.customer_email
701
        today = date.today().strftime("%d-%B-%Y (%A)")
702
 
703
        raw_message = '''
704
        Dear Mr. %(customer_name)s,
705
 
706
        In reference to the return of order ID %(order_id)d. We request you to kindly pack the box properly with bubble wrap, and send it along with the original "DOA" certificate and the invoice.
707
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
708
        We have instructed %(provider_name)s to pick up the material from the below mentioned address on %(date)s. %(provider_name)s pickup request number is %(pickup_request_no)s. Kindly keep the parcel ready.
709
 
710
        Pickup will happen from the below mentioned address:-
711
 
712
        %(customer_address)s
713
 
714
        Do let us know in case of any concerns
715
 
716
        Thanks & Regards
717
        Saholic Team
718
        '''
719
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
720
                                         'order_id' : order_id,
721
                                         'provider_name' : provider_name,
722
                                         'date': today,
723
                                         'pickup_request_no' : pickup_number,
724
                                         'customer_address' : __get_order_address(order)}
725
        print message
726
        __generate_return_advice(order, warehouse, provider, filename)
727
        mail(from_user, from_pwd, to_addr, subject, message, get_attachment_part(filename))
728
        order.pickupRequestNo = pickup_number
729
        order.status = OrderStatus.DOA_RETURN_AUTHORIZED
730
        order.statusDescription = "DOA pick up authorized"
2764 chandransh 731
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 732
        session.commit()
733
        return True
734
    except Exception as e:
735
        print sys.exc_info()[0]
736
        return False
737
    finally:
738
        if os.path.exists(filename):
739
            os.remove(filename)
740
 
2764 chandransh 741
def mark_doas_as_picked_up(provider_id, pickup_details):
742
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
743
        order = Order.query.filter_by(pickupRequestNo=pickupNo, logistics_provider_id = provider_id).first()
744
        if order == None or order.status != OrderStatus.DOA_RETURN_AUTHORIZED:
745
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
746
            continue
747
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
748
        order.statusDescription = "DOA picked up by Courier Company"
749
        order.doa_pickup_timestamp = doa_pickup_timestamp
750
    session.commit()
751
 
752
    current_time = datetime.datetime.now()
753
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
754
    from_datetime = to_datetime - datetime.timedelta(2)
755
    orders_not_picked_up = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.DOA_RETURN_AUTHORIZED).filter(Order.doa_auth_timestamp >= from_datetime).filter(Order.doa_auth_timestamp <= to_datetime).all()
756
    return orders_not_picked_up
757
 
2616 chandransh 758
def receive_return(order_id):
2591 chandransh 759
    order = get_order(order_id)
2616 chandransh 760
    if order.status in [OrderStatus.DOA_RETURN_AUTHORIZED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
761
        order.status = OrderStatus.DOA_RECEIVED
762
        order.statusDescription = "DOA package received"
2764 chandransh 763
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 764
        session.commit()
765
    elif order.status == OrderStatus.SALES_RETURN_IN_TRANSIT :
766
        order.status = OrderStatus.SALES_RET_RECEIVED
767
        order.statusDescription = "Sales return received"
2764 chandransh 768
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 769
        session.commit()
770
    else:
2591 chandransh 771
        return False
772
    return True
773
 
774
def validate_doa(order_id, is_valid):
775
    order = get_order(order_id)
2599 chandransh 776
    if order.status != OrderStatus.DOA_RECEIVED:
2591 chandransh 777
        return False
778
    if is_valid:
2609 chandransh 779
        order.status = OrderStatus.DOA_CERT_VALID
780
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 781
    else:
782
        order.status = OrderStatus.DOA_CERT_INVALID
783
        order.statusDescription = "DOA Certificate Invalid"
784
    session.commit()
785
    return True
786
 
2628 chandransh 787
def reship_order(order_id):
788
    """
789
    If the order is in SALES_RET_RECEIVED or DOA_CERT_INVALID state, it does the following:
790
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
791
        2. Marks the current order as one of the final states SALES_RET_RESHIPPED and DOA_INVALID_RESHIPPED depending on what state the order started in.
792
 
793
    If the order is in DOA_CERT_VALID state, it does the following:
794
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
795
        2. Creates a return order for the warehouse executive to return the DOA material.
796
        3. Marks the current order as the final DOA_RESHIPPED state.
797
 
798
    Returns the id of the newly created order.
799
 
800
    Throws an exception if the order with the given id couldn't be found.
801
 
802
    Parameters:
803
     - orderId
804
    """
805
    order = get_order(order_id)
806
    if order.status == OrderStatus.SALES_RET_RECEIVED:
807
        new_order = __clone_order(order, True)
808
        order.status = OrderStatus.SALES_RET_RESHIPPED
809
        order.statusDescription = "Order Reshipped"
810
        session.commit()
811
    elif order.status == OrderStatus.DOA_CERT_INVALID:
812
        new_order = __clone_order(order, True)
813
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
814
        order.statusDescription = "Order Reshipped"
815
        session.commit()
816
    elif order.status == OrderStatus.DOA_CERT_VALID:
817
        new_order = __clone_order(order, False)
818
        ret_order = __create_return_order(order)
819
        order.status = OrderStatus.DOA_RESHIPPED
820
        order.statusDescription = "Order Reshipped"
821
        session.commit()
822
    else:
823
        raise TransactionServiceException(112, "This order can't be reshipped")
824
 
2764 chandransh 825
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 826
    order.new_order_id = new_order.id
827
    session.commit()
828
 
829
    return new_order.id
830
 
831
def refund_order(order_id):
832
    """
833
    If the order is in SALES_RET_RECEIVED, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
834
        1. Creates a refund request for batch processing.
835
        2. Creates a return order for the warehouse executive to return the shipped material.
836
        3. Marks the current order as SALES_RET_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
837
 
838
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
839
        1. Creates a refund request for batch processing.
840
        2. Marks the current order as the REFUNDED final state.
841
 
842
    Returns True if it is successful.
843
 
844
    Throws an exception if the order with the given id couldn't be found.
845
 
846
    Parameters:
847
     - orderId
848
    """
849
    status_transition = {OrderStatus.SALES_RET_RECEIVED : OrderStatus.SALES_RET_REFUNDED,
850
                         OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
851
                         OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
852
                         OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.REFUNDED,
853
                         OrderStatus.INVENTORY_LOW : OrderStatus.REFUNDED
854
                         }
855
    order = get_order(order_id)
856
    if order.status in [OrderStatus.SALES_RET_RECEIVED, OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID] :
857
        __create_return_order(order)
858
        __create_refund(order)
859
        order.status = status_transition[order.status]
860
        order.statusDescription = "Refunded"
861
    elif order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW]:
862
        __create_refund(order)
2687 chandransh 863
        try:
864
            #Reduce the reservation count for all lineitems.
865
            catalog_client = InventoryClient().get_client()
866
            for lineitem in order.lineitems:
867
                catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity);
868
        except:
869
            print "Unable to reduce reservation count"
2628 chandransh 870
        order.status = status_transition[order.status]
871
        order.statusDescription = "Refunded"
872
    else:
873
        raise TransactionServiceException(114, "This order can't be refunded")
874
 
2764 chandransh 875
    order.refund_timestamp = datetime.datetime.now()
2628 chandransh 876
    session.commit()
877
    return True
878
 
879
def __clone_order(order, should_copy_billing_info):
880
    current_time = datetime.datetime.now()
881
    new_order = Order()
882
    new_order.customer_id = order.customer_id
883
    new_order.customer_name = order.customer_name
884
    new_order.customer_city = order.customer_city
885
    new_order.customer_state = order.customer_state
886
    new_order.customer_mobilenumber = order.customer_mobilenumber
887
    new_order.customer_pincode = order.customer_pincode
888
    new_order.customer_address1 = order.customer_address1
889
    new_order.customer_address2 = order.customer_address2
890
    new_order.customer_email = order.customer_email
891
    new_order.total_amount = order.total_amount
892
    new_order.total_weight = order.total_weight
893
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
894
    new_order.statusDescription = 'Submitted for Processing'
895
    new_order.created_timestamp = current_time
896
 
897
    new_order.transaction = order.transaction
898
 
899
    for line_item in order.lineitems:
900
        litem = LineItem()
901
        litem.item_id = line_item.item_id
902
        litem.productGroup = line_item.productGroup
903
        litem.brand = line_item.brand
904
        if line_item.model_number:
905
            litem.model_number = line_item.model_number
906
        if line_item.model_name:    
907
            litem.model_name = line_item.model_name
908
        if line_item.color:
909
            litem.color = line_item.color
910
        if line_item.extra_info:
911
            litem.extra_info = line_item.extra_info
912
        litem.quantity = line_item.quantity
913
        litem.unit_price = line_item.unit_price
914
        litem.unit_weight = line_item.unit_weight
915
        litem.total_price = line_item.total_price
916
        litem.total_weight = line_item.total_weight
917
        litem.transfer_price = line_item.transfer_price
918
        litem.order = new_order
919
 
920
    logistics_client = LogisticsClient().get_client()
921
    item_id = new_order.lineitems[0].item_id
922
    logistics_info = logistics_client.getLogisticsInfo(new_order.customer_pincode, item_id) #TODO: We should be able to pass another flag to suggest ignoring the inventory situation.
923
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
924
 
925
    new_order.warehouse_id = logistics_info.warehouseId
926
    new_order.logistics_provider_id = logistics_info.providerId
927
    new_order.airwaybill_no = logistics_info.airway_billno
928
    new_order.tracking_id = new_order.airwaybill_no
929
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
930
 
931
    if should_copy_billing_info:
932
        new_order.invoice_number = order.invoice_number
933
        new_order.billed_by = order.billed_by
934
        new_order.warehouse_id = order.warehouse_id
935
        new_order.accepted_timestamp = current_time
936
        new_order.billing_timestamp = current_time    
937
        new_order.status = OrderStatus.BILLED
938
        new_order.statusDescription = 'Order Billed'
939
    else:       
940
        catalog_client = InventoryClient().get_client()
941
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, new_order.lineitems[0].quantity)
942
 
943
        item_pricing = catalog_client.getItemPricing(item_id, order.warehouse_id)
944
        new_order.lineitems[0].transfer_price = item_pricing.transferPrice
945
 
946
    return new_order
947
 
948
def __create_return_order(order):
2687 chandransh 949
    ret_order = ReturnOrder(order)
2628 chandransh 950
    return ret_order
951
 
952
def __create_refund(order):
2747 chandransh 953
    payment_client = PaymentClient().get_client()
954
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
955
    return
2628 chandransh 956
 
2536 chandransh 957
def __get_order_address(order):
958
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
959
    if order.customer_address2:
960
        address = address + order.customer_address2 + "\n"
961
    address = address + order.customer_city + "\n"
962
    address = address + order.customer_state + "\n"
963
    address = address + "PIN " + order.customer_pincode + "\n"
964
    address = address + "Phone: " + order.customer_mobilenumber
965
    return address
966
 
967
def __generate_return_advice(order, warehouse, provider, filename):    
968
    pdf = Canvas(filename)
969
    pdf.setFont('Times-Bold',16)
970
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
971
    address_text.textLine("To")
972
    address_text.textLine("Parmod Kumar")
973
    for line in warehouse.location.split("\n"):
974
        address_text.textLine(line)
975
    address_text.textLine("PIN " + warehouse.pincode)
976
    address_text.textLine("")
977
    address_text.textLine("Phone: 9971573026")
978
    pdf.drawText(address_text)
979
 
980
    pdf.setFont('Times-Roman',12)
981
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
982
    order_text.textLine("Pickup CODE: " + provider.accountNo)
983
    lineitem = order.lineitems[0] 
984
    order_text.textLine("Content : " + lineitem.brand + " " + lineitem.model_number + " " + lineitem.color)
985
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
986
    order_text.textLine("Order ID : " + str(order.id))
987
    pdf.drawText(order_text)
988
    pdf.showPage()
989
    pdf.save()
990
    return filename
991
 
2697 chandransh 992
def get_return_orders(warehouse_id, from_date, to_date):
993
    query = ReturnOrder.query.filter_by(processedStatus = False)
994
    if warehouse_id != -1:
995
        query = query.filter_by(warehouseId = warehouse_id)
996
    if from_date:
997
        query = query.filter(Order.created_timestamp >from_date)
998
    if to_date:
999
        query = query.filter(Order.created_timestamp < to_date)
1000
    return [return_order.to_thrift_object() for return_order in query.all()]
1001
 
2700 chandransh 1002
def get_return_order(id):
1003
    ret_order = ReturnOrder.get_by(orderId = id)
1004
    if ret_order is None:
1005
        raise TransactionServiceException(116, "No return order found for the given order id")
1006
    return ret_order.to_thrift_object()
1007
 
2697 chandransh 1008
def process_return(ret_order_id):
1009
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
1010
    if ret_order is None:
1011
        raise TransactionServiceException(116, "No return order found for the given order id")
1012
    ret_order.processedStatus = True
2701 chandransh 1013
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 1014
    session.commit()
1015
 
2819 chandransh 1016
def create_purchase_order(warehouseId):
1017
    if not warehouseId:
1018
        raise TransactionServiceException(101, "bad warehouse id")
1019
 
1020
    query = Order.query.filter_by(warehouse_id=warehouseId)
1021
    query = query.filter_by(status=OrderStatus.SUBMITTED_FOR_PROCESSING)
1022
    query = query.filter_by(purchase_order_id=None)
1023
    query = query.order_by(Order.created_timestamp)
1024
    pending_orders = query.all()
1025
 
1026
    if not pending_orders:
1027
        return -1
1028
 
1029
    inventory_client = InventoryClient().get_client()
1030
    t_warehouse = inventory_client.getWarehouse(warehouseId)
1031
 
1032
    t_purchase_order = PurchaseOrder()
1033
    t_purchase_order.supplierId = t_warehouse.vendorId
1034
    t_purchase_order.warehouseId = warehouseId
1035
    t_purchase_order.lineitems = []
1036
 
1037
    lineitems = {}
1038
 
1039
    for order in pending_orders:
1040
        for lineitem in order.lineitems:
1041
            item_id = lineitem.item_id
1042
            if lineitems.has_key(item_id):
1043
                lineitems[item_id].quantity = lineitems[item_id].quantity + lineitem.quantity
1044
            else:
1045
                t_po_lineitem = POLineItem()
1046
                t_po_lineitem.productGroup = lineitem.productGroup
1047
                t_po_lineitem.brand = lineitem.brand
1048
                t_po_lineitem.modelNumber = lineitem.model_number
1049
                t_po_lineitem.modelName = lineitem.model_name
1050
                t_po_lineitem.color = lineitem.color
1051
                t_po_lineitem.itemId = lineitem.item_id
1052
                t_po_lineitem.quantity = lineitem.quantity
1053
                t_po_lineitem.unitPrice = lineitem.transfer_price
1054
                lineitems[item_id] = t_po_lineitem
1055
                t_purchase_order.lineitems.append(t_po_lineitem)
1056
 
1057
    warehouse_client = WarehouseClient().get_client()
1058
    po_id = warehouse_client.createPurchaseOrder(t_purchase_order)
1059
 
1060
    for order in pending_orders:
1061
        order.purchase_order_id = po_id
1062
    session.commit()
1063
    return po_id
1064
 
766 rajveer 1065
def close_session():
1066
    if session.is_active:
1067
        print "session is active. closing it."
2783 chandransh 1068
        session.close()