Subversion Repositories SmartDukaan

Rev

Rev 4591 | Rev 4599 | 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
 
4369 rajveer 7
from datetime import date, timedelta
2536 chandransh 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.CatalogClient import CatalogClient
13
from shop2020.clients.HelperClient import HelperClient
14
from shop2020.clients.LogisticsClient import LogisticsClient
2747 chandransh 15
from shop2020.clients.PaymentClient import PaymentClient
4501 mandeep.dh 16
from shop2020.clients.PurchaseClient import PurchaseClient
3499 mandeep.dh 17
from shop2020.clients.UserClient import UserClient
18
from shop2020.clients.WarehouseClient import WarehouseClient
4421 mandeep.dh 19
from shop2020.config.client.ConfigClient import ConfigClient
3499 mandeep.dh 20
from shop2020.model.v1 import order
21
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem, \
4435 mandeep.dh 22
    Order, BatchNoGenerator, InvoiceIDGenerator, TransactionRequiringExtraProcessing, \
23
    OrderInventory, Alert
2687 chandransh 24
from shop2020.model.v1.order.impl.model.ReturnOrder import ReturnOrder
4541 mandeep.dh 25
from shop2020.thriftpy.generic.ttypes import ExceptionType
3499 mandeep.dh 26
from shop2020.thriftpy.logistics.ttypes import DeliveryType
4435 mandeep.dh 27
from shop2020.thriftpy.model.v1.catalog.ttypes import BillingType, \
28
    InventoryServiceException
29
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
30
    TransactionStatus, OrderStatus, DelayReason, ExtraTransactionProcessingType, \
31
    HotspotAction, TimeoutSummary
4421 mandeep.dh 32
from shop2020.thriftpy.payments.ttypes import PaymentException
4541 mandeep.dh 33
from shop2020.thriftpy.purchase.ttypes import PurchaseOrder, \
34
    LineItem as POLineItem
35
from shop2020.thriftpy.warehouse.ttypes import ScanType, \
36
    WarehouseServiceException
3499 mandeep.dh 37
from shop2020.utils.EmailAttachmentSender import mail, get_attachment_part
855 rajveer 38
from shop2020.utils.Utils import to_py_date, to_java_date
4008 mandeep.dh 39
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
3499 mandeep.dh 40
from sqlalchemy.sql import func
41
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct
42
from string import Template
43
from textwrap import dedent
44
import datetime
45
import logging
46
import os
4421 mandeep.dh 47
import sys
4435 mandeep.dh 48
import time
4421 mandeep.dh 49
import traceback
3499 mandeep.dh 50
logging.basicConfig(level=logging.DEBUG)
104 ashish 51
 
3499 mandeep.dh 52
 
4019 chandransh 53
try:
54
    config_client = ConfigClient()
55
    PREPAID_SHIPPING_CUTOFF_TIME = int(config_client.get_property('delivery_cutoff_time'))
56
except Exception as ex:
57
    print "[ERROR] Unexpected config error:", sys.exc_info()[0]
58
    PREPAID_SHIPPING_CUTOFF_TIME = 15
3499 mandeep.dh 59
 
4019 chandransh 60
COD_SHIPPING_CUTOFF_TIME = 12
3499 mandeep.dh 61
 
2819 chandransh 62
PAGE_HEIGHT=defaultPageSize[1]
63
PAGE_WIDTH=defaultPageSize[0]
64
 
3499 mandeep.dh 65
ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT = {
4484 rajveer 66
        OrderStatus.RTO_RESHIPPED     :  3,
67
        OrderStatus.RTO_IN_TRANSIT : -5,
3499 mandeep.dh 68
        OrderStatus.DELIVERY_SUCCESS        :  1,
3578 mandeep.dh 69
        OrderStatus.DOA_CERT_INVALID        : -5
3499 mandeep.dh 70
}
71
 
104 ashish 72
def get_new_transaction():
73
    transaction = Transaction()
74
    transaction.createdOn = datetime.datetime.now()
738 chandransh 75
    transaction.status = TransactionStatus.INIT
104 ashish 76
    transaction.status_message = "New transaction"
483 rajveer 77
    return transaction
78
 
79
def create_order(t_order):
80
    order = Order()
81
    if t_order.warehouse_id:
82
        order.warehouse_id = t_order.warehouse_id
509 rajveer 83
    if t_order.logistics_provider_id:    
483 rajveer 84
        order.logistics_provider_id = t_order.logistics_provider_id
85
        order.airwaybill_no = t_order.airwaybill_no
86
        order.tracking_id = t_order.tracking_id
4009 chandransh 87
    if t_order.expected_shipping_time:
4019 chandransh 88
        order.expected_shipping_time = to_py_date(t_order.expected_shipping_time).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 89
        order.promised_shipping_time = order.expected_shipping_time
4009 chandransh 90
    if t_order.expected_delivery_time:
483 rajveer 91
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
4102 chandransh 92
        order.promised_delivery_time = order.expected_delivery_time
483 rajveer 93
    if t_order.customer_id:    
94
        order.customer_id = t_order.customer_id
95
        order.customer_name = t_order.customer_name
860 rajveer 96
        order.customer_city = t_order.customer_city
97
        order.customer_state = t_order.customer_state
483 rajveer 98
        order.customer_mobilenumber = t_order.customer_mobilenumber
99
        order.customer_pincode = t_order.customer_pincode
738 chandransh 100
        order.customer_address1 = t_order.customer_address1
101
        order.customer_address2 = t_order.customer_address2
483 rajveer 102
        order.customer_email = t_order.customer_email
103
    #new status and status description to be added    
716 rajveer 104
    order.status = t_order.status  
483 rajveer 105
    order.statusDescription = t_order.statusDescription
106
    order.total_amount = t_order.total_amount
107
    order.total_weight = t_order.total_weight
108
    if t_order.created_timestamp:
109
        order.created_timestamp = to_py_date(t_order.created_timestamp)
110
    else:
685 chandransh 111
        order.created_timestamp = datetime.datetime.now()
483 rajveer 112
    return order
113
 
114
def create_transaction(t_transaction):
115
    t_orders = t_transaction.orders
116
    if not t_orders:
117
        raise TransactionServiceException(101, "Orders missing from the transaction")
118
    transaction = get_new_transaction()
119
    transaction.customer_id = t_transaction.customer_id 
120
    transaction.shopping_cart_id = t_transaction.shoppingCartid
2219 varun.gupt 121
    transaction.coupon_code = t_transaction.coupon_code
2815 vikas 122
    transaction.session_source = t_transaction.sessionSource
123
    transaction.session_start_time = to_py_date(t_transaction.sessionStartTime)
3858 vikas 124
    transaction.first_source = t_transaction.firstSource
125
    transaction.first_source_start_time = to_py_date(t_transaction.firstSourceTime)
483 rajveer 126
 
127
    for t_order in t_orders:
128
        order = create_order(t_order)
129
        order.transaction = transaction 
130
        for line_item in t_order.lineitems:
131
            litem = LineItem()
716 rajveer 132
            litem.item_id = line_item.item_id
963 chandransh 133
            litem.productGroup = line_item.productGroup
483 rajveer 134
            litem.brand = line_item.brand
135
            if line_item.model_number:
136
                litem.model_number = line_item.model_number
137
            if line_item.model_name:    
138
                litem.model_name = line_item.model_name
908 chandransh 139
            if line_item.color:
140
                litem.color = line_item.color
483 rajveer 141
            if line_item.extra_info:
142
                litem.extra_info = line_item.extra_info
143
            litem.quantity = line_item.quantity
144
            litem.unit_price = line_item.unit_price
145
            litem.unit_weight = line_item.unit_weight
146
            litem.total_price = line_item.total_price
147
            litem.total_weight = line_item.total_weight
4283 anupam.sin 148
            '''litem.transfer_price = line_item.transfer_price'''
4172 rajveer 149
            litem.dealText = line_item.dealText
4295 varun.gupt 150
            litem.warranty_expiry_timestamp = to_py_date(line_item.warrantry_expiry_timestamp)
1976 varun.gupt 151
 
483 rajveer 152
            """
153
            if line_item.addedOn:
154
                litem.added_on = to_py_date(line_item.addedOn)
155
            else:
156
                litem.added_on = datetime.datetime.now()
157
            """
158
            litem.order = order
159
    session.commit()
160
    return transaction.id
161
 
162
def get_transaction(transaction_id):
163
    transaction = Transaction.get_by(id=transaction_id)
164
    if not transaction:
165
        raise TransactionServiceException(108, "no such transaction")
166
 
167
    return transaction
168
 
169
def get_transactions_for_customer(customer_id, from_date, to_date, status):
170
    if not customer_id:
171
        raise TransactionServiceException(101, "bad customer id")
172
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 173
    if status is not None:
483 rajveer 174
        query = query.filter(Transaction.status == status)
175
    if from_date:
176
        query = query.filter(Transaction.createdOn >from_date)
177
    if to_date:
178
        query = query.filter(Transaction.createdOn < to_date)
179
    return query.all()
180
 
181
def get_transactions_for_shopping_cart_id(shopping_cart_id):
182
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
183
    return transactions
184
 
185
def get_transaction_status(transaction_id):
186
    if not transaction_id:
187
        raise TransactionServiceException(101, "bad transaction id")
188
 
189
    transaction = get_transaction(transaction_id)
190
 
191
    return transaction.status
192
 
193
def change_transaction_status(transaction_id, new_status, description):
194
    transaction = get_transaction(transaction_id)
195
    transaction.status = new_status
196
    transaction.status_message = description
690 chandransh 197
    if new_status == TransactionStatus.FAILED:
198
        for order in transaction.orders:
199
            order.status = OrderStatus.PAYMENT_FAILED
2339 chandransh 200
            order.statusDescription = "Payment Failed"
4247 rajveer 201
    elif new_status == TransactionStatus.AUTHORIZED or new_status == TransactionStatus.FLAGGED:
690 chandransh 202
        for order in transaction.orders:
4247 rajveer 203
            if new_status == TransactionStatus.AUTHORIZED:
204
                order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
205
                order.statusDescription = "Submitted to warehouse"
206
            elif new_status == TransactionStatus.FLAGGED:
207
                order.status = OrderStatus.PAYMENT_FLAGGED
208
                order.statusDescription = "Payment flagged by gateway"
3092 chandransh 209
            order.cod = False
743 rajveer 210
            #After we got payment success, we will set logistics info also 
211
            logistics_client = LogisticsClient().get_client()
212
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 213
            item_id = order.lineitems[0].item_id
3044 chandransh 214
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID)
743 rajveer 215
 
1730 ankur.sing 216
            current_time = datetime.datetime.now()
217
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 218
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
1730 ankur.sing 219
 
743 rajveer 220
            order.warehouse_id = logistics_info.warehouseId
221
            order.logistics_provider_id = logistics_info.providerId
222
            order.airwaybill_no = logistics_info.airway_billno
223
            order.tracking_id = order.airwaybill_no
4019 chandransh 224
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 225
            order.promised_shipping_time = order.expected_shipping_time
1730 ankur.sing 226
            order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 227
            order.promised_delivery_time = order.expected_delivery_time 
871 chandransh 228
 
3133 rajveer 229
            catalog_client = CatalogClient().get_client()
871 chandransh 230
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, order.lineitems[0].quantity)
1351 varun.gupt 231
 
4316 anupam.sin 232
            try:
233
                item_pricing = catalog_client.getItemPricing(item_id, -1)
234
                order.lineitems[0].transfer_price = item_pricing.transferPrice
235
            except:
236
                print "Not able to get transfer price. Skipping"
3064 chandransh 237
    elif new_status == TransactionStatus.COD_IN_PROCESS:
238
        for order in transaction.orders:
239
            order.status = OrderStatus.INIT
240
            order.statusDescription = "Verification Pending"
241
            order.cod = True
242
            #After we got payment success, we will set logistics info also 
243
            logistics_client = LogisticsClient().get_client()
244
            #FIXME line item is only one now. If multiple will come, need to fix.
245
            item_id = order.lineitems[0].item_id
246
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.COD)
247
 
248
            current_time = datetime.datetime.now()
249
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 250
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
3064 chandransh 251
 
252
            order.warehouse_id = logistics_info.warehouseId
253
            order.logistics_provider_id = logistics_info.providerId
254
            order.airwaybill_no = logistics_info.airway_billno
255
            order.tracking_id = order.airwaybill_no
4019 chandransh 256
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 257
            order.promised_shipping_time = order.expected_shipping_time
3064 chandransh 258
            order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 259
            order.promised_delivery_time = order.expected_delivery_time
3064 chandransh 260
 
3133 rajveer 261
            catalog_client = CatalogClient().get_client()
3064 chandransh 262
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, order.lineitems[0].quantity)
263
 
4316 anupam.sin 264
            try:
265
                item_pricing = catalog_client.getItemPricing(item_id, -1)
266
                order.lineitems[0].transfer_price = item_pricing.transferPrice        
267
            except:
268
                print "Not able to get transfer price. Skipping"
483 rajveer 269
    session.commit()
3499 mandeep.dh 270
 
3530 mandeep.dh 271
    try:
272
        if new_status == TransactionStatus.COD_IN_PROCESS:
4008 mandeep.dh 273
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
274
            transaction_requiring_extra_processing.category = 'COD_VERIFICATION'
275
            transaction_requiring_extra_processing.transaction_id = transaction_id
276
            session.commit()
4247 rajveer 277
        elif new_status == TransactionStatus.FLAGGED:
278
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
279
            transaction_requiring_extra_processing.category = 'PAYMENT_FLAGGED'
280
            transaction_requiring_extra_processing.transaction_id = transaction_id
281
            session.commit()
3530 mandeep.dh 282
    except Exception as e:
4065 mandeep.dh 283
        print "Error inserting transaction Id: " + str(transaction_id) + " due to " + str(e)
3499 mandeep.dh 284
 
483 rajveer 285
    return True
286
 
3994 chandransh 287
def __get_holidays(start_time=0L, to_time=-1L):
288
    '''
289
    Get the list of all public holidays since start time including the
290
    day of start time if it's a holiday
291
    '''
292
    midnightTime = start_time.replace(hour=0, minute=0, second=0, microsecond=0)
1730 ankur.sing 293
    fromDate = to_java_date(midnightTime)
294
    logistics_client = LogisticsClient().get_client()
3994 chandransh 295
    #TODO: This list should be cached after the first call.
296
    #Calling logistics server is also unnecessary.
297
    holidays = logistics_client.getHolidays(fromDate, to_time)
298
    holidays = [to_py_date(holiday).date() for holiday in holidays]
299
    return holidays
300
 
301
 
302
def adjust_delivery_time(start_time, delivery_days):
303
    '''
304
    Returns the actual no. of days which will pass while 'delivery_days'
305
    no. of business days will pass since 'order_time'. 
306
    '''
307
    start_date = start_time.date()
308
    end_date = start_date + datetime.timedelta(days = delivery_days)
309
    holidays = __get_holidays(start_time)
1730 ankur.sing 310
 
3994 chandransh 311
    while start_date <= end_date:
312
        if start_date.weekday() == 6 or start_date in holidays:
1730 ankur.sing 313
            delivery_days = delivery_days + 1
3994 chandransh 314
            end_date = end_date + datetime.timedelta(days = 1)
4088 chandransh 315
        start_date = start_date + datetime.timedelta(days = 1)
3994 chandransh 316
 
1730 ankur.sing 317
    return delivery_days
318
 
1398 varun.gupt 319
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 320
    transaction = get_transaction(transaction_id)
321
 
322
    html_header = """
323
<html>
324
<body>
325
<div>
326
    <p>
327
        Hello,<br /><br />
1742 rajveer 328
        Thanks for placing order with us. Following are the details of your order:
1262 varun.gupt 329
    </p>
330
    <div>
331
        Order Date: $order_date
1569 varun.gupt 332
    </div>
1262 varun.gupt 333
    <div>
334
        <table>
1569 varun.gupt 335
        <tr><td colspan="5"><hr /></td></tr>
336
        <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
337
        <tr><td colspan="5"><hr /></td></tr>
1262 varun.gupt 338
        <tr>
2050 varun.gupt 339
            <th width="100">Order No.</th>
340
            <th>Product</th>
341
            <th width="100">Quantity</th>
342
            <th width="100">Unit Price</th>
343
            <th width="100">Amount</th>
1262 varun.gupt 344
        </tr>
345
    """
1398 varun.gupt 346
    user_email = ""
1262 varun.gupt 347
    total_amount = 0.0
348
    html_table = ""
1569 varun.gupt 349
    order_date = datetime.datetime.now()
1262 varun.gupt 350
 
351
    for order in transaction.orders:
352
        order_date = order.created_timestamp
1398 varun.gupt 353
        user_email = order.customer_email
1569 varun.gupt 354
        html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
1262 varun.gupt 355
 
356
        for lineitem in order.lineitems:
2050 varun.gupt 357
            lineitem_total_price = round(lineitem.total_price, 2)
358
 
1276 chandransh 359
            html_tr += "<td>" + str(lineitem) + "</td>"
2050 varun.gupt 360
            html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
361
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
362
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
363
            total_amount += lineitem_total_price
1262 varun.gupt 364
            html_table += html_tr
2050 varun.gupt 365
 
1262 varun.gupt 366
    html_footer = """
367
        <tr><td colspan=5>&nbsp;</td></tr>
1565 varun.gupt 368
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 369
        <tr>
370
            <td colspan=4>Total Amount</td>
2050 varun.gupt 371
            <td> Rs. $total_amount</td>
1262 varun.gupt 372
        </tr>
373
        </table>
1569 varun.gupt 374
    </div>
1262 varun.gupt 375
    <p>
376
        Best Wishes,<br />
377
        Saholic Team
378
    </p>
379
</div>
380
</body>
381
</html>
382
    """
1398 varun.gupt 383
 
1569 varun.gupt 384
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 385
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
386
 
1262 varun.gupt 387
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date))
2050 varun.gupt 388
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount))
1262 varun.gupt 389
 
1351 varun.gupt 390
    try:
391
        helper_client = HelperClient().get_client()
1398 varun.gupt 392
        helper_client.saveUserEmailForSending(user_email, "", "Saholic - Order Details", email_header + html_table + email_footer, str(transaction_id), "TransactionInfo")
1351 varun.gupt 393
        return True
394
    except Exception as e:
395
        print e
396
        return False
1262 varun.gupt 397
 
483 rajveer 398
def get_order(order_id):
399
    order = Order.get_by(id=order_id)
400
    if not order:
401
        raise TransactionServiceException(108, "no such order")
402
 
403
    return order
404
 
3014 chandransh 405
def get_orders_for_customer(customer_id, from_date, to_date, statuses):
483 rajveer 406
    if not customer_id:
407
        raise TransactionServiceException(101, "bad customer id")
408
    query = Order.query.filter(Order.customer_id == customer_id)
3014 chandransh 409
    if statuses:
410
        query = query.filter(Order.status.in_(tuple(statuses)))
483 rajveer 411
    if from_date:
412
        query = query.filter(Order.created_timestamp >from_date)
413
    if to_date:
414
        query = query.filter(Order.created_timestamp < to_date)
415
    return query.all()
416
 
1528 ankur.sing 417
def get_order_for_customer(order_id, customer_id):
418
    if not customer_id:
419
        raise TransactionServiceException(101, "bad customer id")
420
    order = get_order(order_id)
421
    if order.customer_id != customer_id:
422
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
423
    return order
424
 
483 rajveer 425
def get_all_orders(status, from_date, to_date, warehouse_id):
426
    if not warehouse_id:
427
        raise TransactionServiceException(101, "bad warehouse id")
428
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
429
    if status:
430
        query = query.filter(Order.status == status)
431
    if from_date:
432
        query = query.filter(Order.created_timestamp >from_date)
433
    if to_date:
434
        query = query.filter(Order.created_timestamp < to_date)
435
    return query.all()
436
 
4133 chandransh 437
def get_orders_in_batch(statuses=[], offset=0, limit=0, warehouse_id=None):
4296 rajveer 438
    query = Order.query
439
    if warehouse_id:
440
        query = query.filter(Order.warehouse_id == warehouse_id)
4133 chandransh 441
    if statuses:
442
        query = query.filter(Order.status.in_(statuses))
443
    query = query.offset(offset)
444
    if limit:
445
        query = query.limit(limit)
446
    return query.all()
447
 
448
def get_order_count(statuses=[], warehouse_id=None):
449
    if not warehouse_id:
450
        raise TransactionServiceException(101, "bad warehouse id")
451
    query = session.query(func.count(Order.id)).filter(Order.warehouse_id == warehouse_id)
452
    if statuses:
453
        query = query.filter(Order.status.in_(statuses))
454
    return query.scalar()
455
 
1382 varun.gupt 456
def get_returnable_orders_for_customer(customer_id, limit = None):
457
    if not customer_id:
458
        raise TransactionServiceException(101, "bad customer id")
459
 
460
    query = Order.query.filter(Order.customer_id == customer_id)
461
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
462
    query = query.filter(Order.status != OrderStatus.REJECTED)
463
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
464
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
465
    orders = query.all()
466
    order_ids = [order.id for order in orders]
467
    return order_ids
468
 
469
def get_cancellable_orders_for_customer(customer_id, limit = None):
470
    if not customer_id:
471
        raise TransactionServiceException(101, "bad customer id")
472
 
473
    query = Order.query.filter(Order.customer_id == customer_id)
4343 varun.gupt 474
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
1382 varun.gupt 475
    query = query.filter(Order.status != OrderStatus.REJECTED)
4288 anupam.sin 476
    query = query.filter(Order.status <= OrderStatus.BILLED)
1382 varun.gupt 477
    orders = query.all()
478
    return [order.id for order in orders]
479
 
995 varun.gupt 480
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
481
    if not warehouse_id:
482
        raise TransactionServiceException(101, "bad warehouse id")
483
 
484
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
485
 
486
    if status:
487
        query = query.filter(Order.status == status)
488
 
489
    if start_billing_date:
490
        query = query.filter(Order.billing_timestamp >= start_billing_date)
491
 
492
    if end_billing_date:
493
        query = query.filter(Order.billing_timestamp <= end_billing_date)
494
 
495
    return query.all()
496
 
3451 chandransh 497
def get_orders_by_shipping_date(from_shipping_date, to_shipping_date, provider_id, warehouse_id, cod):
498
    query = Order.query.filter(Order.cod == cod)
3427 chandransh 499
 
500
    if warehouse_id and warehouse_id != -1:
501
        query = query.filter(Order.warehouse_id == warehouse_id)
502
 
503
    if provider_id and provider_id != -1:
504
        query = query.filter(Order.logistics_provider_id == provider_id)
505
 
506
    if from_shipping_date:
507
        query = query.filter(Order.shipping_timestamp >= from_shipping_date)
508
 
509
    if to_shipping_date:
510
        query = query.filter(Order.shipping_timestamp <= to_shipping_date)
511
 
512
    query = query.order_by(Order.airwaybill_no)
513
 
514
    return query.all()
515
 
1528 ankur.sing 516
def get_orders_for_transaction(transaction_id, customer_id):
517
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
518
 
1208 chandransh 519
    if not orders:
520
        raise TransactionServiceException(101, "No order for the transaction")
521
    return orders
522
 
1405 ankur.sing 523
def get_undelivered_orders(provider_id, warehouse_id):
524
    query = Order.query
525
    if provider_id != -1:
526
        query = query.filter_by(Order.logistics_provider_id == provider_id)
527
    if warehouse_id != -1:
528
        query = query.filter(Order.warehouse_id == warehouse_id)
529
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
530
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 531
    #Get last midnight time instead of current time as courier company would have sent the 
532
    #delivery records updated at least till midnight and not by the current time.
533
    time_format = "%Y-%m-%d %H:%M:%S.%f"
534
    t = time.strptime(str(datetime.datetime.now()), time_format)
535
    midnightTime = datetime.datetime(*t[:3])
536
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 537
    orders = query.all()
538
    return orders
539
 
1208 chandransh 540
def get_line_items_for_order(order_id):
541
    query = LineItem.query.filter(LineItem.order_id == order_id)
542
    return query.all()
543
 
483 rajveer 544
def change_order_status(self, orderId, status, description):
545
    order = get_order(orderId)
546
    order.status = status
547
    order.statusDescription = description
548
    session.commit()
3578 mandeep.dh 549
    update_trust_level(order)
550
    return True
3499 mandeep.dh 551
 
3578 mandeep.dh 552
def update_trust_level(order):
3530 mandeep.dh 553
    try:
3578 mandeep.dh 554
        trust_level_delta = 0
555
        if order.cod == True:
556
            trust_level_delta = ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT.get(order.status, 0)
557
 
3530 mandeep.dh 558
        if (trust_level_delta != 0):
559
            user_client = UserClient().get_client()
560
            user_client.increaseTrustLevel(order.customer_id, trust_level_delta)
561
    except Exception as e:
562
        print e
3499 mandeep.dh 563
 
483 rajveer 564
    return True
3064 chandransh 565
 
566
def verify_order(self, orderId):
567
    logging.info("Verifying order no: " + str(orderId))
568
    order = get_order(orderId)
569
    if order.status == OrderStatus.INIT:
570
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
571
        order.statusDescription = "Submitted for processing"
572
        order.verification_timestamp = datetime.datetime.now()
573
        session.commit()
574
        logging.info("Successfully verified order no: " + str(orderId))
575
        return True
576
    else:
577
        logging.warning("Verify called for order no." + str(orderId) +" which is not in verification pending state");
578
        return False
579
 
4285 rajveer 580
def accept_order(orderId):
3064 chandransh 581
    logging.info("Accepting order no: " + str(orderId))
921 rajveer 582
    order = get_order(orderId)
4306 rajveer 583
    if order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT]:
3064 chandransh 584
        if not order.cod:
585
            if order.transaction.status == TransactionStatus.AUTHORIZED:
4421 mandeep.dh 586
                __capture_txn(order)
3010 chandransh 587
        order.status = OrderStatus.ACCEPTED
588
        order.statusDescription = "Order Accepted"
589
        order.accepted_timestamp = datetime.datetime.now()
590
        session.commit()
3064 chandransh 591
        logging.info("Successfully accepted the order no.:" + str(orderId))
3010 chandransh 592
        return True
593
    else:
3064 chandransh 594
        logging.warning("Accept called for the unacceptable order: " + str(orderId))
3010 chandransh 595
        return False
921 rajveer 596
 
4421 mandeep.dh 597
def __capture_txn(order):
598
    txnId = order.transaction_id
3010 chandransh 599
    logging.info("Capturing payment for merchant txn:" + str(txnId))
4421 mandeep.dh 600
    try:
601
        payment_client = PaymentClient().get_client()
602
        capture_result = payment_client.capturePayment(txnId)
603
        if capture_result:
604
            logging.info("Successfully captured payment for merchant txn:" + str(txnId))
605
            change_transaction_status(txnId, TransactionStatus.IN_PROCESS, "Payment received")
606
        else:
607
            raise TransactionServiceException(115, "Payment capture failed.")
608
    except PaymentException as e:
609
        if e.error_code == 106:
610
            order.status = OrderStatus.CAPTURE_IN_PROCESS
611
            session.commit()
612
            raise TransactionServiceException(122, "Unable to capture payment due to connection issue.")
613
        else:
614
            raise TransactionServiceException(115, "Payment capture failed.")
3010 chandransh 615
 
4285 rajveer 616
def add_billing_details(orderId, invoice_number, imeiNumber, itemNumber, billedBy, jacketNumber, billingType, vendorId):
617
    if jacketNumber is None or jacketNumber <= 0:
2783 chandransh 618
        raise TransactionServiceException(110, "Invalid jacket number")
619
 
4285 rajveer 620
    if billedBy is None or billedBy.strip() == "":
2783 chandransh 621
        raise TransactionServiceException(110, "Invalid Biller")
622
 
1149 chandransh 623
    order = Order.get_by(id=orderId)
624
    if not order:
2783 chandransh 625
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
626
 
4283 anupam.sin 627
    if order.status == OrderStatus.ACCEPTED:
4285 rajveer 628
        order.jacket_number = jacketNumber
629
        if billingType == BillingType.OURS:
630
            if itemNumber is None or itemNumber.strip() == "":
4283 anupam.sin 631
                raise TransactionServiceException(110, "Invalid item number")
632
 
633
            order.invoice_number = get_next_invoice_number()
634
            lineitem = order.lineitems[0]
4285 rajveer 635
            if lineitem.productGroup == "Handsets" and imeiNumber <= 0:
4283 anupam.sin 636
                raise TransactionServiceException(110, "No IMEI number supplied for a handset.")
4285 rajveer 637
            lineitem.item_number = itemNumber
638
            if imeiNumber > 0:
639
                lineitem.imei_number = str(imeiNumber)
4283 anupam.sin 640
        else:
641
            order.invoice_number = invoice_number
642
 
2842 chandransh 643
        order.status = OrderStatus.BILLED
644
        order.statusDescription = "Order Billed"
645
        order.billing_timestamp = datetime.datetime.now()
4285 rajveer 646
        order.billed_by = billedBy
2842 chandransh 647
        lineitem = order.lineitems[0]
4283 anupam.sin 648
        item_id = lineitem.item_id
4435 mandeep.dh 649
 
650
        # Not letting the billing process fail in cases where we are unable to 
651
        # fill in transfer price
652
        item_pricing = None
653
        try:
654
            catalog_client = CatalogClient().get_client()
655
            item_pricing = catalog_client.getItemPricing(item_id, vendorId)
656
        except InventoryServiceException as e:
657
            print sys.exc_info()[0]
658
            print e.message
659
 
4285 rajveer 660
        order.vendorId = vendorId
4283 anupam.sin 661
        lineitems = order.lineitems
662
        for lineitem in lineitems:
663
            catalog_client.reduceReservationCount(item_id, order.warehouse_id, lineitem.quantity)
4435 mandeep.dh 664
 
665
        # Putting NULL as transfer price for cases where its missing
4541 mandeep.dh 666
        if item_pricing is not None:
4435 mandeep.dh 667
            order.lineitems[0].transfer_price = item_pricing.transferPrice
4365 mandeep.dh 668
 
669
        # For Mahipal warehouse, we need to scan out items for every billed order
4576 mandeep.dh 670
        if order.warehouse_id == 7:
4365 mandeep.dh 671
            try:
672
                warehouse_client = WarehouseClient().get_client()
4554 mandeep.dh 673
                inventoryItem = warehouse_client.scanSerializedItemForOrder(str(imeiNumber), ScanType.SALE, orderId, order.warehouse_id)
4541 mandeep.dh 674
                if (inventoryItem.itemId != item_id):
675
                    item = catalog_client.getItem(inventoryItem.itemId)
676
                    lineitem = order.lineitems[0]
677
                    scanItemString = " ".join([item.brand, item.modelName, item.modelNumber, item.color])
678
                    lineItemString = " ".join([lineitem.brand, lineitem.model_name, lineitem.model_number, lineitem.color])
679
                    raise TransactionServiceException(110, 'Trying to scan ' + scanItemString + ' instead of ' + lineItemString)
4554 mandeep.dh 680
                lineitem.transfer_price = inventoryItem.unitPrice
681
                order.vendorId = inventoryItem.supplierId
4541 mandeep.dh 682
            except WarehouseServiceException as e:
4365 mandeep.dh 683
                print sys.exc_info()[0]
4541 mandeep.dh 684
                print 'Could not scan out orders due to: ' + e.message
685
                if e.exceptionType == ExceptionType.ILLEGAL_ARGUMENTS:
686
                    raise TransactionServiceException(110, e.message)
4365 mandeep.dh 687
 
4541 mandeep.dh 688
        session.commit()
4283 anupam.sin 689
        return True
690
    else:
691
        return False
1149 chandransh 692
 
4579 rajveer 693
def add_invoice_number(orderId, invoiceNumber):
694
    order = Order.get_by(id=orderId)
695
    if not order:
696
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
697
 
698
    if order.status == OrderStatus.ACCEPTED:
699
        order.invoice_number = invoiceNumber
700
    session.commit()
701
 
1220 chandransh 702
def batch_orders(warehouseId):
703
    if not warehouseId:
704
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 705
 
706
    batchno_generator = BatchNoGenerator()
707
    session.commit()
1220 chandransh 708
    query = Order.query.filter_by(warehouse_id=warehouseId)
4592 mandeep.dh 709
    query = query.filter(Order.status == OrderStatus.LOW_INV_PO_RAISED)
1220 chandransh 710
    query = query.order_by(Order.created_timestamp)
711
    pending_orders = query.all()
1225 chandransh 712
 
1220 chandransh 713
    serial_no = 1
714
    for order in pending_orders:
1276 chandransh 715
        order.batchNo = batchno_generator.id
1220 chandransh 716
        order.serialNo = serial_no
717
        serial_no += 1
718
    session.commit() 
719
    pending_orders = query.all()
720
    return pending_orders
721
 
722
def order_outofstock(orderId):
1911 chandransh 723
    '''
724
    Mark order as out of stock
725
    '''
1220 chandransh 726
    order = get_order(orderId)
727
    order.status = OrderStatus.INVENTORY_LOW
728
    order.statusDescription = "Low Inventory"
729
    order.outofstock_timestamp = datetime.datetime.now()
730
    session.commit()
731
    return True
732
 
3064 chandransh 733
def mark_orders_as_manifested(warehouse_id, provider_id, cod):
759 chandransh 734
    try:
3064 chandransh 735
        orders = Order.query.filter_by(warehouse_id = warehouse_id, logistics_provider_id = provider_id, status = OrderStatus.BILLED, cod = cod).all()
759 chandransh 736
        for order in orders:
4410 rajveer 737
            order.status = OrderStatus.MANIFESTED
738
            order.statusDescription = "Order manifested"
739
        session.commit()
740
        return True
741
    except:
742
        return False
743
 
744
def mark_orders_as_shipped_from_warehouse(warehouse_id, provider_id, cod):
745
    try:
746
        current_timestamp = datetime.datetime.now()
747
        orders = Order.query.filter_by(warehouse_id = warehouse_id, logistics_provider_id = provider_id, status = OrderStatus.MANIFESTED, cod = cod).all()
748
        for order in orders:
759 chandransh 749
            order.status = OrderStatus.SHIPPED_FROM_WH
987 chandransh 750
            order.statusDescription = "Order shipped from warehouse"
986 chandransh 751
            order.shipping_timestamp = current_timestamp
759 chandransh 752
        session.commit()
753
        return True
754
    except:
755
        return False
4410 rajveer 756
 
1113 chandransh 757
def mark_orders_as_picked_up(provider_id, pickup_details):
758
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 759
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 760
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 761
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
762
            continue
1113 chandransh 763
        order.status = OrderStatus.SHIPPED_TO_LOGST
764
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 765
        order.pickup_timestamp = pickup_timestamp
1113 chandransh 766
    session.commit()
1217 chandransh 767
 
1132 chandransh 768
    current_time = datetime.datetime.now()
769
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1246 chandransh 770
    from_datetime = to_datetime - datetime.timedelta(2)
1132 chandransh 771
    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 772
    return orders_not_picked_up
773
 
1132 chandransh 774
def mark_orders_as_delivered(provider_id, delivered_orders):
775
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 776
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 777
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1911 chandransh 778
            continue
779
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1132 chandransh 780
        order.status = OrderStatus.DELIVERY_SUCCESS
781
        order.statusDescription = "Order delivered"
782
        order.delivery_timestamp, order.receiver = detail.split('|')
3578 mandeep.dh 783
        update_trust_level(order)
1132 chandransh 784
    session.commit()
785
 
1135 chandransh 786
def mark_orders_as_failed(provider_id, returned_orders):
787
    for awb, detail in returned_orders.iteritems():
788
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 789
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
790
            continue
791
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 792
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 793
        order.delivery_timestamp, reason = detail.split('|')
794
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 795
        update_trust_level(order)
1911 chandransh 796
    session.commit()
1135 chandransh 797
 
1246 chandransh 798
def update_non_delivery_reason(provider_id, undelivered_orders):
799
    for awb, reason in undelivered_orders.iteritems():
800
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
801
        if order == None:
2684 chandransh 802
            continue
803
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 804
        order.statusDescription = reason
805
    session.commit()
4581 phani.kuma 806
 
807
    current_time = datetime.datetime.now()
808
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
809
    upto_datetime = today_datetime - datetime.timedelta(4)
810
    orders_not_delivered = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST))).filter(or_(Order.shipping_timestamp <= upto_datetime, Order.pickup_timestamp <= upto_datetime)).all()
811
    return orders_not_delivered
1246 chandransh 812
 
4444 rajveer 813
def get_alerts(type, warehouseId, status, timestamp):
814
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
815
    if type != -1 :
816
        query = query.filter(Alert.type == type)
817
    if status != -1 :
818
        query = query.filter(Alert.status == status)
4394 rajveer 819
    if timestamp:
820
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 821
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 822
    return query.all()
823
 
4447 rajveer 824
def add_alert(type, warehouseId, description):
4394 rajveer 825
    alert = Alert()
826
    alert.type = type
827
    alert.status = 1
828
    alert.description = description
829
    alert.timestamp = datetime.datetime.now()
4447 rajveer 830
    alert.warehouseId = warehouseId
4444 rajveer 831
    session.commit()
766 rajveer 832
 
4444 rajveer 833
def mark_alerts_as_seen(warehouseId):
834
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
835
    alerts = query.all()
836
    for alert in alerts:
837
        alert.status = 0    
838
    session.commit()
839
 
1596 ankur.sing 840
def get_valid_order_count():
2851 chandransh 841
    '''
842
    Returns the number of orders which we processed. The reshipped orders are not
843
    counted since there'll always be a new compensating order present.
844
    '''
4484 rajveer 845
    return Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).filter(not_(Order.status.in_((OrderStatus.RTO_RESHIPPED, OrderStatus.DOA_INVALID_RESHIPPED, OrderStatus.DOA_VALID_RESHIPPED, OrderStatus.CANCELED)))).count()
1596 ankur.sing 846
 
1627 ankur.sing 847
def get_cust_count_with_successful_txn():
2851 chandransh 848
    '''
849
    Returns the number of distinct customers who have done successful transactions.
850
    It uses the sqlalchemy func module to construct an efficient query.
851
    '''
852
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 853
 
1730 ankur.sing 854
def get_valid_orders_amount_range():
2851 chandransh 855
    '''
856
    Returns a list containing the minimum and maximum amount across all
857
    orders placed with us. No need to consider reshippped orders for min/max
858
    amount of orders.
859
    '''
860
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 861
 
1886 ankur.sing 862
def get_valid_orders(limit):
2851 chandransh 863
    '''
864
    Returns the last limit number of valid orders placed with us. Ignored the
865
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
866
    less than 0. 
867
    '''
868
    if limit < 0:
869
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
3072 chandransh 870
    query = Order.query.filter(Order.status >= OrderStatus.INIT)
1886 ankur.sing 871
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 872
    if limit != 0:
1886 ankur.sing 873
        query = query.limit(limit)
874
    return query.all()
875
 
2783 chandransh 876
def get_next_invoice_number():
877
    entity_id = InvoiceIDGenerator.query.with_lockmode("update").one()
878
    invoice_number = entity_id.id + 1
879
    entity_id.id = invoice_number
880
    return invoice_number
881
 
2536 chandransh 882
def toggle_doa_flag(order_id):
883
    order = get_order(order_id)
884
    if(order.doaFlag):
885
        order.doaFlag = False
886
    else:
887
        order.doaFlag = True
888
    session.commit()
889
    return order.doaFlag
890
 
4454 rajveer 891
def mark_order_doa_request_received(orderId):
892
    order = get_order(orderId)
893
    if order.status != OrderStatus.DELIVERY_SUCCESS:
894
        return False
895
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 896
    order.statusDescription = "DOA Request Received"
4454 rajveer 897
    session.commit()
898
    return True
899
 
900
def mark_order_doa_request_authorized(orderId, isAuthorized):
901
    order = get_order(orderId)
902
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
903
        return False
904
    if isAuthorized:
905
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 906
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 907
    else:
908
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 909
        order.statusDescription = "Order delivered"
4454 rajveer 910
    session.commit()
911
    return True
912
 
4488 rajveer 913
def mark_order_return_request_received(orderId):
914
    order = get_order(orderId)
915
    if order.status != OrderStatus.DELIVERY_SUCCESS:
916
        return False
917
    order.status = OrderStatus.RET_REQUEST_RECEIVED
918
    order.statusDescription = "Return Request Received"
919
    session.commit()
920
    return True
921
 
922
def mark_order_return_request_authorized(orderId, isAuthorized):
923
    order = get_order(orderId)
924
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
925
        return False
926
    if isAuthorized:
927
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
928
        order.statusDescription = "Return Request Authorized"
929
    else:
930
        order.status = OrderStatus.DELIVERY_SUCCESS
931
        order.statusDescription = "Order delivered"
932
    session.commit()
933
    return True
934
 
4579 rajveer 935
def request_pickup_number(order_id, providerId):
2536 chandransh 936
    order = get_order(order_id)
4495 rajveer 937
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 938
        return False
939
    from_user = 'cnc.center@shop2020.in'
940
    from_pwd = '5h0p2o2o'
941
 
4227 rajveer 942
    subject = "Pickup request from " + order.customer_city
2536 chandransh 943
    try:
3133 rajveer 944
        catalog_client = CatalogClient().get_client()
2536 chandransh 945
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
946
 
947
        logistics_client = LogisticsClient().get_client()
4579 rajveer 948
        provider = logistics_client.getProvider(providerId)
3051 chandransh 949
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 950
        raw_message = '''
951
        Dear Sir/Madam,
952
 
2559 chandransh 953
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 954
 
955
        Pickup CODE: %(provider_code)s
956
        Total Weight: %(order_weight)s kg
957
 
2559 chandransh 958
        Pickup Address:
2536 chandransh 959
 
960
        %(customer_address)s
961
 
962
        Delivery Address:
963
 
964
        %(warehouse_executive)s
965
        %(warehouse_address)s
966
        PIN %(warehouse_pin)s
967
        Phone: %(warehouse_phone)s
968
 
969
        Thanks and Regards
4227 rajveer 970
        Sandeep Sachdeva
2536 chandransh 971
        '''
4579 rajveer 972
 
973
        if warehouse.id == 7:
974
            executive = 'Amit Kumar'
975
            executive_phone = '9911122634'
976
        else:
977
            executive = 'Prashant Sharma'
978
            executive_phone = '8826894193'
979
 
980
 
2559 chandransh 981
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 982
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
2536 chandransh 983
                                          'order_weight' : str(order.total_weight),
984
                                          'customer_address' : __get_order_address(order),
4579 rajveer 985
                                          'warehouse_executive' : executive,
2536 chandransh 986
                                          'warehouse_address' : warehouse.location,
987
                                          'warehouse_pin' : warehouse.pincode,
4579 rajveer 988
                                          'warehouse_phone': executive_phone}
4227 rajveer 989
        #FIXME Email is hardcoded for bluedart
990
        mail(from_user, from_pwd, [to_addr, 'sonikap@bluedart.com'], subject, message)
4495 rajveer 991
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
992
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
993
            order.statusDescription = "Pick up requested for RETURN"
994
        else:
995
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
996
            order.statusDescription = "Pick up requested for DOA"
2536 chandransh 997
        session.commit()
998
        return True
999
    except Exception as e:
1000
        print sys.exc_info()[0]
1001
        return False
1002
 
1003
def authorize_pickup(order_id, pickup_number):
1004
    order = get_order(order_id)
4495 rajveer 1005
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 1006
        return False
1007
    from_user = 'help@shop2020.in'
1008
    from_pwd = '5h0p2o2o'
1009
    subject = 'Pickup details'
1010
    filename = "/tmp/" +  str(order.id) +".pdf" 
1011
    try:
3133 rajveer 1012
        catalog_client = CatalogClient().get_client()
2536 chandransh 1013
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1014
 
1015
        logistics_client = LogisticsClient().get_client()
1016
        provider = logistics_client.getProvider(order.logistics_provider_id)
1017
        provider_name = provider.name
1018
 
1019
        to_addr = order.customer_email
1020
        today = date.today().strftime("%d-%B-%Y (%A)")
1021
 
1022
        raw_message = '''
1023
        Dear Mr. %(customer_name)s,
1024
 
4495 rajveer 1025
        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 (in case of DOA) and the invoice.
2536 chandransh 1026
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
1027
        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.
1028
 
1029
        Pickup will happen from the below mentioned address:-
1030
 
1031
        %(customer_address)s
1032
 
1033
        Do let us know in case of any concerns
1034
 
1035
        Thanks & Regards
1036
        Saholic Team
1037
        '''
1038
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
1039
                                         'order_id' : order_id,
1040
                                         'provider_name' : provider_name,
1041
                                         'date': today,
1042
                                         'pickup_request_no' : pickup_number,
1043
                                         'customer_address' : __get_order_address(order)}
1044
        print message
1045
        __generate_return_advice(order, warehouse, provider, filename)
3527 chandransh 1046
        mail(from_user, from_pwd, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 1047
        order.pickupRequestNo = pickup_number
4495 rajveer 1048
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1049
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
1050
            order.statusDescription = "RETURN pick up confirmed"
1051
        else:
1052
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
1053
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 1054
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 1055
        session.commit()
1056
        return True
1057
    except Exception as e:
4234 rajveer 1058
        print sys.exc_info()
4506 phani.kuma 1059
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 1060
        return False
1061
    finally:
1062
        if os.path.exists(filename):
1063
            os.remove(filename)
1064
 
2764 chandransh 1065
def mark_doas_as_picked_up(provider_id, pickup_details):
1066
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
1067
        order = Order.query.filter_by(pickupRequestNo=pickupNo, logistics_provider_id = provider_id).first()
4452 rajveer 1068
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 1069
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1070
            continue
1071
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
1072
        order.statusDescription = "DOA picked up by Courier Company"
1073
        order.doa_pickup_timestamp = doa_pickup_timestamp
1074
    session.commit()
1075
 
1076
    current_time = datetime.datetime.now()
1077
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1078
    from_datetime = to_datetime - datetime.timedelta(2)
4452 rajveer 1079
    orders_not_picked_up = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.DOA_PICKUP_CONFIRMED).filter(Order.doa_auth_timestamp >= from_datetime).filter(Order.doa_auth_timestamp <= to_datetime).all()
2764 chandransh 1080
    return orders_not_picked_up
1081
 
4479 rajveer 1082
def receive_return(order_id, receiveCondition):
2591 chandransh 1083
    order = get_order(order_id)
4365 mandeep.dh 1084
 
1085
    # FIXME: For Mahipal warehouse, we need to scan in items for every sales return
4576 mandeep.dh 1086
    if order.warehouse_id == 7:
4365 mandeep.dh 1087
        try:
1088
            warehouse_client = WarehouseClient().get_client()
1089
            lineitem = order.lineitems[0]
1090
 
1091
            # Inventory should not be updated for DOA returns 
4484 rajveer 1092
            if order.status == OrderStatus.RTO_IN_TRANSIT:
4555 mandeep.dh 1093
                warehouse_client.scanSerializedItemForOrder(str(lineitem.imei_number), ScanType.SALE_RET, order.id, order.warehouse_id)
1094
                # In case of RTOs increasing availibility only if we receive item in prestine state
1095
                if not receiveCondition:
1096
                    catalog_client = CatalogClient().get_client()
1097
                    catalog_client.addInventory(lineitem.item_id, order.warehouse_id, lineitem.quantity)
4452 rajveer 1098
            elif order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4555 mandeep.dh 1099
                warehouse_client.scanSerializedItemForOrder(str(lineitem.imei_number), ScanType.DOA_IN, order.id, order.warehouse_id)
4365 mandeep.dh 1100
        except:
1101
            print sys.exc_info()[0]
1102
            print 'Could not scan in sales return orders'
1103
 
4452 rajveer 1104
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 1105
        if receiveCondition == 0:
1106
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
1107
            order.statusDescription = "DOA package received"
1108
        elif receiveCondition == 1:
1109
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
1110
            order.statusDescription = "DOA received damaged"
1111
        elif receiveCondition == 2:
1112
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
1113
            order.statusDescription = "DOA lost in transit"
2764 chandransh 1114
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1115
        session.commit()
4495 rajveer 1116
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
1117
        if receiveCondition == 0:
1118
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
1119
            order.statusDescription = "RETURN package received"
1120
        elif receiveCondition == 1:
1121
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
1122
            order.statusDescription = "RETURN received damaged"
1123
        elif receiveCondition == 2:
1124
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
1125
            order.statusDescription = "RETURN lost in transit"
1126
        order.received_return_timestamp = datetime.datetime.now()
1127
        session.commit()
4484 rajveer 1128
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 1129
        if receiveCondition == 0:
1130
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 1131
            order.statusDescription = "Returned to origin"
4486 rajveer 1132
        elif receiveCondition == 1:
1133
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
1134
            order.statusDescription = "RTO received damaged"
1135
        elif receiveCondition == 2:
1136
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
1137
            order.statusDescription = "RTO lost in transit"
2764 chandransh 1138
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1139
        session.commit()
1140
    else:
2591 chandransh 1141
        return False
1142
    return True
1143
 
1144
def validate_doa(order_id, is_valid):
1145
    order = get_order(order_id)
4452 rajveer 1146
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 1147
        return False
1148
    if is_valid:
2609 chandransh 1149
        order.status = OrderStatus.DOA_CERT_VALID
1150
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 1151
    else:
1152
        order.status = OrderStatus.DOA_CERT_INVALID
1153
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 1154
        update_trust_level(order)
2591 chandransh 1155
    session.commit()
1156
    return True
1157
 
4495 rajveer 1158
def validate_return_product(order_id, is_usable):
1159
    order = get_order(order_id)
1160
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
1161
        return False
1162
    if is_usable:
1163
        order.status = OrderStatus.RET_PRODUCT_USABLE
1164
        order.statusDescription = "Return product usable"
4555 mandeep.dh 1165
        lineitem = order.lineitems[0]
4576 mandeep.dh 1166
        if order.warehouse_id == 7:
4555 mandeep.dh 1167
            catalog_client = CatalogClient().get_client()
1168
            catalog_client.addInventory(lineitem.item_id, order.warehouse_id, lineitem.quantity)
4495 rajveer 1169
    else:
1170
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
1171
        order.statusDescription = "Return product unusable"
1172
        update_trust_level(order)
1173
    session.commit()
1174
    return True
1175
 
2628 chandransh 1176
def reship_order(order_id):
1177
    """
4484 rajveer 1178
    If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1179
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
4484 rajveer 1180
        2. Marks the current order as one of the final states RTO_RESHIPPED and DOA_INVALID_RESHIPPED depending on what state the order started in.
2628 chandransh 1181
 
1182
    If the order is in DOA_CERT_VALID state, it does the following:
1183
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
1184
        2. Creates a return order for the warehouse executive to return the DOA material.
4452 rajveer 1185
        3. Marks the current order as the final DOA_VALID_RESHIPPED state.
2628 chandransh 1186
 
1187
    Returns the id of the newly created order.
1188
 
1189
    Throws an exception if the order with the given id couldn't be found.
1190
 
1191
    Parameters:
1192
     - orderId
1193
    """
1194
    order = get_order(order_id)
4484 rajveer 1195
    if order.status == OrderStatus.RTO_RECEIVED_PRESTINE:
4220 rajveer 1196
        new_order = __clone_order(order, True, order.cod)
4484 rajveer 1197
        order.status = OrderStatus.RTO_RESHIPPED
2628 chandransh 1198
        order.statusDescription = "Order Reshipped"
1199
        session.commit()
3578 mandeep.dh 1200
        update_trust_level(order)
4486 rajveer 1201
    elif order.status == OrderStatus.RTO_RECEIVED_DAMAGED:
1202
        new_order = __clone_order(order, False, order.cod)
1203
        ret_order = __create_return_order(order)
1204
        order.status = OrderStatus.RTO_DAMAGED_RESHIPPED
1205
        order.statusDescription = "Order Reshipped Received Damaged"
1206
        session.commit()
1207
    elif order.status == OrderStatus.RTO_LOST_IN_TRANSIT:
1208
        new_order = __clone_order(order, False, order.cod)
1209
        order.status = OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED
1210
        order.statusDescription = "Order Reshipped Lost In Transit"
1211
        session.commit()
2628 chandransh 1212
    elif order.status == OrderStatus.DOA_CERT_INVALID:
4220 rajveer 1213
        new_order = __clone_order(order, True, False)
2628 chandransh 1214
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
1215
        order.statusDescription = "Order Reshipped"
1216
        session.commit()
1217
    elif order.status == OrderStatus.DOA_CERT_VALID:
4220 rajveer 1218
        new_order = __clone_order(order, False, False)
2628 chandransh 1219
        ret_order = __create_return_order(order)
4452 rajveer 1220
        order.status = OrderStatus.DOA_VALID_RESHIPPED
2628 chandransh 1221
        order.statusDescription = "Order Reshipped"
1222
        session.commit()
4479 rajveer 1223
    elif order.status == OrderStatus.DOA_RECEIVED_DAMAGED:
1224
        new_order = __clone_order(order, False, False)
1225
        ret_order = __create_return_order(order)
1226
        order.status = OrderStatus.DOA_RESHIPPED_RCVD_DAMAGED
1227
        order.statusDescription = "Order Reshipped Received Damaged"
1228
        session.commit()
1229
    elif order.status == OrderStatus.DOA_LOST_IN_TRANSIT:
1230
        new_order = __clone_order(order, False, False)
1231
        order.status = OrderStatus.DOA_RESHIPPED_LOST_IN_TRANSIT
1232
        order.statusDescription = "Order Reshipped Lost In Transit"
1233
        session.commit()
4495 rajveer 1234
    elif order.status == OrderStatus.RET_PRODUCT_UNUSABLE:
1235
        new_order = __clone_order(order, True, False)
1236
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE_RESHIPPED
1237
        order.statusDescription = "Order Reshipped"
1238
        session.commit()
1239
    elif order.status == OrderStatus.RET_PRODUCT_USABLE:
1240
        new_order = __clone_order(order, False, False)
1241
        ret_order = __create_return_order(order)
1242
        order.status = OrderStatus.RET_PRODUCT_USABLE_RESHIPPED
1243
        order.statusDescription = "Order Reshipped"
1244
        session.commit()
1245
    elif order.status == OrderStatus.RET_RECEIVED_DAMAGED:
1246
        new_order = __clone_order(order, False, False)
1247
        ret_order = __create_return_order(order)
1248
        order.status = OrderStatus.RET_RESHIPPED_RCVD_DAMAGED
1249
        order.statusDescription = "Order Reshipped Received Damaged"
1250
        session.commit()
1251
    elif order.status == OrderStatus.RET_LOST_IN_TRANSIT:
1252
        new_order = __clone_order(order, False, False)
1253
        order.status = OrderStatus.RET_RESHIPPED_LOST_IN_TRANSIT
1254
        order.statusDescription = "Order Reshipped Lost In Transit"
1255
        session.commit()
2628 chandransh 1256
    else:
1257
        raise TransactionServiceException(112, "This order can't be reshipped")
1258
 
2764 chandransh 1259
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 1260
    order.new_order_id = new_order.id
1261
    session.commit()
1262
 
1263
    return new_order.id
1264
 
3226 chandransh 1265
def refund_order(order_id, refunded_by, reason):
2628 chandransh 1266
    """
4484 rajveer 1267
    If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1268
        1. Creates a refund request for batch processing.
1269
        2. Creates a return order for the warehouse executive to return the shipped material.
4484 rajveer 1270
        3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2628 chandransh 1271
 
1272
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
1273
        1. Creates a refund request for batch processing.
3226 chandransh 1274
        2. Cancels the reservation of the item in the warehouse.
1275
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 1276
 
3226 chandransh 1277
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
1278
        1. Cancels the reservation of the item in the warehouse.
1279
        2. Marks the current order as CANCELED.
1280
 
1281
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
1282
 
1283
    Returns True if it is successful, False otherwise.
2628 chandransh 1284
 
1285
    Throws an exception if the order with the given id couldn't be found.
1286
 
1287
    Parameters:
3226 chandransh 1288
     - order_id
1289
     - refunded_by
1290
     - reason
2628 chandransh 1291
    """
3414 chandransh 1292
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 1293
    order = get_order(order_id)
3186 chandransh 1294
 
1295
 
3366 chandransh 1296
 
3226 chandransh 1297
    if order.cod:
3414 chandransh 1298
        logging.info("Refunding COD order with status " + str(order.status))
4484 rajveer 1299
        status_transition = {OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 1300
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
1301
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 1302
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
1303
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 1304
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
1305
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 1306
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
1307
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
1308
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
1309
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
3366 chandransh 1310
                     OrderStatus.INIT : OrderStatus.CANCELED,
1311
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELED,
1312
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELED,
4306 rajveer 1313
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELED,
1314
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELED,
1315
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELED,
3366 chandransh 1316
                     OrderStatus.ACCEPTED : OrderStatus.CANCELED,
4247 rajveer 1317
                     OrderStatus.BILLED : OrderStatus.CANCELED,
1318
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST
3366 chandransh 1319
                     }
1320
        if order.status not in status_transition.keys():
1321
            raise TransactionServiceException(114, "This order can't be refunded")
1322
 
3413 chandransh 1323
        if order.status < OrderStatus.BILLED:
3226 chandransh 1324
            __update_inventory_reservation(order)
1325
            order.statusDescription = "Order Cancelled"
3415 chandransh 1326
        elif order.status == OrderStatus.BILLED:
3413 chandransh 1327
            __create_return_order(order)
1328
            order.statusDescription = "Order Cancelled"
4486 rajveer 1329
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
3226 chandransh 1330
            __create_return_order(order)
4486 rajveer 1331
            order.statusDescription = "RTO Refunded"
4479 rajveer 1332
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
4078 chandransh 1333
            __create_return_order(order)
3226 chandransh 1334
            __create_refund(order)
4495 rajveer 1335
            order.statusDescription = "DOA Refunded"
1336
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
1337
            __create_return_order(order)
1338
            __create_refund(order)
1339
            order.statusDescription = "Return Refunded"
4247 rajveer 1340
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
1341
            if order.previousStatus  < OrderStatus.BILLED:
1342
                __update_inventory_reservation(order)
1343
                order.statusDescription = "Order Cancelled on customer request"
1344
            elif order.previousStatus == OrderStatus.BILLED:
1345
                __create_return_order(order)
1346
                order.statusDescription = "Order Cancelled on customer request"
3226 chandransh 1347
    else:
4484 rajveer 1348
        status_transition = {OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 1349
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
1350
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 1351
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
1352
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 1353
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
1354
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 1355
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
1356
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
1357
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
1358
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
3366 chandransh 1359
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.REFUNDED,
3731 chandransh 1360
                     OrderStatus.INVENTORY_LOW : OrderStatus.REFUNDED,
4306 rajveer 1361
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.REFUNDED,
1362
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.REFUNDED,
1363
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.REFUNDED,
3731 chandransh 1364
                     OrderStatus.ACCEPTED : OrderStatus.REFUNDED,
4247 rajveer 1365
                     OrderStatus.BILLED : OrderStatus.REFUNDED,
1366
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
1367
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 1368
                     }
1369
        if order.status not in status_transition.keys():
1370
            raise TransactionServiceException(114, "This order can't be refunded")
1371
 
4495 rajveer 1372
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
3226 chandransh 1373
            __create_return_order(order)
1374
            __create_refund(order)
4495 rajveer 1375
            order.statusDescription = "RTO Refunded"
1376
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
1377
            __create_return_order(order)
1378
            __create_refund(order)
1379
            order.statusDescription = "DOA Refunded"
1380
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
1381
            __create_return_order(order)
1382
            __create_refund(order)
1383
            order.statusDescription = "Return Refunded"
4306 rajveer 1384
        elif order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT]:
3191 chandransh 1385
            __create_cancellation(order)
3226 chandransh 1386
            __update_inventory_reservation(order)
1387
            order.statusDescription = "Order Refunded"
4247 rajveer 1388
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
1389
            if order.previousStatus  < OrderStatus.BILLED:
1390
                __create_refund(order)
1391
                __update_inventory_reservation(order)
1392
                order.statusDescription = "Order Cancelled on customer request"
1393
            elif order.previousStatus == OrderStatus.BILLED:
1394
                __create_return_order(order)
1395
                __create_refund(order)
1396
                order.statusDescription = "Order Cancelled on customer request"
1397
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
1398
            __update_inventory_reservation(order)
1399
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 1400
 
1401
    order.status = status_transition[order.status]
1402
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 1403
    order.refunded_by = refunded_by
1404
    order.refund_reason = reason
2628 chandransh 1405
 
1406
    session.commit()
1407
    return True
1408
 
3186 chandransh 1409
def __update_inventory_reservation(order):
3191 chandransh 1410
    '''
1411
    Reduce the reservation count for all line items of the given order.
1412
    '''
3186 chandransh 1413
    try:
1414
        catalog_client = CatalogClient().get_client()
1415
        for lineitem in order.lineitems:
1416
            catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity);
1417
    except:
1418
        print "Unable to reduce reservation count"
1419
 
4220 rajveer 1420
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 1421
    current_time = datetime.datetime.now()
1422
    new_order = Order()
1423
    new_order.customer_id = order.customer_id
1424
    new_order.customer_name = order.customer_name
1425
    new_order.customer_city = order.customer_city
1426
    new_order.customer_state = order.customer_state
1427
    new_order.customer_mobilenumber = order.customer_mobilenumber
1428
    new_order.customer_pincode = order.customer_pincode
1429
    new_order.customer_address1 = order.customer_address1
1430
    new_order.customer_address2 = order.customer_address2
1431
    new_order.customer_email = order.customer_email
1432
    new_order.total_amount = order.total_amount
1433
    new_order.total_weight = order.total_weight
1434
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1435
    new_order.statusDescription = 'Submitted for Processing'
1436
    new_order.created_timestamp = current_time
1437
 
1438
    new_order.transaction = order.transaction
4220 rajveer 1439
    new_order.cod = is_cod
2628 chandransh 1440
 
1441
    for line_item in order.lineitems:
1442
        litem = LineItem()
1443
        litem.item_id = line_item.item_id
1444
        litem.productGroup = line_item.productGroup
1445
        litem.brand = line_item.brand
1446
        if line_item.model_number:
1447
            litem.model_number = line_item.model_number
1448
        if line_item.model_name:    
1449
            litem.model_name = line_item.model_name
1450
        if line_item.color:
1451
            litem.color = line_item.color
1452
        if line_item.extra_info:
1453
            litem.extra_info = line_item.extra_info
1454
        litem.quantity = line_item.quantity
1455
        litem.unit_price = line_item.unit_price
1456
        litem.unit_weight = line_item.unit_weight
1457
        litem.total_price = line_item.total_price
1458
        litem.total_weight = line_item.total_weight
1459
        litem.transfer_price = line_item.transfer_price
1460
        litem.order = new_order
1461
 
1462
    logistics_client = LogisticsClient().get_client()
1463
    item_id = new_order.lineitems[0].item_id
4479 rajveer 1464
    logistics_info = logistics_client.getLogisticsInfo(new_order.customer_pincode, item_id, is_cod) #TODO: We should be able to pass another flag to suggest ignoring the inventory situation.
2628 chandransh 1465
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
1466
 
1467
    new_order.warehouse_id = logistics_info.warehouseId
1468
    new_order.logistics_provider_id = logistics_info.providerId
1469
    new_order.airwaybill_no = logistics_info.airway_billno
1470
    new_order.tracking_id = new_order.airwaybill_no
1471
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 1472
    new_order.promised_delivery_time = new_order.expected_delivery_time
4299 rajveer 1473
 
2628 chandransh 1474
    if should_copy_billing_info:
1475
        new_order.invoice_number = order.invoice_number
1476
        new_order.billed_by = order.billed_by
1477
        new_order.warehouse_id = order.warehouse_id
1478
        new_order.accepted_timestamp = current_time
1479
        new_order.billing_timestamp = current_time    
1480
        new_order.status = OrderStatus.BILLED
1481
        new_order.statusDescription = 'Order Billed'
1482
    else:       
3133 rajveer 1483
        catalog_client = CatalogClient().get_client()
2628 chandransh 1484
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, new_order.lineitems[0].quantity)
1485
 
1486
    return new_order
1487
 
1488
def __create_return_order(order):
2687 chandransh 1489
    ret_order = ReturnOrder(order)
2628 chandransh 1490
    return ret_order
1491
 
1492
def __create_refund(order):
4078 chandransh 1493
    payment_client = PaymentClient().get_client()
1494
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 1495
    return
2628 chandransh 1496
 
3035 chandransh 1497
def __create_cancellation(order):
1498
    return
1499
 
2536 chandransh 1500
def __get_order_address(order):
1501
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
1502
    if order.customer_address2:
1503
        address = address + order.customer_address2 + "\n"
1504
    address = address + order.customer_city + "\n"
1505
    address = address + order.customer_state + "\n"
1506
    address = address + "PIN " + order.customer_pincode + "\n"
1507
    address = address + "Phone: " + order.customer_mobilenumber
1508
    return address
1509
 
1510
def __generate_return_advice(order, warehouse, provider, filename):    
1511
    pdf = Canvas(filename)
1512
    pdf.setFont('Times-Bold',16)
1513
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
1514
    address_text.textLine("To")
1515
    address_text.textLine("Parmod Kumar")
1516
    for line in warehouse.location.split("\n"):
1517
        address_text.textLine(line)
1518
    address_text.textLine("PIN " + warehouse.pincode)
1519
    address_text.textLine("")
1520
    address_text.textLine("Phone: 9971573026")
1521
    pdf.drawText(address_text)
1522
 
1523
    pdf.setFont('Times-Roman',12)
1524
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 1525
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 1526
    lineitem = order.lineitems[0] 
4234 rajveer 1527
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 1528
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
1529
    order_text.textLine("Order ID : " + str(order.id))
1530
    pdf.drawText(order_text)
1531
    pdf.showPage()
1532
    pdf.save()
1533
    return filename
1534
 
2697 chandransh 1535
def get_return_orders(warehouse_id, from_date, to_date):
1536
    query = ReturnOrder.query.filter_by(processedStatus = False)
1537
    if warehouse_id != -1:
1538
        query = query.filter_by(warehouseId = warehouse_id)
1539
    if from_date:
4118 chandransh 1540
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 1541
    if to_date:
4118 chandransh 1542
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 1543
    return [return_order.to_thrift_object() for return_order in query.all()]
1544
 
2700 chandransh 1545
def get_return_order(id):
1546
    ret_order = ReturnOrder.get_by(orderId = id)
1547
    if ret_order is None:
1548
        raise TransactionServiceException(116, "No return order found for the given order id")
1549
    return ret_order.to_thrift_object()
1550
 
2697 chandransh 1551
def process_return(ret_order_id):
1552
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
1553
    if ret_order is None:
1554
        raise TransactionServiceException(116, "No return order found for the given order id")
1555
    ret_order.processedStatus = True
2701 chandransh 1556
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 1557
    session.commit()
1558
 
2819 chandransh 1559
def create_purchase_order(warehouseId):
1560
    if not warehouseId:
1561
        raise TransactionServiceException(101, "bad warehouse id")
1562
 
3451 chandransh 1563
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4586 mandeep.dh 1564
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW, Order.status == OrderStatus.ACCEPTED))
2819 chandransh 1565
    query = query.filter_by(purchase_order_id=None)
1566
    query = query.order_by(Order.created_timestamp)
1567
    pending_orders = query.all()
4586 mandeep.dh 1568
 
2819 chandransh 1569
    if not pending_orders:
4586 mandeep.dh 1570
        return None
4434 mandeep.dh 1571
 
1572
    catalog_client = CatalogClient().get_client()
1573
    availability = {}
1574
    for item in catalog_client.getAllItemsForWarehouse(warehouseId):
4586 mandeep.dh 1575
        availability[item.id] = [item.itemInventory.availability[warehouseId], item]
4434 mandeep.dh 1576
 
4586 mandeep.dh 1577
    requirements = {}
1578
    for order in pending_orders:
2819 chandransh 1579
        for lineitem in order.lineitems:
4586 mandeep.dh 1580
            if (requirements.has_key(lineitem.item_id)):
1581
                requirements[lineitem.item_id] += lineitem.quantity
2819 chandransh 1582
            else:
4586 mandeep.dh 1583
                requirements[lineitem.item_id] = lineitem.quantity
4434 mandeep.dh 1584
 
4586 mandeep.dh 1585
    net_requirements = {}
1586
    for itemId in requirements.keys():
1587
        requirementsCount = requirements.get(itemId)
1588
        if  availability.has_key(itemId):
1589
            availabilityCount = availability.get(itemId)[0]
1590
            item              = availability.get(itemId)[1]
1591
            if item.preferredVendor is None or item.preferredVendor == 1:
1592
                continue
1593
            if requirementsCount > availabilityCount:
1594
                if (net_requirements.has_key(item.preferredVendor)):
1595
                    net_requirements[item.preferredVendor].append([item, requirementsCount - availabilityCount])
1596
                else:
1597
                    net_requirements[item.preferredVendor] = [[item, requirementsCount - availabilityCount]];
1598
        else:
1599
            item = catalog_client.getItem(itemId);
1600
            if item.preferredVendor is None or item.preferredVendor == 1:
1601
                continue
1602
            if (net_requirements.has_key(item.preferredVendor)):
1603
                net_requirements[item.preferredVendor].append([item, requirementsCount])
1604
            else:
1605
                net_requirements[item.preferredVendor] = [[item, requirementsCount]];
4434 mandeep.dh 1606
 
4586 mandeep.dh 1607
    if not net_requirements:
1608
        return None
4434 mandeep.dh 1609
 
4586 mandeep.dh 1610
    purchaseOrderIds = []
1611
    for vendorId in net_requirements.keys():
1612
        t_purchase_order = PurchaseOrder()
1613
        t_purchase_order.supplierId = vendorId
1614
        t_purchase_order.warehouseId = warehouseId
1615
        t_purchase_order.lineitems = []
1616
        for key in net_requirements.get(vendorId):
1617
            item     = key[0]
1618
            quantity = key[1]
1619
            t_po_lineitem = POLineItem()
1620
            t_po_lineitem.productGroup = item.productGroup
1621
            t_po_lineitem.brand = item.brand
1622
            t_po_lineitem.modelNumber = item.modelNumber
1623
            t_po_lineitem.modelName = item.modelName
1624
            t_po_lineitem.color = item.color
1625
            t_po_lineitem.itemId = item.id
1626
            t_po_lineitem.quantity = quantity
1627
            try:
1628
                item_pricing = catalog_client.getItemPricing(item.id, vendorId)
1629
            except Exception as e:
1630
                purchase_client = PurchaseClient().get_client()
1631
                vendor = purchase_client.getSupplier(vendorId)
1632
                print 'Could not find transfer price for Item id: ' + str(item.id) + ' and vendor id: ' + str(vendorId)
1633
                print e
1634
                raise TransactionServiceException(101, 'Transfer price missing for ' + vendor.name + ' and ' + " ".join([item.brand, item.modelName, item.modelNumber, item.color]))
1635
            t_po_lineitem.unitPrice = item_pricing.transferPrice
1636
            t_purchase_order.lineitems.append(t_po_lineitem)
1637
        purchase_client = PurchaseClient().get_client()
1638
        poId = purchase_client.createPurchaseOrder(t_purchase_order)
1639
        purchaseOrderIds.append(poId)
1640
 
2819 chandransh 1641
    for order in pending_orders:
4586 mandeep.dh 1642
        order.purchase_order_id = purchaseOrderIds[len(purchaseOrderIds) - 1]
4434 mandeep.dh 1643
        order.status = OrderStatus.LOW_INV_PO_RAISED
1644
        order.statusDescription = 'In Process'
2819 chandransh 1645
    session.commit()
4586 mandeep.dh 1646
    return purchaseOrderIds
2819 chandransh 1647
 
3451 chandransh 1648
def update_weight(order_id, weight):
3469 chandransh 1649
    '''
1650
    Update the weight of order
1651
    '''
3451 chandransh 1652
    order = get_order(order_id)
1653
    order.total_weight = weight
3469 chandransh 1654
    lineitem = order.lineitems[0]
1655
    lineitem.total_weight = weight
1656
    lineitem.unit_weight = weight
3451 chandransh 1657
 
3469 chandransh 1658
    session.commit()
1659
    return order
1660
 
1661
def change_product(order_id, item_id):
1662
    '''
1663
    Ship a product of a different color to the customer.
1664
    '''
1665
    order = get_order(order_id)
4306 rajveer 1666
    if order.status not in [OrderStatus.INIT, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT]:
3469 chandransh 1667
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
1668
 
1669
    lineitem = order.lineitems[0]
3451 chandransh 1670
 
3469 chandransh 1671
    catalog_client = CatalogClient().get_client()
1672
 
1673
    old_item = catalog_client.getItem(lineitem.item_id)
1674
    item = catalog_client.getItem(item_id)
1675
    if old_item.catalogItemId != item.catalogItemId:
1676
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
1677
 
1678
    catalog_client.reserveItemInWarehouse(item_id, order.warehouse_id, lineitem.quantity)
1679
    catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity)
1680
    #TODO: Check that this new item has the same price
1681
 
1682
    lineitem.item_id = item_id
1683
    lineitem.color = item.color
1684
 
3451 chandransh 1685
    session.commit()
3469 chandransh 1686
 
1687
    order = get_order(order_id)
3451 chandransh 1688
    return order
3469 chandransh 1689
 
1690
def change_warehouse(order_id, warehouse_id):
1691
    '''
1692
    Update the warehouse which will be used to fulfil this order.
1693
    '''
1694
    order = get_order(order_id)
4306 rajveer 1695
    if order.status not in [OrderStatus.INIT, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT]:
3469 chandransh 1696
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
1697
 
1698
    if warehouse_id == order.warehouse_id:
1699
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
1700
 
1701
    lineitem = order.lineitems[0]
1702
    catalog_client = CatalogClient().get_client()
1703
    try:
1704
        warehouse = catalog_client.getWarehouse(warehouse_id)
1705
    except:
1706
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
1707
 
1708
    catalog_client.reserveItemInWarehouse(lineitem.item_id, warehouse_id, lineitem.quantity)
1709
    catalog_client.reduceReservationCount(lineitem.item_id, order.warehouse_id, lineitem.quantity)
3451 chandransh 1710
 
3469 chandransh 1711
    order.warehouse_id = warehouse_id
1712
    session.commit()
1713
    return order
3553 chandransh 1714
 
3986 chandransh 1715
def add_delay_reason(order_id, reason, further_delay=0):
3553 chandransh 1716
    '''
3994 chandransh 1717
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 1718
    '''
1719
    order = get_order(order_id)
1720
    try:
3581 chandransh 1721
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4009 chandransh 1722
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
1723
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 1724
 
1725
        if order.status < OrderStatus.SHIPPED_FROM_WH:
1726
            actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
1727
            order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
1728
 
3553 chandransh 1729
        session.commit()
4008 mandeep.dh 1730
 
1731
        try:
1732
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
1733
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
1734
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
1735
            session.commit()
1736
        except Exception as e:
4065 mandeep.dh 1737
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 1738
 
3553 chandransh 1739
        return True
1740
    except:
3994 chandransh 1741
        print sys.exc_info()[0]
3553 chandransh 1742
        return False
3956 chandransh 1743
 
1744
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
1745
    unprocessed_awbs = {}
1746
    for awb, amount in collected_amount_map.iteritems():
1747
        try:
1748
            order = Order.query.filter_by(airwaybill_no=awb).one()
1749
        except NoResultFound:
1750
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
1751
            continue
1752
        except MultipleResultsFound:
1753
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
1754
            continue
1755
 
1756
        if order.cod_reconciliation_timestamp:
1757
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
1758
            continue
1759
 
1760
        if order.status < OrderStatus.DELIVERY_SUCCESS:
1761
            #Order has not been delivered yet. No way we can receive the payment.
1762
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
1763
            continue
1764
 
4252 rajveer 1765
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
1766
        if abs(amount - order.total_amount) > 0.5:
3956 chandransh 1767
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
1768
            unprocessed_awbs[awb] = "Payment of Rs. " + str(amount) + " has been received against the total value of Rs. " + str(order.total_amount) + " for order: " + str(order.id)
1769
            continue
1770
 
1771
        try:
1772
            payment_client = PaymentClient().get_client()
1773
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
1774
        except Exception:
1775
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
1776
            continue
1777
 
1778
        #Payment has been recorded now. We can update the order peacefully.
1779
        order.cod_reconciliation_timestamp = datetime.datetime.now()
1780
        session.commit()
3469 chandransh 1781
 
3956 chandransh 1782
    return unprocessed_awbs
4008 mandeep.dh 1783
 
1784
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 1785
    """
1786
    Returns the list of transaction ids that require some extra processing and
1787
    which belong to a particular category. This is currently used by CRM
1788
    application. If no such transaction ids are present, it returns an empty list.
1789
    """
1790
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 1791
 
4065 mandeep.dh 1792
    if category is not None:
1793
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 1794
 
4065 mandeep.dh 1795
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 1796
 
1797
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 1798
    """
1799
    Marks a particular transaction as processed for a particular cateogory.
1800
    It essentially deletes the transaction id record for a particular
1801
    processing type category (if present) from DB.
1802
    This is currently used by CRM application.
1803
    """
4008 mandeep.dh 1804
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
1805
    session.commit()
1806
 
4018 chandransh 1807
def get_item_wise_risky_orders_count():
1808
    """
1809
    Returns a map containing the number of risky orders keyed by item id. A risky order
1810
    is defined as one whose shipping date is about to expire.
1811
    """
1812
    item_wise_risky_orders_count = {}
4019 chandransh 1813
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 1814
    orders = Order.query.filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.ACCEPTED]))).filter(Order.expected_shipping_time <= shipping_cutoff_time).all()
1815
    for order in orders:
1816
        for lineitem in order.lineitems:
1817
            quantity = lineitem.quantity
1818
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
1819
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
1820
 
1821
            item_wise_risky_orders_count[lineitem.item_id] = quantity
1822
    return item_wise_risky_orders_count
1823
 
4324 mandeep.dh 1824
def update_shipment_address(order_id, address_id):
1825
    """
1826
    Updates shipment address of an order. Delivery and shipping date estimates
1827
    etc. are also updated here.
1828
 
1829
    Throws TransactionServiceException in case address change is not
1830
    possible due to certain reasons such as new pincode in address is
1831
    not serviceable etc.
1832
 
1833
    Parameters:
1834
     - orderId
1835
     - addressId
1836
    """
1837
    user_client = UserClient().get_client()
1838
    address     = user_client.getAddressById(address_id)
1839
    order       = get_order(order_id)
1840
 
1841
    logistics_client = LogisticsClient().get_client()
1842
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin)
1843
 
1844
    # Check for new estimate. Raise exception if new address is not serviceable
1845
    if logistics_info.deliveryTime == -1:
1846
        raise TransactionServiceException(1, 'Location not serviceable')
1847
 
1848
    # COD services are not available everywhere
1849
    if order.cod:
1850
        if not logistics_client.isCodAllowed(address.pin):
1851
            raise TransactionServiceException(2, 'COD service not available')
1852
 
1853
    current_time = datetime.datetime.now()
1854
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
1855
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
1856
 
1857
    order.customer_name         = address.name
1858
    order.customer_pincode      = address.pin
1859
    order.customer_address1     = address.line1
1860
    order.customer_address2     = address.line2
1861
    order.customer_city         = address.city
1862
    order.customer_state        = address.state
1863
    order.customer_mobilenumber = address.phone
1864
 
1865
    if order.cod:
1866
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
1867
    else:
1868
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
1869
 
1870
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
1871
    order.promised_shipping_time = order.expected_shipping_time
1872
    order.promised_delivery_time = order.expected_delivery_time 
1873
 
1874
    session.commit()
1875
 
4247 rajveer 1876
def mark_order_cancellation_request_received(orderId):
1877
    """
1878
    Mark order as cancellation request received. If customer sends request of cancellation of
1879
    a particular order, this method will be called. It will just change status of the order
1880
    depending on its current status. It also records the previous status, so that we can move
1881
    back to that status if cancellation request is denied.
1882
 
1883
    Parameters:
1884
     - orderId
1885
    """
1886
    status_transition = {OrderStatus.INIT : OrderStatus.CANCEL_REQUEST_RECEIVED,
1887
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
1888
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 1889
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
1890
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
1891
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 1892
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
1893
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
1894
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
1895
             }
1896
    if order.status not in status_transition.keys():
1897
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
1898
 
1899
    order = get_order(orderId)
1900
    order.previousStatus = order.status
1901
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
1902
    order.statusDescription = "Cancellation request received from user"
1903
    session.commit()
1904
 
4258 rajveer 1905
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 1906
    """
4258 rajveer 1907
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
1908
    Changed transaction and all orders status to payment accepted.
4247 rajveer 1909
 
1910
    Parameters:
4258 rajveer 1911
     - transactionId
4247 rajveer 1912
    """
4258 rajveer 1913
    transaction = get_transaction(transactionId)
1914
    transaction.status = TransactionStatus.AUTHORIZED
1915
    for order in transaction.orders:
1916
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1917
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 1918
    session.commit()
1919
 
4259 anupam.sin 1920
def refund_transaction(transactionId, refundedBy, reason):
1921
    """
1922
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
1923
    need to be cancelled
1924
 
1925
    Parameters:
1926
     - transactionId
1927
    """
1928
    transaction = get_transaction(transactionId)
1929
    transaction.status = TransactionStatus.FAILED
1930
    for order in transaction.orders:
1931
        refund_order(order.id, refundedBy, reason)
1932
    session.commit()
1933
 
4247 rajveer 1934
def mark_order_cancellation_request_denied(orderId):
1935
    """
4283 anupam.sin 1936
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 1937
 
1938
    Parameters:
1939
     - orderId
1940
    """
1941
    order = get_order(orderId)
1942
    order.status = order.previousStatus
1943
    order.previousStatus = None
1944
    order.statusDescription = "Cancellation request denied"
1945
    session.commit()
1946
 
1947
def mark_order_cancellation_request_confirmed(orderId):
1948
    """
1949
    If we decide to to cancel order, CRM will call this method to move the status of order to
1950
    cancellation request confirmed. After this OM will be able to cancel the order.
1951
 
1952
    Parameters:
1953
     - orderId
1954
    """
1955
    order = get_order(orderId)
1956
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
1957
    order.statusDescription = "Cancellation request confirmed"
1958
    session.commit()
1959
 
4285 rajveer 1960
def accept_orders_for_item_id(itemId, inventory):
1961
    """
1962
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
1963
    given order is not a COD order, it also captures the payment if the same has not been captured.
1964
 
1965
    Parameters:
1966
     - itemId
1967
     - inventory
1968
    """
4351 rajveer 1969
    orders = Order.query.filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS]))).order_by(Order.expected_shipping_time).all()
4285 rajveer 1970
    for order in orders:
4301 rajveer 1971
        if inventory > 0:
1972
            lineitem = order.lineitems[0]
1973
            if itemId == lineitem.item_id:
1974
                try:
1975
                    accept_order(order.id)
1976
                    inventory = inventory - lineitem.quantity
1977
                except:
1978
                    logging.info("Unable to accept the order")
1979
        else:
1980
            order_outofstock(order.id)
4285 rajveer 1981
    return
1982
 
4369 rajveer 1983
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
1984
    if isReminder:
1985
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
1986
    else:
1987
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
1988
 
1989
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 1990
    for order in orders:
1991
        lineitem = order.lineitems[0]
1992
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
1993
            if estimate > 0:
1994
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
1995
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 1996
            order.statusDescription = "PO Raised"
4303 rajveer 1997
            quantity = quantity - lineitem.quantity
1998
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
1999
            session.commit()
2000
 
4369 rajveer 2001
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
2002
    if isReminder:
2003
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2004
    else:
2005
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2006
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2007
    for order in orders:
2008
        lineitem = order.lineitems[0]
2009
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2010
            if estimate > 0:
2011
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2012
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 2013
            order.statusDescription = "Reversal Initiated"
4303 rajveer 2014
            quantity = quantity - lineitem.quantity
2015
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
2016
            session.commit()
2017
 
4369 rajveer 2018
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
2019
    if isReminder:
2020
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2021
    else:
2022
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2023
 
2024
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2025
    for order in orders:
2026
        lineitem = order.lineitems[0]
2027
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2028
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 2029
            order.statusDescription = "Not Available"
4303 rajveer 2030
            quantity = quantity - lineitem.quantity
2031
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
2032
            session.commit()
2033
 
2034
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 2035
    orderInv = OrderInventory.get_by(order_id=order.id)
2036
    if not orderInv:
2037
        orderInv = OrderInventory()
2038
        orderInv.order = order
4303 rajveer 2039
    orderInv.hotspotAction = hotspotAction  
2040
    orderInv.estimate = estimate
2041
    orderInv.itemId = itemId
2042
    orderInv.timestamp = datetime.datetime.now()
2043
    orderInv.quantity = quantity
2044
 
4556 mandeep.dh 2045
'''    
4369 rajveer 2046
def mark_orders_as_timeout(vendorId):
2047
    ret_timeouts = {}
2048
    orderInvs = OrderInventory.query.all()
2049
    for orderInv in orderInvs:
2050
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
2051
            if not ret_timeouts.has_key(orderInv.itemId):
2052
                timeout = TimeoutSummary()
2053
                ret_timeouts[orderInv.itemId] = timeout
2054
            else:
2055
                timeout = ret_timeouts.get(orderInv.itemId)
2056
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2057
                if timeout.poRaised:
2058
                    timeout.poRaised += 1
2059
                else:
2060
                    timeout.poRaised = 1
2061
 
2062
                if timeout.poEstimate:
2063
                    timeout.poEstimate += orderInv.estimate
2064
                else:
2065
                    timeout.poEstimate = orderInv.estimate
2066
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
2067
                orderInv.order.statusDescription = "PO Raised Timeout"
2068
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2069
                if timeout.reversalInitiated:
2070
                    timeout.reversalInitiated += 1
2071
                else:
2072
                    timeout.reversalInitiated = 1
2073
 
2074
                if timeout.reversalEstimate:
2075
                    timeout.reversalEstimate += orderInv.estimate
2076
                else:
2077
                    timeout.reversalEstimate = orderInv.estimate
2078
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
2079
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
2080
            else:
2081
                orderInv.delete()
2082
    session.commit()
2083
    return ret_timeouts
4556 mandeep.dh 2084
'''
2085
 
2086
 
2087
def mark_orders_as_timeout(vendorId):
2088
    ret_timeouts = {}
2089
    orderInvs = OrderInventory.query.all()
2090
    for orderInv in orderInvs:
2091
        if not ret_timeouts.has_key(orderInv.itemId):
2092
            timeout = TimeoutSummary()
2093
            ret_timeouts[orderInv.itemId] = timeout
2094
        else:
2095
            timeout = ret_timeouts.get(orderInv.itemId)
2096
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2097
            if timeout.poRaised:
2098
                timeout.poRaised += 1
2099
            else:
2100
                timeout.poRaised = 1
2101
 
2102
            if timeout.poEstimate:
2103
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
2104
            else:
2105
                timeout.poEstimate = orderInv.estimate
2106
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2107
            if timeout.reversalInitiated:
2108
                timeout.reversalInitiated += 1
2109
            else:
2110
                timeout.reversalInitiated = 1
2111
 
2112
            if timeout.reversalEstimate:
2113
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
2114
            else:
2115
                timeout.reversalEstimate = orderInv.estimate
2116
        orderInv.order.status = OrderStatus.INVENTORY_LOW
2117
        orderInv.order.statusDescription = "Low Inventory"
2118
        orderInv.delete()
2119
    session.commit()
2120
    return ret_timeouts
2121
 
4386 anupam.sin 2122
def get_order_for_awb(awb):
2123
    order = Order.get_by(airwaybill_no=awb)
2124
    if not order:
2125
        raise TransactionServiceException(108, "no such order")
2126
 
2127
    return order
4369 rajveer 2128
 
4506 phani.kuma 2129
def get_orders_for_provider_for_status(provider_id, order_status):
2130
    if not provider_id or not order_status:
2131
        raise TransactionServiceException(101, "bad provider id or order status")
2132
    query = Order.query.filter_by(logistics_provider_id = provider_id, status = order_status)
2133
    return query.all()
4386 anupam.sin 2134
 
766 rajveer 2135
def close_session():
2136
    if session.is_active:
2137
        print "session is active. closing it."
2783 chandransh 2138
        session.close()
3376 rajveer 2139
 
2140
def is_alive():
2141
    try:
2142
        session.query(Transaction.id).limit(1).one()
2143
        return True
2144
    except:
4343 varun.gupt 2145
        return False