Subversion Repositories SmartDukaan

Rev

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

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