Subversion Repositories SmartDukaan

Rev

Rev 5386 | Rev 5388 | 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:
1671
        new_order.invoice_number = order.invoice_number
1672
        new_order.billed_by = order.billed_by
1673
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 1674
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
2628 chandransh 1675
        new_order.accepted_timestamp = current_time
1676
        new_order.billing_timestamp = current_time    
1677
        new_order.status = OrderStatus.BILLED
1678
        new_order.statusDescription = 'Order Billed'
1679
    else:       
3133 rajveer 1680
        catalog_client = CatalogClient().get_client()
5110 mandeep.dh 1681
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, new_order.lineitems[0].quantity)
2628 chandransh 1682
 
1683
    return new_order
1684
 
1685
def __create_return_order(order):
2687 chandransh 1686
    ret_order = ReturnOrder(order)
2628 chandransh 1687
    return ret_order
1688
 
1689
def __create_refund(order):
4078 chandransh 1690
    payment_client = PaymentClient().get_client()
1691
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 1692
    return
2628 chandransh 1693
 
2536 chandransh 1694
def __get_order_address(order):
1695
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
1696
    if order.customer_address2:
1697
        address = address + order.customer_address2 + "\n"
1698
    address = address + order.customer_city + "\n"
1699
    address = address + order.customer_state + "\n"
1700
    address = address + "PIN " + order.customer_pincode + "\n"
1701
    address = address + "Phone: " + order.customer_mobilenumber
1702
    return address
1703
 
4815 phani.kuma 1704
def __generate_return_advice(order, warehouse, provider, filename):
1705
    if warehouse.id == 7:
1706
        executive = 'Amit Kumar'
1707
    else:
4966 phani.kuma 1708
        executive = 'Dinesh Kumar'
2536 chandransh 1709
    pdf = Canvas(filename)
1710
    pdf.setFont('Times-Bold',16)
1711
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
1712
    address_text.textLine("To")
4815 phani.kuma 1713
    address_text.textLine(executive)
2536 chandransh 1714
    for line in warehouse.location.split("\n"):
1715
        address_text.textLine(line)
1716
    address_text.textLine("PIN " + warehouse.pincode)
1717
    pdf.drawText(address_text)
1718
 
1719
    pdf.setFont('Times-Roman',12)
1720
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 1721
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 1722
    lineitem = order.lineitems[0] 
4234 rajveer 1723
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 1724
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
1725
    order_text.textLine("Order ID : " + str(order.id))
1726
    pdf.drawText(order_text)
1727
    pdf.showPage()
1728
    pdf.save()
1729
    return filename
1730
 
2697 chandransh 1731
def get_return_orders(warehouse_id, from_date, to_date):
1732
    query = ReturnOrder.query.filter_by(processedStatus = False)
1733
    if warehouse_id != -1:
1734
        query = query.filter_by(warehouseId = warehouse_id)
1735
    if from_date:
4118 chandransh 1736
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 1737
    if to_date:
4118 chandransh 1738
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 1739
    return [return_order.to_thrift_object() for return_order in query.all()]
1740
 
2700 chandransh 1741
def get_return_order(id):
1742
    ret_order = ReturnOrder.get_by(orderId = id)
1743
    if ret_order is None:
1744
        raise TransactionServiceException(116, "No return order found for the given order id")
1745
    return ret_order.to_thrift_object()
1746
 
2697 chandransh 1747
def process_return(ret_order_id):
1748
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
1749
    if ret_order is None:
1750
        raise TransactionServiceException(116, "No return order found for the given order id")
1751
    ret_order.processedStatus = True
2701 chandransh 1752
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 1753
    session.commit()
1754
 
4757 mandeep.dh 1755
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
1756
    """
1757
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
1758
    the quantities for which the PO is raised.
1759
 
1760
    Parameters:
1761
     - itemIdQuantityMap
1762
     - purchaseOrderId
1763
     - warehouseId
1764
    """
3451 chandransh 1765
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 1766
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 1767
    query = query.filter_by(purchase_order_id=None)
1768
    query = query.order_by(Order.created_timestamp)
1769
    pending_orders = query.all()
4586 mandeep.dh 1770
 
1771
    for order in pending_orders:
4757 mandeep.dh 1772
        lineitem = order.lineitems[0]
1773
        if itemIdQuantityMap.has_key(lineitem.item_id):
1774
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
1775
                order.status = OrderStatus.LOW_INV_PO_RAISED
1776
                order.statusDescription = 'In Process'
1777
                order.purchase_order_id = purchaseOrderId
1778
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 1779
 
2819 chandransh 1780
    session.commit()
1781
 
3451 chandransh 1782
def update_weight(order_id, weight):
3469 chandransh 1783
    '''
1784
    Update the weight of order
1785
    '''
3451 chandransh 1786
    order = get_order(order_id)
1787
    order.total_weight = weight
3469 chandransh 1788
    lineitem = order.lineitems[0]
1789
    lineitem.total_weight = weight
1790
    lineitem.unit_weight = weight
3451 chandransh 1791
 
3469 chandransh 1792
    session.commit()
1793
    return order
1794
 
1795
def change_product(order_id, item_id):
1796
    '''
1797
    Ship a product of a different color to the customer.
1798
    '''
1799
    order = get_order(order_id)
4662 rajveer 1800
    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 1801
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
1802
 
1803
    lineitem = order.lineitems[0]
3451 chandransh 1804
 
3469 chandransh 1805
    catalog_client = CatalogClient().get_client()
1806
 
1807
    old_item = catalog_client.getItem(lineitem.item_id)
1808
    item = catalog_client.getItem(item_id)
1809
    if old_item.catalogItemId != item.catalogItemId:
1810
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
1811
 
5110 mandeep.dh 1812
    catalog_client.reserveItemInWarehouse(item_id, order.fulfilmentWarehouseId, lineitem.quantity)
1813
    __update_inventory_reservation(order)
3469 chandransh 1814
    #TODO: Check that this new item has the same price
1815
 
1816
    lineitem.item_id = item_id
1817
    lineitem.color = item.color
1818
 
3451 chandransh 1819
    session.commit()
3469 chandransh 1820
 
1821
    order = get_order(order_id)
3451 chandransh 1822
    return order
3469 chandransh 1823
 
1824
def change_warehouse(order_id, warehouse_id):
1825
    '''
1826
    Update the warehouse which will be used to fulfil this order.
1827
    '''
1828
    order = get_order(order_id)
4662 rajveer 1829
    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 1830
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
1831
 
1832
    if warehouse_id == order.warehouse_id:
1833
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
1834
 
1835
    lineitem = order.lineitems[0]
1836
    catalog_client = CatalogClient().get_client()
1837
    try:
1838
        warehouse = catalog_client.getWarehouse(warehouse_id)
1839
    except:
1840
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 1841
 
5147 mandeep.dh 1842
    if warehouse.billingWarehouseId is None:
1843
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 1844
 
5147 mandeep.dh 1845
    # If One gives a shipping location for warehouse shift, we should assign order to the GOOD warehouse
1846
    # present with this shipping location with maximum availability
1847
    if warehouse.inventoryType != InventoryType.GOOD:
1848
        warehouses = catalog_client.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
1849
        if warehouses:
1850
            itemInventory = catalog_client.getItemInventoryByItemId(lineitem.item_id)
1851
            warehouse = warehouses[0]
1852
            maxAvailability = 0
1853
            for goodWarehouse in warehouses:
1854
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
1855
                    warehouse = goodWarehouse
1856
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
1857
 
1858
            # Use preferred vendor's warehouse if not available anywhere
1859
            if not maxAvailability:
1860
                item = catalog_client.getItem(lineitem.item_id)
1861
                if item.preferredVendor:
1862
                    for goodWarehouse in warehouses:
1863
                        if goodWarehouse.vendor.id == item.preferredVendor:
1864
                            warehouse = goodWarehouse
1865
        else:
1866
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
1867
 
5199 mandeep.dh 1868
    catalog_client.reserveItemInWarehouse(lineitem.item_id, warehouse.id, lineitem.quantity)
5110 mandeep.dh 1869
    __update_inventory_reservation(order)
1870
 
1871
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 1872
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 1873
    session.commit()
1874
    return order
3553 chandransh 1875
 
4647 rajveer 1876
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 1877
    '''
3994 chandransh 1878
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 1879
    '''
1880
    order = get_order(order_id)
1881
    try:
3581 chandransh 1882
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 1883
        order.delayReasonText = delayReasonText
4009 chandransh 1884
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
1885
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 1886
 
4842 rajveer 1887
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
1888
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 1889
 
3553 chandransh 1890
        session.commit()
4008 mandeep.dh 1891
 
1892
        try:
1893
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
1894
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
1895
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
1896
            session.commit()
1897
        except Exception as e:
4065 mandeep.dh 1898
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 1899
 
3553 chandransh 1900
        return True
1901
    except:
3994 chandransh 1902
        print sys.exc_info()[0]
3553 chandransh 1903
        return False
3956 chandransh 1904
 
1905
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
1906
    unprocessed_awbs = {}
1907
    for awb, amount in collected_amount_map.iteritems():
1908
        try:
1909
            order = Order.query.filter_by(airwaybill_no=awb).one()
1910
        except NoResultFound:
1911
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
1912
            continue
1913
        except MultipleResultsFound:
1914
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
1915
            continue
1916
 
1917
        if order.cod_reconciliation_timestamp:
1918
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
1919
            continue
1920
 
1921
        if order.status < OrderStatus.DELIVERY_SUCCESS:
1922
            #Order has not been delivered yet. No way we can receive the payment.
1923
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
1924
            continue
1925
 
4252 rajveer 1926
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
1927
        if abs(amount - order.total_amount) > 0.5:
3956 chandransh 1928
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
1929
            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)
1930
            continue
1931
 
1932
        try:
1933
            payment_client = PaymentClient().get_client()
1934
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
1935
        except Exception:
1936
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
1937
            continue
1938
 
1939
        #Payment has been recorded now. We can update the order peacefully.
1940
        order.cod_reconciliation_timestamp = datetime.datetime.now()
1941
        session.commit()
3469 chandransh 1942
 
3956 chandransh 1943
    return unprocessed_awbs
4008 mandeep.dh 1944
 
1945
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 1946
    """
1947
    Returns the list of transaction ids that require some extra processing and
1948
    which belong to a particular category. This is currently used by CRM
1949
    application. If no such transaction ids are present, it returns an empty list.
1950
    """
1951
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 1952
 
4065 mandeep.dh 1953
    if category is not None:
1954
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 1955
 
4065 mandeep.dh 1956
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 1957
 
1958
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 1959
    """
1960
    Marks a particular transaction as processed for a particular cateogory.
1961
    It essentially deletes the transaction id record for a particular
1962
    processing type category (if present) from DB.
1963
    This is currently used by CRM application.
1964
    """
4008 mandeep.dh 1965
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
1966
    session.commit()
1967
 
4018 chandransh 1968
def get_item_wise_risky_orders_count():
1969
    """
1970
    Returns a map containing the number of risky orders keyed by item id. A risky order
1971
    is defined as one whose shipping date is about to expire.
1972
    """
1973
    item_wise_risky_orders_count = {}
4019 chandransh 1974
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 1975
    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()
1976
    for order in orders:
1977
        for lineitem in order.lineitems:
1978
            quantity = lineitem.quantity
1979
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
1980
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
1981
 
1982
            item_wise_risky_orders_count[lineitem.item_id] = quantity
1983
    return item_wise_risky_orders_count
1984
 
4324 mandeep.dh 1985
def update_shipment_address(order_id, address_id):
1986
    """
1987
    Updates shipment address of an order. Delivery and shipping date estimates
1988
    etc. are also updated here.
1989
 
1990
    Throws TransactionServiceException in case address change is not
1991
    possible due to certain reasons such as new pincode in address is
1992
    not serviceable etc.
1993
 
1994
    Parameters:
1995
     - orderId
1996
     - addressId
1997
    """
1998
    user_client = UserClient().get_client()
1999
    address     = user_client.getAddressById(address_id)
2000
    order       = get_order(order_id)
2001
 
4630 mandeep.dh 2002
    type = DeliveryType.PREPAID
2003
    if order.cod:
2004
        type = DeliveryType.COD
2005
 
4324 mandeep.dh 2006
    logistics_client = LogisticsClient().get_client()
4630 mandeep.dh 2007
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type)
4324 mandeep.dh 2008
 
2009
    # Check for new estimate. Raise exception if new address is not serviceable
2010
    if logistics_info.deliveryTime == -1:
2011
        raise TransactionServiceException(1, 'Location not serviceable')
2012
 
2013
    # COD services are not available everywhere
2014
    if order.cod:
4868 rajveer 2015
        if not logistics_info.codAllowed:
4324 mandeep.dh 2016
            raise TransactionServiceException(2, 'COD service not available')
2017
 
2018
    current_time = datetime.datetime.now()
2019
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2020
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2021
 
2022
    order.customer_name         = address.name
2023
    order.customer_pincode      = address.pin
2024
    order.customer_address1     = address.line1
2025
    order.customer_address2     = address.line2
2026
    order.customer_city         = address.city
2027
    order.customer_state        = address.state
2028
    order.customer_mobilenumber = address.phone
2029
 
2030
    if order.cod:
2031
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2032
    else:
2033
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2034
 
2035
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
2036
    order.promised_shipping_time = order.expected_shipping_time
2037
    order.promised_delivery_time = order.expected_delivery_time 
2038
 
2039
    session.commit()
2040
 
4247 rajveer 2041
def mark_order_cancellation_request_received(orderId):
2042
    """
2043
    Mark order as cancellation request received. If customer sends request of cancellation of
2044
    a particular order, this method will be called. It will just change status of the order
2045
    depending on its current status. It also records the previous status, so that we can move
2046
    back to that status if cancellation request is denied.
2047
 
2048
    Parameters:
2049
     - orderId
2050
    """
4662 rajveer 2051
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2052
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
2053
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 2054
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2055
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
2056
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2057
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2058
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2059
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
2060
             }
4662 rajveer 2061
 
2062
    order = get_order(orderId)
4247 rajveer 2063
    if order.status not in status_transition.keys():
2064
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
2065
 
4662 rajveer 2066
 
4247 rajveer 2067
    order.previousStatus = order.status
2068
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
2069
    order.statusDescription = "Cancellation request received from user"
2070
    session.commit()
2071
 
4662 rajveer 2072
def mark_order_as_lost_in_transit(orderId):
2073
    """
2074
    Parameters:
2075
     - orderId
2076
    """
2077
    order = get_order(orderId)
4910 phani.kuma 2078
    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 2079
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
2080
    order.status = OrderStatus.LOST_IN_TRANSIT
2081
    order.statusDescription = "Lost in Transit"
2082
    session.commit()
2083
 
4258 rajveer 2084
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 2085
    """
4258 rajveer 2086
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
2087
    Changed transaction and all orders status to payment accepted.
4247 rajveer 2088
 
2089
    Parameters:
4258 rajveer 2090
     - transactionId
4247 rajveer 2091
    """
4258 rajveer 2092
    transaction = get_transaction(transactionId)
2093
    transaction.status = TransactionStatus.AUTHORIZED
2094
    for order in transaction.orders:
2095
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2096
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 2097
    session.commit()
2098
 
4259 anupam.sin 2099
def refund_transaction(transactionId, refundedBy, reason):
2100
    """
2101
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
2102
    need to be cancelled
2103
 
2104
    Parameters:
2105
     - transactionId
2106
    """
2107
    transaction = get_transaction(transactionId)
2108
    transaction.status = TransactionStatus.FAILED
2109
    for order in transaction.orders:
2110
        refund_order(order.id, refundedBy, reason)
2111
    session.commit()
2112
 
4247 rajveer 2113
def mark_order_cancellation_request_denied(orderId):
2114
    """
4283 anupam.sin 2115
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 2116
 
2117
    Parameters:
2118
     - orderId
2119
    """
2120
    order = get_order(orderId)
2121
    order.status = order.previousStatus
2122
    order.previousStatus = None
2123
    order.statusDescription = "Cancellation request denied"
2124
    session.commit()
2125
 
2126
def mark_order_cancellation_request_confirmed(orderId):
2127
    """
2128
    If we decide to to cancel order, CRM will call this method to move the status of order to
2129
    cancellation request confirmed. After this OM will be able to cancel the order.
2130
 
2131
    Parameters:
2132
     - orderId
2133
    """
2134
    order = get_order(orderId)
2135
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
2136
    order.statusDescription = "Cancellation request confirmed"
2137
    session.commit()
2138
 
4285 rajveer 2139
def accept_orders_for_item_id(itemId, inventory):
2140
    """
2141
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
2142
    given order is not a COD order, it also captures the payment if the same has not been captured.
2143
 
2144
    Parameters:
2145
     - itemId
2146
     - inventory
2147
    """
4938 rajveer 2148
    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 2149
    for order in orders:
4301 rajveer 2150
        if inventory > 0:
2151
            lineitem = order.lineitems[0]
2152
            if itemId == lineitem.item_id:
2153
                try:
2154
                    accept_order(order.id)
2155
                    inventory = inventory - lineitem.quantity
2156
                except:
2157
                    logging.info("Unable to accept the order")
2158
        else:
2159
            order_outofstock(order.id)
4285 rajveer 2160
    return
2161
 
4607 rajveer 2162
def get_slipped_sipping_date_orders():
4662 rajveer 2163
    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 2164
 
2165
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
2166
    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 2167
 
4369 rajveer 2168
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
2169
    if isReminder:
2170
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2171
    else:
2172
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2173
 
2174
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2175
    for order in orders:
2176
        lineitem = order.lineitems[0]
2177
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2178
            if estimate > 0:
2179
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2180
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 2181
            order.statusDescription = "PO Raised"
4303 rajveer 2182
            quantity = quantity - lineitem.quantity
2183
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
2184
            session.commit()
2185
 
4369 rajveer 2186
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
2187
    if isReminder:
2188
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2189
    else:
2190
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2191
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2192
    for order in orders:
2193
        lineitem = order.lineitems[0]
2194
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2195
            if estimate > 0:
2196
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2197
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 2198
            order.statusDescription = "Reversal Initiated"
4303 rajveer 2199
            quantity = quantity - lineitem.quantity
2200
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
2201
            session.commit()
2202
 
4369 rajveer 2203
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
2204
    if isReminder:
2205
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2206
    else:
2207
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2208
 
2209
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2210
    for order in orders:
2211
        lineitem = order.lineitems[0]
2212
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2213
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 2214
            order.statusDescription = "Not Available"
4303 rajveer 2215
            quantity = quantity - lineitem.quantity
2216
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
2217
            session.commit()
2218
 
2219
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 2220
    orderInv = OrderInventory.get_by(order_id=order.id)
2221
    if not orderInv:
2222
        orderInv = OrderInventory()
2223
        orderInv.order = order
4303 rajveer 2224
    orderInv.hotspotAction = hotspotAction  
2225
    orderInv.estimate = estimate
2226
    orderInv.itemId = itemId
2227
    orderInv.timestamp = datetime.datetime.now()
2228
    orderInv.quantity = quantity
2229
 
4556 mandeep.dh 2230
'''    
4369 rajveer 2231
def mark_orders_as_timeout(vendorId):
2232
    ret_timeouts = {}
2233
    orderInvs = OrderInventory.query.all()
2234
    for orderInv in orderInvs:
2235
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
2236
            if not ret_timeouts.has_key(orderInv.itemId):
2237
                timeout = TimeoutSummary()
2238
                ret_timeouts[orderInv.itemId] = timeout
2239
            else:
2240
                timeout = ret_timeouts.get(orderInv.itemId)
2241
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2242
                if timeout.poRaised:
2243
                    timeout.poRaised += 1
2244
                else:
2245
                    timeout.poRaised = 1
2246
 
2247
                if timeout.poEstimate:
2248
                    timeout.poEstimate += orderInv.estimate
2249
                else:
2250
                    timeout.poEstimate = orderInv.estimate
2251
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
2252
                orderInv.order.statusDescription = "PO Raised Timeout"
2253
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2254
                if timeout.reversalInitiated:
2255
                    timeout.reversalInitiated += 1
2256
                else:
2257
                    timeout.reversalInitiated = 1
2258
 
2259
                if timeout.reversalEstimate:
2260
                    timeout.reversalEstimate += orderInv.estimate
2261
                else:
2262
                    timeout.reversalEstimate = orderInv.estimate
2263
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
2264
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
2265
            else:
2266
                orderInv.delete()
2267
    session.commit()
2268
    return ret_timeouts
4556 mandeep.dh 2269
'''
2270
 
2271
 
2272
def mark_orders_as_timeout(vendorId):
2273
    ret_timeouts = {}
2274
    orderInvs = OrderInventory.query.all()
2275
    for orderInv in orderInvs:
2276
        if not ret_timeouts.has_key(orderInv.itemId):
2277
            timeout = TimeoutSummary()
2278
            ret_timeouts[orderInv.itemId] = timeout
2279
        else:
2280
            timeout = ret_timeouts.get(orderInv.itemId)
2281
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2282
            if timeout.poRaised:
2283
                timeout.poRaised += 1
2284
            else:
2285
                timeout.poRaised = 1
2286
 
2287
            if timeout.poEstimate:
2288
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
2289
            else:
2290
                timeout.poEstimate = orderInv.estimate
2291
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2292
            if timeout.reversalInitiated:
2293
                timeout.reversalInitiated += 1
2294
            else:
2295
                timeout.reversalInitiated = 1
2296
 
2297
            if timeout.reversalEstimate:
2298
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
2299
            else:
2300
                timeout.reversalEstimate = orderInv.estimate
2301
        orderInv.order.status = OrderStatus.INVENTORY_LOW
2302
        orderInv.order.statusDescription = "Low Inventory"
2303
        orderInv.delete()
2304
    session.commit()
2305
    return ret_timeouts
2306
 
4386 anupam.sin 2307
def get_order_for_awb(awb):
2308
    order = Order.get_by(airwaybill_no=awb)
2309
    if not order:
2310
        raise TransactionServiceException(108, "no such order")
2311
 
2312
    return order
4369 rajveer 2313
 
4910 phani.kuma 2314
def get_orders_for_provider_for_status(provider_id, order_status_list):
2315
    if not provider_id or not order_status_list:
4506 phani.kuma 2316
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 2317
    doa_provider = False
2318
    for order_status in order_status_list:
2319
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
2320
            doa_provider = True
2321
    if doa_provider:
2322
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 2323
    else:
4910 phani.kuma 2324
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 2325
    return query.all()
4386 anupam.sin 2326
 
4600 varun.gupt 2327
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 2328
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
2329
 
2330
    if vendor_id:
2331
        query = query.filter_by(vendorId = vendor_id)
2332
 
4600 varun.gupt 2333
    if billing_date_from:
2334
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 2335
 
4600 varun.gupt 2336
    if billing_date_to:
2337
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 2338
 
4600 varun.gupt 2339
    return query.all()
2340
 
4875 varun.gupt 2341
def get_orders_where_vendor_not_paid(vendor_id):
5386 phani.kuma 2342
    query = Order.query.filter(Order.billing_timestamp != None)
5139 varun.gupt 2343
    query = query.filter(Order.vendor_paid != True)
5386 phani.kuma 2344
    if vendor_id != -1:
2345
        query = query.filter_by(vendorId = vendor_id)
2346
 
4885 varun.gupt 2347
    return query.all()
4875 varun.gupt 2348
 
4600 varun.gupt 2349
def save_bluedart_settlements(map_awb_and_amount):
2350
    payment_client = PaymentClient().get_client()
2351
 
2352
    for awb, amount in map_awb_and_amount.iteritems():
2353
        order = Order.get_by(airwaybill_no = awb)
2354
 
2355
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
2356
        settlement = PaymentSettlement()
2357
        settlement.paymentId = payment.paymentId
2358
        settlement.paymentGatewayId = payment.gatewayId
2359
        settlement.netCollection = amount
2360
        session.commit()
2361
 
4905 varun.gupt 2362
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 2363
    originalOrderId = None
2364
    if paymentGatewayId == 4:
2365
        cod_order = Order.get_by(id = referenceId)
2366
        if cod_order.originalOrderId:
2367
            originalOrderId = cod_order.originalOrderId
2368
        else:
2369
            originalOrderId = referenceId
4600 varun.gupt 2370
    settlement = PaymentSettlement()
2371
    settlement.settlementDate = settlementDate
2372
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 2373
    if originalOrderId is not None:
2374
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 2375
    settlement.referenceId = referenceId
4600 varun.gupt 2376
    settlement.serviceTax = serviceTax
2377
    settlement.otherCharges = otherCharges
2378
    settlement.netCollection = netCollection
2379
    session.commit()
2380
 
5386 phani.kuma 2381
def get_settlement_for_Prepaid(reference_id, is_refund = False):
2382
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 2383
 
5189 varun.gupt 2384
    if is_refund:
2385
        query = query.filter(PaymentSettlement.netCollection < 0)
2386
    else:
2387
        query = query.filter(PaymentSettlement.netCollection > 0)
2388
 
5386 phani.kuma 2389
    return query.first()
2390
 
2391
def get_settlement_for_Cod(orderId, is_refund = False):
2392
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 2393
 
5386 phani.kuma 2394
    if is_refund:
2395
        query = query.filter(PaymentSettlement.netCollection < 0)
2396
    else:
2397
        query = query.filter(PaymentSettlement.netCollection > 0)
2398
 
5189 varun.gupt 2399
    return query.first()
4600 varun.gupt 2400
 
2401
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
2402
    summary = EBSSettlementSummary()
2403
    summary.settlementId = settlement_id
2404
    summary.settlementDate = settlement_date
2405
    summary.transactionDateFrom = transaction_date_from
2406
    summary.transactionDateTo = transaction_date_to
2407
    summary.amount = amount
2408
    summary.detailsUploaded = False
2409
    session.commit()
2410
 
2411
def get_ebs_settlement_summaries():
2412
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
2413
    summary_map = {}
2414
 
2415
    for summary in summaries:
2416
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
2417
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
2418
 
2419
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
2420
 
2421
    return summary_map
2422
 
2423
def get_ebs_settlement_date(settlement_id):
2424
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
2425
 
2426
    if summary:
2427
        return summary.settlementDate
2428
 
2429
def mark_ebs_settlement_uploaded(settlement_id):
2430
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
2431
 
2432
    if summary:
2433
        summary.detailsUploaded = True
2434
        session.commit()
4715 varun.gupt 2435
 
2436
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
2437
    query = PaymentSettlement.query
4600 varun.gupt 2438
 
4715 varun.gupt 2439
    if settlement_date_from:
2440
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
2441
 
2442
    if settlement_date_to:
2443
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
2444
 
4749 varun.gupt 2445
    if is_refund is True:
2446
        query = query.filter(PaymentSettlement.netCollection < 0.0)
2447
    else:
2448
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 2449
 
4749 varun.gupt 2450
    return query.all()
4715 varun.gupt 2451
 
2452
def get_reshipped_order_ids(order_ids):
2453
    reshipped_order_ids = []
2454
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
2455
 
4749 varun.gupt 2456
def get_shipping_confirmation_email_body(order):
2457
 
2458
    html = """
2459
<html>
2460
<body>
2461
<div>
2462
    <p>Dear Customer,</p>
2463
    <p>
4885 varun.gupt 2464
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 2465
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
4749 varun.gupt 2466
    </p>
2467
    <p>
2468
        Expected delivery date for your order is $expected_delivery_date. 
2469
        The product can be delivered to you between business hours of 10am to 6pm. 
2470
        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.
2471
    </p>
2472
    <p>
2473
        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#.
2474
    </p>
5139 varun.gupt 2475
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 2476
    <p>
2477
        Warm Regards,<br />
2478
        Saholic Team
2479
    </p>
4750 varun.gupt 2480
</div>
4749 varun.gupt 2481
</body>
2482
</html>
2483
    """
5139 varun.gupt 2484
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}}
2485
    provider_name = logistics_providers[order.logistics_provider_id]['name']
2486
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
2487
 
4749 varun.gupt 2488
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 2489
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
4749 varun.gupt 2490
    product = "%s %s %s" % (order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number)
4885 varun.gupt 2491
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (order.promised_delivery_time - order.promised_shipping_time).days))
2492
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
5139 varun.gupt 2493
    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 2494
    return Template(html).substitute(info)
4749 varun.gupt 2495
 
2496
def enqueue_shipping_confirmation_email(orders):
4915 varun.gupt 2497
    # Calling helper service on production
2498
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5139 varun.gupt 2499
 
4749 varun.gupt 2500
    for order in orders:
2501
        try:
2502
            emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
2503
            emailBody = get_shipping_confirmation_email_body(order)
4885 varun.gupt 2504
            helperClient.saveUserEmailForSending(order.customer_email, None, emailSubject, emailBody, '', 'ShippingConfirmation')
4749 varun.gupt 2505
        except Exception as e:
2506
            print e
2507
 
4915 varun.gupt 2508
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 2509
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
2510
    query = query.filter(Order.created_timestamp >= start_date)
2511
    query = query.filter(Order.created_timestamp <= end_date)
2512
    return query.all()
4915 varun.gupt 2513
 
5067 varun.gupt 2514
def get_order_ids_for_status(status, start_datetime, end_datetime):
2515
    query = Order.query.filter(Order.status == status)
2516
    query = query.filter(Order.created_timestamp >= start_datetime)
2517
    query = query.filter(Order.created_timestamp <= end_datetime)
2518
    return query.all()
2519
 
5099 varun.gupt 2520
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 2521
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 2522
 
5139 varun.gupt 2523
    if paid_order.originalOrderId is None:
2524
        paid_order.vendor_paid = True
5099 varun.gupt 2525
        session.commit()
5139 varun.gupt 2526
 
2527
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
2528
            order.vendor_paid = True
2529
            session.commit()
2530
    else:
5208 varun.gupt 2531
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 2532
 
5208 varun.gupt 2533
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 2534
            order.vendor_paid = True
2535
            session.commit()
2536
 
2537
        original_order = Order.get_by(id = original_order_id)
2538
        if original_order:  original_order.vendor_paid = True
2539
        session.commit()
5348 anupam.sin 2540
 
2541
def update_COD_agent(agentEmailId, orderId):
2542
    order = Order.get_by(id=orderId)
2543
    if not order:
2544
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
2545
    agent = CodVerificationAgent()
2546
    agent.orderId = orderId
2547
    agent.verificationAgent = agentEmailId
2548
    session.commit()
2549
 
5099 varun.gupt 2550
 
5386 phani.kuma 2551
def update_order_only_as_paid_to_vendor(order_id):
2552
    paid_order = Order.get_by(id = order_id)
2553
    if paid_order is None:
2554
        raise TransactionServiceException(116, "No order found for the given order id")
2555
    paid_order.vendor_paid = True
2556
    session.commit()
2557
 
5208 varun.gupt 2558
def get_refunded_orders_marked_paid():
2559
    orderStatusGroup = OrderStatusGroups()
2560
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
2561
 
766 rajveer 2562
def close_session():
2563
    if session.is_active:
2564
        print "session is active. closing it."
2783 chandransh 2565
        session.close()
3376 rajveer 2566
 
2567
def is_alive():
2568
    try:
2569
        session.query(Transaction.id).limit(1).one()
2570
        return True
2571
    except:
4343 varun.gupt 2572
        return False