Subversion Repositories SmartDukaan

Rev

Rev 5099 | Rev 5123 | 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)
4365 mandeep.dh 694
 
5110 mandeep.dh 695
        __update_inventory_reservation(order)
4541 mandeep.dh 696
        session.commit()
4283 anupam.sin 697
        return True
698
    else:
699
        return False
1149 chandransh 700
 
4763 rajveer 701
def add_invoice_number(orderId, invoiceNumber, color):
4579 rajveer 702
    order = Order.get_by(id=orderId)
703
    if not order:
704
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
705
 
706
    if order.status == OrderStatus.ACCEPTED:
707
        order.invoice_number = invoiceNumber
4767 rajveer 708
        if color:
709
            billedOrdersColorMap[orderId] = color;
4579 rajveer 710
    session.commit()
711
 
1220 chandransh 712
def batch_orders(warehouseId):
713
    if not warehouseId:
714
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 715
 
716
    batchno_generator = BatchNoGenerator()
717
    session.commit()
1220 chandransh 718
    query = Order.query.filter_by(warehouse_id=warehouseId)
4592 mandeep.dh 719
    query = query.filter(Order.status == OrderStatus.LOW_INV_PO_RAISED)
1220 chandransh 720
    query = query.order_by(Order.created_timestamp)
721
    pending_orders = query.all()
1225 chandransh 722
 
1220 chandransh 723
    serial_no = 1
724
    for order in pending_orders:
1276 chandransh 725
        order.batchNo = batchno_generator.id
1220 chandransh 726
        order.serialNo = serial_no
727
        serial_no += 1
728
    session.commit() 
729
    pending_orders = query.all()
730
    return pending_orders
731
 
732
def order_outofstock(orderId):
1911 chandransh 733
    '''
734
    Mark order as out of stock
735
    '''
1220 chandransh 736
    order = get_order(orderId)
737
    order.status = OrderStatus.INVENTORY_LOW
738
    order.statusDescription = "Low Inventory"
739
    order.outofstock_timestamp = datetime.datetime.now()
740
    session.commit()
741
    return True
742
 
4789 rajveer 743
def mark_orders_as_shipped_from_warehouse(warehouseId, providerId, cod, orderIds):
4410 rajveer 744
    try:
745
        current_timestamp = datetime.datetime.now()
4789 rajveer 746
        orders = Order.query.filter_by(warehouse_id = warehouseId, logistics_provider_id = providerId, status = OrderStatus.BILLED, cod = cod).all()
4410 rajveer 747
        for order in orders:
4789 rajveer 748
            if order.id in orderIds:
749
                order.status = OrderStatus.SHIPPED_FROM_WH
750
                order.statusDescription = "Order shipped from warehouse"
751
                order.shipping_timestamp = current_timestamp
759 chandransh 752
        session.commit()
4749 varun.gupt 753
 
754
        try:
755
            enqueue_shipping_confirmation_email(orders)
756
        except Exception as e:
757
            print e
758
 
759 chandransh 759
        return True
760
    except:
761
        return False
4410 rajveer 762
 
1113 chandransh 763
def mark_orders_as_picked_up(provider_id, pickup_details):
764
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 765
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 766
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 767
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
768
            continue
1113 chandransh 769
        order.status = OrderStatus.SHIPPED_TO_LOGST
770
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 771
        order.pickup_timestamp = pickup_timestamp
1113 chandransh 772
    session.commit()
1217 chandransh 773
 
4910 phani.kuma 774
def get_orders_not_picked_up(provider_id):
1132 chandransh 775
    current_time = datetime.datetime.now()
776
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4741 phani.kuma 777
    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 778
    return orders_not_picked_up
779
 
1132 chandransh 780
def mark_orders_as_delivered(provider_id, delivered_orders):
781
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 782
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 783
        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 784
            continue
785
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1132 chandransh 786
        order.status = OrderStatus.DELIVERY_SUCCESS
787
        order.statusDescription = "Order delivered"
4910 phani.kuma 788
        timestamp, receiver = detail.split('|')
789
        if order.first_dlvyatmp_timestamp is None:
790
            order.first_dlvyatmp_timestamp = timestamp
791
        order.delivery_timestamp = timestamp
792
        order.receiver = receiver
3578 mandeep.dh 793
        update_trust_level(order)
1132 chandransh 794
    session.commit()
795
 
4712 rajveer 796
def mark_order_as_delivered(orderId, deliveryTimestamp, receiver):
797
    order = Order.get_by(id=orderId)
4982 rajveer 798
    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 799
        raise TransactionServiceException(101, "Either wrond order id or invalid state " + str(orderId))
800
 
4910 phani.kuma 801
    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 802
        order.delivery_timestamp = deliveryTimestamp
803
        order.receiver = receiver
804
    order.status = OrderStatus.DELIVERY_SUCCESS
805
    order.statusDescription = "Order delivered"
806
    update_trust_level(order)
807
    session.commit()
808
 
4910 phani.kuma 809
def mark_orders_as_rto(provider_id, returned_orders):
1135 chandransh 810
    for awb, detail in returned_orders.iteritems():
811
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 812
        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 813
            continue
814
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 815
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 816
        order.delivery_timestamp, reason = detail.split('|')
817
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 818
        update_trust_level(order)
1911 chandransh 819
    session.commit()
1135 chandransh 820
 
4910 phani.kuma 821
def get_rto_orders(provider_id):
822
    current_time = datetime.datetime.now()
823
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
824
    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()
825
    return rto_orders
826
 
1246 chandransh 827
def update_non_delivery_reason(provider_id, undelivered_orders):
828
    for awb, reason in undelivered_orders.iteritems():
829
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4920 phani.kuma 830
        if order == None or order.status == OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE:
2684 chandransh 831
            continue
832
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 833
        order.statusDescription = reason
834
    session.commit()
4910 phani.kuma 835
 
836
def get_non_delivered_orders_by_courier(provider_id):
4581 phani.kuma 837
    current_time = datetime.datetime.now()
838
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
839
    upto_datetime = today_datetime - datetime.timedelta(4)
4910 phani.kuma 840
    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 841
    return orders_not_delivered
1246 chandransh 842
 
4910 phani.kuma 843
def mark_orders_as_local_connected(provider_id, local_connected_orders):
844
    for awb, timestamp in local_connected_orders.iteritems():
845
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
846
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
847
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
848
            continue
849
        order.status = OrderStatus.SHIPPED_TO_DESTINATION_CITY
850
        order.statusDescription = "Left Out of Origin City"
851
        order.local_connected_timestamp = timestamp
852
    session.commit()
853
 
854
def get_orders_not_local_connected(provider_id):
855
    current_time = datetime.datetime.now()
856
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
857
    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()
858
    return orders_pending_local_connection
859
 
860
def mark_orders_as_destinationCityReached(provider_id, destination_city_reached_orders):
861
    for awb, timestamp in destination_city_reached_orders.iteritems():
862
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
863
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY]:
864
            continue
865
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
866
        order.status = OrderStatus.REACHED_DESTINATION_CITY
867
        order.statusDescription = "Reached Destination City"
868
        order.reached_destination_timestamp = timestamp
869
    session.commit()
870
 
871
def mark_orders_as_firstDeliveryAttempted(provider_id, first_atdl_orders):
872
    for awb, detail in first_atdl_orders.iteritems():
873
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
874
        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]:
875
            continue
876
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
877
        order.status = OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
878
        order.first_dlvyatmp_timestamp, reason = detail.split('|')
879
        order.statusDescription = reason
880
    session.commit()
881
 
4783 phani.kuma 882
def get_orders_not_met_expected_delivery_date():
883
    current_time = datetime.datetime.now()
884
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4910 phani.kuma 885
    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 886
    return orders_not_delivered
887
 
4444 rajveer 888
def get_alerts(type, warehouseId, status, timestamp):
889
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
890
    if type != -1 :
891
        query = query.filter(Alert.type == type)
892
    if status != -1 :
893
        query = query.filter(Alert.status == status)
4394 rajveer 894
    if timestamp:
895
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 896
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 897
    return query.all()
898
 
4447 rajveer 899
def add_alert(type, warehouseId, description):
4394 rajveer 900
    alert = Alert()
901
    alert.type = type
902
    alert.status = 1
903
    alert.description = description
904
    alert.timestamp = datetime.datetime.now()
4447 rajveer 905
    alert.warehouseId = warehouseId
4444 rajveer 906
    session.commit()
766 rajveer 907
 
4444 rajveer 908
def mark_alerts_as_seen(warehouseId):
909
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
910
    alerts = query.all()
911
    for alert in alerts:
912
        alert.status = 0    
913
    session.commit()
914
 
1596 ankur.sing 915
def get_valid_order_count():
2851 chandransh 916
    '''
917
    Returns the number of orders which we processed. The reshipped orders are not
918
    counted since there'll always be a new compensating order present.
919
    '''
4682 rajveer 920
    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 921
 
1627 ankur.sing 922
def get_cust_count_with_successful_txn():
2851 chandransh 923
    '''
924
    Returns the number of distinct customers who have done successful transactions.
925
    It uses the sqlalchemy func module to construct an efficient query.
926
    '''
927
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 928
 
1730 ankur.sing 929
def get_valid_orders_amount_range():
2851 chandransh 930
    '''
931
    Returns a list containing the minimum and maximum amount across all
932
    orders placed with us. No need to consider reshippped orders for min/max
933
    amount of orders.
934
    '''
935
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 936
 
1886 ankur.sing 937
def get_valid_orders(limit):
2851 chandransh 938
    '''
939
    Returns the last limit number of valid orders placed with us. Ignored the
940
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
941
    less than 0. 
942
    '''
943
    if limit < 0:
944
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
4662 rajveer 945
    query = Order.query.filter(Order.status >= OrderStatus.COD_VERIFICATION_PENDING)
1886 ankur.sing 946
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 947
    if limit != 0:
1886 ankur.sing 948
        query = query.limit(limit)
949
    return query.all()
950
 
2783 chandransh 951
def get_next_invoice_number():
952
    entity_id = InvoiceIDGenerator.query.with_lockmode("update").one()
953
    invoice_number = entity_id.id + 1
954
    entity_id.id = invoice_number
955
    return invoice_number
956
 
2536 chandransh 957
def toggle_doa_flag(order_id):
958
    order = get_order(order_id)
959
    if(order.doaFlag):
960
        order.doaFlag = False
961
    else:
962
        order.doaFlag = True
963
    session.commit()
964
    return order.doaFlag
965
 
4454 rajveer 966
def mark_order_doa_request_received(orderId):
967
    order = get_order(orderId)
968
    if order.status != OrderStatus.DELIVERY_SUCCESS:
969
        return False
970
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 971
    order.statusDescription = "DOA Request Received"
4454 rajveer 972
    session.commit()
973
    return True
974
 
975
def mark_order_doa_request_authorized(orderId, isAuthorized):
976
    order = get_order(orderId)
977
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
978
        return False
979
    if isAuthorized:
980
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 981
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 982
    else:
983
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 984
        order.statusDescription = "Order delivered"
4454 rajveer 985
    session.commit()
986
    return True
987
 
4488 rajveer 988
def mark_order_return_request_received(orderId):
989
    order = get_order(orderId)
990
    if order.status != OrderStatus.DELIVERY_SUCCESS:
991
        return False
992
    order.status = OrderStatus.RET_REQUEST_RECEIVED
993
    order.statusDescription = "Return Request Received"
994
    session.commit()
995
    return True
996
 
997
def mark_order_return_request_authorized(orderId, isAuthorized):
998
    order = get_order(orderId)
999
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
1000
        return False
1001
    if isAuthorized:
1002
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
1003
        order.statusDescription = "Return Request Authorized"
1004
    else:
1005
        order.status = OrderStatus.DELIVERY_SUCCESS
1006
        order.statusDescription = "Order delivered"
1007
    session.commit()
1008
    return True
1009
 
4579 rajveer 1010
def request_pickup_number(order_id, providerId):
2536 chandransh 1011
    order = get_order(order_id)
4495 rajveer 1012
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 1013
        return False
1014
    from_user = 'cnc.center@shop2020.in'
1015
    from_pwd = '5h0p2o2o'
1016
 
4227 rajveer 1017
    subject = "Pickup request from " + order.customer_city
2536 chandransh 1018
    try:
3133 rajveer 1019
        catalog_client = CatalogClient().get_client()
2536 chandransh 1020
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1021
 
1022
        logistics_client = LogisticsClient().get_client()
4579 rajveer 1023
        provider = logistics_client.getProvider(providerId)
3051 chandransh 1024
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 1025
        raw_message = '''
1026
        Dear Sir/Madam,
1027
 
2559 chandransh 1028
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 1029
 
1030
        Pickup CODE: %(provider_code)s
1031
        Total Weight: %(order_weight)s kg
1032
 
2559 chandransh 1033
        Pickup Address:
2536 chandransh 1034
 
1035
        %(customer_address)s
1036
 
1037
        Delivery Address:
1038
 
1039
        %(warehouse_executive)s
1040
        %(warehouse_address)s
1041
        PIN %(warehouse_pin)s
1042
 
1043
        Thanks and Regards
4227 rajveer 1044
        Sandeep Sachdeva
2536 chandransh 1045
        '''
4579 rajveer 1046
 
1047
        if warehouse.id == 7:
1048
            executive = 'Amit Kumar'
1049
        else:
4966 phani.kuma 1050
            executive = 'Dinesh Kumar'
4579 rajveer 1051
 
2559 chandransh 1052
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 1053
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
2536 chandransh 1054
                                          'order_weight' : str(order.total_weight),
1055
                                          'customer_address' : __get_order_address(order),
4579 rajveer 1056
                                          'warehouse_executive' : executive,
2536 chandransh 1057
                                          'warehouse_address' : warehouse.location,
4966 phani.kuma 1058
                                          'warehouse_pin' : warehouse.pincode}
4227 rajveer 1059
        #FIXME Email is hardcoded for bluedart
4606 rajveer 1060
        if providerId == 1:
1061
            to_addresses = [to_addr, 'sonikap@bluedart.com']
1062
        else:
1063
            to_addresses = [to_addr]
4966 phani.kuma 1064
 
4606 rajveer 1065
        mail(from_user, from_pwd, to_addresses, subject, message)
4495 rajveer 1066
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
1067
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
1068
            order.statusDescription = "Pick up requested for RETURN"
1069
        else:
1070
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
1071
            order.statusDescription = "Pick up requested for DOA"
4815 phani.kuma 1072
        order.doa_logistics_provider_id = providerId
2536 chandransh 1073
        session.commit()
1074
        return True
1075
    except Exception as e:
1076
        print sys.exc_info()[0]
1077
        return False
1078
 
4602 rajveer 1079
def authorize_pickup(order_id, pickup_number, providerId):
2536 chandransh 1080
    order = get_order(order_id)
4495 rajveer 1081
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 1082
        return False
4815 phani.kuma 1083
    if order.doa_logistics_provider_id is not None:
1084
        providerId = order.doa_logistics_provider_id    #previously we are not storing this so data is taken from omdashboarduser
2536 chandransh 1085
    from_user = 'help@shop2020.in'
1086
    from_pwd = '5h0p2o2o'
1087
    subject = 'Pickup details'
1088
    filename = "/tmp/" +  str(order.id) +".pdf" 
1089
    try:
3133 rajveer 1090
        catalog_client = CatalogClient().get_client()
2536 chandransh 1091
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1092
 
1093
        logistics_client = LogisticsClient().get_client()
4602 rajveer 1094
        provider = logistics_client.getProvider(providerId)
2536 chandransh 1095
        provider_name = provider.name
1096
 
1097
        to_addr = order.customer_email
1098
        today = date.today().strftime("%d-%B-%Y (%A)")
1099
 
1100
        raw_message = '''
1101
        Dear Mr. %(customer_name)s,
1102
 
4815 phani.kuma 1103
        In reference to the return of order ID %(order_id)d, ''' + __generate_mail_body_for_authorize_pickup(order)
1104
        raw_message = raw_message + '''
2536 chandransh 1105
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
1106
        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.
1107
 
1108
        Pickup will happen from the below mentioned address:-
1109
 
1110
        %(customer_address)s
1111
 
1112
        Do let us know in case of any concerns
1113
 
1114
        Thanks & Regards
1115
        Saholic Team
1116
        '''
1117
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
1118
                                         'order_id' : order_id,
1119
                                         'provider_name' : provider_name,
1120
                                         'date': today,
1121
                                         'pickup_request_no' : pickup_number,
1122
                                         'customer_address' : __get_order_address(order)}
1123
        print message
1124
        __generate_return_advice(order, warehouse, provider, filename)
3527 chandransh 1125
        mail(from_user, from_pwd, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 1126
        order.pickupRequestNo = pickup_number
4495 rajveer 1127
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1128
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
1129
            order.statusDescription = "RETURN pick up confirmed"
1130
        else:
1131
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
1132
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 1133
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 1134
        session.commit()
1135
        return True
1136
    except Exception as e:
4234 rajveer 1137
        print sys.exc_info()
4506 phani.kuma 1138
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 1139
        return False
1140
    finally:
1141
        if os.path.exists(filename):
1142
            os.remove(filename)
1143
 
4815 phani.kuma 1144
def __generate_mail_body_for_authorize_pickup(order):
1145
    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.',
1146
                         '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.',
1147
                         '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.',
1148
                         'Sony Ericsson' : 'we request you to kindly pack the original DOA certificate and the invoice.',
1149
                         '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.',
1150
                         '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.',
1151
                         'Accessories' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original product and the invoice.'}
1152
    categories = ["Handsets", "Tablets", "Laptops"]
1153
    lineitem = order.lineitems[0]
1154
    brand = lineitem.brand
1155
    productGroup = lineitem.productGroup
1156
    searchkey = None
1157
    if productGroup not in categories:
1158
        searchkey = 'Accessories'
1159
    elif order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1160
        searchkey = 'Handsets Return'
1161
    elif brand == 'Nokia':
1162
        searchkey = 'Nokia'
1163
    elif brand == 'Micromax':
1164
        searchkey = 'Micromax'
1165
    elif brand == 'Karbonn':
1166
        searchkey = 'Karbonn'
1167
    elif brand == 'Sony Ericsson':
1168
        searchkey = 'Sony Ericsson'
1169
    else:
1170
        searchkey = 'Others Handsets'
1171
    return brand_msgbody_map.get(searchkey)
1172
 
2764 chandransh 1173
def mark_doas_as_picked_up(provider_id, pickup_details):
1174
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1175
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4452 rajveer 1176
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 1177
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1178
            continue
1179
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
1180
        order.statusDescription = "DOA picked up by Courier Company"
1181
        order.doa_pickup_timestamp = doa_pickup_timestamp
1182
    session.commit()
1183
 
4910 phani.kuma 1184
def get_doas_not_picked_up(provider_id):
2764 chandransh 1185
    current_time = datetime.datetime.now()
1186
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1187
    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 1188
    return orders_not_picked_up
1189
 
4741 phani.kuma 1190
def mark_return_orders_as_picked_up(provider_id, pickup_details):
1191
    for pickupNo, return_order_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1192
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4741 phani.kuma 1193
        if order == None or order.status != OrderStatus.RET_PICKUP_CONFIRMED:
1194
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1195
            continue
1196
        order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1197
        order.statusDescription = "Return order picked up by Courier Company"
1198
        order.doa_pickup_timestamp = return_order_pickup_timestamp
1199
    session.commit()
1200
 
4910 phani.kuma 1201
def get_return_orders_not_picked_up(provider_id):
4741 phani.kuma 1202
    current_time = datetime.datetime.now()
1203
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1204
    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 1205
    return orders_not_picked_up
1206
 
4479 rajveer 1207
def receive_return(order_id, receiveCondition):
2591 chandransh 1208
    order = get_order(order_id)
4365 mandeep.dh 1209
 
4452 rajveer 1210
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 1211
        if receiveCondition == 0:
1212
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
1213
            order.statusDescription = "DOA package received"
1214
        elif receiveCondition == 1:
1215
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
1216
            order.statusDescription = "DOA received damaged"
1217
        elif receiveCondition == 2:
1218
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
1219
            order.statusDescription = "DOA lost in transit"
2764 chandransh 1220
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1221
        session.commit()
4495 rajveer 1222
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
1223
        if receiveCondition == 0:
1224
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
1225
            order.statusDescription = "RETURN package received"
1226
        elif receiveCondition == 1:
1227
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
1228
            order.statusDescription = "RETURN received damaged"
1229
        elif receiveCondition == 2:
1230
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
1231
            order.statusDescription = "RETURN lost in transit"
1232
        order.received_return_timestamp = datetime.datetime.now()
1233
        session.commit()
4484 rajveer 1234
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 1235
        if receiveCondition == 0:
1236
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 1237
            order.statusDescription = "Returned to origin"
4486 rajveer 1238
        elif receiveCondition == 1:
1239
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
1240
            order.statusDescription = "RTO received damaged"
1241
        elif receiveCondition == 2:
1242
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
1243
            order.statusDescription = "RTO lost in transit"
2764 chandransh 1244
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1245
        session.commit()
1246
    else:
2591 chandransh 1247
        return False
5110 mandeep.dh 1248
 
1249
    # For OUR warehouses, we need to scan in items for every return
1250
    catalogClient = CatalogClient().get_client()
1251
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1252
    if warehouse.billingType == BillingType.OURS:
1253
        try:
1254
            scanMap = {
1255
                OrderStatus.RTO_RECEIVED_PRESTINE : ScanType.SALE_RET,
1256
                OrderStatus.RTO_RECEIVED_DAMAGED  : ScanType.SALE_RET_UNUSABLE,
1257
                OrderStatus.RTO_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT,
1258
                OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
1259
                OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
1260
                OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
1261
            }
1262
 
1263
            scanType = scanMap[order.status]
1264
            if scanType:
1265
                lineitem = order.lineitems[0]
1266
                warehouseClient = WarehouseClient().get_client()
1267
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
1268
        except Exception as e:
1269
            print sys.exc_info()[0]
1270
            print 'Could not scan in sales return orders' + str(e)
1271
 
2591 chandransh 1272
    return True
1273
 
1274
def validate_doa(order_id, is_valid):
1275
    order = get_order(order_id)
4452 rajveer 1276
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 1277
        return False
1278
    if is_valid:
2609 chandransh 1279
        order.status = OrderStatus.DOA_CERT_VALID
1280
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 1281
    else:
1282
        order.status = OrderStatus.DOA_CERT_INVALID
1283
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 1284
        update_trust_level(order)
2591 chandransh 1285
    session.commit()
1286
    return True
1287
 
4495 rajveer 1288
def validate_return_product(order_id, is_usable):
1289
    order = get_order(order_id)
1290
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
1291
        return False
5110 mandeep.dh 1292
 
1293
    scanType = ScanType.SALE_RET_UNUSABLE
4495 rajveer 1294
    if is_usable:
1295
        order.status = OrderStatus.RET_PRODUCT_USABLE
1296
        order.statusDescription = "Return product usable"
5110 mandeep.dh 1297
        scanType = ScanType.SALE_RET
4495 rajveer 1298
    else:
1299
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
1300
        order.statusDescription = "Return product unusable"
1301
        update_trust_level(order)
1302
    session.commit()
5110 mandeep.dh 1303
 
1304
    # For OUR warehouses, we need to scan in items for every return
1305
    catalogClient = CatalogClient().get_client()
1306
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1307
    if warehouse.billingType == BillingType.OURS:
1308
        lineitem = order.lineitems[0]
1309
        warehouse_client = WarehouseClient().get_client()
1310
        warehouse_client.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
4495 rajveer 1311
    return True
1312
 
2628 chandransh 1313
def reship_order(order_id):
1314
    """
4484 rajveer 1315
    If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1316
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
4484 rajveer 1317
        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 1318
 
1319
    If the order is in DOA_CERT_VALID state, it does the following:
1320
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
1321
        2. Creates a return order for the warehouse executive to return the DOA material.
4452 rajveer 1322
        3. Marks the current order as the final DOA_VALID_RESHIPPED state.
2628 chandransh 1323
 
1324
    Returns the id of the newly created order.
1325
 
1326
    Throws an exception if the order with the given id couldn't be found.
1327
 
1328
    Parameters:
1329
     - orderId
1330
    """
1331
    order = get_order(order_id)
4484 rajveer 1332
    if order.status == OrderStatus.RTO_RECEIVED_PRESTINE:
4220 rajveer 1333
        new_order = __clone_order(order, True, order.cod)
4484 rajveer 1334
        order.status = OrderStatus.RTO_RESHIPPED
2628 chandransh 1335
        order.statusDescription = "Order Reshipped"
1336
        session.commit()
3578 mandeep.dh 1337
        update_trust_level(order)
4486 rajveer 1338
    elif order.status == OrderStatus.RTO_RECEIVED_DAMAGED:
1339
        new_order = __clone_order(order, False, order.cod)
1340
        ret_order = __create_return_order(order)
1341
        order.status = OrderStatus.RTO_DAMAGED_RESHIPPED
1342
        order.statusDescription = "Order Reshipped Received Damaged"
1343
        session.commit()
1344
    elif order.status == OrderStatus.RTO_LOST_IN_TRANSIT:
1345
        new_order = __clone_order(order, False, order.cod)
1346
        order.status = OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED
1347
        order.statusDescription = "Order Reshipped Lost In Transit"
1348
        session.commit()
4662 rajveer 1349
    elif order.status == OrderStatus.LOST_IN_TRANSIT:
1350
        new_order = __clone_order(order, False, order.cod)
1351
        order.status = OrderStatus.LOST_IN_TRANSIT_RESHIPPED
1352
        order.statusDescription = "Order Reshipped Lost In Transit"
1353
        session.commit()
2628 chandransh 1354
    elif order.status == OrderStatus.DOA_CERT_INVALID:
4220 rajveer 1355
        new_order = __clone_order(order, True, False)
2628 chandransh 1356
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
1357
        order.statusDescription = "Order Reshipped"
1358
        session.commit()
1359
    elif order.status == OrderStatus.DOA_CERT_VALID:
4220 rajveer 1360
        new_order = __clone_order(order, False, False)
2628 chandransh 1361
        ret_order = __create_return_order(order)
4452 rajveer 1362
        order.status = OrderStatus.DOA_VALID_RESHIPPED
2628 chandransh 1363
        order.statusDescription = "Order Reshipped"
1364
        session.commit()
4479 rajveer 1365
    elif order.status == OrderStatus.DOA_RECEIVED_DAMAGED:
1366
        new_order = __clone_order(order, False, False)
1367
        ret_order = __create_return_order(order)
1368
        order.status = OrderStatus.DOA_RESHIPPED_RCVD_DAMAGED
1369
        order.statusDescription = "Order Reshipped Received Damaged"
1370
        session.commit()
1371
    elif order.status == OrderStatus.DOA_LOST_IN_TRANSIT:
1372
        new_order = __clone_order(order, False, False)
1373
        order.status = OrderStatus.DOA_RESHIPPED_LOST_IN_TRANSIT
1374
        order.statusDescription = "Order Reshipped Lost In Transit"
1375
        session.commit()
4614 rajveer 1376
    elif order.status == OrderStatus.RET_PRODUCT_USABLE:
4495 rajveer 1377
        new_order = __clone_order(order, True, False)
4614 rajveer 1378
        order.status = OrderStatus.RET_PRODUCT_USABLE_RESHIPPED
4495 rajveer 1379
        order.statusDescription = "Order Reshipped"
1380
        session.commit()
4614 rajveer 1381
    elif order.status == OrderStatus.RET_PRODUCT_UNUSABLE:
4495 rajveer 1382
        new_order = __clone_order(order, False, False)
1383
        ret_order = __create_return_order(order)
4614 rajveer 1384
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE_RESHIPPED
4495 rajveer 1385
        order.statusDescription = "Order Reshipped"
1386
        session.commit()
1387
    elif order.status == OrderStatus.RET_RECEIVED_DAMAGED:
1388
        new_order = __clone_order(order, False, False)
1389
        ret_order = __create_return_order(order)
1390
        order.status = OrderStatus.RET_RESHIPPED_RCVD_DAMAGED
1391
        order.statusDescription = "Order Reshipped Received Damaged"
1392
        session.commit()
1393
    elif order.status == OrderStatus.RET_LOST_IN_TRANSIT:
1394
        new_order = __clone_order(order, False, False)
1395
        order.status = OrderStatus.RET_RESHIPPED_LOST_IN_TRANSIT
1396
        order.statusDescription = "Order Reshipped Lost In Transit"
1397
        session.commit()
2628 chandransh 1398
    else:
1399
        raise TransactionServiceException(112, "This order can't be reshipped")
1400
 
2764 chandransh 1401
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 1402
    order.new_order_id = new_order.id
1403
    session.commit()
1404
 
1405
    return new_order.id
1406
 
3226 chandransh 1407
def refund_order(order_id, refunded_by, reason):
2628 chandransh 1408
    """
4484 rajveer 1409
    If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1410
        1. Creates a refund request for batch processing.
1411
        2. Creates a return order for the warehouse executive to return the shipped material.
4484 rajveer 1412
        3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2628 chandransh 1413
 
1414
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
1415
        1. Creates a refund request for batch processing.
3226 chandransh 1416
        2. Cancels the reservation of the item in the warehouse.
1417
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 1418
 
3226 chandransh 1419
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
1420
        1. Cancels the reservation of the item in the warehouse.
1421
        2. Marks the current order as CANCELED.
1422
 
1423
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
1424
 
1425
    Returns True if it is successful, False otherwise.
2628 chandransh 1426
 
1427
    Throws an exception if the order with the given id couldn't be found.
1428
 
1429
    Parameters:
3226 chandransh 1430
     - order_id
1431
     - refunded_by
1432
     - reason
2628 chandransh 1433
    """
3414 chandransh 1434
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 1435
    order = get_order(order_id)
3186 chandransh 1436
 
3226 chandransh 1437
    if order.cod:
3414 chandransh 1438
        logging.info("Refunding COD order with status " + str(order.status))
4662 rajveer 1439
        status_transition = { OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
1440
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 1441
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
1442
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 1443
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
1444
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 1445
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
1446
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 1447
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
1448
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
1449
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
1450
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 1451
                     OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.COD_VERIFICATION_FAILED,
1452
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1453
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1454
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1455
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1456
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1457
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1458
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 1459
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST
3366 chandransh 1460
                     }
1461
        if order.status not in status_transition.keys():
1462
            raise TransactionServiceException(114, "This order can't be refunded")
1463
 
3413 chandransh 1464
        if order.status < OrderStatus.BILLED:
3226 chandransh 1465
            __update_inventory_reservation(order)
1466
            order.statusDescription = "Order Cancelled"
3415 chandransh 1467
        elif order.status == OrderStatus.BILLED:
3413 chandransh 1468
            __create_return_order(order)
1469
            order.statusDescription = "Order Cancelled"
4486 rajveer 1470
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
3226 chandransh 1471
            __create_return_order(order)
4486 rajveer 1472
            order.statusDescription = "RTO Refunded"
4662 rajveer 1473
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
1474
            __create_return_order(order)
1475
            order.statusDescription = "Lost in Transit Refunded"
4479 rajveer 1476
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
4078 chandransh 1477
            __create_return_order(order)
3226 chandransh 1478
            __create_refund(order)
4495 rajveer 1479
            order.statusDescription = "DOA Refunded"
1480
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
1481
            __create_return_order(order)
1482
            __create_refund(order)
1483
            order.statusDescription = "Return Refunded"
4247 rajveer 1484
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
1485
            if order.previousStatus  < OrderStatus.BILLED:
1486
                __update_inventory_reservation(order)
1487
                order.statusDescription = "Order Cancelled on customer request"
1488
            elif order.previousStatus == OrderStatus.BILLED:
1489
                __create_return_order(order)
1490
                order.statusDescription = "Order Cancelled on customer request"
3226 chandransh 1491
    else:
4662 rajveer 1492
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
1493
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 1494
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
1495
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 1496
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
1497
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 1498
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
1499
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 1500
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
1501
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
1502
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
1503
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 1504
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1505
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1506
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1507
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1508
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1509
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
1510
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 1511
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
1512
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 1513
                     }
1514
        if order.status not in status_transition.keys():
1515
            raise TransactionServiceException(114, "This order can't be refunded")
1516
 
4495 rajveer 1517
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
3226 chandransh 1518
            __create_return_order(order)
1519
            __create_refund(order)
4495 rajveer 1520
            order.statusDescription = "RTO Refunded"
4662 rajveer 1521
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
1522
            __create_return_order(order)
1523
            __create_refund(order)
1524
            order.statusDescription = "Lost in Transit Refunded"
4495 rajveer 1525
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
1526
            __create_return_order(order)
1527
            __create_refund(order)
1528
            order.statusDescription = "DOA Refunded"
1529
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
1530
            __create_return_order(order)
1531
            __create_refund(order)
1532
            order.statusDescription = "Return Refunded"
4306 rajveer 1533
        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 1534
            __create_refund(order)
3226 chandransh 1535
            __update_inventory_reservation(order)
1536
            order.statusDescription = "Order Refunded"
4247 rajveer 1537
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
1538
            if order.previousStatus  < OrderStatus.BILLED:
4672 rajveer 1539
                if order.previousStatus == OrderStatus.ACCEPTED:
1540
                    __create_refund(order)
4247 rajveer 1541
                __update_inventory_reservation(order)
1542
                order.statusDescription = "Order Cancelled on customer request"
1543
            elif order.previousStatus == OrderStatus.BILLED:
1544
                __create_return_order(order)
1545
                __create_refund(order)
1546
                order.statusDescription = "Order Cancelled on customer request"
1547
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
1548
            __update_inventory_reservation(order)
1549
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 1550
 
4873 mandeep.dh 1551
    # For orders that are cancelled after being billed, we need to scan in the scanned out
1552
    # inventory item and change availability accordingly
5110 mandeep.dh 1553
    catalogClient = CatalogClient().get_client()
1554
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1555
    if warehouse.billingType == BillingType.OURS:
4873 mandeep.dh 1556
        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]):
1557
            lineitem = order.lineitems[0]
1558
            warehouseClient = WarehouseClient().get_client()
5110 mandeep.dh 1559
            warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
4873 mandeep.dh 1560
 
3195 chandransh 1561
    order.status = status_transition[order.status]
1562
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 1563
    order.refunded_by = refunded_by
1564
    order.refund_reason = reason
4873 mandeep.dh 1565
 
2628 chandransh 1566
    session.commit()
1567
    return True
1568
 
3186 chandransh 1569
def __update_inventory_reservation(order):
3191 chandransh 1570
    '''
1571
    Reduce the reservation count for all line items of the given order.
1572
    '''
3186 chandransh 1573
    try:
1574
        catalog_client = CatalogClient().get_client()
1575
        for lineitem in order.lineitems:
5110 mandeep.dh 1576
            catalog_client.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, lineitem.quantity);
3186 chandransh 1577
    except:
1578
        print "Unable to reduce reservation count"
1579
 
4220 rajveer 1580
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 1581
    current_time = datetime.datetime.now()
1582
    new_order = Order()
1583
    new_order.customer_id = order.customer_id
1584
    new_order.customer_name = order.customer_name
1585
    new_order.customer_city = order.customer_city
1586
    new_order.customer_state = order.customer_state
1587
    new_order.customer_mobilenumber = order.customer_mobilenumber
1588
    new_order.customer_pincode = order.customer_pincode
1589
    new_order.customer_address1 = order.customer_address1
1590
    new_order.customer_address2 = order.customer_address2
1591
    new_order.customer_email = order.customer_email
1592
    new_order.total_amount = order.total_amount
1593
    new_order.total_weight = order.total_weight
1594
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1595
    new_order.statusDescription = 'Submitted for Processing'
1596
    new_order.created_timestamp = current_time
5062 varun.gupt 1597
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 1598
 
1599
    new_order.transaction = order.transaction
4220 rajveer 1600
    new_order.cod = is_cod
2628 chandransh 1601
 
1602
    for line_item in order.lineitems:
1603
        litem = LineItem()
1604
        litem.item_id = line_item.item_id
1605
        litem.productGroup = line_item.productGroup
1606
        litem.brand = line_item.brand
1607
        if line_item.model_number:
1608
            litem.model_number = line_item.model_number
1609
        if line_item.model_name:    
1610
            litem.model_name = line_item.model_name
1611
        if line_item.color:
1612
            litem.color = line_item.color
1613
        if line_item.extra_info:
1614
            litem.extra_info = line_item.extra_info
1615
        litem.quantity = line_item.quantity
1616
        litem.unit_price = line_item.unit_price
1617
        litem.unit_weight = line_item.unit_weight
1618
        litem.total_price = line_item.total_price
1619
        litem.total_weight = line_item.total_weight
1620
        litem.transfer_price = line_item.transfer_price
4840 mandeep.dh 1621
        litem.dealText = line_item.dealText
2628 chandransh 1622
        litem.order = new_order
1623
 
1624
    logistics_client = LogisticsClient().get_client()
1625
    item_id = new_order.lineitems[0].item_id
4479 rajveer 1626
    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 1627
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
1628
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 1629
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 1630
    new_order.logistics_provider_id = logistics_info.providerId
1631
    new_order.airwaybill_no = logistics_info.airway_billno
1632
    new_order.tracking_id = new_order.airwaybill_no
1633
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 1634
    new_order.promised_delivery_time = new_order.expected_delivery_time
4299 rajveer 1635
 
2628 chandransh 1636
    if should_copy_billing_info:
1637
        new_order.invoice_number = order.invoice_number
1638
        new_order.billed_by = order.billed_by
1639
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 1640
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
2628 chandransh 1641
        new_order.accepted_timestamp = current_time
1642
        new_order.billing_timestamp = current_time    
1643
        new_order.status = OrderStatus.BILLED
1644
        new_order.statusDescription = 'Order Billed'
1645
    else:       
3133 rajveer 1646
        catalog_client = CatalogClient().get_client()
5110 mandeep.dh 1647
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, new_order.lineitems[0].quantity)
2628 chandransh 1648
 
1649
    return new_order
1650
 
1651
def __create_return_order(order):
2687 chandransh 1652
    ret_order = ReturnOrder(order)
2628 chandransh 1653
    return ret_order
1654
 
1655
def __create_refund(order):
4078 chandransh 1656
    payment_client = PaymentClient().get_client()
1657
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 1658
    return
2628 chandransh 1659
 
2536 chandransh 1660
def __get_order_address(order):
1661
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
1662
    if order.customer_address2:
1663
        address = address + order.customer_address2 + "\n"
1664
    address = address + order.customer_city + "\n"
1665
    address = address + order.customer_state + "\n"
1666
    address = address + "PIN " + order.customer_pincode + "\n"
1667
    address = address + "Phone: " + order.customer_mobilenumber
1668
    return address
1669
 
4815 phani.kuma 1670
def __generate_return_advice(order, warehouse, provider, filename):
1671
    if warehouse.id == 7:
1672
        executive = 'Amit Kumar'
1673
    else:
4966 phani.kuma 1674
        executive = 'Dinesh Kumar'
2536 chandransh 1675
    pdf = Canvas(filename)
1676
    pdf.setFont('Times-Bold',16)
1677
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
1678
    address_text.textLine("To")
4815 phani.kuma 1679
    address_text.textLine(executive)
2536 chandransh 1680
    for line in warehouse.location.split("\n"):
1681
        address_text.textLine(line)
1682
    address_text.textLine("PIN " + warehouse.pincode)
1683
    pdf.drawText(address_text)
1684
 
1685
    pdf.setFont('Times-Roman',12)
1686
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 1687
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 1688
    lineitem = order.lineitems[0] 
4234 rajveer 1689
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 1690
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
1691
    order_text.textLine("Order ID : " + str(order.id))
1692
    pdf.drawText(order_text)
1693
    pdf.showPage()
1694
    pdf.save()
1695
    return filename
1696
 
2697 chandransh 1697
def get_return_orders(warehouse_id, from_date, to_date):
1698
    query = ReturnOrder.query.filter_by(processedStatus = False)
1699
    if warehouse_id != -1:
1700
        query = query.filter_by(warehouseId = warehouse_id)
1701
    if from_date:
4118 chandransh 1702
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 1703
    if to_date:
4118 chandransh 1704
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 1705
    return [return_order.to_thrift_object() for return_order in query.all()]
1706
 
2700 chandransh 1707
def get_return_order(id):
1708
    ret_order = ReturnOrder.get_by(orderId = id)
1709
    if ret_order is None:
1710
        raise TransactionServiceException(116, "No return order found for the given order id")
1711
    return ret_order.to_thrift_object()
1712
 
2697 chandransh 1713
def process_return(ret_order_id):
1714
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
1715
    if ret_order is None:
1716
        raise TransactionServiceException(116, "No return order found for the given order id")
1717
    ret_order.processedStatus = True
2701 chandransh 1718
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 1719
    session.commit()
1720
 
4757 mandeep.dh 1721
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
1722
    """
1723
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
1724
    the quantities for which the PO is raised.
1725
 
1726
    Parameters:
1727
     - itemIdQuantityMap
1728
     - purchaseOrderId
1729
     - warehouseId
1730
    """
3451 chandransh 1731
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 1732
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 1733
    query = query.filter_by(purchase_order_id=None)
1734
    query = query.order_by(Order.created_timestamp)
1735
    pending_orders = query.all()
4586 mandeep.dh 1736
 
1737
    for order in pending_orders:
4757 mandeep.dh 1738
        lineitem = order.lineitems[0]
1739
        if itemIdQuantityMap.has_key(lineitem.item_id):
1740
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
1741
                order.status = OrderStatus.LOW_INV_PO_RAISED
1742
                order.statusDescription = 'In Process'
1743
                order.purchase_order_id = purchaseOrderId
1744
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 1745
 
2819 chandransh 1746
    session.commit()
1747
 
3451 chandransh 1748
def update_weight(order_id, weight):
3469 chandransh 1749
    '''
1750
    Update the weight of order
1751
    '''
3451 chandransh 1752
    order = get_order(order_id)
1753
    order.total_weight = weight
3469 chandransh 1754
    lineitem = order.lineitems[0]
1755
    lineitem.total_weight = weight
1756
    lineitem.unit_weight = weight
3451 chandransh 1757
 
3469 chandransh 1758
    session.commit()
1759
    return order
1760
 
1761
def change_product(order_id, item_id):
1762
    '''
1763
    Ship a product of a different color to the customer.
1764
    '''
1765
    order = get_order(order_id)
4662 rajveer 1766
    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 1767
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
1768
 
1769
    lineitem = order.lineitems[0]
3451 chandransh 1770
 
3469 chandransh 1771
    catalog_client = CatalogClient().get_client()
1772
 
1773
    old_item = catalog_client.getItem(lineitem.item_id)
1774
    item = catalog_client.getItem(item_id)
1775
    if old_item.catalogItemId != item.catalogItemId:
1776
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
1777
 
5110 mandeep.dh 1778
    catalog_client.reserveItemInWarehouse(item_id, order.fulfilmentWarehouseId, lineitem.quantity)
1779
    __update_inventory_reservation(order)
3469 chandransh 1780
    #TODO: Check that this new item has the same price
1781
 
1782
    lineitem.item_id = item_id
1783
    lineitem.color = item.color
1784
 
3451 chandransh 1785
    session.commit()
3469 chandransh 1786
 
1787
    order = get_order(order_id)
3451 chandransh 1788
    return order
3469 chandransh 1789
 
1790
def change_warehouse(order_id, warehouse_id):
1791
    '''
1792
    Update the warehouse which will be used to fulfil this order.
1793
    '''
1794
    order = get_order(order_id)
4662 rajveer 1795
    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 1796
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
1797
 
1798
    if warehouse_id == order.warehouse_id:
1799
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
1800
 
1801
    lineitem = order.lineitems[0]
1802
    catalog_client = CatalogClient().get_client()
1803
    try:
1804
        warehouse = catalog_client.getWarehouse(warehouse_id)
1805
    except:
1806
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 1807
 
1808
    if warehouse.billingWarehouseId is None or warehouse.inventoryType != InventoryType.GOOD:
1809
        raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
1810
 
3469 chandransh 1811
    catalog_client.reserveItemInWarehouse(lineitem.item_id, warehouse_id, lineitem.quantity)
5110 mandeep.dh 1812
    __update_inventory_reservation(order)
1813
 
1814
    order.warehouse_id = warehouse.billingWarehouseId
1815
    order.fulfilmentWarehouseId = warehouse_id
3469 chandransh 1816
    session.commit()
1817
    return order
3553 chandransh 1818
 
4647 rajveer 1819
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 1820
    '''
3994 chandransh 1821
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 1822
    '''
1823
    order = get_order(order_id)
1824
    try:
3581 chandransh 1825
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 1826
        order.delayReasonText = delayReasonText
4009 chandransh 1827
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
1828
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 1829
 
4842 rajveer 1830
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
1831
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 1832
 
3553 chandransh 1833
        session.commit()
4008 mandeep.dh 1834
 
1835
        try:
1836
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
1837
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
1838
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
1839
            session.commit()
1840
        except Exception as e:
4065 mandeep.dh 1841
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 1842
 
3553 chandransh 1843
        return True
1844
    except:
3994 chandransh 1845
        print sys.exc_info()[0]
3553 chandransh 1846
        return False
3956 chandransh 1847
 
1848
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
1849
    unprocessed_awbs = {}
1850
    for awb, amount in collected_amount_map.iteritems():
1851
        try:
1852
            order = Order.query.filter_by(airwaybill_no=awb).one()
1853
        except NoResultFound:
1854
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
1855
            continue
1856
        except MultipleResultsFound:
1857
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
1858
            continue
1859
 
1860
        if order.cod_reconciliation_timestamp:
1861
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
1862
            continue
1863
 
1864
        if order.status < OrderStatus.DELIVERY_SUCCESS:
1865
            #Order has not been delivered yet. No way we can receive the payment.
1866
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
1867
            continue
1868
 
4252 rajveer 1869
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
1870
        if abs(amount - order.total_amount) > 0.5:
3956 chandransh 1871
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
1872
            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)
1873
            continue
1874
 
1875
        try:
1876
            payment_client = PaymentClient().get_client()
1877
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
1878
        except Exception:
1879
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
1880
            continue
1881
 
1882
        #Payment has been recorded now. We can update the order peacefully.
1883
        order.cod_reconciliation_timestamp = datetime.datetime.now()
1884
        session.commit()
3469 chandransh 1885
 
3956 chandransh 1886
    return unprocessed_awbs
4008 mandeep.dh 1887
 
1888
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 1889
    """
1890
    Returns the list of transaction ids that require some extra processing and
1891
    which belong to a particular category. This is currently used by CRM
1892
    application. If no such transaction ids are present, it returns an empty list.
1893
    """
1894
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 1895
 
4065 mandeep.dh 1896
    if category is not None:
1897
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 1898
 
4065 mandeep.dh 1899
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 1900
 
1901
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 1902
    """
1903
    Marks a particular transaction as processed for a particular cateogory.
1904
    It essentially deletes the transaction id record for a particular
1905
    processing type category (if present) from DB.
1906
    This is currently used by CRM application.
1907
    """
4008 mandeep.dh 1908
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
1909
    session.commit()
1910
 
4018 chandransh 1911
def get_item_wise_risky_orders_count():
1912
    """
1913
    Returns a map containing the number of risky orders keyed by item id. A risky order
1914
    is defined as one whose shipping date is about to expire.
1915
    """
1916
    item_wise_risky_orders_count = {}
4019 chandransh 1917
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 1918
    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()
1919
    for order in orders:
1920
        for lineitem in order.lineitems:
1921
            quantity = lineitem.quantity
1922
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
1923
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
1924
 
1925
            item_wise_risky_orders_count[lineitem.item_id] = quantity
1926
    return item_wise_risky_orders_count
1927
 
4324 mandeep.dh 1928
def update_shipment_address(order_id, address_id):
1929
    """
1930
    Updates shipment address of an order. Delivery and shipping date estimates
1931
    etc. are also updated here.
1932
 
1933
    Throws TransactionServiceException in case address change is not
1934
    possible due to certain reasons such as new pincode in address is
1935
    not serviceable etc.
1936
 
1937
    Parameters:
1938
     - orderId
1939
     - addressId
1940
    """
1941
    user_client = UserClient().get_client()
1942
    address     = user_client.getAddressById(address_id)
1943
    order       = get_order(order_id)
1944
 
4630 mandeep.dh 1945
    type = DeliveryType.PREPAID
1946
    if order.cod:
1947
        type = DeliveryType.COD
1948
 
4324 mandeep.dh 1949
    logistics_client = LogisticsClient().get_client()
4630 mandeep.dh 1950
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type)
4324 mandeep.dh 1951
 
1952
    # Check for new estimate. Raise exception if new address is not serviceable
1953
    if logistics_info.deliveryTime == -1:
1954
        raise TransactionServiceException(1, 'Location not serviceable')
1955
 
1956
    # COD services are not available everywhere
1957
    if order.cod:
4868 rajveer 1958
        if not logistics_info.codAllowed:
4324 mandeep.dh 1959
            raise TransactionServiceException(2, 'COD service not available')
1960
 
1961
    current_time = datetime.datetime.now()
1962
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
1963
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
1964
 
1965
    order.customer_name         = address.name
1966
    order.customer_pincode      = address.pin
1967
    order.customer_address1     = address.line1
1968
    order.customer_address2     = address.line2
1969
    order.customer_city         = address.city
1970
    order.customer_state        = address.state
1971
    order.customer_mobilenumber = address.phone
1972
 
1973
    if order.cod:
1974
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
1975
    else:
1976
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
1977
 
1978
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
1979
    order.promised_shipping_time = order.expected_shipping_time
1980
    order.promised_delivery_time = order.expected_delivery_time 
1981
 
1982
    session.commit()
1983
 
4247 rajveer 1984
def mark_order_cancellation_request_received(orderId):
1985
    """
1986
    Mark order as cancellation request received. If customer sends request of cancellation of
1987
    a particular order, this method will be called. It will just change status of the order
1988
    depending on its current status. It also records the previous status, so that we can move
1989
    back to that status if cancellation request is denied.
1990
 
1991
    Parameters:
1992
     - orderId
1993
    """
4662 rajveer 1994
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 1995
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
1996
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 1997
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
1998
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
1999
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2000
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2001
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2002
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
2003
             }
4662 rajveer 2004
 
2005
    order = get_order(orderId)
4247 rajveer 2006
    if order.status not in status_transition.keys():
2007
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
2008
 
4662 rajveer 2009
 
4247 rajveer 2010
    order.previousStatus = order.status
2011
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
2012
    order.statusDescription = "Cancellation request received from user"
2013
    session.commit()
2014
 
4662 rajveer 2015
def mark_order_as_lost_in_transit(orderId):
2016
    """
2017
    Parameters:
2018
     - orderId
2019
    """
2020
    order = get_order(orderId)
4910 phani.kuma 2021
    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 2022
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
2023
    order.status = OrderStatus.LOST_IN_TRANSIT
2024
    order.statusDescription = "Lost in Transit"
2025
    session.commit()
2026
 
4258 rajveer 2027
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 2028
    """
4258 rajveer 2029
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
2030
    Changed transaction and all orders status to payment accepted.
4247 rajveer 2031
 
2032
    Parameters:
4258 rajveer 2033
     - transactionId
4247 rajveer 2034
    """
4258 rajveer 2035
    transaction = get_transaction(transactionId)
2036
    transaction.status = TransactionStatus.AUTHORIZED
2037
    for order in transaction.orders:
2038
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2039
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 2040
    session.commit()
2041
 
4259 anupam.sin 2042
def refund_transaction(transactionId, refundedBy, reason):
2043
    """
2044
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
2045
    need to be cancelled
2046
 
2047
    Parameters:
2048
     - transactionId
2049
    """
2050
    transaction = get_transaction(transactionId)
2051
    transaction.status = TransactionStatus.FAILED
2052
    for order in transaction.orders:
2053
        refund_order(order.id, refundedBy, reason)
2054
    session.commit()
2055
 
4247 rajveer 2056
def mark_order_cancellation_request_denied(orderId):
2057
    """
4283 anupam.sin 2058
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 2059
 
2060
    Parameters:
2061
     - orderId
2062
    """
2063
    order = get_order(orderId)
2064
    order.status = order.previousStatus
2065
    order.previousStatus = None
2066
    order.statusDescription = "Cancellation request denied"
2067
    session.commit()
2068
 
2069
def mark_order_cancellation_request_confirmed(orderId):
2070
    """
2071
    If we decide to to cancel order, CRM will call this method to move the status of order to
2072
    cancellation request confirmed. After this OM will be able to cancel the order.
2073
 
2074
    Parameters:
2075
     - orderId
2076
    """
2077
    order = get_order(orderId)
2078
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
2079
    order.statusDescription = "Cancellation request confirmed"
2080
    session.commit()
2081
 
4285 rajveer 2082
def accept_orders_for_item_id(itemId, inventory):
2083
    """
2084
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
2085
    given order is not a COD order, it also captures the payment if the same has not been captured.
2086
 
2087
    Parameters:
2088
     - itemId
2089
     - inventory
2090
    """
4938 rajveer 2091
    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 2092
    for order in orders:
4301 rajveer 2093
        if inventory > 0:
2094
            lineitem = order.lineitems[0]
2095
            if itemId == lineitem.item_id:
2096
                try:
2097
                    accept_order(order.id)
2098
                    inventory = inventory - lineitem.quantity
2099
                except:
2100
                    logging.info("Unable to accept the order")
2101
        else:
2102
            order_outofstock(order.id)
4285 rajveer 2103
    return
2104
 
4607 rajveer 2105
def get_slipped_sipping_date_orders():
4662 rajveer 2106
    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 2107
 
2108
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
2109
    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 2110
 
4369 rajveer 2111
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
2112
    if isReminder:
2113
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2114
    else:
2115
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2116
 
2117
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2118
    for order in orders:
2119
        lineitem = order.lineitems[0]
2120
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2121
            if estimate > 0:
2122
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2123
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 2124
            order.statusDescription = "PO Raised"
4303 rajveer 2125
            quantity = quantity - lineitem.quantity
2126
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
2127
            session.commit()
2128
 
4369 rajveer 2129
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
2130
    if isReminder:
2131
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2132
    else:
2133
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2134
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2135
    for order in orders:
2136
        lineitem = order.lineitems[0]
2137
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2138
            if estimate > 0:
2139
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2140
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 2141
            order.statusDescription = "Reversal Initiated"
4303 rajveer 2142
            quantity = quantity - lineitem.quantity
2143
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
2144
            session.commit()
2145
 
4369 rajveer 2146
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
2147
    if isReminder:
2148
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2149
    else:
2150
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2151
 
2152
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2153
    for order in orders:
2154
        lineitem = order.lineitems[0]
2155
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2156
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 2157
            order.statusDescription = "Not Available"
4303 rajveer 2158
            quantity = quantity - lineitem.quantity
2159
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
2160
            session.commit()
2161
 
2162
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 2163
    orderInv = OrderInventory.get_by(order_id=order.id)
2164
    if not orderInv:
2165
        orderInv = OrderInventory()
2166
        orderInv.order = order
4303 rajveer 2167
    orderInv.hotspotAction = hotspotAction  
2168
    orderInv.estimate = estimate
2169
    orderInv.itemId = itemId
2170
    orderInv.timestamp = datetime.datetime.now()
2171
    orderInv.quantity = quantity
2172
 
4556 mandeep.dh 2173
'''    
4369 rajveer 2174
def mark_orders_as_timeout(vendorId):
2175
    ret_timeouts = {}
2176
    orderInvs = OrderInventory.query.all()
2177
    for orderInv in orderInvs:
2178
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
2179
            if not ret_timeouts.has_key(orderInv.itemId):
2180
                timeout = TimeoutSummary()
2181
                ret_timeouts[orderInv.itemId] = timeout
2182
            else:
2183
                timeout = ret_timeouts.get(orderInv.itemId)
2184
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2185
                if timeout.poRaised:
2186
                    timeout.poRaised += 1
2187
                else:
2188
                    timeout.poRaised = 1
2189
 
2190
                if timeout.poEstimate:
2191
                    timeout.poEstimate += orderInv.estimate
2192
                else:
2193
                    timeout.poEstimate = orderInv.estimate
2194
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
2195
                orderInv.order.statusDescription = "PO Raised Timeout"
2196
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2197
                if timeout.reversalInitiated:
2198
                    timeout.reversalInitiated += 1
2199
                else:
2200
                    timeout.reversalInitiated = 1
2201
 
2202
                if timeout.reversalEstimate:
2203
                    timeout.reversalEstimate += orderInv.estimate
2204
                else:
2205
                    timeout.reversalEstimate = orderInv.estimate
2206
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
2207
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
2208
            else:
2209
                orderInv.delete()
2210
    session.commit()
2211
    return ret_timeouts
4556 mandeep.dh 2212
'''
2213
 
2214
 
2215
def mark_orders_as_timeout(vendorId):
2216
    ret_timeouts = {}
2217
    orderInvs = OrderInventory.query.all()
2218
    for orderInv in orderInvs:
2219
        if not ret_timeouts.has_key(orderInv.itemId):
2220
            timeout = TimeoutSummary()
2221
            ret_timeouts[orderInv.itemId] = timeout
2222
        else:
2223
            timeout = ret_timeouts.get(orderInv.itemId)
2224
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2225
            if timeout.poRaised:
2226
                timeout.poRaised += 1
2227
            else:
2228
                timeout.poRaised = 1
2229
 
2230
            if timeout.poEstimate:
2231
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
2232
            else:
2233
                timeout.poEstimate = orderInv.estimate
2234
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2235
            if timeout.reversalInitiated:
2236
                timeout.reversalInitiated += 1
2237
            else:
2238
                timeout.reversalInitiated = 1
2239
 
2240
            if timeout.reversalEstimate:
2241
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
2242
            else:
2243
                timeout.reversalEstimate = orderInv.estimate
2244
        orderInv.order.status = OrderStatus.INVENTORY_LOW
2245
        orderInv.order.statusDescription = "Low Inventory"
2246
        orderInv.delete()
2247
    session.commit()
2248
    return ret_timeouts
2249
 
4386 anupam.sin 2250
def get_order_for_awb(awb):
2251
    order = Order.get_by(airwaybill_no=awb)
2252
    if not order:
2253
        raise TransactionServiceException(108, "no such order")
2254
 
2255
    return order
4369 rajveer 2256
 
4910 phani.kuma 2257
def get_orders_for_provider_for_status(provider_id, order_status_list):
2258
    if not provider_id or not order_status_list:
4506 phani.kuma 2259
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 2260
    doa_provider = False
2261
    for order_status in order_status_list:
2262
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
2263
            doa_provider = True
2264
    if doa_provider:
2265
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 2266
    else:
4910 phani.kuma 2267
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 2268
    return query.all()
4386 anupam.sin 2269
 
4600 varun.gupt 2270
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
2271
    query = Order.query.filter_by(vendorId = vendor_id)
2272
    query = query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
2273
    if billing_date_from:
2274
        query = query.filter(Order.billing_timestamp >= billing_date_from)
2275
 
2276
    if billing_date_to:
2277
        query = query.filter(Order.billing_timestamp <= billing_date_to)
2278
 
2279
    return query.all()
2280
 
4875 varun.gupt 2281
def get_orders_where_vendor_not_paid(vendor_id):
4885 varun.gupt 2282
    query = Order.query.filter_by(vendorId = vendor_id)
2283
    query = query.filter(Order.billing_timestamp != None)
2284
    query = query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
2285
    query = query.filter(Order.vendor_paid == False)
2286
    return query.all()
4875 varun.gupt 2287
 
4600 varun.gupt 2288
def save_bluedart_settlements(map_awb_and_amount):
2289
    payment_client = PaymentClient().get_client()
2290
 
2291
    for awb, amount in map_awb_and_amount.iteritems():
2292
        order = Order.get_by(airwaybill_no = awb)
2293
 
2294
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
2295
        settlement = PaymentSettlement()
2296
        settlement.paymentId = payment.paymentId
2297
        settlement.paymentGatewayId = payment.gatewayId
2298
        settlement.netCollection = amount
2299
        session.commit()
2300
 
4905 varun.gupt 2301
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
4600 varun.gupt 2302
 
2303
    settlement = PaymentSettlement()
2304
    settlement.settlementDate = settlementDate
2305
    settlement.paymentGatewayId = paymentGatewayId
4905 varun.gupt 2306
    settlement.referenceId = referenceId
4600 varun.gupt 2307
    settlement.serviceTax = serviceTax
2308
    settlement.otherCharges = otherCharges
2309
    settlement.netCollection = netCollection
2310
    session.commit()
2311
 
2312
def get_settlement_for_paymentId(payment_id):
2313
    payment_settlement = PaymentSettlement.get_by(paymentId = payment_id)
2314
 
2315
    return payment_settlement
2316
 
2317
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
2318
    summary = EBSSettlementSummary()
2319
    summary.settlementId = settlement_id
2320
    summary.settlementDate = settlement_date
2321
    summary.transactionDateFrom = transaction_date_from
2322
    summary.transactionDateTo = transaction_date_to
2323
    summary.amount = amount
2324
    summary.detailsUploaded = False
2325
    session.commit()
2326
 
2327
def get_ebs_settlement_summaries():
2328
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
2329
    summary_map = {}
2330
 
2331
    for summary in summaries:
2332
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
2333
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
2334
 
2335
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
2336
 
2337
    return summary_map
2338
 
2339
def get_ebs_settlement_date(settlement_id):
2340
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
2341
 
2342
    if summary:
2343
        return summary.settlementDate
2344
 
2345
def mark_ebs_settlement_uploaded(settlement_id):
2346
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
2347
 
2348
    if summary:
2349
        summary.detailsUploaded = True
2350
        session.commit()
4715 varun.gupt 2351
 
2352
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
2353
    query = PaymentSettlement.query
4600 varun.gupt 2354
 
4715 varun.gupt 2355
    if settlement_date_from:
2356
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
2357
 
2358
    if settlement_date_to:
2359
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
2360
 
4749 varun.gupt 2361
    if is_refund is True:
2362
        query = query.filter(PaymentSettlement.netCollection < 0.0)
2363
    else:
2364
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 2365
 
4749 varun.gupt 2366
    return query.all()
4715 varun.gupt 2367
 
2368
def get_reshipped_order_ids(order_ids):
2369
    reshipped_order_ids = []
2370
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
2371
 
4749 varun.gupt 2372
def get_shipping_confirmation_email_body(order):
2373
 
2374
    html = """
2375
<html>
2376
<body>
2377
<div>
2378
    <p>Dear Customer,</p>
2379
    <p>
4885 varun.gupt 2380
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
4749 varun.gupt 2381
        The shipment will be delivered to you via Bluedart/Aramex Courier Service vide AWB# $awb.
2382
    </p>
2383
    <p>
2384
        Expected delivery date for your order is $expected_delivery_date. 
2385
        The product can be delivered to you between business hours of 10am to 6pm. 
2386
        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.
2387
    </p>
2388
    <p>
2389
        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#.
2390
    </p>
2391
    <p>Bluedart: 011-66111234<br />Aramex:  0124- 39419900</p>
2392
    <p>
2393
        Warm Regards,<br />
2394
        Saholic Team
2395
    </p>
4750 varun.gupt 2396
</div>
4749 varun.gupt 2397
</body>
2398
</html>
2399
    """
2400
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 2401
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
4749 varun.gupt 2402
    product = "%s %s %s" % (order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number)
4885 varun.gupt 2403
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (order.promised_delivery_time - order.promised_shipping_time).days))
2404
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
4749 varun.gupt 2405
    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 2406
    return Template(html).substitute(info)
4749 varun.gupt 2407
 
2408
def enqueue_shipping_confirmation_email(orders):
4915 varun.gupt 2409
    # Calling helper service on production
2410
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
4749 varun.gupt 2411
 
2412
    for order in orders:
2413
        try:
2414
            emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
2415
            emailBody = get_shipping_confirmation_email_body(order)
4885 varun.gupt 2416
            helperClient.saveUserEmailForSending(order.customer_email, None, emailSubject, emailBody, '', 'ShippingConfirmation')
4749 varun.gupt 2417
        except Exception as e:
2418
            print e
2419
 
4915 varun.gupt 2420
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 2421
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
2422
    query = query.filter(Order.created_timestamp >= start_date)
2423
    query = query.filter(Order.created_timestamp <= end_date)
2424
    return query.all()
4915 varun.gupt 2425
 
5067 varun.gupt 2426
def get_order_ids_for_status(status, start_datetime, end_datetime):
2427
    query = Order.query.filter(Order.status == status)
2428
    query = query.filter(Order.created_timestamp >= start_datetime)
2429
    query = query.filter(Order.created_timestamp <= end_datetime)
2430
    return query.all()
2431
 
5099 varun.gupt 2432
def update_orders_as_paid_to_vendor(order_id):
2433
    query = Order.query.filter(Order.originalOrderId == order_id)
2434
    query = query.filter(Order.id == order_id)
2435
 
2436
    for order in query.all():
2437
        order.vendor_paid = True
2438
        session.commit()
2439
 
766 rajveer 2440
def close_session():
2441
    if session.is_active:
2442
        print "session is active. closing it."
2783 chandransh 2443
        session.close()
3376 rajveer 2444
 
2445
def is_alive():
2446
    try:
2447
        session.query(Transaction.id).limit(1).one()
2448
        return True
2449
    except:
4343 varun.gupt 2450
        return False