Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
104 ashish 1
'''
2
Created on 29-Mar-2010
3
 
2536 chandransh 4
@author: Chandranshu
104 ashish 5
'''
2536 chandransh 6
 
4369 rajveer 7
from datetime import date, timedelta
2536 chandransh 8
from elixir import *
3499 mandeep.dh 9
from reportlab.lib.units import inch
2536 chandransh 10
from reportlab.pdfgen.canvas import Canvas
11
from reportlab.rl_config import defaultPageSize
3499 mandeep.dh 12
from shop2020.clients.CatalogClient import CatalogClient
13
from shop2020.clients.HelperClient import HelperClient
14
from shop2020.clients.LogisticsClient import LogisticsClient
2747 chandransh 15
from shop2020.clients.PaymentClient import PaymentClient
3499 mandeep.dh 16
from shop2020.clients.UserClient import UserClient
17
from shop2020.clients.WarehouseClient import WarehouseClient
18
from shop2020.model.v1 import order
19
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem, \
4435 mandeep.dh 20
    Order, BatchNoGenerator, InvoiceIDGenerator, TransactionRequiringExtraProcessing, \
5348 anupam.sin 21
    OrderInventory, Alert, PaymentSettlement, EBSSettlementSummary, \
5527 anupam.sin 22
    CodVerificationAgent, Attribute, RechargeVoucherTracker
5793 rajveer 23
 
2687 chandransh 24
from shop2020.model.v1.order.impl.model.ReturnOrder import ReturnOrder
5793 rajveer 25
from shop2020.thriftpy.generic.ttypes import ExceptionType
5785 mandeep.dh 26
from shop2020.thriftpy.alert.ttypes import MonitoredEntity, EntityType
5527 anupam.sin 27
from shop2020.thriftpy.logistics.ttypes import DeliveryType, PickUpType
4435 mandeep.dh 28
from shop2020.thriftpy.model.v1.catalog.ttypes import BillingType, \
5110 mandeep.dh 29
    InventoryServiceException, WarehouseType, ItemType, InventoryType
4435 mandeep.dh 30
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
31
    TransactionStatus, OrderStatus, DelayReason, ExtraTransactionProcessingType, \
5527 anupam.sin 32
    HotspotAction, TimeoutSummary, OrderStatusGroups, OrderType
4421 mandeep.dh 33
from shop2020.thriftpy.payments.ttypes import PaymentException
5110 mandeep.dh 34
from shop2020.thriftpy.warehouse.ttypes import ScanType, \
35
    WarehouseServiceException
5793 rajveer 36
from shop2020.utils.EmailAttachmentSender import mail, get_attachment_part,\
37
    mail_html
855 rajveer 38
from shop2020.utils.Utils import to_py_date, to_java_date
4008 mandeep.dh 39
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
3499 mandeep.dh 40
from sqlalchemy.sql import func
5527 anupam.sin 41
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, select
3499 mandeep.dh 42
from string import Template
43
from textwrap import dedent
44
import datetime
45
import logging
46
import os
4421 mandeep.dh 47
import sys
4435 mandeep.dh 48
import time
4421 mandeep.dh 49
import traceback
5793 rajveer 50
from shop2020.thriftpy.model.v1.user.ttypes import VoucherType
51
from random import randrange
52
from shop2020.clients.AlertClient import AlertClient
5806 rajveer 53
import httplib
54
import urllib
3499 mandeep.dh 55
logging.basicConfig(level=logging.DEBUG)
104 ashish 56
 
3499 mandeep.dh 57
 
4763 rajveer 58
PREPAID_SHIPPING_CUTOFF_TIME = 15
4019 chandransh 59
COD_SHIPPING_CUTOFF_TIME = 12
3499 mandeep.dh 60
 
2819 chandransh 61
PAGE_HEIGHT=defaultPageSize[1]
62
PAGE_WIDTH=defaultPageSize[0]
63
 
4763 rajveer 64
billedOrdersColorMap = {}
65
 
3499 mandeep.dh 66
ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT = {
4873 mandeep.dh 67
        OrderStatus.RTO_RESHIPPED    :  3,
68
        OrderStatus.RTO_IN_TRANSIT   : -5,
69
        OrderStatus.DELIVERY_SUCCESS :  1,
70
        OrderStatus.DOA_CERT_INVALID : -5
3499 mandeep.dh 71
}
72
 
5783 rajveer 73
delhi_pincodes = ['110001','110002','110003','110004','110005','110006','110007','110008','110009','110010','110011','110012','110013','110014','110015',\
74
                '110016','110017','110018','110019','110020','110021','110022','110023','110024','110025','110026','110027','110028','110029','110030',\
75
                '110031','110032','110033','110034','110035','110037','110038','110041','110042','110044','110045','110046','110047','110048','110049',\
76
                '110051','110052','110053','110054','110055','110056','110057','110058','110059','110060','110061','110062','110063','110064','110065',\
77
                '110066','110067','110068','110070','110071','110074','110075','110076','110078','110081','110082','110083','110084','110085','110086',\
78
                '110087','110088','110089','110091','110092','110093','110094','110095','110096','110101','110103','110104','110105','110106','110107',\
79
                '110108','110109','110110','110112','110113','110114','110115','110116','110117','110118','110119','110120','110122','110124','110125',\
80
                '110301','110302','110501','110502','110503','110504','110505','110510','110511','110512','110601','110602','110603','110604','110605',\
81
                '110606','110607','110608','110609']
82
 
104 ashish 83
def get_new_transaction():
84
    transaction = Transaction()
85
    transaction.createdOn = datetime.datetime.now()
738 chandransh 86
    transaction.status = TransactionStatus.INIT
104 ashish 87
    transaction.status_message = "New transaction"
483 rajveer 88
    return transaction
89
 
90
def create_order(t_order):
91
    order = Order()
92
    if t_order.warehouse_id:
93
        order.warehouse_id = t_order.warehouse_id
509 rajveer 94
    if t_order.logistics_provider_id:    
483 rajveer 95
        order.logistics_provider_id = t_order.logistics_provider_id
96
        order.airwaybill_no = t_order.airwaybill_no
97
        order.tracking_id = t_order.tracking_id
4009 chandransh 98
    if t_order.expected_shipping_time:
4019 chandransh 99
        order.expected_shipping_time = to_py_date(t_order.expected_shipping_time).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 100
        order.promised_shipping_time = order.expected_shipping_time
4009 chandransh 101
    if t_order.expected_delivery_time:
483 rajveer 102
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
4102 chandransh 103
        order.promised_delivery_time = order.expected_delivery_time
483 rajveer 104
    if t_order.customer_id:    
105
        order.customer_id = t_order.customer_id
106
        order.customer_name = t_order.customer_name
860 rajveer 107
        order.customer_city = t_order.customer_city
108
        order.customer_state = t_order.customer_state
483 rajveer 109
        order.customer_mobilenumber = t_order.customer_mobilenumber
110
        order.customer_pincode = t_order.customer_pincode
738 chandransh 111
        order.customer_address1 = t_order.customer_address1
112
        order.customer_address2 = t_order.customer_address2
483 rajveer 113
        order.customer_email = t_order.customer_email
114
    #new status and status description to be added    
716 rajveer 115
    order.status = t_order.status  
483 rajveer 116
    order.statusDescription = t_order.statusDescription
117
    order.total_amount = t_order.total_amount
118
    order.total_weight = t_order.total_weight
119
    if t_order.created_timestamp:
120
        order.created_timestamp = to_py_date(t_order.created_timestamp)
121
    else:
685 chandransh 122
        order.created_timestamp = datetime.datetime.now()
5555 rajveer 123
    order.pickupStoreId = t_order.pickupStoreId
483 rajveer 124
    return order
125
 
126
def create_transaction(t_transaction):
127
    t_orders = t_transaction.orders
128
    if not t_orders:
129
        raise TransactionServiceException(101, "Orders missing from the transaction")
130
    transaction = get_new_transaction()
131
    transaction.customer_id = t_transaction.customer_id 
132
    transaction.shopping_cart_id = t_transaction.shoppingCartid
2219 varun.gupt 133
    transaction.coupon_code = t_transaction.coupon_code
2815 vikas 134
    transaction.session_source = t_transaction.sessionSource
135
    transaction.session_start_time = to_py_date(t_transaction.sessionStartTime)
3858 vikas 136
    transaction.first_source = t_transaction.firstSource
137
    transaction.first_source_start_time = to_py_date(t_transaction.firstSourceTime)
483 rajveer 138
 
139
    for t_order in t_orders:
140
        order = create_order(t_order)
141
        order.transaction = transaction 
142
        for line_item in t_order.lineitems:
143
            litem = LineItem()
716 rajveer 144
            litem.item_id = line_item.item_id
963 chandransh 145
            litem.productGroup = line_item.productGroup
483 rajveer 146
            litem.brand = line_item.brand
147
            if line_item.model_number:
148
                litem.model_number = line_item.model_number
149
            if line_item.model_name:    
150
                litem.model_name = line_item.model_name
908 chandransh 151
            if line_item.color:
152
                litem.color = line_item.color
483 rajveer 153
            if line_item.extra_info:
154
                litem.extra_info = line_item.extra_info
155
            litem.quantity = line_item.quantity
156
            litem.unit_price = line_item.unit_price
157
            litem.unit_weight = line_item.unit_weight
158
            litem.total_price = line_item.total_price
159
            litem.total_weight = line_item.total_weight
4283 anupam.sin 160
            '''litem.transfer_price = line_item.transfer_price'''
4172 rajveer 161
            litem.dealText = line_item.dealText
4295 varun.gupt 162
            litem.warranty_expiry_timestamp = to_py_date(line_item.warrantry_expiry_timestamp)
1976 varun.gupt 163
 
483 rajveer 164
            """
165
            if line_item.addedOn:
166
                litem.added_on = to_py_date(line_item.addedOn)
167
            else:
168
                litem.added_on = datetime.datetime.now()
169
            """
170
            litem.order = order
171
    session.commit()
172
    return transaction.id
173
 
174
def get_transaction(transaction_id):
175
    transaction = Transaction.get_by(id=transaction_id)
176
    if not transaction:
177
        raise TransactionServiceException(108, "no such transaction")
178
 
179
    return transaction
180
 
181
def get_transactions_for_customer(customer_id, from_date, to_date, status):
182
    if not customer_id:
183
        raise TransactionServiceException(101, "bad customer id")
184
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 185
    if status is not None:
483 rajveer 186
        query = query.filter(Transaction.status == status)
187
    if from_date:
188
        query = query.filter(Transaction.createdOn >from_date)
189
    if to_date:
190
        query = query.filter(Transaction.createdOn < to_date)
191
    return query.all()
192
 
193
def get_transactions_for_shopping_cart_id(shopping_cart_id):
194
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
195
    return transactions
196
 
197
def get_transaction_status(transaction_id):
198
    if not transaction_id:
199
        raise TransactionServiceException(101, "bad transaction id")
200
 
201
    transaction = get_transaction(transaction_id)
202
 
203
    return transaction.status
204
 
5527 anupam.sin 205
def change_transaction_status(transaction_id, new_status, description, pickUp, orderType):
483 rajveer 206
    transaction = get_transaction(transaction_id)
207
    transaction.status = new_status
208
    transaction.status_message = description
5783 rajveer 209
    ## Assign runner in case of delhi pincodes
5784 rajveer 210
    if transaction.orders[0].pickupStoreId:
211
        logistics_client = LogisticsClient().get_client() 
212
        store = logistics_client.getPickupStore(transaction.orders[0].pickupStoreId)
213
        if delhi_pincodes.__contains__(store.pin):
5793 rajveer 214
            pickUp = PickUpType.RUNNER  
5783 rajveer 215
 
690 chandransh 216
    if new_status == TransactionStatus.FAILED:
217
        for order in transaction.orders:
218
            order.status = OrderStatus.PAYMENT_FAILED
2339 chandransh 219
            order.statusDescription = "Payment Failed"
4247 rajveer 220
    elif new_status == TransactionStatus.AUTHORIZED or new_status == TransactionStatus.FLAGGED:
690 chandransh 221
        for order in transaction.orders:
4247 rajveer 222
            if new_status == TransactionStatus.AUTHORIZED:
223
                order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
224
                order.statusDescription = "Submitted to warehouse"
225
            elif new_status == TransactionStatus.FLAGGED:
226
                order.status = OrderStatus.PAYMENT_FLAGGED
227
                order.statusDescription = "Payment flagged by gateway"
3092 chandransh 228
            order.cod = False
5527 anupam.sin 229
            order.orderType = orderType
743 rajveer 230
            #After we got payment success, we will set logistics info also 
231
            logistics_client = LogisticsClient().get_client()
232
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 233
            item_id = order.lineitems[0].item_id
5767 rajveer 234
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID, pickUp)
743 rajveer 235
 
1730 ankur.sing 236
            current_time = datetime.datetime.now()
237
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 238
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
5110 mandeep.dh 239
 
743 rajveer 240
            order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 241
            order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
743 rajveer 242
            order.logistics_provider_id = logistics_info.providerId
243
            order.airwaybill_no = logistics_info.airway_billno
244
            order.tracking_id = order.airwaybill_no
4019 chandransh 245
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 246
            order.promised_shipping_time = order.expected_shipping_time
5165 rajveer 247
            order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3986 chandransh 248
            order.promised_delivery_time = order.expected_delivery_time 
871 chandransh 249
 
3133 rajveer 250
            catalog_client = CatalogClient().get_client()
5110 mandeep.dh 251
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, order.lineitems[0].quantity)
1351 varun.gupt 252
 
4316 anupam.sin 253
            try:
254
                item_pricing = catalog_client.getItemPricing(item_id, -1)
255
                order.lineitems[0].transfer_price = item_pricing.transferPrice
256
            except:
257
                print "Not able to get transfer price. Skipping"
5767 rajveer 258
 
5508 rajveer 259
            voucherAmount = catalog_client.getVoucherAmount(item_id, VoucherType.SPICEDECK_MOBILE)
260
            if voucherAmount:
5514 rajveer 261
                __create_recharge_voucher_tracker(order, voucherAmount, VoucherType.SPICEDECK_MOBILE)
5508 rajveer 262
 
3064 chandransh 263
    elif new_status == TransactionStatus.COD_IN_PROCESS:
264
        for order in transaction.orders:
4662 rajveer 265
            order.status = OrderStatus.COD_VERIFICATION_PENDING
3064 chandransh 266
            order.statusDescription = "Verification Pending"
267
            order.cod = True
5527 anupam.sin 268
            order.orderType = orderType
3064 chandransh 269
            #After we got payment success, we will set logistics info also 
270
            logistics_client = LogisticsClient().get_client()
271
            #FIXME line item is only one now. If multiple will come, need to fix.
272
            item_id = order.lineitems[0].item_id
5555 rajveer 273
            if order.pickupStoreId:
5767 rajveer 274
                logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID, pickUp)
5555 rajveer 275
            else:
5767 rajveer 276
                logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.COD, pickUp)
3064 chandransh 277
            current_time = datetime.datetime.now()
278
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 279
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
3064 chandransh 280
 
281
            order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 282
            order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
3064 chandransh 283
            order.logistics_provider_id = logistics_info.providerId
284
            order.airwaybill_no = logistics_info.airway_billno
285
            order.tracking_id = order.airwaybill_no
4019 chandransh 286
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 287
            order.promised_shipping_time = order.expected_shipping_time
5165 rajveer 288
            order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3986 chandransh 289
            order.promised_delivery_time = order.expected_delivery_time
3064 chandransh 290
 
3133 rajveer 291
            catalog_client = CatalogClient().get_client()
5110 mandeep.dh 292
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, order.lineitems[0].quantity)
3064 chandransh 293
 
4316 anupam.sin 294
            try:
295
                item_pricing = catalog_client.getItemPricing(item_id, -1)
296
                order.lineitems[0].transfer_price = item_pricing.transferPrice        
297
            except:
298
                print "Not able to get transfer price. Skipping"
5508 rajveer 299
 
300
            voucherAmount = catalog_client.getVoucherAmount(item_id, VoucherType.SPICEDECK_MOBILE)
301
            if voucherAmount:
5514 rajveer 302
                __create_recharge_voucher_tracker(order, voucherAmount, VoucherType.SPICEDECK_MOBILE)
483 rajveer 303
    session.commit()
3499 mandeep.dh 304
 
3530 mandeep.dh 305
    try:
306
        if new_status == TransactionStatus.COD_IN_PROCESS:
4008 mandeep.dh 307
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
308
            transaction_requiring_extra_processing.category = 'COD_VERIFICATION'
309
            transaction_requiring_extra_processing.transaction_id = transaction_id
310
            session.commit()
4247 rajveer 311
        elif new_status == TransactionStatus.FLAGGED:
312
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
313
            transaction_requiring_extra_processing.category = 'PAYMENT_FLAGGED'
314
            transaction_requiring_extra_processing.transaction_id = transaction_id
315
            session.commit()
3530 mandeep.dh 316
    except Exception as e:
4065 mandeep.dh 317
        print "Error inserting transaction Id: " + str(transaction_id) + " due to " + str(e)
3499 mandeep.dh 318
 
483 rajveer 319
    return True
320
 
5514 rajveer 321
def __create_recharge_voucher_tracker(order, amount, voucherType):
5508 rajveer 322
    rvt = RechargeVoucherTracker()
323
    rvt.order = order
324
    rvt.amount = amount
325
    rvt.voucherIssued = False
5514 rajveer 326
    rvt.voucherType = voucherType
5508 rajveer 327
 
3994 chandransh 328
def __get_holidays(start_time=0L, to_time=-1L):
329
    '''
330
    Get the list of all public holidays since start time including the
331
    day of start time if it's a holiday
332
    '''
333
    midnightTime = start_time.replace(hour=0, minute=0, second=0, microsecond=0)
1730 ankur.sing 334
    fromDate = to_java_date(midnightTime)
335
    logistics_client = LogisticsClient().get_client()
3994 chandransh 336
    #TODO: This list should be cached after the first call.
337
    #Calling logistics server is also unnecessary.
338
    holidays = logistics_client.getHolidays(fromDate, to_time)
339
    holidays = [to_py_date(holiday).date() for holiday in holidays]
340
    return holidays
341
 
342
def adjust_delivery_time(start_time, delivery_days):
343
    '''
344
    Returns the actual no. of days which will pass while 'delivery_days'
345
    no. of business days will pass since 'order_time'. 
346
    '''
347
    start_date = start_time.date()
348
    end_date = start_date + datetime.timedelta(days = delivery_days)
349
    holidays = __get_holidays(start_time)
1730 ankur.sing 350
 
3994 chandransh 351
    while start_date <= end_date:
352
        if start_date.weekday() == 6 or start_date in holidays:
1730 ankur.sing 353
            delivery_days = delivery_days + 1
3994 chandransh 354
            end_date = end_date + datetime.timedelta(days = 1)
4088 chandransh 355
        start_date = start_date + datetime.timedelta(days = 1)
3994 chandransh 356
 
1730 ankur.sing 357
    return delivery_days
358
 
1398 varun.gupt 359
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 360
    transaction = get_transaction(transaction_id)
5793 rajveer 361
    customer_name = "" 
1262 varun.gupt 362
    html_header = """
363
<html>
364
<body>
365
<div>
366
    <p>
5793 rajveer 367
        Hello $customer_name,<br /><br />
1742 rajveer 368
        Thanks for placing order with us. Following are the details of your order:
1262 varun.gupt 369
    </p>
370
    <div>
371
        Order Date: $order_date
1569 varun.gupt 372
    </div>
1262 varun.gupt 373
    <div>
374
        <table>
1569 varun.gupt 375
        <tr><td colspan="5"><hr /></td></tr>
376
        <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
377
        <tr><td colspan="5"><hr /></td></tr>
1262 varun.gupt 378
        <tr>
2050 varun.gupt 379
            <th width="100">Order No.</th>
380
            <th>Product</th>
381
            <th width="100">Quantity</th>
382
            <th width="100">Unit Price</th>
383
            <th width="100">Amount</th>
1262 varun.gupt 384
        </tr>
385
    """
1398 varun.gupt 386
    user_email = ""
1262 varun.gupt 387
    total_amount = 0.0
388
    html_table = ""
1569 varun.gupt 389
    order_date = datetime.datetime.now()
5676 rajveer 390
 
391
    orders = transaction.orders
392
    html_pickup_text = ""
393
    random_text = ""
5697 rajveer 394
    if orders[0].pickupStoreId:
5793 rajveer 395
        random_text = str(randrange(100000, 999999)) 
5676 rajveer 396
 
397
    for order in orders:
5793 rajveer 398
        customer_name = order.customer_name
1262 varun.gupt 399
        order_date = order.created_timestamp
1398 varun.gupt 400
        user_email = order.customer_email
1569 varun.gupt 401
        html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
5676 rajveer 402
 
403
        if order.pickupStoreId:
404
            attribute = Attribute()
405
            attribute.orderId = order.id
406
            attribute.name = "SECRET_CODE"
407
            attribute.value = random_text
408
            session.commit()
1262 varun.gupt 409
 
410
        for lineitem in order.lineitems:
2050 varun.gupt 411
            lineitem_total_price = round(lineitem.total_price, 2)
412
 
1276 chandransh 413
            html_tr += "<td>" + str(lineitem) + "</td>"
2050 varun.gupt 414
            html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
415
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
416
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
417
            total_amount += lineitem_total_price
1262 varun.gupt 418
            html_table += html_tr
2050 varun.gupt 419
 
1262 varun.gupt 420
    html_footer = """
421
        <tr><td colspan=5>&nbsp;</td></tr>
1565 varun.gupt 422
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 423
        <tr>
424
            <td colspan=4>Total Amount</td>
2050 varun.gupt 425
            <td> Rs. $total_amount</td>
1262 varun.gupt 426
        </tr>
427
        </table>
1569 varun.gupt 428
    </div>
5676 rajveer 429
    """
5793 rajveer 430
 
431
    store_address = ""
432
    if orders[0].pickupStoreId:
433
        store = LogisticsClient().get_client().getPickupStore(orders[0].pickupStoreId)
434
        store_address = __get_store_address_html(store)
435
 
436
        html_pickup_text = html_pickup_text + """
437
        <h3>Steps to Pickup In Store</h3>
438
        1) Estimated arrival date of your product(s) is $store_delivery_date at your selected Store.<br>
439
        2) You will receive a confirmation email from us when your product(s) reaches the store. Once you receive the same, please visit the following store selected by you.<br>
440
        <br><i>$store_address</i><br>
441
        """
442
 
443
        if orders[0].cod:
444
            html_pickup_text = html_pickup_text + """
445
            3) Pay Rs. $total_amount, present a valid Photo Identity Proof* and use your Secret Code <b><i>$secret_code</i></b> to claim your Product(s).<br><br>
446
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
447
            <br>
448
            In case you have any questions please visit <a href="www.saholic.com/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="http://www.saholic.com/contact-us">http://www.saholic.com/contact-us</a>
449
            </br><hr />
450
            """
451
        else:
452
            html_pickup_text = html_pickup_text + """
453
            3) Present a valid Photo Identity Proof* and use your Secret Code <b><i>$secret_code</i></b> to claim your Product(s).<br><br>
454
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
455
            <br>
5797 anupam.sin 456
            In case you have any questions please visit <a href="www.saholic.com/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="http://www.saholic.com/contact-us">http://www.saholic.com/contact-us</a>
5793 rajveer 457
            </br><hr />
458
            """
459
 
5676 rajveer 460
    html_footer = html_footer + html_pickup_text + """
1262 varun.gupt 461
    <p>
462
        Best Wishes,<br />
463
        Saholic Team
464
    </p>
465
</div>
466
</body>
467
</html>
468
    """
1398 varun.gupt 469
 
1569 varun.gupt 470
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 471
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
5793 rajveer 472
 
473
    sdt = datetime.datetime.strptime(str(orders[0].expected_delivery_time), "%Y-%m-%d %H:%M:%S")
474
    store_delivery_date = sdt.strftime("%A, %d %B %Y")
475
 
476
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name))
477
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount, secret_code = random_text, store_address = store_address, store_delivery_date = store_delivery_date))
1565 varun.gupt 478
 
1351 varun.gupt 479
    try:
480
        helper_client = HelperClient().get_client()
1398 varun.gupt 481
        helper_client.saveUserEmailForSending(user_email, "", "Saholic - Order Details", email_header + html_table + email_footer, str(transaction_id), "TransactionInfo")
1351 varun.gupt 482
        return True
483
    except Exception as e:
484
        print e
485
        return False
1262 varun.gupt 486
 
5802 rajveer 487
def enqueue_received_at_store_email(order):
488
    html_header = """
489
    <html>
490
    <body>
491
    <div>
492
        <p>
493
            Hello $customer_name,<br /><br />
494
            Your Product has reached the Store selected by you and is available for pickup. Please pick up your product on or before $order_expiry_date. Following are the details of your order and steps to pickup the same:
495
        </p>
496
        <div>
497
            Order Date: $order_date
498
        </div>
499
        <div>
500
            <table>
501
            <tr><td colspan="5"><hr /></td></tr>
502
            <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
503
            <tr><td colspan="5"><hr /></td></tr>
504
            <tr>
505
                <th width="100">Order No.</th>
506
                <th>Product</th>
507
                <th width="100">Quantity</th>
508
                <th width="100">Unit Price</th>
509
                <th width="100">Amount</th>
510
            </tr>
511
    """
512
    total_amount = 0.0
513
    html_table = ""
514
 
515
    html_pickup_text = ""
516
    random_text = __get_secret_code(order.id)
517
 
518
    customer_name = order.customer_name
519
    order_date = order.created_timestamp
520
    user_email = order.customer_email
521
    html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
522
 
523
    for lineitem in order.lineitems:
524
        lineitem_total_price = round(lineitem.total_price, 2)
525
 
526
        html_tr += "<td>" + str(lineitem) + "</td>"
527
        html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
528
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
529
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
530
        total_amount += lineitem_total_price
531
        html_table += html_tr
532
 
533
    html_footer = """
534
        <tr><td colspan=5>&nbsp;</td></tr>
535
        <tr><td colspan=5><hr /></td></tr>
536
        <tr>
537
            <td colspan=4>Total Amount</td>
538
            <td> Rs. $total_amount</td>
539
        </tr>
540
        </table>
541
    </div>
542
    """
543
 
544
    store_address = ""
545
    if order.pickupStoreId:
546
        store = LogisticsClient().get_client().getPickupStore(order.pickupStoreId)
547
        store_address = __get_store_address_html(store)
548
 
549
        html_pickup_text = html_pickup_text + """
550
        <h3>Steps to Pickup In Store</h3>
551
        1) Please visit the following store selected by you on or before $order_expiry_date<br>
552
        <br><i>$store_address</i><br>
553
        """
554
 
555
        if order.cod:
556
            html_pickup_text = html_pickup_text + """
557
            2) Pay Rs. $total_amount, present a valid Photo Identity Proof* and quote your Secret Code <b><i>$secret_code</i></b> to claim your Product.<br><br>
558
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
559
            <br>
560
            In case you have any questions please visit <a href="www.saholic.com/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="http://www.saholic.com/contact-us">http://www.saholic.com/contact-us</a>
561
            </br><hr />
562
            """
563
        else:
564
            html_pickup_text = html_pickup_text + """
565
            2) Present a valid Photo Identity Proof* and use your Secret Code <b><i>$secret_code</i></b> to claim your Product(s).<br><br>
566
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
567
            <br>
568
            In case you have any questions please visit <a href="www.saholic.com/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="http://www.saholic.com/contact-us">http://www.saholic.com/contact-us</a>
569
            </br><hr />
570
            """
571
 
572
        html_footer = html_footer + html_pickup_text + """
573
        <p>
574
            Best Wishes,<br />
575
            Saholic Team
576
        </p>
577
        </div>
578
        </body>
579
        </html>
580
        """
581
 
582
    subject = "Your order for " + str(order.lineitems[0]) + " is ready for Pickup in Store"
583
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
584
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
585
 
586
    oetd = datetime.datetime.now() + datetime.timedelta(days=4)
587
    formated_order_expiry_date = oetd.strftime("%A, %d %B %Y")
588
 
589
 
590
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, order_expiry_date = formated_order_expiry_date))
591
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount, secret_code = random_text, store_address = store_address, order_expiry_date = formated_order_expiry_date))
592
 
593
    try:
594
        helper_client = HelperClient().get_client()
595
        helper_client.saveUserEmailForSending(user_email, "", subject, email_header + html_table + email_footer, str(order.id), "ReceivedAtStore")
596
        return True
597
    except Exception as e:
598
        print e
599
        return False
600
 
5807 rajveer 601
def enqueue_delivery_successe_mail(order):
602
    html_header = """
603
    <html>
604
    <body>
605
    <div>
606
        <p>
607
            Dear $customer_name,<br /><br />
608
    """
609
 
610
    if order.pickupStoreId:
611
        pickup_text = "Pickup Date: " + order.delivery_timestamp.strftime("%A, %d. %B %Y %I:%M%p")
612
        thank_you_html = """
613
        Thank you for shopping with us and picking up your order in Store. Please do join us at our <a href="http://www.facebook.com/mysaholic">Facebook Page</a>, and share your experience with other shoppers.<br><br>
614
 
615
        Following are the details of your order for which the pickup has happened. If you have not picked up this product please <a href="http://www.saholic.com/contact-us" target="_blank">contact us</a> immediately.<br>
616
        """
617
    else:
618
        pickup_text = ""
619
        thank_you_html = """
620
        Thank you for shopping with us. Please do join us at our <a href="http://www.facebook.com/mysaholic">Facebook Page</a>, and share your experience with other shoppers. Following are the details of your order.<br>
621
        """ 
622
 
623
    html_header = html_header + thank_you_html + """        
624
        </p>
625
        <div>
626
            Order Date: $order_date <br>
627
            $pickup_text
628
        </div>
629
        <div>
630
            <table>
631
            <tr><td colspan="5"><hr /></td></tr>
632
            <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
633
            <tr><td colspan="5"><hr /></td></tr>
634
            <tr>
635
                <th width="100">Order No.</th>
636
                <th>Product</th>
637
                <th width="100">Quantity</th>
638
                <th width="100">Unit Price</th>
639
                <th width="100">Amount</th>
640
            </tr>
641
    """
642
    total_amount = 0.0
643
    html_table = ""
5802 rajveer 644
 
5807 rajveer 645
    customer_name = order.customer_name
646
    order_date = order.created_timestamp
647
    user_email = order.customer_email
648
    html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
649
 
650
    for lineitem in order.lineitems:
651
        lineitem_total_price = round(lineitem.total_price, 2)
652
 
653
        html_tr += "<td>" + str(lineitem) + "</td>"
654
        html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
655
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
656
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
657
        total_amount += lineitem_total_price
658
        html_table += html_tr
659
 
660
    html_footer = """
661
        <tr><td colspan=5>&nbsp;</td></tr>
662
        <tr><td colspan=5><hr /></td></tr>
663
        <tr>
664
            <td colspan=4>Total Amount</td>
665
            <td> Rs. $total_amount</td>
666
        </tr>
667
        </table>
668
    </div>
669
    <p>
670
        Best Wishes,<br />
671
        Saholic Team
672
    </p>
673
    </div>
674
    </body>
675
    </html>
676
    """
677
 
678
    subject = "Your order for " + str(order.lineitems[0]) + " is now complete"
679
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
680
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
681
 
682
 
683
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, pickup_text = pickup_text))
684
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount))
685
 
686
    try:
687
        helper_client = HelperClient().get_client()
688
        helper_client.saveUserEmailForSending(user_email, "", subject, email_header + html_table + email_footer, str(order.id), "DeliverySuccess")
689
        return True
690
    except Exception as e:
691
        print e
692
        return False
693
 
5802 rajveer 694
def __get_secret_code(order_id):
5806 rajveer 695
    __get_order_attribute_value(order_id, 'SECRET_CODE')
696
 
697
def __get_order_attribute_value(order_id, attribute_name):
5808 rajveer 698
    existingAttribute = Attribute.query.filter(Attribute.orderId == order_id).filter(Attribute.name == attribute_name).first()
699
    if existingAttribute:
700
        return existingAttribute.value
5802 rajveer 701
    return ""
5806 rajveer 702
 
483 rajveer 703
def get_order(order_id):
704
    order = Order.get_by(id=order_id)
705
    if not order:
706
        raise TransactionServiceException(108, "no such order")
707
 
708
    return order
709
 
4999 phani.kuma 710
def get_order_list(order_ids):
711
    orders = Order.query.filter(Order.id.in_(tuple(order_ids)))
712
    return orders
713
 
5386 phani.kuma 714
def get_order_list_for_vendor(order_ids, vendor_id):
715
    if vendor_id == -1:
716
        return get_order_list(order_ids)
717
    else:
718
        orders = Order.query.filter_by(vendorId = vendor_id).filter(Order.id.in_(tuple(order_ids)))
719
        return orders
720
 
3014 chandransh 721
def get_orders_for_customer(customer_id, from_date, to_date, statuses):
483 rajveer 722
    if not customer_id:
723
        raise TransactionServiceException(101, "bad customer id")
724
    query = Order.query.filter(Order.customer_id == customer_id)
3014 chandransh 725
    if statuses:
726
        query = query.filter(Order.status.in_(tuple(statuses)))
483 rajveer 727
    if from_date:
728
        query = query.filter(Order.created_timestamp >from_date)
729
    if to_date:
730
        query = query.filter(Order.created_timestamp < to_date)
731
    return query.all()
732
 
1528 ankur.sing 733
def get_order_for_customer(order_id, customer_id):
734
    if not customer_id:
735
        raise TransactionServiceException(101, "bad customer id")
736
    order = get_order(order_id)
737
    if order.customer_id != customer_id:
738
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
739
    return order
740
 
4801 anupam.sin 741
def get_all_orders(statuses, from_date, to_date, warehouse_id):
742
    if not len(statuses):
743
        raise TransactionServiceException(101, "Status list is empty")
744
    query = Order.query.filter(Order.status.in_(statuses))
745
    if warehouse_id:
746
        query = query.filter(Order.warehouse_id == warehouse_id)
747
        #raise TransactionServiceException(101, "bad warehouse id")
483 rajveer 748
    if from_date:
749
        query = query.filter(Order.created_timestamp >from_date)
750
    if to_date:
751
        query = query.filter(Order.created_timestamp < to_date)
752
    return query.all()
753
 
4133 chandransh 754
def get_orders_in_batch(statuses=[], offset=0, limit=0, warehouse_id=None):
4296 rajveer 755
    query = Order.query
756
    if warehouse_id:
757
        query = query.filter(Order.warehouse_id == warehouse_id)
4133 chandransh 758
    if statuses:
759
        query = query.filter(Order.status.in_(statuses))
760
    query = query.offset(offset)
761
    if limit:
762
        query = query.limit(limit)
763
    return query.all()
764
 
765
def get_order_count(statuses=[], warehouse_id=None):
766
    if not warehouse_id:
767
        raise TransactionServiceException(101, "bad warehouse id")
768
    query = session.query(func.count(Order.id)).filter(Order.warehouse_id == warehouse_id)
769
    if statuses:
770
        query = query.filter(Order.status.in_(statuses))
771
    return query.scalar()
772
 
1382 varun.gupt 773
def get_returnable_orders_for_customer(customer_id, limit = None):
774
    if not customer_id:
775
        raise TransactionServiceException(101, "bad customer id")
776
 
777
    query = Order.query.filter(Order.customer_id == customer_id)
778
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
779
    query = query.filter(Order.status != OrderStatus.REJECTED)
780
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
781
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
782
    orders = query.all()
783
    order_ids = [order.id for order in orders]
784
    return order_ids
785
 
786
def get_cancellable_orders_for_customer(customer_id, limit = None):
787
    if not customer_id:
788
        raise TransactionServiceException(101, "bad customer id")
4815 phani.kuma 789
    cancellableOrderStatuses = OrderStatusGroups().codCancellable
1382 varun.gupt 790
    query = Order.query.filter(Order.customer_id == customer_id)
4815 phani.kuma 791
    query = query.filter(Order.status.in_(cancellableOrderStatuses))
1382 varun.gupt 792
    orders = query.all()
793
    return [order.id for order in orders]
794
 
995 varun.gupt 795
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
796
    if not warehouse_id:
797
        raise TransactionServiceException(101, "bad warehouse id")
798
 
799
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
800
 
801
    if status:
802
        query = query.filter(Order.status == status)
803
 
804
    if start_billing_date:
805
        query = query.filter(Order.billing_timestamp >= start_billing_date)
806
 
807
    if end_billing_date:
808
        query = query.filter(Order.billing_timestamp <= end_billing_date)
809
 
810
    return query.all()
811
 
3451 chandransh 812
def get_orders_by_shipping_date(from_shipping_date, to_shipping_date, provider_id, warehouse_id, cod):
813
    query = Order.query.filter(Order.cod == cod)
3427 chandransh 814
 
815
    if warehouse_id and warehouse_id != -1:
816
        query = query.filter(Order.warehouse_id == warehouse_id)
817
 
818
    if provider_id and provider_id != -1:
819
        query = query.filter(Order.logistics_provider_id == provider_id)
820
 
821
    if from_shipping_date:
822
        query = query.filter(Order.shipping_timestamp >= from_shipping_date)
823
 
824
    if to_shipping_date:
825
        query = query.filter(Order.shipping_timestamp <= to_shipping_date)
826
 
827
    query = query.order_by(Order.airwaybill_no)
828
 
829
    return query.all()
830
 
1528 ankur.sing 831
def get_orders_for_transaction(transaction_id, customer_id):
832
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
833
 
1208 chandransh 834
    if not orders:
835
        raise TransactionServiceException(101, "No order for the transaction")
836
    return orders
837
 
1405 ankur.sing 838
def get_undelivered_orders(provider_id, warehouse_id):
839
    query = Order.query
840
    if provider_id != -1:
841
        query = query.filter_by(Order.logistics_provider_id == provider_id)
842
    if warehouse_id != -1:
843
        query = query.filter(Order.warehouse_id == warehouse_id)
844
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
845
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 846
    #Get last midnight time instead of current time as courier company would have sent the 
847
    #delivery records updated at least till midnight and not by the current time.
848
    time_format = "%Y-%m-%d %H:%M:%S.%f"
849
    t = time.strptime(str(datetime.datetime.now()), time_format)
850
    midnightTime = datetime.datetime(*t[:3])
851
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 852
    orders = query.all()
853
    return orders
854
 
1208 chandransh 855
def get_line_items_for_order(order_id):
856
    query = LineItem.query.filter(LineItem.order_id == order_id)
857
    return query.all()
858
 
483 rajveer 859
def change_order_status(self, orderId, status, description):
860
    order = get_order(orderId)
861
    order.status = status
862
    order.statusDescription = description
863
    session.commit()
3578 mandeep.dh 864
    update_trust_level(order)
865
    return True
3499 mandeep.dh 866
 
3578 mandeep.dh 867
def update_trust_level(order):
3530 mandeep.dh 868
    try:
3578 mandeep.dh 869
        trust_level_delta = 0
870
        if order.cod == True:
871
            trust_level_delta = ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT.get(order.status, 0)
872
 
3530 mandeep.dh 873
        if (trust_level_delta != 0):
874
            user_client = UserClient().get_client()
875
            user_client.increaseTrustLevel(order.customer_id, trust_level_delta)
876
    except Exception as e:
877
        print e
3499 mandeep.dh 878
 
483 rajveer 879
    return True
3064 chandransh 880
 
881
def verify_order(self, orderId):
882
    logging.info("Verifying order no: " + str(orderId))
883
    order = get_order(orderId)
4662 rajveer 884
    if order.status == OrderStatus.COD_VERIFICATION_PENDING:
3064 chandransh 885
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
886
        order.statusDescription = "Submitted for processing"
887
        order.verification_timestamp = datetime.datetime.now()
888
        session.commit()
889
        logging.info("Successfully verified order no: " + str(orderId))
890
        return True
891
    else:
892
        logging.warning("Verify called for order no." + str(orderId) +" which is not in verification pending state");
893
        return False
894
 
4285 rajveer 895
def accept_order(orderId):
3064 chandransh 896
    logging.info("Accepting order no: " + str(orderId))
921 rajveer 897
    order = get_order(orderId)
5110 mandeep.dh 898
    if order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.CAPTURE_IN_PROCESS]:
3064 chandransh 899
        if not order.cod:
900
            if order.transaction.status == TransactionStatus.AUTHORIZED:
4421 mandeep.dh 901
                __capture_txn(order)
3010 chandransh 902
        order.status = OrderStatus.ACCEPTED
903
        order.statusDescription = "Order Accepted"
904
        order.accepted_timestamp = datetime.datetime.now()
5530 mandeep.dh 905
        __amend_fulfilment_warehouse(order)
3010 chandransh 906
        session.commit()
3064 chandransh 907
        logging.info("Successfully accepted the order no.:" + str(orderId))
3010 chandransh 908
        return True
909
    else:
3064 chandransh 910
        logging.warning("Accept called for the unacceptable order: " + str(orderId))
3010 chandransh 911
        return False
921 rajveer 912
 
4421 mandeep.dh 913
def __capture_txn(order):
914
    txnId = order.transaction_id
3010 chandransh 915
    logging.info("Capturing payment for merchant txn:" + str(txnId))
4421 mandeep.dh 916
    try:
917
        payment_client = PaymentClient().get_client()
918
        capture_result = payment_client.capturePayment(txnId)
919
        if capture_result:
920
            logging.info("Successfully captured payment for merchant txn:" + str(txnId))
5527 anupam.sin 921
            change_transaction_status(txnId, TransactionStatus.IN_PROCESS, "Payment received", PickUpType.COURIER, order.orderType)
4421 mandeep.dh 922
        else:
923
            raise TransactionServiceException(115, "Payment capture failed.")
924
    except PaymentException as e:
925
        if e.error_code == 106:
926
            order.status = OrderStatus.CAPTURE_IN_PROCESS
927
            session.commit()
928
            raise TransactionServiceException(122, "Unable to capture payment due to connection issue.")
929
        else:
930
            raise TransactionServiceException(115, "Payment capture failed.")
3010 chandransh 931
 
5530 mandeep.dh 932
def __amend_fulfilment_warehouse(order):
933
    itemId = order.lineitems[0].item_id
934
    catalogClient = CatalogClient().get_client()
935
    inventory = catalogClient.getItemInventoryByItemId(itemId)
936
    if not (inventory.availability.has_key(order.fulfilmentWarehouseId) and inventory.availability[order.fulfilmentWarehouseId]):
937
        for warehouse in catalogClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, order.warehouse_id, 0):
5558 mandeep.dh 938
            if inventory.availability.has_key(warehouse.id) and inventory.availability[warehouse.id] >= inventory.reserved[warehouse.id] + order.lineitems[0].quantity:
5530 mandeep.dh 939
                catalogClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, order.lineitems[0].quantity)
940
                catalogClient.reserveItemInWarehouse(itemId, warehouse.id, order.lineitems[0].quantity)
5637 mandeep.dh 941
                order.fulfilmentWarehouseId = warehouse.id
5530 mandeep.dh 942
                break
943
 
5411 rajveer 944
def add_billing_details(orderId, invoice_number, serialNumbers, itemNumbers, billedBy, jacketNumber, billingType, fulfilmentWarehouseId, authorize):
4285 rajveer 945
    if jacketNumber is None or jacketNumber <= 0:
2783 chandransh 946
        raise TransactionServiceException(110, "Invalid jacket number")
947
 
4285 rajveer 948
    if billedBy is None or billedBy.strip() == "":
2783 chandransh 949
        raise TransactionServiceException(110, "Invalid Biller")
950
 
1149 chandransh 951
    order = Order.get_by(id=orderId)
952
    if not order:
2783 chandransh 953
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
5110 mandeep.dh 954
 
955
    lineitem = order.lineitems[0]
956
    item_id = lineitem.item_id
957
    catalog_client = CatalogClient().get_client()
958
    item = catalog_client.getItem(item_id)
4283 anupam.sin 959
    if order.status == OrderStatus.ACCEPTED:
4285 rajveer 960
        order.jacket_number = jacketNumber
961
        if billingType == BillingType.OURS:
5411 rajveer 962
            if itemNumbers:
963
                lineitem.item_number = itemNumbers[0]    
4283 anupam.sin 964
 
5411 rajveer 965
            if ItemType.SERIALIZED == item.type and not (serialNumbers and serialNumbers[0]):
966
                raise TransactionServiceException(110, "No Serial Number supplied")
967
            if serialNumbers:
968
                lineitem.serial_number = serialNumbers[0]
969
 
5527 anupam.sin 970
            order.invoice_number = get_next_invoice_number(order.orderType)
4283 anupam.sin 971
        else:
972
            order.invoice_number = invoice_number
4763 rajveer 973
            # In case of hotspot billing, we should try to verify that color billed in ETP is same as color in order.
974
            if billedOrdersColorMap.has_key(orderId):
975
                etpColor = billedOrdersColorMap.get(orderId)
976
                ourColor = order.lineitems[0].color
4781 rajveer 977
                if ourColor and etpColor != ourColor and not authorize:
4763 rajveer 978
                    raise TransactionServiceException(777, "ETP color: " + etpColor + " and Order color: " + ourColor)
979
                else:
980
                    billedOrdersColorMap.pop(orderId)
4283 anupam.sin 981
 
2842 chandransh 982
        order.status = OrderStatus.BILLED
983
        order.statusDescription = "Order Billed"
984
        order.billing_timestamp = datetime.datetime.now()
4285 rajveer 985
        order.billed_by = billedBy
4435 mandeep.dh 986
 
5436 mandeep.dh 987
        # Letting the billing process fail in cases where we are unable to 
4435 mandeep.dh 988
        # fill in transfer price
989
        try:
990
            catalog_client = CatalogClient().get_client()
5110 mandeep.dh 991
            warehouse = catalog_client.getWarehouse(fulfilmentWarehouseId)
992
            item_pricing = catalog_client.getItemPricing(item_id, warehouse.vendor.id)
993
            lineitem.transfer_price = item_pricing.transferPrice
994
            order.vendorId = warehouse.vendor.id
4435 mandeep.dh 995
        except InventoryServiceException as e:
996
            print sys.exc_info()[0]
997
            print e.message
5110 mandeep.dh 998
            raise TransactionServiceException(110, 'Transfer price missing for itemId: ' + str(item_id) + ' and vendor: ' + str(warehouse.vendor.id))
4435 mandeep.dh 999
 
5110 mandeep.dh 1000
        # For OUR warehouse, we need to scan out items for every billed order
1001
        if billingType == BillingType.OURS:
5530 mandeep.dh 1002
            for index, serialNumber in enumerate(serialNumbers):
5411 rajveer 1003
                try:
1004
                    warehouse_client = WarehouseClient().get_client()
5436 mandeep.dh 1005
                    # Fetching GOOD w/h corresponding to the virtual one here
1006
                    if warehouse.billingWarehouseId is None:
1007
                        warehouse = catalog_client.getWarehouses(None, InventoryType.GOOD, warehouse.vendor.id, order.warehouse_id, 0)[0]
1008
 
5411 rajveer 1009
                    if ItemType.SERIALIZED == item.type:
1010
                        inventoryItem = warehouse_client.getInventoryItem(serialNumber)
1011
                    else:
5661 mandeep.dh 1012
                        inventoryItem = warehouse_client.getNonSeralizedInventoryItem(itemNumbers[index], item_id, warehouse.id)
5411 rajveer 1013
 
1014
                    if (inventoryItem.itemId != item_id):
1015
                        catalog_client = CatalogClient().get_client()
1016
                        item = catalog_client.getItem(inventoryItem.itemId)
1017
                        scanItemString = " ".join([str(item.brand), str(item.modelName), str(item.modelNumber), str(item.color)])
1018
                        lineItemString = " ".join([str(lineitem.brand), str(lineitem.model_name), str(lineitem.model_number), str(lineitem.color)])
1019
                        raise TransactionServiceException(110, 'Trying to scan ' + scanItemString + ' instead of ' + lineItemString)
1020
 
1021
                    if ItemType.SERIALIZED == item.type:
5661 mandeep.dh 1022
                        inventoryItem = warehouse_client.scanSerializedItemForOrder(serialNumber, ScanType.SALE, orderId, warehouse.id, 1, order.warehouse_id)
5411 rajveer 1023
                    else:
5661 mandeep.dh 1024
                        inventoryItem = warehouse_client.scanForOrder(inventoryItem, ScanType.SALE, 1, order.id, warehouse.id, order.warehouse_id)
5411 rajveer 1025
 
1026
                    lineitem.transfer_price = inventoryItem.unitPrice
1027
                    order.vendorId = inventoryItem.supplierId
5636 amar.kumar 1028
                    catalog_client = CatalogClient().get_client()
5411 rajveer 1029
                except WarehouseServiceException as e:
1030
                    print sys.exc_info()[0]
1031
                    print 'Could not scan out orders due to: ' + e.message
1032
                    raise TransactionServiceException(110, e.message)
5123 mandeep.dh 1033
        else:
1034
            if not warehouse.isAvailabilityMonitored:
1035
                catalog_client = CatalogClient().get_client()
1036
                catalog_client.addInventory(item.id, warehouse.id, -1 * lineitem.quantity)
4365 mandeep.dh 1037
 
5110 mandeep.dh 1038
        __update_inventory_reservation(order)
5661 mandeep.dh 1039
        order.fulfilmentWarehouseId = warehouse.id
4541 mandeep.dh 1040
        session.commit()
4283 anupam.sin 1041
        return True
1042
    else:
1043
        return False
1149 chandransh 1044
 
4763 rajveer 1045
def add_invoice_number(orderId, invoiceNumber, color):
4579 rajveer 1046
    order = Order.get_by(id=orderId)
1047
    if not order:
1048
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
1049
 
1050
    if order.status == OrderStatus.ACCEPTED:
1051
        order.invoice_number = invoiceNumber
4767 rajveer 1052
        if color:
1053
            billedOrdersColorMap[orderId] = color;
4579 rajveer 1054
    session.commit()
1055
 
1220 chandransh 1056
def batch_orders(warehouseId):
1057
    if not warehouseId:
1058
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 1059
 
1060
    batchno_generator = BatchNoGenerator()
1061
    session.commit()
1220 chandransh 1062
    query = Order.query.filter_by(warehouse_id=warehouseId)
4592 mandeep.dh 1063
    query = query.filter(Order.status == OrderStatus.LOW_INV_PO_RAISED)
1220 chandransh 1064
    query = query.order_by(Order.created_timestamp)
1065
    pending_orders = query.all()
1225 chandransh 1066
 
1220 chandransh 1067
    serial_no = 1
1068
    for order in pending_orders:
1276 chandransh 1069
        order.batchNo = batchno_generator.id
1220 chandransh 1070
        order.serialNo = serial_no
1071
        serial_no += 1
1072
    session.commit() 
1073
    pending_orders = query.all()
1074
    return pending_orders
1075
 
1076
def order_outofstock(orderId):
1911 chandransh 1077
    '''
1078
    Mark order as out of stock
1079
    '''
1220 chandransh 1080
    order = get_order(orderId)
1081
    order.status = OrderStatus.INVENTORY_LOW
1082
    order.statusDescription = "Low Inventory"
1083
    order.outofstock_timestamp = datetime.datetime.now()
1084
    session.commit()
1085
    return True
1086
 
4789 rajveer 1087
def mark_orders_as_shipped_from_warehouse(warehouseId, providerId, cod, orderIds):
4410 rajveer 1088
    try:
1089
        current_timestamp = datetime.datetime.now()
4789 rajveer 1090
        orders = Order.query.filter_by(warehouse_id = warehouseId, logistics_provider_id = providerId, status = OrderStatus.BILLED, cod = cod).all()
4410 rajveer 1091
        for order in orders:
4789 rajveer 1092
            if order.id in orderIds:
1093
                order.status = OrderStatus.SHIPPED_FROM_WH
1094
                order.statusDescription = "Order shipped from warehouse"
1095
                order.shipping_timestamp = current_timestamp
5636 amar.kumar 1096
                try:
1097
                    print "Trying to schedule alert"
1098
                    monitoredEntity = MonitoredEntity();
1099
                    monitoredEntity.entityType=EntityType.COURIER;
1100
                    monitoredEntity.eventType=OrderStatus.SHIPPED_FROM_WH;
1101
                    monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1102
                    adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1103
                    sec = datetime.datetime.now()
1104
                    #Warn alert time is taken as 16 hrs
1105
                    warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=16))
1106
                    #Critical alert time is taken as 26 hrs                    
1107
                    critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=26))
1108
                    monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1109
                    monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1110
                    monitoredEntity.description="warehouseId = " + str(warehouseId) + " providerId = " + str(providerId) + " orderId = "  + str(order.id);
1111
                    alert_client = AlertClient().get_client()
1112
                    alert_client.scheduleAlert(monitoredEntity)
1113
                except Exception as e:
5801 amar.kumar 1114
                    print "Exception in scheduling alert in ShippedFromWarehouse method"
5636 amar.kumar 1115
                    print e
759 chandransh 1116
        session.commit()
4749 varun.gupt 1117
 
1118
        try:
1119
            enqueue_shipping_confirmation_email(orders)
1120
        except Exception as e:
1121
            print e
1122
 
759 chandransh 1123
        return True
1124
    except:
1125
        return False
4410 rajveer 1126
 
5713 rajveer 1127
def mark_orders_as_returned_from_store(providerId, orderIds, awbs):
5676 rajveer 1128
    try:
1129
        current_timestamp = datetime.datetime.now()
1130
        orders = Order.query.filter_by(logistics_provider_id = providerId, status = OrderStatus.RET_PICKUP_REQUEST_RAISED).all()
1131
        for order in orders:
1132
            if order.id in orderIds:
1133
                order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1134
                order.statusDescription = "Order returned from store"
1135
                order.doa_pickup_timestamp = current_timestamp
5713 rajveer 1136
                #order.airwaybill_no = awbs[orderIds.index(order.id)]
1137
                order.tracking_id = awbs[orderIds.index(order.id)]
5676 rajveer 1138
        session.commit()
1139
 
1140
        return True
1141
    except:
1142
        return False    
1143
 
1144
def set_order_attributes(orderId, attributes):
5791 anupam.sin 1145
    existingAttributes = Attribute.query.filter_by(orderId=orderId).all()
1146
    if existingAttributes :
1147
        for existingAttribute in existingAttributes :
1148
            for attribute in attributes :
1149
                if attribute.name == existingAttribute.name :
1150
                    existingAttribute.value = attribute.value
1151
    else :                
1152
        for t_attribute in attributes:
1153
            attribute = Attribute()
1154
            attribute.orderId = orderId
1155
            attribute.name = t_attribute.name
1156
            attribute.value = t_attribute.value
1157
    session.commit()
5724 rajveer 1158
 
1113 chandransh 1159
def mark_orders_as_picked_up(provider_id, pickup_details):
1160
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 1161
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 1162
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 1163
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1164
            continue
1113 chandransh 1165
        order.status = OrderStatus.SHIPPED_TO_LOGST
1166
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 1167
        order.pickup_timestamp = pickup_timestamp
5636 amar.kumar 1168
 
1169
        try:
1170
            monitoredEntity = MonitoredEntity();
1171
            monitoredEntity.entityType=EntityType.COURIER;
1172
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_LOGST
1173
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1174
            adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1175
            sec = datetime.datetime.now()
1176
            #Warn alert time is taken as 16 hrs
1177
            warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=16))
1178
            #Critical alert time is taken as 26 hrs                    
1179
            critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=26))
1180
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1181
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1182
            monitoredEntity.description="providerId = " + str(provider_id) + "   " + pickup_details
1183
            alert_client = AlertClient().get_client()
1184
            alert_client.updateMonitoredObject(monitoredEntity)
1185
        except Exception as e:
5801 amar.kumar 1186
            print "Exception in updating alert in MarkOrdersAsPickedUp method"
5636 amar.kumar 1187
            print e
1113 chandransh 1188
    session.commit()
1217 chandransh 1189
 
4910 phani.kuma 1190
def get_orders_not_picked_up(provider_id):
1132 chandransh 1191
    current_time = datetime.datetime.now()
1192
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4741 phani.kuma 1193
    orders_not_picked_up = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.SHIPPED_FROM_WH).filter(Order.shipping_timestamp <= to_datetime).all()
1113 chandransh 1194
    return orders_not_picked_up
1195
 
1132 chandransh 1196
def mark_orders_as_delivered(provider_id, delivered_orders):
1197
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 1198
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 1199
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE]:
1911 chandransh 1200
            continue
1201
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
5555 rajveer 1202
        if order.pickupStoreId:
1203
            order.status = OrderStatus.DELIVERED_AT_STORE
1204
            order.statusDescription = "Order delivered At Store"
5762 amar.kumar 1205
            try:
1206
                monitoredEntity = MonitoredEntity();
1207
                monitoredEntity.entityType=EntityType.COURIER;
1208
                monitoredEntity.eventType=OrderStatus.RECEIVED_AT_STORE;
1209
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1210
                #adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1211
                sec = datetime.datetime.now()
1212
                #Critical alert time is taken as 26 hrs                    
1213
                critical_time = (sec + timedelta(hours=4))
1214
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1215
                monitoredEntity.description="deliveryTimeAtStore = " + str(order.delivery_timestamp) + " orderId = "  + str(order.id);
1216
                alert_client = AlertClient().get_client()
1217
                alert_client.updateMonitoredObject(monitoredEntity)
1218
            except Exception as e:
1219
                print e
5555 rajveer 1220
        else:
1221
            order.status = OrderStatus.DELIVERY_SUCCESS
1222
            order.statusDescription = "Order delivered"
5762 amar.kumar 1223
            update_trust_level(order)
5807 rajveer 1224
            enqueue_delivery_successe_mail(order)
5762 amar.kumar 1225
            try:
1226
                alert_client = AlertClient().get_client()
1227
                alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1228
            except Exception as e:
5801 amar.kumar 1229
                print "Exception in scheduling alert in ShippedFromWarehouse method"
5762 amar.kumar 1230
                print e
4910 phani.kuma 1231
        timestamp, receiver = detail.split('|')
1232
        if order.first_dlvyatmp_timestamp is None:
1233
            order.first_dlvyatmp_timestamp = timestamp
1234
        order.delivery_timestamp = timestamp
1235
        order.receiver = receiver
5636 amar.kumar 1236
 
1132 chandransh 1237
    session.commit()
1238
 
4712 rajveer 1239
def mark_order_as_delivered(orderId, deliveryTimestamp, receiver):
1240
    order = Order.get_by(id=orderId)
5555 rajveer 1241
    if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_REQUEST_RECEIVED, OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_REQUEST_AUTHORIZED, OrderStatus.RET_PICKUP_REQUEST_RAISED, OrderStatus.RTO_IN_TRANSIT, OrderStatus.BILLED, OrderStatus.RECEIVED_AT_STORE]:
4712 rajveer 1242
        raise TransactionServiceException(101, "Either wrond order id or invalid state " + str(orderId))
5402 rajveer 1243
 
1244
    # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
1245
    if order.status == OrderStatus.BILLED and order.logistics_provider_id != 4:
5807 rajveer 1246
        raise TransactionServiceException(101, "Order is not marked for self pickup: " + str(orderId))
5402 rajveer 1247
 
5555 rajveer 1248
    if order.status in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.RTO_IN_TRANSIT, OrderStatus.BILLED, OrderStatus.RECEIVED_AT_STORE]:
4712 rajveer 1249
        order.delivery_timestamp = deliveryTimestamp
1250
        order.receiver = receiver
1251
    order.status = OrderStatus.DELIVERY_SUCCESS
1252
    order.statusDescription = "Order delivered"
1253
    update_trust_level(order)
1254
    session.commit()
5713 rajveer 1255
 
5806 rajveer 1256
    if order.pickupStoreId:
1257
        __push_collection_to_hotspot(order, "SALE")
1258
 
5807 rajveer 1259
    enqueue_delivery_successe_mail(order)
5713 rajveer 1260
#    if order.pickupStoreId:
1261
#        payment_client = PaymentClient().get_client()
1262
#        payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
1263
#        payment_client = PaymentClient().get_client()
1264
#        payment_client.partiallyCapturePayment(order.transaction.id, order.total_amount, xferBy, xferTxnId, now())
1265
#        order.cod_reconciliation_timestamp = datetime.datetime.now()
1266
#        session.commit()
1267
 
5636 amar.kumar 1268
    try:
1269
        alert_client = AlertClient().get_client()
5744 amar.kumar 1270
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1271
    except Exception as e:
5801 amar.kumar 1272
        print "Exception in ending alert in MarkOrderAsDelivered method"
5636 amar.kumar 1273
        print e
1274
 
4712 rajveer 1275
 
5555 rajveer 1276
def mark_order_as_received_at_store(orderId, deliveryTimestamp):
1277
    order = Order.get_by(id=orderId)
1278
    if order != None or order.status in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DELIVERED_AT_STORE]:
1279
        order.status = OrderStatus.RECEIVED_AT_STORE
1280
        order.statusDescription = "Order received at store"
1281
        order.delivery_timestamp = deliveryTimestamp
1282
    session.commit()
5713 rajveer 1283
    try:
5762 amar.kumar 1284
        alert_client = AlertClient().get_client()
1285
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1286
    except Exception as e:
1287
        print e
1288
 
1289
    try:
5713 rajveer 1290
        enqueue_received_at_store_email(order)
1291
    except Exception as e:
1292
        print e
1293
 
1294
 
5555 rajveer 1295
 
4910 phani.kuma 1296
def mark_orders_as_rto(provider_id, returned_orders):
1135 chandransh 1297
    for awb, detail in returned_orders.iteritems():
1298
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
5713 rajveer 1299
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.DELIVERED_AT_STORE, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE]:
2684 chandransh 1300
            continue
1301
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 1302
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 1303
        order.delivery_timestamp, reason = detail.split('|')
1304
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 1305
        update_trust_level(order)
1911 chandransh 1306
    session.commit()
5636 amar.kumar 1307
    try:
1308
        alert_client = AlertClient().get_client()
5801 amar.kumar 1309
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1310
    except Exception as e:
5801 amar.kumar 1311
        print "Exception in ending alert in MarkOrderAsRTO method"
5636 amar.kumar 1312
        print e
1135 chandransh 1313
 
4910 phani.kuma 1314
def get_rto_orders(provider_id):
1315
    current_time = datetime.datetime.now()
1316
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1317
    rto_orders = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.RTO_IN_TRANSIT).filter(Order.delivery_timestamp <= to_datetime).all()
1318
    return rto_orders
1319
 
5555 rajveer 1320
def get_receive_pending_orders(storeId):
1321
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DELIVERED_AT_STORE))).all()
1322
 
1323
def get_received_at_store_orders(storeId):
5676 rajveer 1324
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.RECEIVED_AT_STORE, OrderStatus.RET_PICKUP_REQUEST_RAISED))).all()
5555 rajveer 1325
 
5713 rajveer 1326
def get_orders_collection_at_store(storeId, fromDate, toDate, onlyCod):
1327
    query = Order.query.filter(Order.status == OrderStatus.DELIVERY_SUCCESS)
1328
    if storeId:
1329
        query = query.filter_by(pickupStoreId = storeId)
5720 rajveer 1330
    else:
1331
        query = query.filter(Order.pickupStoreId != 0)
5713 rajveer 1332
    if onlyCod:
1333
        query = query.filter_by(cod = onlyCod)
1334
    if fromDate:
1335
        query = query.filter(Order.delivery_timestamp >= fromDate)
1336
    if toDate:
1337
        query = query.filter(Order.delivery_timestamp <= toDate)
1338
    return query.all()
1339
 
1246 chandransh 1340
def update_non_delivery_reason(provider_id, undelivered_orders):
1341
    for awb, reason in undelivered_orders.iteritems():
1342
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4920 phani.kuma 1343
        if order == None or order.status == OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE:
2684 chandransh 1344
            continue
1345
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 1346
        order.statusDescription = reason
1347
    session.commit()
4910 phani.kuma 1348
 
1349
def get_non_delivered_orders_by_courier(provider_id):
4581 phani.kuma 1350
    current_time = datetime.datetime.now()
1351
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1352
    upto_datetime = today_datetime - datetime.timedelta(4)
4910 phani.kuma 1353
    orders_not_delivered = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE))).filter(or_(Order.shipping_timestamp <= upto_datetime, Order.pickup_timestamp <= upto_datetime)).all()
4581 phani.kuma 1354
    return orders_not_delivered
1246 chandransh 1355
 
4910 phani.kuma 1356
def mark_orders_as_local_connected(provider_id, local_connected_orders):
1357
    for awb, timestamp in local_connected_orders.iteritems():
1358
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1359
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1360
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1361
            continue
1362
        order.status = OrderStatus.SHIPPED_TO_DESTINATION_CITY
1363
        order.statusDescription = "Left Out of Origin City"
5636 amar.kumar 1364
        current_time = datetime.datetime.now()
1365
        order.local_connected_timestamp = datetime.datetime(current_time.year, current_time.month, current_time.day)
1366
        try:
1367
            monitoredEntity = MonitoredEntity();
1368
            monitoredEntity.entityType=EntityType.COURIER;
1369
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_DESTINATION_CITY
1370
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1371
            #Warn alert time is taken as 23 hrs less than promised delivery time
5801 amar.kumar 1372
            warn_time = (order.expected_delivery_time-timedelta(hours = 23))
5744 amar.kumar 1373
            #Critical alert time is taken as 13 hrs less than promised delivery time                    
5801 amar.kumar 1374
            critical_time = (order.expected_delivery_time-timedelta(hours = 13))
1375
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1376
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1377
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1378
            alert_client = AlertClient().get_client()
1379
            alert_client.updateMonitoredObject(monitoredEntity)
1380
        except Exception as e:
5801 amar.kumar 1381
            print "Exception in updating alert in MarkOrderAsLocalConnected method"
5636 amar.kumar 1382
            print e
1383
        session.commit()
4910 phani.kuma 1384
 
1385
def get_orders_not_local_connected(provider_id):
1386
    current_time = datetime.datetime.now()
1387
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1388
    orders_pending_local_connection = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST))).filter(or_(Order.shipping_timestamp <= to_datetime, Order.pickup_timestamp <= to_datetime)).all()
1389
    return orders_pending_local_connection
1390
 
1391
def mark_orders_as_destinationCityReached(provider_id, destination_city_reached_orders):
1392
    for awb, timestamp in destination_city_reached_orders.iteritems():
1393
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1394
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY]:
1395
            continue
1396
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1397
        order.status = OrderStatus.REACHED_DESTINATION_CITY
1398
        order.statusDescription = "Reached Destination City"
1399
        order.reached_destination_timestamp = timestamp
5636 amar.kumar 1400
        try:
1401
            monitoredEntity = MonitoredEntity();
1402
            monitoredEntity.entityType=EntityType.COURIER;
1403
            monitoredEntity.eventType=OrderStatus.REACHED_DESTINATION_CITY
1404
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5764 amar.kumar 1405
            warn_time = (order.expected_delivery_time)
5801 amar.kumar 1406
            critical_time = (order.expected_delivery_time + timedelta(hours=12))
1407
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1408
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1409
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1410
            alert_client = AlertClient().get_client()
1411
            alert_client.updateMonitoredObject(monitoredEntity)
1412
        except Exception as e:
5801 amar.kumar 1413
            print "Exception in updating alert in MarkOrderAsDestCityReached method"
5636 amar.kumar 1414
            print e
4910 phani.kuma 1415
    session.commit()
1416
 
1417
def mark_orders_as_firstDeliveryAttempted(provider_id, first_atdl_orders):
1418
    for awb, detail in first_atdl_orders.iteritems():
1419
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1420
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY]:
1421
            continue
1422
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1423
        order.status = OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1424
        order.first_dlvyatmp_timestamp, reason = detail.split('|')
1425
        order.statusDescription = reason
5636 amar.kumar 1426
        try:
1427
            monitoredEntity = MonitoredEntity();
1428
            monitoredEntity.entityType=EntityType.COURIER;
1429
            monitoredEntity.eventType=OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1430
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1431
            adjustedDeliveryDaysfor1day = adjust_delivery_time(datetime.datetime.now(), 1);
1432
            adjustedDeliveryDaysfor2days = adjust_delivery_time(datetime.datetime.now(), 2);
1433
            sec = datetime.datetime.now()
1434
            #Warn alert time is taken as 16 hrs
1435
            warn_time = (sec + timedelta(days=(adjustedDeliveryDaysfor1day-1)) + timedelta(hours=24))
1436
            #Critical alert time is taken as 26 hrs                    
1437
            critical_time = (sec + timedelta(days=(adjustedDeliveryDaysfor2days-1)) + timedelta(hours=36))
1438
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1439
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1440
            monitoredEntity.description="providerId = " + str(provider_id) + " first attempt timestamp" + order.first_dlvyatmp_timestamp
1441
            alert_client = AlertClient().get_client()
1442
            alert_client.updateMonitoredObject(monitoredEntity)
1443
        except Exception as e:
5801 amar.kumar 1444
            print "Exception in updating alert in MarkOrdersAsFirstDeliveryAttempted method"
5636 amar.kumar 1445
            print e
4910 phani.kuma 1446
    session.commit()
1447
 
4783 phani.kuma 1448
def get_orders_not_met_expected_delivery_date():
1449
    current_time = datetime.datetime.now()
1450
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4910 phani.kuma 1451
    orders_not_delivered = Order.query.filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY))).filter(Order.expected_delivery_time <= today_datetime).all()
4783 phani.kuma 1452
    return orders_not_delivered
1453
 
4444 rajveer 1454
def get_alerts(type, warehouseId, status, timestamp):
1455
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
1456
    if type != -1 :
1457
        query = query.filter(Alert.type == type)
1458
    if status != -1 :
1459
        query = query.filter(Alert.status == status)
4394 rajveer 1460
    if timestamp:
1461
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 1462
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 1463
    return query.all()
1464
 
4447 rajveer 1465
def add_alert(type, warehouseId, description):
4394 rajveer 1466
    alert = Alert()
1467
    alert.type = type
1468
    alert.status = 1
1469
    alert.description = description
1470
    alert.timestamp = datetime.datetime.now()
4447 rajveer 1471
    alert.warehouseId = warehouseId
4444 rajveer 1472
    session.commit()
766 rajveer 1473
 
4444 rajveer 1474
def mark_alerts_as_seen(warehouseId):
1475
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
1476
    alerts = query.all()
1477
    for alert in alerts:
1478
        alert.status = 0    
1479
    session.commit()
1480
 
1596 ankur.sing 1481
def get_valid_order_count():
2851 chandransh 1482
    '''
1483
    Returns the number of orders which we processed. The reshipped orders are not
1484
    counted since there'll always be a new compensating order present.
1485
    '''
4682 rajveer 1486
    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 1487
 
1627 ankur.sing 1488
def get_cust_count_with_successful_txn():
2851 chandransh 1489
    '''
1490
    Returns the number of distinct customers who have done successful transactions.
1491
    It uses the sqlalchemy func module to construct an efficient query.
1492
    '''
1493
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 1494
 
1730 ankur.sing 1495
def get_valid_orders_amount_range():
2851 chandransh 1496
    '''
1497
    Returns a list containing the minimum and maximum amount across all
1498
    orders placed with us. No need to consider reshippped orders for min/max
1499
    amount of orders.
1500
    '''
1501
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 1502
 
1886 ankur.sing 1503
def get_valid_orders(limit):
2851 chandransh 1504
    '''
1505
    Returns the last limit number of valid orders placed with us. Ignored the
1506
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
1507
    less than 0. 
1508
    '''
1509
    if limit < 0:
1510
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
4662 rajveer 1511
    query = Order.query.filter(Order.status >= OrderStatus.COD_VERIFICATION_PENDING)
1886 ankur.sing 1512
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 1513
    if limit != 0:
1886 ankur.sing 1514
        query = query.limit(limit)
1515
    return query.all()
1516
 
5527 anupam.sin 1517
def get_next_invoice_number(orderType):
1518
    if OrderType.B2Cbulk == orderType:
1519
        orderType = OrderType.B2C
1520
    entity_id = InvoiceIDGenerator.query.filter(InvoiceIDGenerator.orderType == orderType).with_lockmode("update").one()
2783 chandransh 1521
    invoice_number = entity_id.id + 1
1522
    entity_id.id = invoice_number
1523
    return invoice_number
1524
 
2536 chandransh 1525
def toggle_doa_flag(order_id):
1526
    order = get_order(order_id)
1527
    if(order.doaFlag):
1528
        order.doaFlag = False
1529
    else:
1530
        order.doaFlag = True
1531
    session.commit()
1532
    return order.doaFlag
1533
 
4454 rajveer 1534
def mark_order_doa_request_received(orderId):
1535
    order = get_order(orderId)
1536
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1537
        return False
1538
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 1539
    order.statusDescription = "DOA Request Received"
4454 rajveer 1540
    session.commit()
1541
    return True
1542
 
1543
def mark_order_doa_request_authorized(orderId, isAuthorized):
1544
    order = get_order(orderId)
1545
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
1546
        return False
1547
    if isAuthorized:
1548
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 1549
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 1550
    else:
1551
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 1552
        order.statusDescription = "Order delivered"
4454 rajveer 1553
    session.commit()
1554
    return True
1555
 
4488 rajveer 1556
def mark_order_return_request_received(orderId):
1557
    order = get_order(orderId)
1558
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1559
        return False
1560
    order.status = OrderStatus.RET_REQUEST_RECEIVED
1561
    order.statusDescription = "Return Request Received"
1562
    session.commit()
1563
    return True
1564
 
1565
def mark_order_return_request_authorized(orderId, isAuthorized):
1566
    order = get_order(orderId)
1567
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
1568
        return False
1569
    if isAuthorized:
1570
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
1571
        order.statusDescription = "Return Request Authorized"
1572
    else:
1573
        order.status = OrderStatus.DELIVERY_SUCCESS
1574
        order.statusDescription = "Order delivered"
1575
    session.commit()
1576
    return True
1577
 
4579 rajveer 1578
def request_pickup_number(order_id, providerId):
2536 chandransh 1579
    order = get_order(order_id)
4495 rajveer 1580
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 1581
        return False
1582
    from_user = 'cnc.center@shop2020.in'
1583
    from_pwd = '5h0p2o2o'
1584
 
4227 rajveer 1585
    subject = "Pickup request from " + order.customer_city
2536 chandransh 1586
    try:
3133 rajveer 1587
        catalog_client = CatalogClient().get_client()
2536 chandransh 1588
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1589
 
1590
        logistics_client = LogisticsClient().get_client()
4579 rajveer 1591
        provider = logistics_client.getProvider(providerId)
3051 chandransh 1592
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 1593
        raw_message = '''
1594
        Dear Sir/Madam,
1595
 
2559 chandransh 1596
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 1597
 
1598
        Pickup CODE: %(provider_code)s
1599
        Total Weight: %(order_weight)s kg
1600
 
2559 chandransh 1601
        Pickup Address:
2536 chandransh 1602
 
1603
        %(customer_address)s
1604
 
1605
        Delivery Address:
1606
 
1607
        %(warehouse_executive)s
1608
        %(warehouse_address)s
1609
        PIN %(warehouse_pin)s
1610
 
1611
        Thanks and Regards
4227 rajveer 1612
        Sandeep Sachdeva
2536 chandransh 1613
        '''
4579 rajveer 1614
 
1615
        if warehouse.id == 7:
1616
            executive = 'Amit Kumar'
1617
        else:
4966 phani.kuma 1618
            executive = 'Dinesh Kumar'
4579 rajveer 1619
 
2559 chandransh 1620
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 1621
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
2536 chandransh 1622
                                          'order_weight' : str(order.total_weight),
1623
                                          'customer_address' : __get_order_address(order),
4579 rajveer 1624
                                          'warehouse_executive' : executive,
2536 chandransh 1625
                                          'warehouse_address' : warehouse.location,
4966 phani.kuma 1626
                                          'warehouse_pin' : warehouse.pincode}
5256 rajveer 1627
        to_addresses = [to_addr, 'zaffar.kar@shop2020.in', 'suraj.sharma@shop2020.in']
4966 phani.kuma 1628
 
4606 rajveer 1629
        mail(from_user, from_pwd, to_addresses, subject, message)
4495 rajveer 1630
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
1631
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
1632
            order.statusDescription = "Pick up requested for RETURN"
1633
        else:
1634
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
1635
            order.statusDescription = "Pick up requested for DOA"
4815 phani.kuma 1636
        order.doa_logistics_provider_id = providerId
2536 chandransh 1637
        session.commit()
1638
        return True
1639
    except Exception as e:
1640
        print sys.exc_info()[0]
1641
        return False
1642
 
4602 rajveer 1643
def authorize_pickup(order_id, pickup_number, providerId):
2536 chandransh 1644
    order = get_order(order_id)
4495 rajveer 1645
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 1646
        return False
4815 phani.kuma 1647
    if order.doa_logistics_provider_id is not None:
1648
        providerId = order.doa_logistics_provider_id    #previously we are not storing this so data is taken from omdashboarduser
2536 chandransh 1649
    from_user = 'help@shop2020.in'
1650
    from_pwd = '5h0p2o2o'
1651
    subject = 'Pickup details'
1652
    filename = "/tmp/" +  str(order.id) +".pdf" 
1653
    try:
3133 rajveer 1654
        catalog_client = CatalogClient().get_client()
2536 chandransh 1655
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1656
 
1657
        logistics_client = LogisticsClient().get_client()
4602 rajveer 1658
        provider = logistics_client.getProvider(providerId)
2536 chandransh 1659
        provider_name = provider.name
1660
 
1661
        to_addr = order.customer_email
1662
        today = date.today().strftime("%d-%B-%Y (%A)")
1663
 
1664
        raw_message = '''
1665
        Dear Mr. %(customer_name)s,
1666
 
4815 phani.kuma 1667
        In reference to the return of order ID %(order_id)d, ''' + __generate_mail_body_for_authorize_pickup(order)
1668
        raw_message = raw_message + '''
2536 chandransh 1669
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
1670
        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.
1671
 
1672
        Pickup will happen from the below mentioned address:-
1673
 
1674
        %(customer_address)s
1675
 
1676
        Do let us know in case of any concerns
1677
 
1678
        Thanks & Regards
1679
        Saholic Team
1680
        '''
1681
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
1682
                                         'order_id' : order_id,
1683
                                         'provider_name' : provider_name,
1684
                                         'date': today,
1685
                                         'pickup_request_no' : pickup_number,
1686
                                         'customer_address' : __get_order_address(order)}
1687
        print message
1688
        __generate_return_advice(order, warehouse, provider, filename)
3527 chandransh 1689
        mail(from_user, from_pwd, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 1690
        order.pickupRequestNo = pickup_number
4495 rajveer 1691
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1692
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
1693
            order.statusDescription = "RETURN pick up confirmed"
1694
        else:
1695
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
1696
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 1697
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 1698
        session.commit()
1699
        return True
1700
    except Exception as e:
4234 rajveer 1701
        print sys.exc_info()
4506 phani.kuma 1702
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 1703
        return False
1704
    finally:
1705
        if os.path.exists(filename):
1706
            os.remove(filename)
1707
 
4815 phani.kuma 1708
def __generate_mail_body_for_authorize_pickup(order):
1709
    brand_msgbody_map = {'Nokia' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1710
                         'Micromax' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1711
                         'Karbonn' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1712
                         'Sony Ericsson' : 'we request you to kindly pack the original DOA certificate and the invoice.',
1713
                         'Others Handsets' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original "DOA" certificate and the invoice. Please paste the original DOA on the sealed box. Kindly ensure that the product is properly sealed. If we receive open sealed products, we will not be able to accept.',
1714
                         'Handsets Return' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1715
                         'Accessories' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original product and the invoice.'}
1716
    categories = ["Handsets", "Tablets", "Laptops"]
1717
    lineitem = order.lineitems[0]
1718
    brand = lineitem.brand
1719
    productGroup = lineitem.productGroup
1720
    searchkey = None
1721
    if productGroup not in categories:
1722
        searchkey = 'Accessories'
1723
    elif order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1724
        searchkey = 'Handsets Return'
1725
    elif brand == 'Nokia':
1726
        searchkey = 'Nokia'
1727
    elif brand == 'Micromax':
1728
        searchkey = 'Micromax'
1729
    elif brand == 'Karbonn':
1730
        searchkey = 'Karbonn'
1731
    elif brand == 'Sony Ericsson':
1732
        searchkey = 'Sony Ericsson'
1733
    else:
1734
        searchkey = 'Others Handsets'
1735
    return brand_msgbody_map.get(searchkey)
1736
 
2764 chandransh 1737
def mark_doas_as_picked_up(provider_id, pickup_details):
1738
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1739
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4452 rajveer 1740
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 1741
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1742
            continue
1743
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
1744
        order.statusDescription = "DOA picked up by Courier Company"
1745
        order.doa_pickup_timestamp = doa_pickup_timestamp
1746
    session.commit()
1747
 
4910 phani.kuma 1748
def get_doas_not_picked_up(provider_id):
2764 chandransh 1749
    current_time = datetime.datetime.now()
1750
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1751
    orders_not_picked_up = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter_by(status=OrderStatus.DOA_PICKUP_CONFIRMED).filter(Order.doa_auth_timestamp <= to_datetime).all()
2764 chandransh 1752
    return orders_not_picked_up
1753
 
4741 phani.kuma 1754
def mark_return_orders_as_picked_up(provider_id, pickup_details):
1755
    for pickupNo, return_order_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1756
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4741 phani.kuma 1757
        if order == None or order.status != OrderStatus.RET_PICKUP_CONFIRMED:
1758
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1759
            continue
1760
        order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1761
        order.statusDescription = "Return order picked up by Courier Company"
1762
        order.doa_pickup_timestamp = return_order_pickup_timestamp
1763
    session.commit()
1764
 
4910 phani.kuma 1765
def get_return_orders_not_picked_up(provider_id):
4741 phani.kuma 1766
    current_time = datetime.datetime.now()
1767
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1768
    orders_not_picked_up = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter_by(status=OrderStatus.RET_PICKUP_CONFIRMED).filter(Order.doa_auth_timestamp <= to_datetime).all()
4741 phani.kuma 1769
    return orders_not_picked_up
1770
 
4479 rajveer 1771
def receive_return(order_id, receiveCondition):
2591 chandransh 1772
    order = get_order(order_id)
4365 mandeep.dh 1773
 
4452 rajveer 1774
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 1775
        if receiveCondition == 0:
1776
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
1777
            order.statusDescription = "DOA package received"
1778
        elif receiveCondition == 1:
1779
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
1780
            order.statusDescription = "DOA received damaged"
1781
        elif receiveCondition == 2:
1782
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
1783
            order.statusDescription = "DOA lost in transit"
2764 chandransh 1784
        order.received_return_timestamp = datetime.datetime.now()
4495 rajveer 1785
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
1786
        if receiveCondition == 0:
1787
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
1788
            order.statusDescription = "RETURN package received"
1789
        elif receiveCondition == 1:
1790
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
1791
            order.statusDescription = "RETURN received damaged"
1792
        elif receiveCondition == 2:
1793
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
1794
            order.statusDescription = "RETURN lost in transit"
1795
        order.received_return_timestamp = datetime.datetime.now()
4484 rajveer 1796
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 1797
        if receiveCondition == 0:
1798
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 1799
            order.statusDescription = "Returned to origin"
4486 rajveer 1800
        elif receiveCondition == 1:
1801
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
1802
            order.statusDescription = "RTO received damaged"
1803
        elif receiveCondition == 2:
1804
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
1805
            order.statusDescription = "RTO lost in transit"
2764 chandransh 1806
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1807
    else:
2591 chandransh 1808
        return False
5110 mandeep.dh 1809
 
1810
    # For OUR warehouses, we need to scan in items for every return
1811
    catalogClient = CatalogClient().get_client()
1812
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1813
    if warehouse.billingType == BillingType.OURS:
5361 mandeep.dh 1814
        scanMap = {
1815
            OrderStatus.RTO_RECEIVED_PRESTINE : ScanType.SALE_RET,
1816
            OrderStatus.RTO_RECEIVED_DAMAGED  : ScanType.SALE_RET_UNUSABLE,
1817
            OrderStatus.RTO_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT,
1818
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
1819
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
1820
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
1821
        }
5110 mandeep.dh 1822
 
5419 mandeep.dh 1823
        if scanMap.has_key(order.status):
1824
            scanType = scanMap[order.status]
5361 mandeep.dh 1825
            lineitem = order.lineitems[0]
1826
            item = catalogClient.getItem(lineitem.item_id)
1827
            warehouseClient = WarehouseClient().get_client()
1828
            if item.type == ItemType.SERIALIZED:
5110 mandeep.dh 1829
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 1830
            else:
1831
                warehouseClient.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
5110 mandeep.dh 1832
 
5558 mandeep.dh 1833
    session.commit()
2591 chandransh 1834
    return True
1835
 
1836
def validate_doa(order_id, is_valid):
1837
    order = get_order(order_id)
4452 rajveer 1838
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 1839
        return False
1840
    if is_valid:
2609 chandransh 1841
        order.status = OrderStatus.DOA_CERT_VALID
1842
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 1843
    else:
1844
        order.status = OrderStatus.DOA_CERT_INVALID
1845
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 1846
        update_trust_level(order)
2591 chandransh 1847
    session.commit()
1848
    return True
1849
 
4495 rajveer 1850
def validate_return_product(order_id, is_usable):
1851
    order = get_order(order_id)
1852
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
1853
        return False
5110 mandeep.dh 1854
 
1855
    scanType = ScanType.SALE_RET_UNUSABLE
4495 rajveer 1856
    if is_usable:
1857
        order.status = OrderStatus.RET_PRODUCT_USABLE
1858
        order.statusDescription = "Return product usable"
5110 mandeep.dh 1859
        scanType = ScanType.SALE_RET
4495 rajveer 1860
    else:
1861
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
1862
        order.statusDescription = "Return product unusable"
1863
        update_trust_level(order)
1864
    session.commit()
5110 mandeep.dh 1865
 
1866
    # For OUR warehouses, we need to scan in items for every return
1867
    catalogClient = CatalogClient().get_client()
1868
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1869
    if warehouse.billingType == BillingType.OURS:
1870
        lineitem = order.lineitems[0]
5361 mandeep.dh 1871
        item = catalogClient.getItem(lineitem.item_id)
5110 mandeep.dh 1872
        warehouse_client = WarehouseClient().get_client()
5361 mandeep.dh 1873
        if item.type == ItemType.SERIALIZED:
1874
            warehouse_client.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
1875
        else:
1876
            warehouse_client.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4495 rajveer 1877
    return True
1878
 
2628 chandransh 1879
def reship_order(order_id):
1880
    """
4484 rajveer 1881
    If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1882
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
4484 rajveer 1883
        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 1884
 
1885
    If the order is in DOA_CERT_VALID state, it does the following:
1886
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
1887
        2. Creates a return order for the warehouse executive to return the DOA material.
4452 rajveer 1888
        3. Marks the current order as the final DOA_VALID_RESHIPPED state.
2628 chandransh 1889
 
1890
    Returns the id of the newly created order.
1891
 
1892
    Throws an exception if the order with the given id couldn't be found.
1893
 
1894
    Parameters:
1895
     - orderId
1896
    """
1897
    order = get_order(order_id)
4484 rajveer 1898
    if order.status == OrderStatus.RTO_RECEIVED_PRESTINE:
4220 rajveer 1899
        new_order = __clone_order(order, True, order.cod)
4484 rajveer 1900
        order.status = OrderStatus.RTO_RESHIPPED
2628 chandransh 1901
        order.statusDescription = "Order Reshipped"
1902
        session.commit()
3578 mandeep.dh 1903
        update_trust_level(order)
4486 rajveer 1904
    elif order.status == OrderStatus.RTO_RECEIVED_DAMAGED:
1905
        new_order = __clone_order(order, False, order.cod)
1906
        ret_order = __create_return_order(order)
1907
        order.status = OrderStatus.RTO_DAMAGED_RESHIPPED
1908
        order.statusDescription = "Order Reshipped Received Damaged"
1909
        session.commit()
1910
    elif order.status == OrderStatus.RTO_LOST_IN_TRANSIT:
1911
        new_order = __clone_order(order, False, order.cod)
1912
        order.status = OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED
1913
        order.statusDescription = "Order Reshipped Lost In Transit"
1914
        session.commit()
4662 rajveer 1915
    elif order.status == OrderStatus.LOST_IN_TRANSIT:
1916
        new_order = __clone_order(order, False, order.cod)
1917
        order.status = OrderStatus.LOST_IN_TRANSIT_RESHIPPED
1918
        order.statusDescription = "Order Reshipped Lost In Transit"
1919
        session.commit()
2628 chandransh 1920
    elif order.status == OrderStatus.DOA_CERT_INVALID:
4220 rajveer 1921
        new_order = __clone_order(order, True, False)
2628 chandransh 1922
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
1923
        order.statusDescription = "Order Reshipped"
1924
        session.commit()
5620 mandeep.dh 1925
        warehouseClient = WarehouseClient().get_client()
1926
        inventoryItem = warehouseClient.getInventoryItemFromOrder(order_id)
1927
        warehouseClient.scanForOrder(inventoryItem, ScanType.SALE, new_order.lineitems[0].quantity, new_order.id, new_order.fulfilmentWarehouseId, new_order.warehouse_id)
2628 chandransh 1928
    elif order.status == OrderStatus.DOA_CERT_VALID:
4220 rajveer 1929
        new_order = __clone_order(order, False, False)
2628 chandransh 1930
        ret_order = __create_return_order(order)
4452 rajveer 1931
        order.status = OrderStatus.DOA_VALID_RESHIPPED
2628 chandransh 1932
        order.statusDescription = "Order Reshipped"
1933
        session.commit()
4479 rajveer 1934
    elif order.status == OrderStatus.DOA_RECEIVED_DAMAGED:
1935
        new_order = __clone_order(order, False, False)
1936
        ret_order = __create_return_order(order)
1937
        order.status = OrderStatus.DOA_RESHIPPED_RCVD_DAMAGED
1938
        order.statusDescription = "Order Reshipped Received Damaged"
1939
        session.commit()
1940
    elif order.status == OrderStatus.DOA_LOST_IN_TRANSIT:
1941
        new_order = __clone_order(order, False, False)
1942
        order.status = OrderStatus.DOA_RESHIPPED_LOST_IN_TRANSIT
1943
        order.statusDescription = "Order Reshipped Lost In Transit"
1944
        session.commit()
4614 rajveer 1945
    elif order.status == OrderStatus.RET_PRODUCT_USABLE:
5620 mandeep.dh 1946
        new_order = __clone_order(order, False, False)
4614 rajveer 1947
        order.status = OrderStatus.RET_PRODUCT_USABLE_RESHIPPED
4495 rajveer 1948
        order.statusDescription = "Order Reshipped"
1949
        session.commit()
4614 rajveer 1950
    elif order.status == OrderStatus.RET_PRODUCT_UNUSABLE:
4495 rajveer 1951
        new_order = __clone_order(order, False, False)
1952
        ret_order = __create_return_order(order)
4614 rajveer 1953
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE_RESHIPPED
4495 rajveer 1954
        order.statusDescription = "Order Reshipped"
1955
        session.commit()
1956
    elif order.status == OrderStatus.RET_RECEIVED_DAMAGED:
1957
        new_order = __clone_order(order, False, False)
1958
        ret_order = __create_return_order(order)
1959
        order.status = OrderStatus.RET_RESHIPPED_RCVD_DAMAGED
1960
        order.statusDescription = "Order Reshipped Received Damaged"
1961
        session.commit()
1962
    elif order.status == OrderStatus.RET_LOST_IN_TRANSIT:
1963
        new_order = __clone_order(order, False, False)
1964
        order.status = OrderStatus.RET_RESHIPPED_LOST_IN_TRANSIT
1965
        order.statusDescription = "Order Reshipped Lost In Transit"
1966
        session.commit()
2628 chandransh 1967
    else:
1968
        raise TransactionServiceException(112, "This order can't be reshipped")
1969
 
2764 chandransh 1970
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 1971
    order.new_order_id = new_order.id
1972
    session.commit()
1973
 
1974
    return new_order.id
1975
 
3226 chandransh 1976
def refund_order(order_id, refunded_by, reason):
2628 chandransh 1977
    """
4484 rajveer 1978
    If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1979
        1. Creates a refund request for batch processing.
1980
        2. Creates a return order for the warehouse executive to return the shipped material.
4484 rajveer 1981
        3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2628 chandransh 1982
 
1983
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
1984
        1. Creates a refund request for batch processing.
3226 chandransh 1985
        2. Cancels the reservation of the item in the warehouse.
1986
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 1987
 
3226 chandransh 1988
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
1989
        1. Cancels the reservation of the item in the warehouse.
1990
        2. Marks the current order as CANCELED.
1991
 
1992
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
1993
 
1994
    Returns True if it is successful, False otherwise.
2628 chandransh 1995
 
1996
    Throws an exception if the order with the given id couldn't be found.
1997
 
1998
    Parameters:
3226 chandransh 1999
     - order_id
2000
     - refunded_by
2001
     - reason
2628 chandransh 2002
    """
3414 chandransh 2003
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 2004
    order = get_order(order_id)
3186 chandransh 2005
 
3226 chandransh 2006
    if order.cod:
3414 chandransh 2007
        logging.info("Refunding COD order with status " + str(order.status))
4662 rajveer 2008
        status_transition = { OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2009
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2010
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2011
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2012
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2013
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2014
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2015
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2016
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2017
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2018
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2019
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2020
                     OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.COD_VERIFICATION_FAILED,
2021
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2022
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2023
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2024
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2025
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2026
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2027
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2028
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST
3366 chandransh 2029
                     }
2030
        if order.status not in status_transition.keys():
2031
            raise TransactionServiceException(114, "This order can't be refunded")
2032
 
5199 mandeep.dh 2033
        if order.status in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
3226 chandransh 2034
            __update_inventory_reservation(order)
2035
            order.statusDescription = "Order Cancelled"
3415 chandransh 2036
        elif order.status == OrderStatus.BILLED:
3413 chandransh 2037
            __create_return_order(order)
2038
            order.statusDescription = "Order Cancelled"
4486 rajveer 2039
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
5386 phani.kuma 2040
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2041
                __create_return_order(order)
4486 rajveer 2042
            order.statusDescription = "RTO Refunded"
4662 rajveer 2043
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2044
            #__create_return_order(order)
4662 rajveer 2045
            order.statusDescription = "Lost in Transit Refunded"
4479 rajveer 2046
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2047
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2048
                __create_return_order(order)
3226 chandransh 2049
            __create_refund(order)
4495 rajveer 2050
            order.statusDescription = "DOA Refunded"
2051
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2052
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2053
                __create_return_order(order)
4495 rajveer 2054
            __create_refund(order)
2055
            order.statusDescription = "Return Refunded"
4247 rajveer 2056
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5199 mandeep.dh 2057
            if order.previousStatus in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
4247 rajveer 2058
                __update_inventory_reservation(order)
2059
                order.statusDescription = "Order Cancelled on customer request"
2060
            elif order.previousStatus == OrderStatus.BILLED:
2061
                __create_return_order(order)
2062
                order.statusDescription = "Order Cancelled on customer request"
3226 chandransh 2063
    else:
4662 rajveer 2064
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2065
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2066
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2067
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2068
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2069
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2070
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2071
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2072
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2073
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2074
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2075
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2076
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2077
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2078
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2079
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2080
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2081
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2082
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2083
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
2084
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 2085
                     }
2086
        if order.status not in status_transition.keys():
2087
            raise TransactionServiceException(114, "This order can't be refunded")
2088
 
4495 rajveer 2089
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
5386 phani.kuma 2090
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2091
                __create_return_order(order)
3226 chandransh 2092
            __create_refund(order)
4495 rajveer 2093
            order.statusDescription = "RTO Refunded"
4662 rajveer 2094
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2095
            #__create_return_order(order)
4662 rajveer 2096
            __create_refund(order)
2097
            order.statusDescription = "Lost in Transit Refunded"
4495 rajveer 2098
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2099
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2100
                __create_return_order(order)
4495 rajveer 2101
            __create_refund(order)
2102
            order.statusDescription = "DOA Refunded"
2103
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2104
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2105
                __create_return_order(order)
4495 rajveer 2106
            __create_refund(order)
2107
            order.statusDescription = "Return Refunded"
5199 mandeep.dh 2108
        elif order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
3226 chandransh 2109
            __update_inventory_reservation(order)
2110
            order.statusDescription = "Order Refunded"
4247 rajveer 2111
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5272 mandeep.dh 2112
            if order.previousStatus in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.PAYMENT_FLAGGED, OrderStatus.ACCEPTED]:
4672 rajveer 2113
                if order.previousStatus == OrderStatus.ACCEPTED:
2114
                    __create_refund(order)
4247 rajveer 2115
                __update_inventory_reservation(order)
2116
                order.statusDescription = "Order Cancelled on customer request"
2117
            elif order.previousStatus == OrderStatus.BILLED:
2118
                __create_return_order(order)
2119
                __create_refund(order)
2120
                order.statusDescription = "Order Cancelled on customer request"
2121
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
2122
            __update_inventory_reservation(order)
2123
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 2124
 
4873 mandeep.dh 2125
    # For orders that are cancelled after being billed, we need to scan in the scanned out
2126
    # inventory item and change availability accordingly
5110 mandeep.dh 2127
    catalogClient = CatalogClient().get_client()
2128
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
2129
    if warehouse.billingType == BillingType.OURS:
4873 mandeep.dh 2130
        if order.status in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH] or (order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED and order.previousStatus in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH]):
2131
            lineitem = order.lineitems[0]
5177 mandeep.dh 2132
            item = catalogClient.getItem(lineitem.item_id)
5361 mandeep.dh 2133
            warehouseClient = WarehouseClient().get_client()
5177 mandeep.dh 2134
            if ItemType.SERIALIZED == item.type:
2135
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 2136
            else:
2137
                warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4873 mandeep.dh 2138
 
3195 chandransh 2139
    order.status = status_transition[order.status]
2140
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 2141
    order.refunded_by = refunded_by
2142
    order.refund_reason = reason
4873 mandeep.dh 2143
 
2628 chandransh 2144
    session.commit()
2145
    return True
2146
 
3186 chandransh 2147
def __update_inventory_reservation(order):
3191 chandransh 2148
    '''
2149
    Reduce the reservation count for all line items of the given order.
2150
    '''
3186 chandransh 2151
    try:
2152
        catalog_client = CatalogClient().get_client()
2153
        for lineitem in order.lineitems:
5530 mandeep.dh 2154
            catalog_client.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, lineitem.quantity)
3186 chandransh 2155
    except:
2156
        print "Unable to reduce reservation count"
2157
 
4220 rajveer 2158
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 2159
    current_time = datetime.datetime.now()
2160
    new_order = Order()
2161
    new_order.customer_id = order.customer_id
2162
    new_order.customer_name = order.customer_name
2163
    new_order.customer_city = order.customer_city
2164
    new_order.customer_state = order.customer_state
2165
    new_order.customer_mobilenumber = order.customer_mobilenumber
2166
    new_order.customer_pincode = order.customer_pincode
2167
    new_order.customer_address1 = order.customer_address1
2168
    new_order.customer_address2 = order.customer_address2
2169
    new_order.customer_email = order.customer_email
2170
    new_order.total_amount = order.total_amount
2171
    new_order.total_weight = order.total_weight
2172
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2173
    new_order.statusDescription = 'Submitted for Processing'
2174
    new_order.created_timestamp = current_time
5062 varun.gupt 2175
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 2176
 
2177
    new_order.transaction = order.transaction
4220 rajveer 2178
    new_order.cod = is_cod
5527 anupam.sin 2179
    new_order.orderType = order.orderType
2628 chandransh 2180
 
2181
    for line_item in order.lineitems:
2182
        litem = LineItem()
2183
        litem.item_id = line_item.item_id
2184
        litem.productGroup = line_item.productGroup
2185
        litem.brand = line_item.brand
2186
        if line_item.model_number:
2187
            litem.model_number = line_item.model_number
2188
        if line_item.model_name:    
2189
            litem.model_name = line_item.model_name
2190
        if line_item.color:
2191
            litem.color = line_item.color
2192
        if line_item.extra_info:
2193
            litem.extra_info = line_item.extra_info
2194
        litem.quantity = line_item.quantity
2195
        litem.unit_price = line_item.unit_price
2196
        litem.unit_weight = line_item.unit_weight
2197
        litem.total_price = line_item.total_price
2198
        litem.total_weight = line_item.total_weight
2199
        litem.transfer_price = line_item.transfer_price
4840 mandeep.dh 2200
        litem.dealText = line_item.dealText
2628 chandransh 2201
        litem.order = new_order
2202
 
2203
    logistics_client = LogisticsClient().get_client()
2204
    item_id = new_order.lineitems[0].item_id
5785 mandeep.dh 2205
    logistics_info = logistics_client.getLogisticsInfo(new_order.customer_pincode, item_id, is_cod, PickUpType.COURIER) #TODO: We should be able to pass another flag to suggest ignoring the inventory situation.
2628 chandransh 2206
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2207
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 2208
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 2209
    new_order.logistics_provider_id = logistics_info.providerId
2210
    new_order.airwaybill_no = logistics_info.airway_billno
2211
    new_order.tracking_id = new_order.airwaybill_no
2212
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 2213
    new_order.promised_delivery_time = new_order.expected_delivery_time
4299 rajveer 2214
 
2628 chandransh 2215
    if should_copy_billing_info:
5388 phani.kuma 2216
        new_order.vendorId = order.vendorId
2628 chandransh 2217
        new_order.invoice_number = order.invoice_number
2218
        new_order.billed_by = order.billed_by
2219
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 2220
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
5620 mandeep.dh 2221
        new_order.jacket_number = order.jacket_number
2222
        new_order.lineitems[0].serial_number = order.lineitems[0].serial_number
2223
        new_order.lineitems[0].item_number   = order.lineitems[0].item_number
2628 chandransh 2224
        new_order.accepted_timestamp = current_time
2225
        new_order.billing_timestamp = current_time    
2226
        new_order.status = OrderStatus.BILLED
2227
        new_order.statusDescription = 'Order Billed'
2228
    else:       
3133 rajveer 2229
        catalog_client = CatalogClient().get_client()
5110 mandeep.dh 2230
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, new_order.lineitems[0].quantity)
2628 chandransh 2231
 
2232
    return new_order
2233
 
2234
def __create_return_order(order):
2687 chandransh 2235
    ret_order = ReturnOrder(order)
2628 chandransh 2236
    return ret_order
2237
 
2238
def __create_refund(order):
4078 chandransh 2239
    payment_client = PaymentClient().get_client()
2240
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 2241
    return
2628 chandransh 2242
 
2536 chandransh 2243
def __get_order_address(order):
2244
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
2245
    if order.customer_address2:
2246
        address = address + order.customer_address2 + "\n"
2247
    address = address + order.customer_city + "\n"
2248
    address = address + order.customer_state + "\n"
2249
    address = address + "PIN " + order.customer_pincode + "\n"
2250
    address = address + "Phone: " + order.customer_mobilenumber
2251
    return address
2252
 
5767 rajveer 2253
def __get_store_address(store):
2254
    address = store.name + "\n" + store.line1 + "\n"
2255
    if store.line2:
2256
        address = address + store.line2 + "\n"
2257
    address = address + store.city + "\n"
2258
    address = address + store.state + "\n"
5802 rajveer 2259
    address = address + "PIN - " + store.pin + "\n"
5793 rajveer 2260
    if store.phone:
5802 rajveer 2261
        address = address + "Phone - " + store.phone + "\n"
2262
    address = address +  "Store timing - 11AM to 8PM (7 days)\n"
5767 rajveer 2263
    return address
2264
 
5793 rajveer 2265
def __get_store_address_html(store):
2266
    address = store.name + "<br>" + store.line1 + "<br>"
2267
    if store.line2:
2268
        address = address + store.line2 + "<br>"
2269
    address = address + store.city + "<br>"
2270
    address = address + store.state + "<br>"
5802 rajveer 2271
    address = address + "PIN - " + store.pin + "<br>"
5793 rajveer 2272
    if store.phone:
5802 rajveer 2273
        address = address + "Phone - " + store.phone + "<br>"
2274
    address = address +  "Store timing - 7 days: 11AM to 8PM  (7 days)<br>"
5793 rajveer 2275
    return address
2276
 
4815 phani.kuma 2277
def __generate_return_advice(order, warehouse, provider, filename):
2278
    if warehouse.id == 7:
2279
        executive = 'Amit Kumar'
2280
    else:
4966 phani.kuma 2281
        executive = 'Dinesh Kumar'
2536 chandransh 2282
    pdf = Canvas(filename)
2283
    pdf.setFont('Times-Bold',16)
2284
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
2285
    address_text.textLine("To")
4815 phani.kuma 2286
    address_text.textLine(executive)
2536 chandransh 2287
    for line in warehouse.location.split("\n"):
2288
        address_text.textLine(line)
2289
    address_text.textLine("PIN " + warehouse.pincode)
2290
    pdf.drawText(address_text)
2291
 
2292
    pdf.setFont('Times-Roman',12)
2293
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 2294
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 2295
    lineitem = order.lineitems[0] 
4234 rajveer 2296
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 2297
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
2298
    order_text.textLine("Order ID : " + str(order.id))
2299
    pdf.drawText(order_text)
2300
    pdf.showPage()
2301
    pdf.save()
2302
    return filename
2303
 
5806 rajveer 2304
def __push_collection_to_hotspot(order, type):
2305
    try:
2306
        logistics_client = LogisticsClient().get_client()
2307
        store = logistics_client.getPickupStore(order.pickupStoreId)
2308
        store_string = "<store>" + store.hotspotId + "</store>"
2309
        order_string = "<orderno>" + str(order.id) + "</orderno>"
2310
        collection_type = "<Type>" + type + "</Type>"
2311
        payment_mode = __get_order_attribute_value(order.id, "PAYMENT_MODE")
2312
        if type == "SALE":
2313
            amount = int(order.total_amount)
2314
            ts = order.delivery_timestamp
2315
        if type == "SALE RETURN":
2316
            amount = -int(order.total_amount)
2317
            ts = order.refund_timestamp
2318
        if payment_mode == "Cash":
2319
            cash_string = "<cash>" + str(amount) + "</cash>"
2320
            card_string = "<hdfc>0</hdfc>"
2321
        if payment_mode == "Card":
2322
            cash_string = "<cash>0</cash>"
2323
            card_string = "<hdfc>" + str(amount) + "</hdfc>"
2324
        date_string = "<date>" + ts.strftime("%Y%m%d") + "</date>"
2325
        time_string = "<time>" + ts.strftime("%H%M%S") + "</time>"
2326
 
2327
        conn = httplib.HTTPConnection("182.71.104.182")
2328
        XML="""
2329
        <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
2330
          <soap:Body>
2331
            <SaholicDataTransfer xmlns="http://tempuri.org/">
2332
        """
2333
 
2334
        XML = XML + store_string + order_string + collection_type + cash_string + card_string + date_string + time_string 
2335
 
2336
        footer = """
2337
            </SaholicDataTransfer>
2338
          </soap:Body>
2339
        </soap:Envelope>
2340
        """
2341
        XML = XML + footer
2342
 
2343
        params = urllib.urlencode({'op': 'SaholicDataTransfer'})
2344
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
2345
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
2346
        conn.send(XML)
2347
        response = conn.getresponse()
2348
        print response.status, response.reason
2349
        resp = response.read()
2350
        conn.close()
2351
        print resp
2352
        if "Saved Successfully" in resp:
2353
            return True
2354
        elif "Error in Saving Data" in resp:
2355
            return False
2356
        else: 
2357
            return False
2358
    except Exception as e:
2359
        print e
2360
        return False
2361
 
2697 chandransh 2362
def get_return_orders(warehouse_id, from_date, to_date):
2363
    query = ReturnOrder.query.filter_by(processedStatus = False)
2364
    if warehouse_id != -1:
2365
        query = query.filter_by(warehouseId = warehouse_id)
2366
    if from_date:
4118 chandransh 2367
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 2368
    if to_date:
4118 chandransh 2369
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 2370
    return [return_order.to_thrift_object() for return_order in query.all()]
2371
 
5481 phani.kuma 2372
def get_all_return_orders(onlyNotProcessed, from_date, to_date):
2373
    query = ReturnOrder.query
2374
    if onlyNotProcessed:
2375
        query = query.filter_by(processedStatus = False)
2376
    if from_date:
2377
        query = query.filter(ReturnOrder.createdAt >= from_date)
2378
    if to_date:
2379
        query = query.filter(ReturnOrder.createdAt <= to_date)
2380
    return [return_order.to_thrift_object() for return_order in query.all()]
2381
 
2700 chandransh 2382
def get_return_order(id):
2383
    ret_order = ReturnOrder.get_by(orderId = id)
2384
    if ret_order is None:
2385
        raise TransactionServiceException(116, "No return order found for the given order id")
2386
    return ret_order.to_thrift_object()
2387
 
2697 chandransh 2388
def process_return(ret_order_id):
2389
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
2390
    if ret_order is None:
2391
        raise TransactionServiceException(116, "No return order found for the given order id")
2392
    ret_order.processedStatus = True
2701 chandransh 2393
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 2394
    session.commit()
2395
 
4757 mandeep.dh 2396
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
2397
    """
2398
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
2399
    the quantities for which the PO is raised.
2400
 
2401
    Parameters:
2402
     - itemIdQuantityMap
2403
     - purchaseOrderId
2404
     - warehouseId
2405
    """
3451 chandransh 2406
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 2407
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 2408
    query = query.filter_by(purchase_order_id=None)
2409
    query = query.order_by(Order.created_timestamp)
2410
    pending_orders = query.all()
4586 mandeep.dh 2411
 
2412
    for order in pending_orders:
4757 mandeep.dh 2413
        lineitem = order.lineitems[0]
2414
        if itemIdQuantityMap.has_key(lineitem.item_id):
2415
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
2416
                order.status = OrderStatus.LOW_INV_PO_RAISED
2417
                order.statusDescription = 'In Process'
2418
                order.purchase_order_id = purchaseOrderId
2419
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 2420
 
2819 chandransh 2421
    session.commit()
2422
 
3451 chandransh 2423
def update_weight(order_id, weight):
3469 chandransh 2424
    '''
2425
    Update the weight of order
2426
    '''
3451 chandransh 2427
    order = get_order(order_id)
2428
    order.total_weight = weight
3469 chandransh 2429
    lineitem = order.lineitems[0]
2430
    lineitem.total_weight = weight
2431
    lineitem.unit_weight = weight
3451 chandransh 2432
 
3469 chandransh 2433
    session.commit()
2434
    return order
2435
 
2436
def change_product(order_id, item_id):
2437
    '''
2438
    Ship a product of a different color to the customer.
2439
    '''
2440
    order = get_order(order_id)
4662 rajveer 2441
    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 2442
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
2443
 
2444
    lineitem = order.lineitems[0]
3451 chandransh 2445
 
3469 chandransh 2446
    catalog_client = CatalogClient().get_client()
2447
 
2448
    old_item = catalog_client.getItem(lineitem.item_id)
2449
    item = catalog_client.getItem(item_id)
2450
    if old_item.catalogItemId != item.catalogItemId:
2451
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
2452
 
5110 mandeep.dh 2453
    catalog_client.reserveItemInWarehouse(item_id, order.fulfilmentWarehouseId, lineitem.quantity)
2454
    __update_inventory_reservation(order)
3469 chandransh 2455
    #TODO: Check that this new item has the same price
2456
 
2457
    lineitem.item_id = item_id
2458
    lineitem.color = item.color
2459
 
3451 chandransh 2460
    session.commit()
3469 chandransh 2461
 
2462
    order = get_order(order_id)
3451 chandransh 2463
    return order
3469 chandransh 2464
 
2465
def change_warehouse(order_id, warehouse_id):
2466
    '''
2467
    Update the warehouse which will be used to fulfil this order.
2468
    '''
2469
    order = get_order(order_id)
4662 rajveer 2470
    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 2471
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
2472
 
2473
    if warehouse_id == order.warehouse_id:
2474
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
2475
 
2476
    lineitem = order.lineitems[0]
2477
    catalog_client = CatalogClient().get_client()
2478
    try:
2479
        warehouse = catalog_client.getWarehouse(warehouse_id)
2480
    except:
2481
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 2482
 
5147 mandeep.dh 2483
    if warehouse.billingWarehouseId is None:
2484
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 2485
 
5620 mandeep.dh 2486
    # If One gives a billing warehouse for warehouse shift, we should assign order to the GOOD warehouse
2487
    # present within it with maximum availability
2488
    if warehouse.id == warehouse.billingWarehouseId:
5147 mandeep.dh 2489
        warehouses = catalog_client.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
2490
        if warehouses:
2491
            itemInventory = catalog_client.getItemInventoryByItemId(lineitem.item_id)
2492
            warehouse = warehouses[0]
2493
            maxAvailability = 0
2494
            for goodWarehouse in warehouses:
2495
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
2496
                    warehouse = goodWarehouse
2497
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
2498
 
2499
            # Use preferred vendor's warehouse if not available anywhere
2500
            if not maxAvailability:
2501
                item = catalog_client.getItem(lineitem.item_id)
2502
                if item.preferredVendor:
2503
                    for goodWarehouse in warehouses:
2504
                        if goodWarehouse.vendor.id == item.preferredVendor:
2505
                            warehouse = goodWarehouse
2506
        else:
2507
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
2508
 
5199 mandeep.dh 2509
    catalog_client.reserveItemInWarehouse(lineitem.item_id, warehouse.id, lineitem.quantity)
5110 mandeep.dh 2510
    __update_inventory_reservation(order)
2511
 
2512
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 2513
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 2514
    session.commit()
2515
    return order
3553 chandransh 2516
 
4647 rajveer 2517
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 2518
    '''
3994 chandransh 2519
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 2520
    '''
2521
    order = get_order(order_id)
2522
    try:
3581 chandransh 2523
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 2524
        order.delayReasonText = delayReasonText
4009 chandransh 2525
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
2526
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 2527
 
4842 rajveer 2528
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
2529
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 2530
 
3553 chandransh 2531
        session.commit()
4008 mandeep.dh 2532
 
2533
        try:
2534
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
2535
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
2536
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
2537
            session.commit()
2538
        except Exception as e:
4065 mandeep.dh 2539
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 2540
 
3553 chandransh 2541
        return True
2542
    except:
3994 chandransh 2543
        print sys.exc_info()[0]
3553 chandransh 2544
        return False
3956 chandransh 2545
 
2546
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
2547
    unprocessed_awbs = {}
2548
    for awb, amount in collected_amount_map.iteritems():
2549
        try:
2550
            order = Order.query.filter_by(airwaybill_no=awb).one()
2551
        except NoResultFound:
2552
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
2553
            continue
2554
        except MultipleResultsFound:
2555
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
2556
            continue
2557
 
2558
        if order.cod_reconciliation_timestamp:
2559
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
2560
            continue
2561
 
2562
        if order.status < OrderStatus.DELIVERY_SUCCESS:
2563
            #Order has not been delivered yet. No way we can receive the payment.
2564
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
2565
            continue
2566
 
4252 rajveer 2567
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
2568
        if abs(amount - order.total_amount) > 0.5:
3956 chandransh 2569
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
2570
            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)
2571
            continue
2572
 
2573
        try:
2574
            payment_client = PaymentClient().get_client()
2575
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
2576
        except Exception:
2577
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
2578
            continue
2579
 
2580
        #Payment has been recorded now. We can update the order peacefully.
2581
        order.cod_reconciliation_timestamp = datetime.datetime.now()
2582
        session.commit()
3469 chandransh 2583
 
3956 chandransh 2584
    return unprocessed_awbs
4008 mandeep.dh 2585
 
2586
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 2587
    """
2588
    Returns the list of transaction ids that require some extra processing and
2589
    which belong to a particular category. This is currently used by CRM
2590
    application. If no such transaction ids are present, it returns an empty list.
2591
    """
2592
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 2593
 
4065 mandeep.dh 2594
    if category is not None:
2595
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 2596
 
4065 mandeep.dh 2597
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 2598
 
2599
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 2600
    """
2601
    Marks a particular transaction as processed for a particular cateogory.
2602
    It essentially deletes the transaction id record for a particular
2603
    processing type category (if present) from DB.
2604
    This is currently used by CRM application.
2605
    """
4008 mandeep.dh 2606
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
2607
    session.commit()
2608
 
4018 chandransh 2609
def get_item_wise_risky_orders_count():
2610
    """
2611
    Returns a map containing the number of risky orders keyed by item id. A risky order
2612
    is defined as one whose shipping date is about to expire.
2613
    """
2614
    item_wise_risky_orders_count = {}
4019 chandransh 2615
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 2616
    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()
2617
    for order in orders:
2618
        for lineitem in order.lineitems:
2619
            quantity = lineitem.quantity
2620
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
2621
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
2622
 
2623
            item_wise_risky_orders_count[lineitem.item_id] = quantity
2624
    return item_wise_risky_orders_count
2625
 
4324 mandeep.dh 2626
def update_shipment_address(order_id, address_id):
2627
    """
2628
    Updates shipment address of an order. Delivery and shipping date estimates
2629
    etc. are also updated here.
2630
 
2631
    Throws TransactionServiceException in case address change is not
2632
    possible due to certain reasons such as new pincode in address is
2633
    not serviceable etc.
2634
 
2635
    Parameters:
2636
     - orderId
2637
     - addressId
2638
    """
2639
    user_client = UserClient().get_client()
2640
    address     = user_client.getAddressById(address_id)
2641
    order       = get_order(order_id)
2642
 
4630 mandeep.dh 2643
    type = DeliveryType.PREPAID
2644
    if order.cod:
2645
        type = DeliveryType.COD
2646
 
4324 mandeep.dh 2647
    logistics_client = LogisticsClient().get_client()
5793 rajveer 2648
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type, PickUpType.COURIER)
4324 mandeep.dh 2649
 
2650
    # Check for new estimate. Raise exception if new address is not serviceable
2651
    if logistics_info.deliveryTime == -1:
2652
        raise TransactionServiceException(1, 'Location not serviceable')
2653
 
2654
    # COD services are not available everywhere
2655
    if order.cod:
4868 rajveer 2656
        if not logistics_info.codAllowed:
4324 mandeep.dh 2657
            raise TransactionServiceException(2, 'COD service not available')
2658
 
5593 mandeep.dh 2659
    if logistics_info.providerId != order.logistics_provider_id:
5793 rajveer 2660
        logistics_info = logistics_client.getLogisticsInfo(address.pin, order.lineitems[0].item_id, type)
5593 mandeep.dh 2661
        order.tracking_id = logistics_info.airway_billno
2662
        order.airwaybill_no = logistics_info.airway_billno
2663
        order.logistics_provider_id = logistics_info.providerId
2664
 
4324 mandeep.dh 2665
    current_time = datetime.datetime.now()
2666
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2667
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2668
 
2669
    order.customer_name         = address.name
2670
    order.customer_pincode      = address.pin
2671
    order.customer_address1     = address.line1
2672
    order.customer_address2     = address.line2
2673
    order.customer_city         = address.city
2674
    order.customer_state        = address.state
2675
    order.customer_mobilenumber = address.phone
2676
 
2677
    if order.cod:
2678
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2679
    else:
2680
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2681
 
2682
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
2683
    order.promised_shipping_time = order.expected_shipping_time
2684
    order.promised_delivery_time = order.expected_delivery_time 
2685
 
2686
    session.commit()
2687
 
4247 rajveer 2688
def mark_order_cancellation_request_received(orderId):
2689
    """
2690
    Mark order as cancellation request received. If customer sends request of cancellation of
2691
    a particular order, this method will be called. It will just change status of the order
2692
    depending on its current status. It also records the previous status, so that we can move
2693
    back to that status if cancellation request is denied.
2694
 
2695
    Parameters:
2696
     - orderId
2697
    """
4662 rajveer 2698
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2699
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
2700
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 2701
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2702
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
2703
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2704
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2705
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2706
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
2707
             }
4662 rajveer 2708
 
2709
    order = get_order(orderId)
4247 rajveer 2710
    if order.status not in status_transition.keys():
2711
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
2712
 
4662 rajveer 2713
 
4247 rajveer 2714
    order.previousStatus = order.status
2715
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
2716
    order.statusDescription = "Cancellation request received from user"
2717
    session.commit()
2718
 
4662 rajveer 2719
def mark_order_as_lost_in_transit(orderId):
2720
    """
2721
    Parameters:
2722
     - orderId
2723
    """
2724
    order = get_order(orderId)
4910 phani.kuma 2725
    if order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE]:
4662 rajveer 2726
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
2727
    order.status = OrderStatus.LOST_IN_TRANSIT
2728
    order.statusDescription = "Lost in Transit"
2729
    session.commit()
2730
 
4258 rajveer 2731
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 2732
    """
4258 rajveer 2733
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
2734
    Changed transaction and all orders status to payment accepted.
4247 rajveer 2735
 
2736
    Parameters:
4258 rajveer 2737
     - transactionId
4247 rajveer 2738
    """
4258 rajveer 2739
    transaction = get_transaction(transactionId)
2740
    transaction.status = TransactionStatus.AUTHORIZED
2741
    for order in transaction.orders:
2742
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2743
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 2744
    session.commit()
2745
 
4259 anupam.sin 2746
def refund_transaction(transactionId, refundedBy, reason):
2747
    """
2748
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
2749
    need to be cancelled
2750
 
2751
    Parameters:
2752
     - transactionId
2753
    """
2754
    transaction = get_transaction(transactionId)
2755
    transaction.status = TransactionStatus.FAILED
2756
    for order in transaction.orders:
2757
        refund_order(order.id, refundedBy, reason)
2758
    session.commit()
2759
 
4247 rajveer 2760
def mark_order_cancellation_request_denied(orderId):
2761
    """
4283 anupam.sin 2762
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 2763
 
2764
    Parameters:
2765
     - orderId
2766
    """
2767
    order = get_order(orderId)
2768
    order.status = order.previousStatus
2769
    order.previousStatus = None
2770
    order.statusDescription = "Cancellation request denied"
2771
    session.commit()
2772
 
2773
def mark_order_cancellation_request_confirmed(orderId):
2774
    """
2775
    If we decide to to cancel order, CRM will call this method to move the status of order to
2776
    cancellation request confirmed. After this OM will be able to cancel the order.
2777
 
2778
    Parameters:
2779
     - orderId
2780
    """
2781
    order = get_order(orderId)
2782
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
2783
    order.statusDescription = "Cancellation request confirmed"
2784
    session.commit()
2785
 
4285 rajveer 2786
def accept_orders_for_item_id(itemId, inventory):
2787
    """
2788
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
2789
    given order is not a COD order, it also captures the payment if the same has not been captured.
2790
 
2791
    Parameters:
2792
     - itemId
2793
     - inventory
2794
    """
4938 rajveer 2795
    orders = Order.query.filter(Order.warehouse_id == 5).filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS]))).order_by(Order.expected_shipping_time).all()
4285 rajveer 2796
    for order in orders:
4301 rajveer 2797
        if inventory > 0:
2798
            lineitem = order.lineitems[0]
2799
            if itemId == lineitem.item_id:
2800
                try:
2801
                    accept_order(order.id)
2802
                    inventory = inventory - lineitem.quantity
2803
                except:
2804
                    logging.info("Unable to accept the order")
2805
        else:
2806
            order_outofstock(order.id)
4285 rajveer 2807
    return
2808
 
4607 rajveer 2809
def get_slipped_sipping_date_orders():
4662 rajveer 2810
    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 2811
 
2812
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
2813
    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 2814
 
4369 rajveer 2815
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
2816
    if isReminder:
2817
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2818
    else:
2819
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2820
 
2821
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2822
    for order in orders:
2823
        lineitem = order.lineitems[0]
2824
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2825
            if estimate > 0:
2826
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2827
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 2828
            order.statusDescription = "PO Raised"
4303 rajveer 2829
            quantity = quantity - lineitem.quantity
2830
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
2831
            session.commit()
2832
 
4369 rajveer 2833
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
2834
    if isReminder:
2835
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2836
    else:
2837
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2838
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2839
    for order in orders:
2840
        lineitem = order.lineitems[0]
2841
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2842
            if estimate > 0:
2843
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2844
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 2845
            order.statusDescription = "Reversal Initiated"
4303 rajveer 2846
            quantity = quantity - lineitem.quantity
2847
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
2848
            session.commit()
2849
 
4369 rajveer 2850
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
2851
    if isReminder:
2852
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2853
    else:
2854
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2855
 
2856
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2857
    for order in orders:
2858
        lineitem = order.lineitems[0]
2859
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2860
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 2861
            order.statusDescription = "Not Available"
4303 rajveer 2862
            quantity = quantity - lineitem.quantity
2863
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
2864
            session.commit()
2865
 
2866
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 2867
    orderInv = OrderInventory.get_by(order_id=order.id)
2868
    if not orderInv:
2869
        orderInv = OrderInventory()
2870
        orderInv.order = order
4303 rajveer 2871
    orderInv.hotspotAction = hotspotAction  
2872
    orderInv.estimate = estimate
2873
    orderInv.itemId = itemId
2874
    orderInv.timestamp = datetime.datetime.now()
2875
    orderInv.quantity = quantity
2876
 
4556 mandeep.dh 2877
'''    
4369 rajveer 2878
def mark_orders_as_timeout(vendorId):
2879
    ret_timeouts = {}
2880
    orderInvs = OrderInventory.query.all()
2881
    for orderInv in orderInvs:
2882
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
2883
            if not ret_timeouts.has_key(orderInv.itemId):
2884
                timeout = TimeoutSummary()
2885
                ret_timeouts[orderInv.itemId] = timeout
2886
            else:
2887
                timeout = ret_timeouts.get(orderInv.itemId)
2888
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2889
                if timeout.poRaised:
2890
                    timeout.poRaised += 1
2891
                else:
2892
                    timeout.poRaised = 1
2893
 
2894
                if timeout.poEstimate:
2895
                    timeout.poEstimate += orderInv.estimate
2896
                else:
2897
                    timeout.poEstimate = orderInv.estimate
2898
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
2899
                orderInv.order.statusDescription = "PO Raised Timeout"
2900
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2901
                if timeout.reversalInitiated:
2902
                    timeout.reversalInitiated += 1
2903
                else:
2904
                    timeout.reversalInitiated = 1
2905
 
2906
                if timeout.reversalEstimate:
2907
                    timeout.reversalEstimate += orderInv.estimate
2908
                else:
2909
                    timeout.reversalEstimate = orderInv.estimate
2910
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
2911
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
2912
            else:
2913
                orderInv.delete()
2914
    session.commit()
2915
    return ret_timeouts
4556 mandeep.dh 2916
'''
2917
 
2918
 
2919
def mark_orders_as_timeout(vendorId):
2920
    ret_timeouts = {}
2921
    orderInvs = OrderInventory.query.all()
2922
    for orderInv in orderInvs:
2923
        if not ret_timeouts.has_key(orderInv.itemId):
2924
            timeout = TimeoutSummary()
2925
            ret_timeouts[orderInv.itemId] = timeout
2926
        else:
2927
            timeout = ret_timeouts.get(orderInv.itemId)
2928
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2929
            if timeout.poRaised:
2930
                timeout.poRaised += 1
2931
            else:
2932
                timeout.poRaised = 1
2933
 
2934
            if timeout.poEstimate:
2935
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
2936
            else:
2937
                timeout.poEstimate = orderInv.estimate
2938
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2939
            if timeout.reversalInitiated:
2940
                timeout.reversalInitiated += 1
2941
            else:
2942
                timeout.reversalInitiated = 1
2943
 
2944
            if timeout.reversalEstimate:
2945
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
2946
            else:
2947
                timeout.reversalEstimate = orderInv.estimate
2948
        orderInv.order.status = OrderStatus.INVENTORY_LOW
2949
        orderInv.order.statusDescription = "Low Inventory"
2950
        orderInv.delete()
2951
    session.commit()
2952
    return ret_timeouts
2953
 
4386 anupam.sin 2954
def get_order_for_awb(awb):
2955
    order = Order.get_by(airwaybill_no=awb)
2956
    if not order:
2957
        raise TransactionServiceException(108, "no such order")
2958
 
2959
    return order
4369 rajveer 2960
 
4910 phani.kuma 2961
def get_orders_for_provider_for_status(provider_id, order_status_list):
2962
    if not provider_id or not order_status_list:
4506 phani.kuma 2963
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 2964
    doa_provider = False
2965
    for order_status in order_status_list:
2966
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
2967
            doa_provider = True
2968
    if doa_provider:
2969
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 2970
    else:
4910 phani.kuma 2971
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 2972
    return query.all()
4386 anupam.sin 2973
 
4600 varun.gupt 2974
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 2975
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
2976
 
2977
    if vendor_id:
2978
        query = query.filter_by(vendorId = vendor_id)
2979
 
4600 varun.gupt 2980
    if billing_date_from:
2981
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 2982
 
4600 varun.gupt 2983
    if billing_date_to:
2984
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 2985
 
4600 varun.gupt 2986
    return query.all()
2987
 
5481 phani.kuma 2988
def get_billed_orders(vendor_id, onlyVendorNotPaid, billing_date_from, billing_date_to):
5386 phani.kuma 2989
    query = Order.query.filter(Order.billing_timestamp != None)
5481 phani.kuma 2990
 
2991
    if onlyVendorNotPaid:
5488 phani.kuma 2992
        query = query.filter_by(vendor_paid = False)
5481 phani.kuma 2993
 
5386 phani.kuma 2994
    if vendor_id != -1:
2995
        query = query.filter_by(vendorId = vendor_id)
2996
 
5481 phani.kuma 2997
    if billing_date_from:
2998
        query = query.filter(Order.billing_timestamp >= billing_date_from)
2999
 
3000
    if billing_date_to:
3001
        query = query.filter(Order.billing_timestamp <= billing_date_to)
3002
 
4885 varun.gupt 3003
    return query.all()
4875 varun.gupt 3004
 
4600 varun.gupt 3005
def save_bluedart_settlements(map_awb_and_amount):
3006
    payment_client = PaymentClient().get_client()
3007
 
3008
    for awb, amount in map_awb_and_amount.iteritems():
3009
        order = Order.get_by(airwaybill_no = awb)
3010
 
3011
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
3012
        settlement = PaymentSettlement()
3013
        settlement.paymentId = payment.paymentId
3014
        settlement.paymentGatewayId = payment.gatewayId
3015
        settlement.netCollection = amount
3016
        session.commit()
3017
 
4905 varun.gupt 3018
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 3019
    originalOrderId = None
3020
    if paymentGatewayId == 4:
3021
        cod_order = Order.get_by(id = referenceId)
3022
        if cod_order.originalOrderId:
3023
            originalOrderId = cod_order.originalOrderId
3024
        else:
3025
            originalOrderId = referenceId
4600 varun.gupt 3026
    settlement = PaymentSettlement()
3027
    settlement.settlementDate = settlementDate
3028
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 3029
    if originalOrderId is not None:
3030
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 3031
    settlement.referenceId = referenceId
4600 varun.gupt 3032
    settlement.serviceTax = serviceTax
3033
    settlement.otherCharges = otherCharges
3034
    settlement.netCollection = netCollection
3035
    session.commit()
3036
 
5386 phani.kuma 3037
def get_settlement_for_Prepaid(reference_id, is_refund = False):
3038
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 3039
 
5189 varun.gupt 3040
    if is_refund:
3041
        query = query.filter(PaymentSettlement.netCollection < 0)
3042
    else:
3043
        query = query.filter(PaymentSettlement.netCollection > 0)
3044
 
5386 phani.kuma 3045
    return query.first()
3046
 
3047
def get_settlement_for_Cod(orderId, is_refund = False):
3048
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 3049
 
5386 phani.kuma 3050
    if is_refund:
3051
        query = query.filter(PaymentSettlement.netCollection < 0)
3052
    else:
3053
        query = query.filter(PaymentSettlement.netCollection > 0)
3054
 
5189 varun.gupt 3055
    return query.first()
4600 varun.gupt 3056
 
3057
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
5551 phani.kuma 3058
    summary = EBSSettlementSummary.query.filter_by(settlementId = settlement_id).first()
5481 phani.kuma 3059
    if summary is None:
3060
        summary = EBSSettlementSummary()
3061
        summary.settlementId = settlement_id
3062
        summary.settlementDate = settlement_date
3063
        summary.transactionDateFrom = transaction_date_from
3064
        summary.transactionDateTo = transaction_date_to
3065
        summary.amount = amount
3066
        summary.detailsUploaded = False
3067
        session.commit()
4600 varun.gupt 3068
 
3069
def get_ebs_settlement_summaries():
3070
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
3071
    summary_map = {}
3072
 
3073
    for summary in summaries:
3074
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
3075
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
3076
 
3077
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
3078
 
3079
    return summary_map
3080
 
3081
def get_ebs_settlement_date(settlement_id):
3082
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3083
 
3084
    if summary:
3085
        return summary.settlementDate
3086
 
3087
def mark_ebs_settlement_uploaded(settlement_id):
3088
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3089
 
3090
    if summary:
3091
        summary.detailsUploaded = True
3092
        session.commit()
4715 varun.gupt 3093
 
3094
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
3095
    query = PaymentSettlement.query
4600 varun.gupt 3096
 
4715 varun.gupt 3097
    if settlement_date_from:
3098
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
3099
 
3100
    if settlement_date_to:
3101
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
3102
 
4749 varun.gupt 3103
    if is_refund is True:
3104
        query = query.filter(PaymentSettlement.netCollection < 0.0)
3105
    else:
3106
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 3107
 
4749 varun.gupt 3108
    return query.all()
4715 varun.gupt 3109
 
3110
def get_reshipped_order_ids(order_ids):
3111
    reshipped_order_ids = []
3112
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
3113
 
4749 varun.gupt 3114
def get_shipping_confirmation_email_body(order):
3115
 
3116
    html = """
3117
<html>
3118
<body>
3119
<div>
3120
    <p>Dear Customer,</p>
3121
    <p>
4885 varun.gupt 3122
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 3123
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
4749 varun.gupt 3124
    </p>
3125
    <p>
3126
        Expected delivery date for your order is $expected_delivery_date. 
3127
        The product can be delivered to you between business hours of 10am to 6pm. 
3128
        You can login to your account on our site and under "Open Orders", please click the AWB and check the current shipment updates for your product.
3129
    </p>
3130
    <p>
5573 amit.gupta 3131
        For scheduling the delivery of your product at some specific timings, we recommend you to contact the helpline for $courier_name with your complete AWB#.
4749 varun.gupt 3132
    </p>
5139 varun.gupt 3133
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 3134
    <p>
3135
        Warm Regards,<br />
3136
        Saholic Team
3137
    </p>
4750 varun.gupt 3138
</div>
4749 varun.gupt 3139
</body>
3140
</html>
3141
    """
5573 amit.gupta 3142
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}}
5139 varun.gupt 3143
    provider_name = logistics_providers[order.logistics_provider_id]['name']
3144
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
3145
 
4749 varun.gupt 3146
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 3147
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
4749 varun.gupt 3148
    product = "%s %s %s" % (order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number)
4885 varun.gupt 3149
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (order.promised_delivery_time - order.promised_shipping_time).days))
3150
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
5139 varun.gupt 3151
    info = dict(order_id = order.id, product_name = product, shipping_datetime = shipping_date, awb = order.airwaybill_no, expected_delivery_date = new_expected_delivery_date, courier_name = provider_name, courier_phone = provider_phone)
4885 varun.gupt 3152
    return Template(html).substitute(info)
4749 varun.gupt 3153
 
3154
def enqueue_shipping_confirmation_email(orders):
4915 varun.gupt 3155
    # Calling helper service on production
3156
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5139 varun.gupt 3157
 
4749 varun.gupt 3158
    for order in orders:
3159
        try:
3160
            emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
3161
            emailBody = get_shipping_confirmation_email_body(order)
4885 varun.gupt 3162
            helperClient.saveUserEmailForSending(order.customer_email, None, emailSubject, emailBody, '', 'ShippingConfirmation')
4749 varun.gupt 3163
        except Exception as e:
3164
            print e
3165
 
4915 varun.gupt 3166
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 3167
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
3168
    query = query.filter(Order.created_timestamp >= start_date)
3169
    query = query.filter(Order.created_timestamp <= end_date)
3170
    return query.all()
4915 varun.gupt 3171
 
5067 varun.gupt 3172
def get_order_ids_for_status(status, start_datetime, end_datetime):
3173
    query = Order.query.filter(Order.status == status)
3174
    query = query.filter(Order.created_timestamp >= start_datetime)
3175
    query = query.filter(Order.created_timestamp <= end_datetime)
3176
    return query.all()
3177
 
5099 varun.gupt 3178
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 3179
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 3180
 
5139 varun.gupt 3181
    if paid_order.originalOrderId is None:
3182
        paid_order.vendor_paid = True
5099 varun.gupt 3183
        session.commit()
5139 varun.gupt 3184
 
3185
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
3186
            order.vendor_paid = True
3187
            session.commit()
3188
    else:
5208 varun.gupt 3189
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 3190
 
5208 varun.gupt 3191
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 3192
            order.vendor_paid = True
3193
            session.commit()
3194
 
3195
        original_order = Order.get_by(id = original_order_id)
3196
        if original_order:  original_order.vendor_paid = True
3197
        session.commit()
5348 anupam.sin 3198
 
3199
def update_COD_agent(agentEmailId, orderId):
3200
    order = Order.get_by(id=orderId)
3201
    if not order:
3202
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
3203
    agent = CodVerificationAgent()
3204
    agent.orderId = orderId
3205
    agent.verificationAgent = agentEmailId
3206
    session.commit()
3207
 
5099 varun.gupt 3208
 
5386 phani.kuma 3209
def update_order_only_as_paid_to_vendor(order_id):
3210
    paid_order = Order.get_by(id = order_id)
3211
    if paid_order is None:
3212
        raise TransactionServiceException(116, "No order found for the given order id")
3213
    paid_order.vendor_paid = True
3214
    session.commit()
3215
 
5208 varun.gupt 3216
def get_refunded_orders_marked_paid():
3217
    orderStatusGroup = OrderStatusGroups()
3218
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
3219
 
5447 anupam.sin 3220
def get_all_verification_agents(minOrderId, maxOrderId):
3221
    return CodVerificationAgent.query.filter(CodVerificationAgent.orderId >= minOrderId).filter(CodVerificationAgent.orderId <= maxOrderId).all()
3222
 
5527 anupam.sin 3223
def get_all_attributes_for_order_id(orderId):
3224
    return Attribute.query.filter(Attribute.orderId == orderId).all()
3225
 
3226
def set_order_attribute_for_transaction(transactionId, t_attribute):
3227
    for order in Order.query.filter_by(transaction_id = transactionId).all():
3228
        attribute = Attribute()
3229
        attribute.orderId = order.id
3230
        attribute.name = t_attribute.name
3231
        attribute.value = t_attribute.value
3232
        session.commit()
5593 mandeep.dh 3233
 
5558 mandeep.dh 3234
def accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
3235
    catalogClient = CatalogClient().get_client()
3236
    inventory = catalogClient.getItemInventoryByItemId(itemId)
5684 mandeep.dh 3237
    orders = Order.query.filter(Order.fulfilmentWarehouseId != fulfilmentWarehouseId).filter(Order.warehouse_id == billingWarehouseId).filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.ACCEPTED, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS]))).order_by(Order.expected_shipping_time).all()
5558 mandeep.dh 3238
    for order in orders:
5593 mandeep.dh 3239
        lineitem = order.lineitems[0]
5558 mandeep.dh 3240
        if lineitem.item_id == itemId and lineitem.quantity <= quantity:
3241
            warehouse = catalogClient.getWarehouse(order.fulfilmentWarehouseId)
5684 mandeep.dh 3242
            if not warehouse.billingWarehouseId and warehouse.warehouseType == WarehouseType.THIRD_PARTY:
3243
                if (inventory.availability[fulfilmentWarehouseId] >= inventory.reserved[fulfilmentWarehouseId] + lineitem.quantity) and inventory.availability[order.fulfilmentWarehouseId] < inventory.reserved[order.fulfilmentWarehouseId]:
3244
                    catalogClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, quantity)
3245
                    catalogClient.reserveItemInWarehouse(itemId, fulfilmentWarehouseId, quantity)
3246
                    order.fulfilmentWarehouseId = fulfilmentWarehouseId
5558 mandeep.dh 3247
                    quantity -= lineitem.quantity
5684 mandeep.dh 3248
                    session.commit()
5593 mandeep.dh 3249
                    if not quantity:
3250
                        break
5558 mandeep.dh 3251
 
766 rajveer 3252
def close_session():
3253
    if session.is_active:
3254
        print "session is active. closing it."
2783 chandransh 3255
        session.close()
3376 rajveer 3256
 
3257
def is_alive():
3258
    try:
3259
        session.query(Transaction.id).limit(1).one()
3260
        return True
3261
    except:
4343 varun.gupt 3262
        return False