Subversion Repositories SmartDukaan

Rev

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