Subversion Repositories SmartDukaan

Rev

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