Subversion Repositories SmartDukaan

Rev

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