Subversion Repositories SmartDukaan

Rev

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

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