Subversion Repositories SmartDukaan

Rev

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

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