Subversion Repositories SmartDukaan

Rev

Rev 3530 | Rev 3578 | 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
from datetime import date
8
from elixir import *
3499 mandeep.dh 9
from reportlab.lib.units import inch
2536 chandransh 10
from reportlab.pdfgen.canvas import Canvas
11
from reportlab.rl_config import defaultPageSize
3499 mandeep.dh 12
from shop2020.clients.CRMClient import CRMClient
13
from shop2020.clients.CatalogClient import CatalogClient
14
from shop2020.clients.HelperClient import HelperClient
15
from shop2020.clients.LogisticsClient import LogisticsClient
2747 chandransh 16
from shop2020.clients.PaymentClient import PaymentClient
3499 mandeep.dh 17
from shop2020.clients.TransactionClient import TransactionClient
18
from shop2020.clients.UserClient import UserClient
19
from shop2020.clients.WarehouseClient import WarehouseClient
20
from shop2020.model.v1 import order
21
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem, \
22
    Alerts, Order, BatchNoGenerator, InvoiceIDGenerator
2687 chandransh 23
from shop2020.model.v1.order.impl.model.ReturnOrder import ReturnOrder
3499 mandeep.dh 24
from shop2020.thriftpy.logistics.ttypes import DeliveryType
25
from shop2020.thriftpy.model.v1.catalog.ttypes import BillingType
26
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as T_Transaction, \
690 chandransh 27
    TransactionServiceException, TransactionStatus, OrderStatus
3499 mandeep.dh 28
from shop2020.thriftpy.warehouse.ttypes import PurchaseOrder, \
29
    LineItem as POLineItem
30
from shop2020.utils.EmailAttachmentSender import mail, get_attachment_part
855 rajveer 31
from shop2020.utils.Utils import to_py_date, to_java_date
3499 mandeep.dh 32
from sqlalchemy.sql import func
33
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct
34
from string import Template
35
from textwrap import dedent
36
import datetime
37
import logging
38
import os
39
import sys
40
import time
41
logging.basicConfig(level=logging.DEBUG)
104 ashish 42
 
3499 mandeep.dh 43
 
44
 
45
 
46
 
47
 
2819 chandransh 48
PAGE_HEIGHT=defaultPageSize[1]
49
PAGE_WIDTH=defaultPageSize[0]
50
 
3499 mandeep.dh 51
ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT = {
52
        OrderStatus.SALES_RET_RESHIPPED     :  3,
53
        OrderStatus.SALES_RETURN_IN_TRANSIT : -5,
54
        OrderStatus.DELIVERY_SUCCESS        :  1,
55
        OrderStatus.DOA_CERT_INVALID        : -5,
56
}
57
 
104 ashish 58
def get_new_transaction():
59
    transaction = Transaction()
60
    transaction.createdOn = datetime.datetime.now()
738 chandransh 61
    transaction.status = TransactionStatus.INIT
104 ashish 62
    transaction.status_message = "New transaction"
483 rajveer 63
    return transaction
64
 
65
def create_order(t_order):
66
    order = Order()
67
    if t_order.warehouse_id:
68
        order.warehouse_id = t_order.warehouse_id
509 rajveer 69
    if t_order.logistics_provider_id:    
483 rajveer 70
        order.logistics_provider_id = t_order.logistics_provider_id
71
        order.airwaybill_no = t_order.airwaybill_no
72
        order.tracking_id = t_order.tracking_id
73
    if t_order.expected_delivery_time:    
74
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
75
    if t_order.customer_id:    
76
        order.customer_id = t_order.customer_id
77
        order.customer_name = t_order.customer_name
860 rajveer 78
        order.customer_city = t_order.customer_city
79
        order.customer_state = t_order.customer_state
483 rajveer 80
        order.customer_mobilenumber = t_order.customer_mobilenumber
81
        order.customer_pincode = t_order.customer_pincode
738 chandransh 82
        order.customer_address1 = t_order.customer_address1
83
        order.customer_address2 = t_order.customer_address2
483 rajveer 84
        order.customer_email = t_order.customer_email
85
    #new status and status description to be added    
716 rajveer 86
    order.status = t_order.status  
483 rajveer 87
    order.statusDescription = t_order.statusDescription
88
    order.total_amount = t_order.total_amount
89
    order.total_weight = t_order.total_weight
90
    if t_order.created_timestamp:
91
        order.created_timestamp = to_py_date(t_order.created_timestamp)
92
    else:
685 chandransh 93
        order.created_timestamp = datetime.datetime.now()
483 rajveer 94
    return order
95
 
96
def create_transaction(t_transaction):
97
    t_orders = t_transaction.orders
98
    if not t_orders:
99
        raise TransactionServiceException(101, "Orders missing from the transaction")
100
    transaction = get_new_transaction()
101
    transaction.customer_id = t_transaction.customer_id 
102
    transaction.shopping_cart_id = t_transaction.shoppingCartid
2219 varun.gupt 103
    transaction.coupon_code = t_transaction.coupon_code
2815 vikas 104
    transaction.session_source = t_transaction.sessionSource
105
    transaction.session_start_time = to_py_date(t_transaction.sessionStartTime)
483 rajveer 106
 
107
    for t_order in t_orders:
108
        order = create_order(t_order)
109
        order.transaction = transaction 
110
        for line_item in t_order.lineitems:
111
            litem = LineItem()
716 rajveer 112
            litem.item_id = line_item.item_id
963 chandransh 113
            litem.productGroup = line_item.productGroup
483 rajveer 114
            litem.brand = line_item.brand
115
            if line_item.model_number:
116
                litem.model_number = line_item.model_number
117
            if line_item.model_name:    
118
                litem.model_name = line_item.model_name
908 chandransh 119
            if line_item.color:
120
                litem.color = line_item.color
483 rajveer 121
            if line_item.extra_info:
122
                litem.extra_info = line_item.extra_info
123
            litem.quantity = line_item.quantity
124
            litem.unit_price = line_item.unit_price
125
            litem.unit_weight = line_item.unit_weight
126
            litem.total_price = line_item.total_price
127
            litem.total_weight = line_item.total_weight
1262 varun.gupt 128
            litem.transfer_price = line_item.transfer_price
1976 varun.gupt 129
 
483 rajveer 130
            """
131
            if line_item.addedOn:
132
                litem.added_on = to_py_date(line_item.addedOn)
133
            else:
134
                litem.added_on = datetime.datetime.now()
135
            """
136
            litem.order = order
137
    session.commit()
138
    return transaction.id
139
 
140
def get_transaction(transaction_id):
141
    transaction = Transaction.get_by(id=transaction_id)
142
    if not transaction:
143
        raise TransactionServiceException(108, "no such transaction")
144
 
145
    return transaction
146
 
147
def get_transactions_for_customer(customer_id, from_date, to_date, status):
148
    if not customer_id:
149
        raise TransactionServiceException(101, "bad customer id")
150
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 151
    if status is not None:
483 rajveer 152
        query = query.filter(Transaction.status == status)
153
    if from_date:
154
        query = query.filter(Transaction.createdOn >from_date)
155
    if to_date:
156
        query = query.filter(Transaction.createdOn < to_date)
157
    return query.all()
158
 
159
def get_transactions_for_shopping_cart_id(shopping_cart_id):
160
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
161
    return transactions
162
 
163
def get_transaction_status(transaction_id):
164
    if not transaction_id:
165
        raise TransactionServiceException(101, "bad transaction id")
166
 
167
    transaction = get_transaction(transaction_id)
168
 
169
    return transaction.status
170
 
171
def change_transaction_status(transaction_id, new_status, description):
172
    transaction = get_transaction(transaction_id)
173
    transaction.status = new_status
174
    transaction.status_message = description
690 chandransh 175
    if new_status == TransactionStatus.FAILED:
176
        for order in transaction.orders:
177
            order.status = OrderStatus.PAYMENT_FAILED
2339 chandransh 178
            order.statusDescription = "Payment Failed"
3010 chandransh 179
    elif new_status == TransactionStatus.AUTHORIZED:
690 chandransh 180
        for order in transaction.orders:
181
            order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1219 chandransh 182
            order.statusDescription = "Submitted to warehouse"
3092 chandransh 183
            order.cod = False
743 rajveer 184
            #After we got payment success, we will set logistics info also 
185
            logistics_client = LogisticsClient().get_client()
186
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 187
            item_id = order.lineitems[0].item_id
3044 chandransh 188
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID)
743 rajveer 189
 
1730 ankur.sing 190
            current_time = datetime.datetime.now()
191
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
192
 
743 rajveer 193
            order.warehouse_id = logistics_info.warehouseId
194
            order.logistics_provider_id = logistics_info.providerId
195
            order.airwaybill_no = logistics_info.airway_billno
196
            order.tracking_id = order.airwaybill_no
1730 ankur.sing 197
            order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
871 chandransh 198
 
3133 rajveer 199
            catalog_client = CatalogClient().get_client()
871 chandransh 200
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, order.lineitems[0].quantity)
1351 varun.gupt 201
 
1341 chandransh 202
            item_pricing = catalog_client.getItemPricing(item_id, order.warehouse_id)
203
            order.lineitems[0].transfer_price = item_pricing.transferPrice
3064 chandransh 204
    elif new_status == TransactionStatus.COD_IN_PROCESS:
205
        for order in transaction.orders:
206
            order.status = OrderStatus.INIT
207
            order.statusDescription = "Verification Pending"
208
            order.cod = True
209
            #After we got payment success, we will set logistics info also 
210
            logistics_client = LogisticsClient().get_client()
211
            #FIXME line item is only one now. If multiple will come, need to fix.
212
            item_id = order.lineitems[0].item_id
213
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.COD)
214
 
215
            current_time = datetime.datetime.now()
216
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
217
 
218
            order.warehouse_id = logistics_info.warehouseId
219
            order.logistics_provider_id = logistics_info.providerId
220
            order.airwaybill_no = logistics_info.airway_billno
221
            order.tracking_id = order.airwaybill_no
222
            order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
223
 
3133 rajveer 224
            catalog_client = CatalogClient().get_client()
3064 chandransh 225
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, order.lineitems[0].quantity)
226
 
227
            item_pricing = catalog_client.getItemPricing(item_id, order.warehouse_id)
228
            order.lineitems[0].transfer_price = item_pricing.transferPrice        
3499 mandeep.dh 229
 
483 rajveer 230
    session.commit()
3499 mandeep.dh 231
 
3530 mandeep.dh 232
    try:
233
        if new_status == TransactionStatus.COD_IN_PROCESS:
234
            crm_client = CRMClient().get_client()
235
            crm_client.processCODTxn(transaction.id)
236
    except Exception as e:
237
        print e
3499 mandeep.dh 238
 
483 rajveer 239
    return True
240
 
1730 ankur.sing 241
def adjust_delivery_time(order_time, delivery_days):
242
    order_date = order_time.date()
243
 
244
    delivery_date = order_date + datetime.timedelta(days = delivery_days)
245
    final_delivery_date = delivery_date
246
 
247
    time_format = "%Y-%m-%d %H:%M:%S.%f"
248
    t = time.strptime(str(order_time), time_format)
249
    midnightTime = datetime.datetime(*t[:3])
250
    fromDate = to_java_date(midnightTime)
251
    toDate = -1L
252
 
253
    logistics_client = LogisticsClient().get_client()
254
    holiday_dates = logistics_client.getHolidays(fromDate, toDate)
255
    holiday_dates = [(to_py_date(h_date)).date() for h_date in holiday_dates]
256
 
257
    while order_date <= final_delivery_date:
258
        if order_date.weekday() == 6 or is_holiday(holiday_dates, order_date):
259
            delivery_days = delivery_days + 1
260
            final_delivery_date = final_delivery_date + datetime.timedelta(days = 1)
261
        order_date = order_date + datetime.timedelta(days = 1)
262
    return delivery_days
263
 
264
 
265
 
266
def is_holiday(holidays, date):
267
    try:
268
        holidays.index(date)
269
        return 1
270
    except:
271
        return 0
272
 
1398 varun.gupt 273
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 274
    transaction = get_transaction(transaction_id)
275
 
276
    html_header = """
277
<html>
278
<body>
279
<div>
280
    <p>
281
        Hello,<br /><br />
1742 rajveer 282
        Thanks for placing order with us. Following are the details of your order:
1262 varun.gupt 283
    </p>
284
    <div>
285
        Order Date: $order_date
1569 varun.gupt 286
    </div>
1262 varun.gupt 287
    <div>
288
        <table>
1569 varun.gupt 289
        <tr><td colspan="5"><hr /></td></tr>
290
        <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
291
        <tr><td colspan="5"><hr /></td></tr>
1262 varun.gupt 292
        <tr>
2050 varun.gupt 293
            <th width="100">Order No.</th>
294
            <th>Product</th>
295
            <th width="100">Quantity</th>
296
            <th width="100">Unit Price</th>
297
            <th width="100">Amount</th>
1262 varun.gupt 298
        </tr>
299
    """
1398 varun.gupt 300
    user_email = ""
1262 varun.gupt 301
    total_amount = 0.0
302
    html_table = ""
1569 varun.gupt 303
    order_date = datetime.datetime.now()
1262 varun.gupt 304
 
305
    for order in transaction.orders:
306
        order_date = order.created_timestamp
1398 varun.gupt 307
        user_email = order.customer_email
1569 varun.gupt 308
        html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
1262 varun.gupt 309
 
310
        for lineitem in order.lineitems:
2050 varun.gupt 311
            lineitem_total_price = round(lineitem.total_price, 2)
312
 
1276 chandransh 313
            html_tr += "<td>" + str(lineitem) + "</td>"
2050 varun.gupt 314
            html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
315
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
316
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
317
            total_amount += lineitem_total_price
1262 varun.gupt 318
            html_table += html_tr
2050 varun.gupt 319
 
1262 varun.gupt 320
    html_footer = """
321
        <tr><td colspan=5>&nbsp;</td></tr>
1565 varun.gupt 322
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 323
        <tr>
324
            <td colspan=4>Total Amount</td>
2050 varun.gupt 325
            <td> Rs. $total_amount</td>
1262 varun.gupt 326
        </tr>
1569 varun.gupt 327
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 328
        </table>
1569 varun.gupt 329
    </div>
1262 varun.gupt 330
    <p>
331
        Best Wishes,<br />
332
        Saholic Team
333
    </p>
334
</div>
335
</body>
336
</html>
337
    """
1398 varun.gupt 338
 
1569 varun.gupt 339
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 340
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
341
 
1262 varun.gupt 342
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date))
2050 varun.gupt 343
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount))
1262 varun.gupt 344
 
1351 varun.gupt 345
    try:
346
        helper_client = HelperClient().get_client()
1398 varun.gupt 347
        helper_client.saveUserEmailForSending(user_email, "", "Saholic - Order Details", email_header + html_table + email_footer, str(transaction_id), "TransactionInfo")
1351 varun.gupt 348
        return True
349
    except Exception as e:
350
        print e
351
        return False
1262 varun.gupt 352
 
483 rajveer 353
def get_order(order_id):
354
    order = Order.get_by(id=order_id)
355
    if not order:
356
        raise TransactionServiceException(108, "no such order")
357
 
358
    return order
359
 
3014 chandransh 360
def get_orders_for_customer(customer_id, from_date, to_date, statuses):
483 rajveer 361
    if not customer_id:
362
        raise TransactionServiceException(101, "bad customer id")
363
    query = Order.query.filter(Order.customer_id == customer_id)
3014 chandransh 364
    if statuses:
365
        query = query.filter(Order.status.in_(tuple(statuses)))
483 rajveer 366
    if from_date:
367
        query = query.filter(Order.created_timestamp >from_date)
368
    if to_date:
369
        query = query.filter(Order.created_timestamp < to_date)
370
    return query.all()
371
 
1528 ankur.sing 372
def get_order_for_customer(order_id, customer_id):
373
    if not customer_id:
374
        raise TransactionServiceException(101, "bad customer id")
375
    order = get_order(order_id)
376
    if order.customer_id != customer_id:
377
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
378
    return order
379
 
483 rajveer 380
def get_all_orders(status, from_date, to_date, warehouse_id):
381
    if not warehouse_id:
382
        raise TransactionServiceException(101, "bad warehouse id")
383
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
384
    if status:
385
        query = query.filter(Order.status == status)
386
    if from_date:
387
        query = query.filter(Order.created_timestamp >from_date)
388
    if to_date:
389
        query = query.filter(Order.created_timestamp < to_date)
390
    return query.all()
391
 
1382 varun.gupt 392
def get_returnable_orders_for_customer(customer_id, limit = None):
393
    if not customer_id:
394
        raise TransactionServiceException(101, "bad customer id")
395
 
396
    query = Order.query.filter(Order.customer_id == customer_id)
397
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
398
    query = query.filter(Order.status != OrderStatus.REJECTED)
399
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
400
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
401
    orders = query.all()
402
    order_ids = [order.id for order in orders]
403
    return order_ids
404
 
405
def get_cancellable_orders_for_customer(customer_id, limit = None):
406
    if not customer_id:
407
        raise TransactionServiceException(101, "bad customer id")
408
 
409
    query = Order.query.filter(Order.customer_id == customer_id)
410
    query = query.filter(Order.status != OrderStatus.REJECTED)
1483 varun.gupt 411
    query = query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING)
1382 varun.gupt 412
    query = query.filter(Order.status < OrderStatus.BILLED)
413
    orders = query.all()
414
    return [order.id for order in orders]
415
 
995 varun.gupt 416
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
417
    if not warehouse_id:
418
        raise TransactionServiceException(101, "bad warehouse id")
419
 
420
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
421
 
422
    if status:
423
        query = query.filter(Order.status == status)
424
 
425
    if start_billing_date:
426
        query = query.filter(Order.billing_timestamp >= start_billing_date)
427
 
428
    if end_billing_date:
429
        query = query.filter(Order.billing_timestamp <= end_billing_date)
430
 
431
    return query.all()
432
 
3451 chandransh 433
def get_orders_by_shipping_date(from_shipping_date, to_shipping_date, provider_id, warehouse_id, cod):
434
    query = Order.query.filter(Order.cod == cod)
3427 chandransh 435
 
436
    if warehouse_id and warehouse_id != -1:
437
        query = query.filter(Order.warehouse_id == warehouse_id)
438
 
439
    if provider_id and provider_id != -1:
440
        query = query.filter(Order.logistics_provider_id == provider_id)
441
 
442
    if from_shipping_date:
443
        query = query.filter(Order.shipping_timestamp >= from_shipping_date)
444
 
445
    if to_shipping_date:
446
        query = query.filter(Order.shipping_timestamp <= to_shipping_date)
447
 
448
    query = query.order_by(Order.airwaybill_no)
449
 
450
    return query.all()
451
 
1528 ankur.sing 452
def get_orders_for_transaction(transaction_id, customer_id):
453
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
454
 
1208 chandransh 455
    if not orders:
456
        raise TransactionServiceException(101, "No order for the transaction")
457
    return orders
458
 
1405 ankur.sing 459
def get_undelivered_orders(provider_id, warehouse_id):
460
    query = Order.query
461
    if provider_id != -1:
462
        query = query.filter_by(Order.logistics_provider_id == provider_id)
463
    if warehouse_id != -1:
464
        query = query.filter(Order.warehouse_id == warehouse_id)
465
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
466
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 467
    #Get last midnight time instead of current time as courier company would have sent the 
468
    #delivery records updated at least till midnight and not by the current time.
469
    time_format = "%Y-%m-%d %H:%M:%S.%f"
470
    t = time.strptime(str(datetime.datetime.now()), time_format)
471
    midnightTime = datetime.datetime(*t[:3])
472
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 473
    orders = query.all()
474
    return orders
475
 
1208 chandransh 476
def get_line_items_for_order(order_id):
477
    query = LineItem.query.filter(LineItem.order_id == order_id)
478
    return query.all()
479
 
483 rajveer 480
def change_order_status(self, orderId, status, description):
481
    order = get_order(orderId)
482
    order.status = status
483
    order.statusDescription = description
484
    session.commit()
3499 mandeep.dh 485
 
3530 mandeep.dh 486
    try:
487
        trust_level_delta = compute_trust_level_delta(order)
488
        if (trust_level_delta != 0):
489
            user_client = UserClient().get_client()
490
            user_client.increaseTrustLevel(order.customer_id, trust_level_delta)
491
    except Exception as e:
492
        print e
3499 mandeep.dh 493
 
483 rajveer 494
    return True
3064 chandransh 495
 
3499 mandeep.dh 496
def compute_trust_level_delta(order):
497
    trust_level_delta = 0
498
 
499
    if order.cod == True:
500
        trust_level_delta = ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT.get(order.status, 0)
501
 
502
    return trust_level_delta
503
 
3064 chandransh 504
def verify_order(self, orderId):
505
    logging.info("Verifying order no: " + str(orderId))
506
    order = get_order(orderId)
507
    if order.status == OrderStatus.INIT:
508
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
509
        order.statusDescription = "Submitted for processing"
510
        order.verification_timestamp = datetime.datetime.now()
511
        session.commit()
512
        logging.info("Successfully verified order no: " + str(orderId))
513
        return True
514
    else:
515
        logging.warning("Verify called for order no." + str(orderId) +" which is not in verification pending state");
516
        return False
517
 
921 rajveer 518
def accept_order(self, orderId):
3064 chandransh 519
    logging.info("Accepting order no: " + str(orderId))
921 rajveer 520
    order = get_order(orderId)
3036 chandransh 521
    if order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW]:
3064 chandransh 522
        if not order.cod:
523
            if order.transaction.status == TransactionStatus.AUTHORIZED:
524
                __capture_txn(order.transaction.id)
3010 chandransh 525
        order.status = OrderStatus.ACCEPTED
526
        order.statusDescription = "Order Accepted"
527
        order.accepted_timestamp = datetime.datetime.now()
528
        session.commit()
3064 chandransh 529
        logging.info("Successfully accepted the order no.:" + str(orderId))
3010 chandransh 530
        return True
531
    else:
3064 chandransh 532
        logging.warning("Accept called for the unacceptable order: " + str(orderId))
3010 chandransh 533
        return False
921 rajveer 534
 
3010 chandransh 535
def __capture_txn(txnId):
536
    logging.info("Capturing payment for merchant txn:" + str(txnId))
537
    payment_client = PaymentClient().get_client()
538
    capture_result = payment_client.capturePayment(txnId)
539
    if capture_result:
3064 chandransh 540
        logging.info("Successfully captured payment for merchant txn:" + str(txnId))
541
        change_transaction_status(txnId, TransactionStatus.IN_PROCESS, "Payment received")
3010 chandransh 542
    else:
543
        raise TransactionServiceException(115, "Payment capture failed.")
544
 
921 rajveer 545
def bill_order(self, orderId):
546
    order = get_order(orderId)
547
    order.status = OrderStatus.BILLED
548
    order.statusDescription = "Order Billed"
549
    order.billing_timestamp = datetime.datetime.now()
550
    session.commit()
1208 chandransh 551
    return True
921 rajveer 552
 
1149 chandransh 553
def add_billing_details(orderId, invoice_number, billed_by):
494 rajveer 554
    order = Order.get_by(id=orderId)
555
    if not order:
2783 chandransh 556
        raise TransactionServiceException(101, "No order found for the given order id:" + str(orderId))
494 rajveer 557
    order.invoice_number = invoice_number
558
    order.billed_by = billed_by
559
    session.commit()
560
    return True
759 chandransh 561
 
2842 chandransh 562
def add_jacket_number(self, orderId, jacket_number, imei_number, item_number, billed_by, billing_type):
2783 chandransh 563
    if jacket_number is None or jacket_number <= 0:
564
        raise TransactionServiceException(110, "Invalid jacket number")
565
 
566
    if item_number is None or item_number.strip() == "":
567
        raise TransactionServiceException(110, "Invalid item number")
568
 
569
    if billed_by is None or billed_by.strip() == "":
570
        raise TransactionServiceException(110, "Invalid Biller")
571
 
1149 chandransh 572
    order = Order.get_by(id=orderId)
573
    if not order:
2783 chandransh 574
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
575
 
576
    order.jacket_number = jacket_number
2842 chandransh 577
    if billing_type == BillingType.OURS:
578
        order.invoice_number = get_next_invoice_number()
579
        order.billed_by = billed_by
580
        order.status = OrderStatus.BILLED
581
        order.statusDescription = "Order Billed"
582
        order.billing_timestamp = datetime.datetime.now()
2783 chandransh 583
 
2842 chandransh 584
        lineitem = order.lineitems[0]
585
        if lineitem.productGroup == "Handsets" and imei_number <= 0:
586
            raise TransactionServiceException(110, "No IMEI number supplied for a handset.")
587
        lineitem.item_number = item_number
588
        if imei_number > 0:
589
            lineitem.imei_number = str(imei_number)
2783 chandransh 590
 
1149 chandransh 591
    session.commit()
592
    return True
593
 
1220 chandransh 594
def batch_orders(warehouseId):
595
    if not warehouseId:
596
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 597
 
598
    batchno_generator = BatchNoGenerator()
599
    session.commit()
1220 chandransh 600
    query = Order.query.filter_by(warehouse_id=warehouseId)
601
    query = query.filter_by(status=OrderStatus.SUBMITTED_FOR_PROCESSING)
602
    query = query.order_by(Order.created_timestamp)
603
    pending_orders = query.all()
1225 chandransh 604
 
1220 chandransh 605
    serial_no = 1
606
    for order in pending_orders:
1276 chandransh 607
        order.batchNo = batchno_generator.id
1220 chandransh 608
        order.serialNo = serial_no
609
        serial_no += 1
610
    session.commit() 
611
    pending_orders = query.all()
612
    return pending_orders
613
 
614
def order_outofstock(orderId):
1911 chandransh 615
    '''
616
    Mark order as out of stock
617
    '''
1220 chandransh 618
    order = get_order(orderId)
619
    order.status = OrderStatus.INVENTORY_LOW
620
    order.statusDescription = "Low Inventory"
621
    order.outofstock_timestamp = datetime.datetime.now()
622
    session.commit()
623
    return True
624
 
3064 chandransh 625
def mark_orders_as_manifested(warehouse_id, provider_id, cod):
759 chandransh 626
    try:
986 chandransh 627
        current_timestamp = datetime.datetime.now()
3064 chandransh 628
        orders = Order.query.filter_by(warehouse_id = warehouse_id, logistics_provider_id = provider_id, status = OrderStatus.BILLED, cod = cod).all()
759 chandransh 629
        for order in orders:
630
            order.status = OrderStatus.SHIPPED_FROM_WH
987 chandransh 631
            order.statusDescription = "Order shipped from warehouse"
986 chandransh 632
            order.shipping_timestamp = current_timestamp
759 chandransh 633
        session.commit()
634
        return True
635
    except:
636
        return False
1113 chandransh 637
 
638
def mark_orders_as_picked_up(provider_id, pickup_details):
639
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 640
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 641
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 642
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
643
            continue
1113 chandransh 644
        order.status = OrderStatus.SHIPPED_TO_LOGST
645
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 646
        order.pickup_timestamp = pickup_timestamp
1113 chandransh 647
    session.commit()
1217 chandransh 648
 
1132 chandransh 649
    current_time = datetime.datetime.now()
650
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1246 chandransh 651
    from_datetime = to_datetime - datetime.timedelta(2)
1132 chandransh 652
    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 653
    return orders_not_picked_up
654
 
1132 chandransh 655
def mark_orders_as_delivered(provider_id, delivered_orders):
656
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 657
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 658
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1911 chandransh 659
            continue
660
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1132 chandransh 661
        order.status = OrderStatus.DELIVERY_SUCCESS
662
        order.statusDescription = "Order delivered"
663
        order.delivery_timestamp, order.receiver = detail.split('|')
664
    session.commit()
665
 
1135 chandransh 666
def mark_orders_as_failed(provider_id, returned_orders):
667
    for awb, detail in returned_orders.iteritems():
668
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 669
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
670
            continue
671
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
672
        order.status = OrderStatus.SALES_RETURN_IN_TRANSIT
1135 chandransh 673
        order.delivery_timestamp, reason = detail.split('|')
674
        order.statusDescription = "Order Returned to Origin:" + reason
1911 chandransh 675
    session.commit()
1135 chandransh 676
 
1246 chandransh 677
def update_non_delivery_reason(provider_id, undelivered_orders):
678
    for awb, reason in undelivered_orders.iteritems():
679
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
680
        if order == None:
2684 chandransh 681
            continue
682
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 683
        order.statusDescription = reason
684
    session.commit()
685
 
483 rajveer 686
def get_alerts(order_id, all):
687
    query = Alerts.query.filter_by(order_id=order_id)
688
    if not all:
689
        query = query.filter_by(valid=True)
690
    return query.all()
691
 
692
def set_alert(order_id, unset, type, comment):
693
    #get existing alert
694
    if unset:
695
        query = Alerts.query.filter_by(order_id=order_id)
696
        query = query.filter_by(type=type)
697
        alerts = query.all()
698
        for alert in alerts:
699
            if alert.valid:
700
                alert.valid = False
701
                alert.comment = comment
702
                alert.time_unset = datetime.datetime.now()
703
    else:
704
        alert = Alerts()
705
        alert.order_id = order_id
706
        alert.valid = True
707
        alert.type = type
708
        alert.comment = comment
709
        alert.time_set = datetime.datetime.now()
766 rajveer 710
    session.commit()    
711
 
1596 ankur.sing 712
def get_valid_order_count():
2851 chandransh 713
    '''
714
    Returns the number of orders which we processed. The reshipped orders are not
715
    counted since there'll always be a new compensating order present.
716
    '''
3216 chandransh 717
    return Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).filter(not_(Order.status.in_((OrderStatus.SALES_RET_RESHIPPED, OrderStatus.DOA_INVALID_RESHIPPED, OrderStatus.DOA_RESHIPPED, OrderStatus.CANCELED)))).count()
1596 ankur.sing 718
 
1627 ankur.sing 719
def get_cust_count_with_successful_txn():
2851 chandransh 720
    '''
721
    Returns the number of distinct customers who have done successful transactions.
722
    It uses the sqlalchemy func module to construct an efficient query.
723
    '''
724
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 725
 
1730 ankur.sing 726
def get_valid_orders_amount_range():
2851 chandransh 727
    '''
728
    Returns a list containing the minimum and maximum amount across all
729
    orders placed with us. No need to consider reshippped orders for min/max
730
    amount of orders.
731
    '''
732
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 733
 
1886 ankur.sing 734
def get_valid_orders(limit):
2851 chandransh 735
    '''
736
    Returns the last limit number of valid orders placed with us. Ignored the
737
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
738
    less than 0. 
739
    '''
740
    if limit < 0:
741
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
3072 chandransh 742
    query = Order.query.filter(Order.status >= OrderStatus.INIT)
1886 ankur.sing 743
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 744
    if limit != 0:
1886 ankur.sing 745
        query = query.limit(limit)
746
    return query.all()
747
 
2783 chandransh 748
def get_next_invoice_number():
749
    entity_id = InvoiceIDGenerator.query.with_lockmode("update").one()
750
    invoice_number = entity_id.id + 1
751
    entity_id.id = invoice_number
752
    session.commit()
753
    return invoice_number
754
 
2536 chandransh 755
def toggle_doa_flag(order_id):
756
    order = get_order(order_id)
757
    if(order.doaFlag):
758
        order.doaFlag = False
759
    else:
760
        order.doaFlag = True
761
    session.commit()
762
    return order.doaFlag
763
 
764
def request_pickup_number(order_id):
765
    order = get_order(order_id)
766
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_PICKUP_REQUESTED:
767
        return False
768
    from_user = 'cnc.center@shop2020.in'
769
    from_pwd = '5h0p2o2o'
770
 
771
    subject = "Pickup request"
772
    try:
3133 rajveer 773
        catalog_client = CatalogClient().get_client()
2536 chandransh 774
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
775
 
776
        logistics_client = LogisticsClient().get_client()
777
        provider = logistics_client.getProvider(order.logistics_provider_id)
3051 chandransh 778
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 779
        raw_message = '''
780
        Dear Sir/Madam,
781
 
2559 chandransh 782
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 783
 
784
        Pickup CODE: %(provider_code)s
785
        Total Weight: %(order_weight)s kg
786
 
2559 chandransh 787
        Pickup Address:
2536 chandransh 788
 
789
        %(customer_address)s
790
 
791
        Delivery Address:
792
 
793
        %(warehouse_executive)s
794
        %(warehouse_address)s
795
        PIN %(warehouse_pin)s
796
        Phone: %(warehouse_phone)s
797
 
798
        Thanks and Regards
799
        Anand Sinha
800
        '''
2559 chandransh 801
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 802
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
2536 chandransh 803
                                          'order_weight' : str(order.total_weight),
804
                                          'customer_address' : __get_order_address(order),
805
                                          'warehouse_executive' : 'Parmod Kumar',
806
                                          'warehouse_address' : warehouse.location,
807
                                          'warehouse_pin' : warehouse.pincode,
808
                                          'warehouse_phone': '9971573026'}
3527 chandransh 809
        mail(from_user, from_pwd, [to_addr], subject, message)
2536 chandransh 810
        order.status = OrderStatus.DOA_PICKUP_REQUESTED
811
        order.statusDescription = "Pick up requested for DOA"
812
        session.commit()
813
        return True
814
    except Exception as e:
815
        print sys.exc_info()[0]
816
        return False
817
 
818
def authorize_pickup(order_id, pickup_number):
819
    order = get_order(order_id)
820
    if order.status != OrderStatus.DOA_PICKUP_REQUESTED:
821
        return False
822
    from_user = 'help@shop2020.in'
823
    from_pwd = '5h0p2o2o'
824
    subject = 'Pickup details'
825
    filename = "/tmp/" +  str(order.id) +".pdf" 
826
    try:
3133 rajveer 827
        catalog_client = CatalogClient().get_client()
2536 chandransh 828
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
829
 
830
        logistics_client = LogisticsClient().get_client()
831
        provider = logistics_client.getProvider(order.logistics_provider_id)
832
        provider_name = provider.name
833
 
834
        to_addr = order.customer_email
835
        today = date.today().strftime("%d-%B-%Y (%A)")
836
 
837
        raw_message = '''
838
        Dear Mr. %(customer_name)s,
839
 
840
        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.
841
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
842
        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.
843
 
844
        Pickup will happen from the below mentioned address:-
845
 
846
        %(customer_address)s
847
 
848
        Do let us know in case of any concerns
849
 
850
        Thanks & Regards
851
        Saholic Team
852
        '''
853
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
854
                                         'order_id' : order_id,
855
                                         'provider_name' : provider_name,
856
                                         'date': today,
857
                                         'pickup_request_no' : pickup_number,
858
                                         'customer_address' : __get_order_address(order)}
859
        print message
860
        __generate_return_advice(order, warehouse, provider, filename)
3527 chandransh 861
        mail(from_user, from_pwd, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 862
        order.pickupRequestNo = pickup_number
863
        order.status = OrderStatus.DOA_RETURN_AUTHORIZED
864
        order.statusDescription = "DOA pick up authorized"
2764 chandransh 865
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 866
        session.commit()
867
        return True
868
    except Exception as e:
869
        print sys.exc_info()[0]
870
        return False
871
    finally:
872
        if os.path.exists(filename):
873
            os.remove(filename)
874
 
2764 chandransh 875
def mark_doas_as_picked_up(provider_id, pickup_details):
876
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
877
        order = Order.query.filter_by(pickupRequestNo=pickupNo, logistics_provider_id = provider_id).first()
878
        if order == None or order.status != OrderStatus.DOA_RETURN_AUTHORIZED:
879
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
880
            continue
881
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
882
        order.statusDescription = "DOA picked up by Courier Company"
883
        order.doa_pickup_timestamp = doa_pickup_timestamp
884
    session.commit()
885
 
886
    current_time = datetime.datetime.now()
887
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
888
    from_datetime = to_datetime - datetime.timedelta(2)
889
    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()
890
    return orders_not_picked_up
891
 
2616 chandransh 892
def receive_return(order_id):
2591 chandransh 893
    order = get_order(order_id)
2616 chandransh 894
    if order.status in [OrderStatus.DOA_RETURN_AUTHORIZED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
895
        order.status = OrderStatus.DOA_RECEIVED
896
        order.statusDescription = "DOA package received"
2764 chandransh 897
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 898
        session.commit()
899
    elif order.status == OrderStatus.SALES_RETURN_IN_TRANSIT :
900
        order.status = OrderStatus.SALES_RET_RECEIVED
901
        order.statusDescription = "Sales return received"
2764 chandransh 902
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 903
        session.commit()
904
    else:
2591 chandransh 905
        return False
906
    return True
907
 
908
def validate_doa(order_id, is_valid):
909
    order = get_order(order_id)
2599 chandransh 910
    if order.status != OrderStatus.DOA_RECEIVED:
2591 chandransh 911
        return False
912
    if is_valid:
2609 chandransh 913
        order.status = OrderStatus.DOA_CERT_VALID
914
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 915
    else:
916
        order.status = OrderStatus.DOA_CERT_INVALID
917
        order.statusDescription = "DOA Certificate Invalid"
918
    session.commit()
919
    return True
920
 
2628 chandransh 921
def reship_order(order_id):
922
    """
923
    If the order is in SALES_RET_RECEIVED or DOA_CERT_INVALID state, it does the following:
924
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
925
        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.
926
 
927
    If the order is in DOA_CERT_VALID state, it does the following:
928
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
929
        2. Creates a return order for the warehouse executive to return the DOA material.
930
        3. Marks the current order as the final DOA_RESHIPPED state.
931
 
932
    Returns the id of the newly created order.
933
 
934
    Throws an exception if the order with the given id couldn't be found.
935
 
936
    Parameters:
937
     - orderId
938
    """
939
    order = get_order(order_id)
940
    if order.status == OrderStatus.SALES_RET_RECEIVED:
941
        new_order = __clone_order(order, True)
942
        order.status = OrderStatus.SALES_RET_RESHIPPED
943
        order.statusDescription = "Order Reshipped"
944
        session.commit()
945
    elif order.status == OrderStatus.DOA_CERT_INVALID:
946
        new_order = __clone_order(order, True)
947
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
948
        order.statusDescription = "Order Reshipped"
949
        session.commit()
950
    elif order.status == OrderStatus.DOA_CERT_VALID:
951
        new_order = __clone_order(order, False)
952
        ret_order = __create_return_order(order)
953
        order.status = OrderStatus.DOA_RESHIPPED
954
        order.statusDescription = "Order Reshipped"
955
        session.commit()
956
    else:
957
        raise TransactionServiceException(112, "This order can't be reshipped")
958
 
2764 chandransh 959
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 960
    order.new_order_id = new_order.id
961
    session.commit()
962
 
963
    return new_order.id
964
 
3226 chandransh 965
def refund_order(order_id, refunded_by, reason):
2628 chandransh 966
    """
967
    If the order is in SALES_RET_RECEIVED, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
968
        1. Creates a refund request for batch processing.
969
        2. Creates a return order for the warehouse executive to return the shipped material.
970
        3. Marks the current order as SALES_RET_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
971
 
972
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
973
        1. Creates a refund request for batch processing.
3226 chandransh 974
        2. Cancels the reservation of the item in the warehouse.
975
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 976
 
3226 chandransh 977
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
978
        1. Cancels the reservation of the item in the warehouse.
979
        2. Marks the current order as CANCELED.
980
 
981
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
982
 
983
    Returns True if it is successful, False otherwise.
2628 chandransh 984
 
985
    Throws an exception if the order with the given id couldn't be found.
986
 
987
    Parameters:
3226 chandransh 988
     - order_id
989
     - refunded_by
990
     - reason
2628 chandransh 991
    """
3414 chandransh 992
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 993
    order = get_order(order_id)
3186 chandransh 994
 
995
 
3366 chandransh 996
 
3226 chandransh 997
    if order.cod:
3414 chandransh 998
        logging.info("Refunding COD order with status " + str(order.status))
3366 chandransh 999
        status_transition = {OrderStatus.SALES_RET_RECEIVED : OrderStatus.SALES_RET_REFUNDED,
1000
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
1001
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
1002
                     OrderStatus.INIT : OrderStatus.CANCELED,
1003
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELED,
1004
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELED,
1005
                     OrderStatus.ACCEPTED : OrderStatus.CANCELED,
1006
                     OrderStatus.BILLED : OrderStatus.CANCELED,
1007
                     }
1008
        if order.status not in status_transition.keys():
1009
            raise TransactionServiceException(114, "This order can't be refunded")
1010
 
3413 chandransh 1011
        if order.status < OrderStatus.BILLED:
3226 chandransh 1012
            __update_inventory_reservation(order)
1013
            order.statusDescription = "Order Cancelled"
3415 chandransh 1014
        elif order.status == OrderStatus.BILLED:
3413 chandransh 1015
            __create_return_order(order)
1016
            order.statusDescription = "Order Cancelled"
3226 chandransh 1017
        elif order.status in [OrderStatus.SALES_RET_RECEIVED, OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID] :
1018
            __create_return_order(order)
1019
            __create_refund(order)
1020
            order.statusDescription = "Order Refunded"
1021
    else:
3366 chandransh 1022
        status_transition = {OrderStatus.SALES_RET_RECEIVED : OrderStatus.SALES_RET_REFUNDED,
1023
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
1024
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
1025
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.REFUNDED,
1026
                     OrderStatus.INVENTORY_LOW : OrderStatus.REFUNDED
1027
                     }
1028
        if order.status not in status_transition.keys():
1029
            raise TransactionServiceException(114, "This order can't be refunded")
1030
 
3226 chandransh 1031
        if order.status in [OrderStatus.SALES_RET_RECEIVED, OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID] :
1032
            __create_return_order(order)
1033
            __create_refund(order)
1034
            order.statusDescription = "Order Refunded"
1035
        elif order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW]:
3191 chandransh 1036
            __create_cancellation(order)
3226 chandransh 1037
            __update_inventory_reservation(order)
1038
            order.statusDescription = "Order Refunded"
3195 chandransh 1039
 
1040
    order.status = status_transition[order.status]
1041
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 1042
    order.refunded_by = refunded_by
1043
    order.refund_reason = reason
2628 chandransh 1044
 
1045
    session.commit()
1046
    return True
1047
 
3186 chandransh 1048
def __update_inventory_reservation(order):
3191 chandransh 1049
    '''
1050
    Reduce the reservation count for all line items of the given order.
1051
    '''
3186 chandransh 1052
    try:
1053
        catalog_client = CatalogClient().get_client()
1054
        for lineitem in order.lineitems:
1055
            catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity);
1056
    except:
1057
        print "Unable to reduce reservation count"
1058
 
2628 chandransh 1059
def __clone_order(order, should_copy_billing_info):
1060
    current_time = datetime.datetime.now()
1061
    new_order = Order()
1062
    new_order.customer_id = order.customer_id
1063
    new_order.customer_name = order.customer_name
1064
    new_order.customer_city = order.customer_city
1065
    new_order.customer_state = order.customer_state
1066
    new_order.customer_mobilenumber = order.customer_mobilenumber
1067
    new_order.customer_pincode = order.customer_pincode
1068
    new_order.customer_address1 = order.customer_address1
1069
    new_order.customer_address2 = order.customer_address2
1070
    new_order.customer_email = order.customer_email
1071
    new_order.total_amount = order.total_amount
1072
    new_order.total_weight = order.total_weight
1073
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1074
    new_order.statusDescription = 'Submitted for Processing'
1075
    new_order.created_timestamp = current_time
1076
 
1077
    new_order.transaction = order.transaction
3239 chandransh 1078
    new_order.cod = False
2628 chandransh 1079
 
1080
    for line_item in order.lineitems:
1081
        litem = LineItem()
1082
        litem.item_id = line_item.item_id
1083
        litem.productGroup = line_item.productGroup
1084
        litem.brand = line_item.brand
1085
        if line_item.model_number:
1086
            litem.model_number = line_item.model_number
1087
        if line_item.model_name:    
1088
            litem.model_name = line_item.model_name
1089
        if line_item.color:
1090
            litem.color = line_item.color
1091
        if line_item.extra_info:
1092
            litem.extra_info = line_item.extra_info
1093
        litem.quantity = line_item.quantity
1094
        litem.unit_price = line_item.unit_price
1095
        litem.unit_weight = line_item.unit_weight
1096
        litem.total_price = line_item.total_price
1097
        litem.total_weight = line_item.total_weight
1098
        litem.transfer_price = line_item.transfer_price
1099
        litem.order = new_order
1100
 
1101
    logistics_client = LogisticsClient().get_client()
1102
    item_id = new_order.lineitems[0].item_id
3239 chandransh 1103
    logistics_info = logistics_client.getLogisticsInfo(new_order.customer_pincode, item_id, DeliveryType.PREPAID) #TODO: We should be able to pass another flag to suggest ignoring the inventory situation.
2628 chandransh 1104
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
1105
 
1106
    new_order.warehouse_id = logistics_info.warehouseId
1107
    new_order.logistics_provider_id = logistics_info.providerId
1108
    new_order.airwaybill_no = logistics_info.airway_billno
1109
    new_order.tracking_id = new_order.airwaybill_no
1110
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
1111
 
1112
    if should_copy_billing_info:
1113
        new_order.invoice_number = order.invoice_number
1114
        new_order.billed_by = order.billed_by
1115
        new_order.warehouse_id = order.warehouse_id
1116
        new_order.accepted_timestamp = current_time
1117
        new_order.billing_timestamp = current_time    
1118
        new_order.status = OrderStatus.BILLED
1119
        new_order.statusDescription = 'Order Billed'
1120
    else:       
3133 rajveer 1121
        catalog_client = CatalogClient().get_client()
2628 chandransh 1122
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, new_order.lineitems[0].quantity)
1123
 
1124
        item_pricing = catalog_client.getItemPricing(item_id, order.warehouse_id)
1125
        new_order.lineitems[0].transfer_price = item_pricing.transferPrice
1126
 
1127
    return new_order
1128
 
1129
def __create_return_order(order):
2687 chandransh 1130
    ret_order = ReturnOrder(order)
2628 chandransh 1131
    return ret_order
1132
 
1133
def __create_refund(order):
2747 chandransh 1134
    payment_client = PaymentClient().get_client()
1135
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
1136
    return
2628 chandransh 1137
 
3035 chandransh 1138
def __create_cancellation(order):
1139
    return
1140
 
2536 chandransh 1141
def __get_order_address(order):
1142
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
1143
    if order.customer_address2:
1144
        address = address + order.customer_address2 + "\n"
1145
    address = address + order.customer_city + "\n"
1146
    address = address + order.customer_state + "\n"
1147
    address = address + "PIN " + order.customer_pincode + "\n"
1148
    address = address + "Phone: " + order.customer_mobilenumber
1149
    return address
1150
 
1151
def __generate_return_advice(order, warehouse, provider, filename):    
1152
    pdf = Canvas(filename)
1153
    pdf.setFont('Times-Bold',16)
1154
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
1155
    address_text.textLine("To")
1156
    address_text.textLine("Parmod Kumar")
1157
    for line in warehouse.location.split("\n"):
1158
        address_text.textLine(line)
1159
    address_text.textLine("PIN " + warehouse.pincode)
1160
    address_text.textLine("")
1161
    address_text.textLine("Phone: 9971573026")
1162
    pdf.drawText(address_text)
1163
 
1164
    pdf.setFont('Times-Roman',12)
1165
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 1166
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 1167
    lineitem = order.lineitems[0] 
1168
    order_text.textLine("Content : " + lineitem.brand + " " + lineitem.model_number + " " + lineitem.color)
1169
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
1170
    order_text.textLine("Order ID : " + str(order.id))
1171
    pdf.drawText(order_text)
1172
    pdf.showPage()
1173
    pdf.save()
1174
    return filename
1175
 
2697 chandransh 1176
def get_return_orders(warehouse_id, from_date, to_date):
1177
    query = ReturnOrder.query.filter_by(processedStatus = False)
1178
    if warehouse_id != -1:
1179
        query = query.filter_by(warehouseId = warehouse_id)
1180
    if from_date:
1181
        query = query.filter(Order.created_timestamp >from_date)
1182
    if to_date:
1183
        query = query.filter(Order.created_timestamp < to_date)
1184
    return [return_order.to_thrift_object() for return_order in query.all()]
1185
 
2700 chandransh 1186
def get_return_order(id):
1187
    ret_order = ReturnOrder.get_by(orderId = id)
1188
    if ret_order is None:
1189
        raise TransactionServiceException(116, "No return order found for the given order id")
1190
    return ret_order.to_thrift_object()
1191
 
2697 chandransh 1192
def process_return(ret_order_id):
1193
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
1194
    if ret_order is None:
1195
        raise TransactionServiceException(116, "No return order found for the given order id")
1196
    ret_order.processedStatus = True
2701 chandransh 1197
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 1198
    session.commit()
1199
 
2819 chandransh 1200
def create_purchase_order(warehouseId):
1201
    if not warehouseId:
1202
        raise TransactionServiceException(101, "bad warehouse id")
1203
 
3451 chandransh 1204
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
2819 chandransh 1205
    query = query.filter_by(status=OrderStatus.SUBMITTED_FOR_PROCESSING)
1206
    query = query.filter_by(purchase_order_id=None)
1207
    query = query.order_by(Order.created_timestamp)
1208
    pending_orders = query.all()
1209
 
1210
    if not pending_orders:
1211
        return -1
1212
 
1213
    t_purchase_order = PurchaseOrder()
2832 chandransh 1214
    t_purchase_order.supplierId = warehouseId
2819 chandransh 1215
    t_purchase_order.warehouseId = warehouseId
1216
    t_purchase_order.lineitems = []
1217
 
1218
    lineitems = {}
1219
 
1220
    for order in pending_orders:
1221
        for lineitem in order.lineitems:
1222
            item_id = lineitem.item_id
1223
            if lineitems.has_key(item_id):
1224
                lineitems[item_id].quantity = lineitems[item_id].quantity + lineitem.quantity
1225
            else:
1226
                t_po_lineitem = POLineItem()
1227
                t_po_lineitem.productGroup = lineitem.productGroup
1228
                t_po_lineitem.brand = lineitem.brand
1229
                t_po_lineitem.modelNumber = lineitem.model_number
1230
                t_po_lineitem.modelName = lineitem.model_name
1231
                t_po_lineitem.color = lineitem.color
1232
                t_po_lineitem.itemId = lineitem.item_id
1233
                t_po_lineitem.quantity = lineitem.quantity
1234
                t_po_lineitem.unitPrice = lineitem.transfer_price
1235
                lineitems[item_id] = t_po_lineitem
1236
                t_purchase_order.lineitems.append(t_po_lineitem)
1237
 
1238
    warehouse_client = WarehouseClient().get_client()
1239
    po_id = warehouse_client.createPurchaseOrder(t_purchase_order)
1240
 
1241
    for order in pending_orders:
1242
        order.purchase_order_id = po_id
1243
    session.commit()
1244
    return po_id
1245
 
3451 chandransh 1246
def update_weight(order_id, weight):
3469 chandransh 1247
    '''
1248
    Update the weight of order
1249
    '''
3451 chandransh 1250
    order = get_order(order_id)
1251
    order.total_weight = weight
3469 chandransh 1252
    lineitem = order.lineitems[0]
1253
    lineitem.total_weight = weight
1254
    lineitem.unit_weight = weight
3451 chandransh 1255
 
3469 chandransh 1256
    session.commit()
1257
    return order
1258
 
1259
def change_product(order_id, item_id):
1260
    '''
1261
    Ship a product of a different color to the customer.
1262
    '''
1263
    order = get_order(order_id)
1264
    if order.status not in [OrderStatus.INIT, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW]:
1265
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
1266
 
1267
    lineitem = order.lineitems[0]
3451 chandransh 1268
 
3469 chandransh 1269
    catalog_client = CatalogClient().get_client()
1270
 
1271
    old_item = catalog_client.getItem(lineitem.item_id)
1272
    item = catalog_client.getItem(item_id)
1273
    if old_item.catalogItemId != item.catalogItemId:
1274
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
1275
 
1276
    catalog_client.reserveItemInWarehouse(item_id, order.warehouse_id, lineitem.quantity)
1277
    catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity)
1278
    #TODO: Check that this new item has the same price
1279
 
1280
    lineitem.item_id = item_id
1281
    lineitem.color = item.color
1282
 
3451 chandransh 1283
    session.commit()
3469 chandransh 1284
 
1285
    order = get_order(order_id)
3451 chandransh 1286
    return order
3469 chandransh 1287
 
1288
def change_warehouse(order_id, warehouse_id):
1289
    '''
1290
    Update the warehouse which will be used to fulfil this order.
1291
    '''
1292
    order = get_order(order_id)
1293
    if order.status not in [OrderStatus.INIT, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW]:
1294
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
1295
 
1296
    if warehouse_id == order.warehouse_id:
1297
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
1298
 
1299
    lineitem = order.lineitems[0]
1300
    catalog_client = CatalogClient().get_client()
1301
    try:
1302
        warehouse = catalog_client.getWarehouse(warehouse_id)
1303
    except:
1304
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
1305
 
1306
    catalog_client.reserveItemInWarehouse(lineitem.item_id, warehouse_id, lineitem.quantity)
1307
    catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity)
3451 chandransh 1308
 
3469 chandransh 1309
    order.warehouse_id = warehouse_id
1310
    session.commit()
1311
    return order
3553 chandransh 1312
 
1313
def add_delay_reason(order_id, reason):
1314
    '''
1315
    Adds a delay reason to the order
1316
    '''
1317
    order = get_order(order_id)
1318
    try:
1319
        order.delay_reason = reason
1320
        session.commit()
1321
        return True
1322
    except:
1323
        return False
3469 chandransh 1324
 
766 rajveer 1325
def close_session():
1326
    if session.is_active:
1327
        print "session is active. closing it."
2783 chandransh 1328
        session.close()
3376 rajveer 1329
 
1330
def is_alive():
1331
    try:
1332
        session.query(Transaction.id).limit(1).one()
1333
        return True
1334
    except:
1335
        return False
3413 chandransh 1336