Subversion Repositories SmartDukaan

Rev

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