Subversion Repositories SmartDukaan

Rev

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