Subversion Repositories SmartDukaan

Rev

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

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