Subversion Repositories SmartDukaan

Rev

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