Subversion Repositories SmartDukaan

Rev

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