Subversion Repositories SmartDukaan

Rev

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

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