Subversion Repositories SmartDukaan

Rev

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