Subversion Repositories SmartDukaan

Rev

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