Subversion Repositories SmartDukaan

Rev

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