Subversion Repositories SmartDukaan

Rev

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