Subversion Repositories SmartDukaan

Rev

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