Subversion Repositories SmartDukaan

Rev

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

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