Subversion Repositories SmartDukaan

Rev

Rev 6665 | Rev 6668 | 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()
435
    diff = (end_date - start_date).days + 1
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
763
                delayedDays = get_business_days_count(order.expected_delivery_time + datetime.timedelta(days = 1), fda_datetime)
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")
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 or Accessory 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"
3226 chandransh 2293
    else:
4662 rajveer 2294
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2295
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2296
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2297
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2298
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2299
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2300
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2301
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2302
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2303
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2304
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2305
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2306
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2307
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2308
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2309
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2310
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2311
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2312
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2313
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
2314
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 2315
                     }
2316
        if order.status not in status_transition.keys():
2317
            raise TransactionServiceException(114, "This order can't be refunded")
2318
 
4495 rajveer 2319
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
5386 phani.kuma 2320
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2321
                __create_return_order(order)
3226 chandransh 2322
            __create_refund(order)
4495 rajveer 2323
            order.statusDescription = "RTO Refunded"
4662 rajveer 2324
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2325
            #__create_return_order(order)
4662 rajveer 2326
            __create_refund(order)
2327
            order.statusDescription = "Lost in Transit Refunded"
4495 rajveer 2328
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2329
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2330
                __create_return_order(order)
4495 rajveer 2331
            __create_refund(order)
2332
            order.statusDescription = "DOA Refunded"
2333
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2334
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2335
                __create_return_order(order)
4495 rajveer 2336
            __create_refund(order)
2337
            order.statusDescription = "Return Refunded"
5199 mandeep.dh 2338
        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 2339
            __update_inventory_reservation(order)
2340
            order.statusDescription = "Order Refunded"
4247 rajveer 2341
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5272 mandeep.dh 2342
            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 2343
                if order.previousStatus == OrderStatus.ACCEPTED:
2344
                    __create_refund(order)
4247 rajveer 2345
                __update_inventory_reservation(order)
2346
                order.statusDescription = "Order Cancelled on customer request"
2347
            elif order.previousStatus == OrderStatus.BILLED:
2348
                __create_return_order(order)
2349
                __create_refund(order)
2350
                order.statusDescription = "Order Cancelled on customer request"
2351
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
2352
            __update_inventory_reservation(order)
2353
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 2354
 
4873 mandeep.dh 2355
    # For orders that are cancelled after being billed, we need to scan in the scanned out
2356
    # inventory item and change availability accordingly
5944 mandeep.dh 2357
    inventoryClient = InventoryClient().get_client()
2358
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
5110 mandeep.dh 2359
    if warehouse.billingType == BillingType.OURS:
4873 mandeep.dh 2360
        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]):
2361
            lineitem = order.lineitems[0]
5944 mandeep.dh 2362
            catalogClient = CatalogClient().get_client()
5177 mandeep.dh 2363
            item = catalogClient.getItem(lineitem.item_id)
5361 mandeep.dh 2364
            warehouseClient = WarehouseClient().get_client()
5177 mandeep.dh 2365
            if ItemType.SERIALIZED == item.type:
2366
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 2367
            else:
2368
                warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4873 mandeep.dh 2369
 
3195 chandransh 2370
    order.status = status_transition[order.status]
2371
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 2372
    order.refunded_by = refunded_by
2373
    order.refund_reason = reason
4873 mandeep.dh 2374
 
2628 chandransh 2375
    session.commit()
2376
    return True
2377
 
3186 chandransh 2378
def __update_inventory_reservation(order):
3191 chandransh 2379
    '''
2380
    Reduce the reservation count for all line items of the given order.
2381
    '''
3186 chandransh 2382
    try:
5944 mandeep.dh 2383
        inventoryClient = InventoryClient().get_client()
3186 chandransh 2384
        for lineitem in order.lineitems:
5966 rajveer 2385
            inventoryClient.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3186 chandransh 2386
    except:
2387
        print "Unable to reduce reservation count"
2388
 
4220 rajveer 2389
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 2390
    current_time = datetime.datetime.now()
2391
    new_order = Order()
2392
    new_order.customer_id = order.customer_id
2393
    new_order.customer_name = order.customer_name
2394
    new_order.customer_city = order.customer_city
2395
    new_order.customer_state = order.customer_state
2396
    new_order.customer_mobilenumber = order.customer_mobilenumber
2397
    new_order.customer_pincode = order.customer_pincode
2398
    new_order.customer_address1 = order.customer_address1
2399
    new_order.customer_address2 = order.customer_address2
2400
    new_order.customer_email = order.customer_email
2401
    new_order.total_amount = order.total_amount
6318 rajveer 2402
    new_order.gvAmount = order.gvAmount
2628 chandransh 2403
    new_order.total_weight = order.total_weight
2404
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2405
    new_order.statusDescription = 'Submitted for Processing'
2406
    new_order.created_timestamp = current_time
5062 varun.gupt 2407
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 2408
 
2409
    new_order.transaction = order.transaction
4220 rajveer 2410
    new_order.cod = is_cod
5527 anupam.sin 2411
    new_order.orderType = order.orderType
2628 chandransh 2412
 
2413
    for line_item in order.lineitems:
2414
        litem = LineItem()
2415
        litem.item_id = line_item.item_id
2416
        litem.productGroup = line_item.productGroup
2417
        litem.brand = line_item.brand
2418
        if line_item.model_number:
2419
            litem.model_number = line_item.model_number
2420
        if line_item.model_name:    
2421
            litem.model_name = line_item.model_name
2422
        if line_item.color:
2423
            litem.color = line_item.color
2424
        if line_item.extra_info:
2425
            litem.extra_info = line_item.extra_info
2426
        litem.quantity = line_item.quantity
2427
        litem.unit_price = line_item.unit_price
2428
        litem.unit_weight = line_item.unit_weight
2429
        litem.total_price = line_item.total_price
2430
        litem.total_weight = line_item.total_weight
2431
        litem.transfer_price = line_item.transfer_price
4840 mandeep.dh 2432
        litem.dealText = line_item.dealText
6423 amit.gupta 2433
        litem.vatRate = line_item.vatRate
2628 chandransh 2434
        litem.order = new_order
2435
 
2436
    logistics_client = LogisticsClient().get_client()
2437
    item_id = new_order.lineitems[0].item_id
5785 mandeep.dh 2438
    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 2439
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2440
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 2441
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 2442
    new_order.logistics_provider_id = logistics_info.providerId
2443
    new_order.airwaybill_no = logistics_info.airway_billno
2444
    new_order.tracking_id = new_order.airwaybill_no
2445
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 2446
    new_order.promised_delivery_time = new_order.expected_delivery_time
6629 anupam.sin 2447
    new_order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2448
    new_order.promised_shipping_time = new_order.expected_shipping_time
2449
 
2628 chandransh 2450
    if should_copy_billing_info:
5388 phani.kuma 2451
        new_order.vendorId = order.vendorId
2628 chandransh 2452
        new_order.invoice_number = order.invoice_number
2453
        new_order.billed_by = order.billed_by
2454
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 2455
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
5620 mandeep.dh 2456
        new_order.jacket_number = order.jacket_number
2457
        new_order.lineitems[0].serial_number = order.lineitems[0].serial_number
2458
        new_order.lineitems[0].item_number   = order.lineitems[0].item_number
2628 chandransh 2459
        new_order.accepted_timestamp = current_time
2460
        new_order.billing_timestamp = current_time    
2461
        new_order.status = OrderStatus.BILLED
2462
        new_order.statusDescription = 'Order Billed'
5966 rajveer 2463
    else:
2464
        session.commit()       
5944 mandeep.dh 2465
        inventoryClient = InventoryClient().get_client()
5966 rajveer 2466
        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 2467
 
2468
    return new_order
2469
 
2470
def __create_return_order(order):
2687 chandransh 2471
    ret_order = ReturnOrder(order)
2628 chandransh 2472
    return ret_order
2473
 
2474
def __create_refund(order):
4078 chandransh 2475
    payment_client = PaymentClient().get_client()
2476
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 2477
    return
2628 chandransh 2478
 
2536 chandransh 2479
def __get_order_address(order):
2480
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
2481
    if order.customer_address2:
2482
        address = address + order.customer_address2 + "\n"
2483
    address = address + order.customer_city + "\n"
2484
    address = address + order.customer_state + "\n"
2485
    address = address + "PIN " + order.customer_pincode + "\n"
2486
    address = address + "Phone: " + order.customer_mobilenumber
2487
    return address
2488
 
5767 rajveer 2489
def __get_store_address(store):
2490
    address = store.name + "\n" + store.line1 + "\n"
2491
    if store.line2:
2492
        address = address + store.line2 + "\n"
2493
    address = address + store.city + "\n"
2494
    address = address + store.state + "\n"
5802 rajveer 2495
    address = address + "PIN - " + store.pin + "\n"
5793 rajveer 2496
    if store.phone:
5802 rajveer 2497
        address = address + "Phone - " + store.phone + "\n"
5855 rajveer 2498
    address = address +  "Store timings - 11AM to 8PM (7 days)\n"
5767 rajveer 2499
    return address
2500
 
5793 rajveer 2501
def __get_store_address_html(store):
2502
    address = store.name + "<br>" + store.line1 + "<br>"
2503
    if store.line2:
2504
        address = address + store.line2 + "<br>"
2505
    address = address + store.city + "<br>"
2506
    address = address + store.state + "<br>"
5802 rajveer 2507
    address = address + "PIN - " + store.pin + "<br>"
5793 rajveer 2508
    if store.phone:
5802 rajveer 2509
        address = address + "Phone - " + store.phone + "<br>"
5855 rajveer 2510
    address = address +  "Store timings - 7 days: 11AM to 8PM  (7 days)<br>"
5793 rajveer 2511
    return address
2512
 
4815 phani.kuma 2513
def __generate_return_advice(order, warehouse, provider, filename):
2514
    if warehouse.id == 7:
2515
        executive = 'Amit Kumar'
2516
    else:
4966 phani.kuma 2517
        executive = 'Dinesh Kumar'
2536 chandransh 2518
    pdf = Canvas(filename)
2519
    pdf.setFont('Times-Bold',16)
2520
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
2521
    address_text.textLine("To")
4815 phani.kuma 2522
    address_text.textLine(executive)
2536 chandransh 2523
    for line in warehouse.location.split("\n"):
2524
        address_text.textLine(line)
2525
    address_text.textLine("PIN " + warehouse.pincode)
2526
    pdf.drawText(address_text)
2527
 
2528
    pdf.setFont('Times-Roman',12)
2529
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 2530
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 2531
    lineitem = order.lineitems[0] 
4234 rajveer 2532
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 2533
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
2534
    order_text.textLine("Order ID : " + str(order.id))
2535
    pdf.drawText(order_text)
2536
    pdf.showPage()
2537
    pdf.save()
2538
    return filename
2539
 
5806 rajveer 2540
def __push_collection_to_hotspot(order, type):
2541
    try:
2542
        logistics_client = LogisticsClient().get_client()
2543
        store = logistics_client.getPickupStore(order.pickupStoreId)
2544
        store_string = "<store>" + store.hotspotId + "</store>"
2545
        order_string = "<orderno>" + str(order.id) + "</orderno>"
2546
        collection_type = "<Type>" + type + "</Type>"
5833 rajveer 2547
        payment_mode = get_order_attribute_value(order.id, "PAYMENT_MODE")
5806 rajveer 2548
        if type == "SALE":
6318 rajveer 2549
            amount = int(order.total_amount-order.gvAmount)
5806 rajveer 2550
            ts = order.delivery_timestamp
2551
        if type == "SALE RETURN":
6318 rajveer 2552
            amount = -int(order.total_amount-order.gvAmount)
5806 rajveer 2553
            ts = order.refund_timestamp
2554
        if payment_mode == "Cash":
2555
            cash_string = "<cash>" + str(amount) + "</cash>"
2556
            card_string = "<hdfc>0</hdfc>"
2557
        if payment_mode == "Card":
2558
            cash_string = "<cash>0</cash>"
2559
            card_string = "<hdfc>" + str(amount) + "</hdfc>"
2560
        date_string = "<date>" + ts.strftime("%Y%m%d") + "</date>"
2561
        time_string = "<time>" + ts.strftime("%H%M%S") + "</time>"
2562
 
2563
        conn = httplib.HTTPConnection("182.71.104.182")
2564
        XML="""
2565
        <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/">
2566
          <soap:Body>
2567
            <SaholicDataTransfer xmlns="http://tempuri.org/">
2568
        """
2569
 
2570
        XML = XML + store_string + order_string + collection_type + cash_string + card_string + date_string + time_string 
2571
 
2572
        footer = """
2573
            </SaholicDataTransfer>
2574
          </soap:Body>
2575
        </soap:Envelope>
2576
        """
2577
        XML = XML + footer
2578
 
2579
        params = urllib.urlencode({'op': 'SaholicDataTransfer'})
2580
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
2581
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
2582
        conn.send(XML)
2583
        response = conn.getresponse()
2584
        print response.status, response.reason
2585
        resp = response.read()
2586
        conn.close()
2587
        print resp
2588
        if "Saved Successfully" in resp:
2589
            return True
2590
        elif "Error in Saving Data" in resp:
2591
            return False
2592
        else: 
2593
            return False
2594
    except Exception as e:
2595
        print e
2596
        return False
2597
 
2697 chandransh 2598
def get_return_orders(warehouse_id, from_date, to_date):
2599
    query = ReturnOrder.query.filter_by(processedStatus = False)
2600
    if warehouse_id != -1:
2601
        query = query.filter_by(warehouseId = warehouse_id)
2602
    if from_date:
4118 chandransh 2603
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 2604
    if to_date:
4118 chandransh 2605
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 2606
    return [return_order.to_thrift_object() for return_order in query.all()]
2607
 
5481 phani.kuma 2608
def get_all_return_orders(onlyNotProcessed, from_date, to_date):
2609
    query = ReturnOrder.query
2610
    if onlyNotProcessed:
2611
        query = query.filter_by(processedStatus = False)
2612
    if from_date:
2613
        query = query.filter(ReturnOrder.createdAt >= from_date)
2614
    if to_date:
2615
        query = query.filter(ReturnOrder.createdAt <= to_date)
2616
    return [return_order.to_thrift_object() for return_order in query.all()]
2617
 
2700 chandransh 2618
def get_return_order(id):
2619
    ret_order = ReturnOrder.get_by(orderId = id)
2620
    if ret_order is None:
2621
        raise TransactionServiceException(116, "No return order found for the given order id")
2622
    return ret_order.to_thrift_object()
2623
 
2697 chandransh 2624
def process_return(ret_order_id):
2625
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
2626
    if ret_order is None:
2627
        raise TransactionServiceException(116, "No return order found for the given order id")
2628
    ret_order.processedStatus = True
2701 chandransh 2629
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 2630
    session.commit()
2631
 
4757 mandeep.dh 2632
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
2633
    """
2634
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
2635
    the quantities for which the PO is raised.
2636
 
2637
    Parameters:
2638
     - itemIdQuantityMap
2639
     - purchaseOrderId
2640
     - warehouseId
2641
    """
3451 chandransh 2642
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 2643
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 2644
    query = query.filter_by(purchase_order_id=None)
2645
    query = query.order_by(Order.created_timestamp)
2646
    pending_orders = query.all()
4586 mandeep.dh 2647
 
2648
    for order in pending_orders:
4757 mandeep.dh 2649
        lineitem = order.lineitems[0]
2650
        if itemIdQuantityMap.has_key(lineitem.item_id):
2651
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
2652
                order.status = OrderStatus.LOW_INV_PO_RAISED
2653
                order.statusDescription = 'In Process'
2654
                order.purchase_order_id = purchaseOrderId
2655
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 2656
 
2819 chandransh 2657
    session.commit()
2658
 
3451 chandransh 2659
def update_weight(order_id, weight):
3469 chandransh 2660
    '''
2661
    Update the weight of order
2662
    '''
3451 chandransh 2663
    order = get_order(order_id)
2664
    order.total_weight = weight
3469 chandransh 2665
    lineitem = order.lineitems[0]
2666
    lineitem.total_weight = weight
2667
    lineitem.unit_weight = weight
3451 chandransh 2668
 
3469 chandransh 2669
    session.commit()
2670
    return order
2671
 
2672
def change_product(order_id, item_id):
2673
    '''
2674
    Ship a product of a different color to the customer.
2675
    '''
2676
    order = get_order(order_id)
4662 rajveer 2677
    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 2678
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
2679
 
2680
    lineitem = order.lineitems[0]
3451 chandransh 2681
 
3469 chandransh 2682
    catalog_client = CatalogClient().get_client()
2683
 
2684
    old_item = catalog_client.getItem(lineitem.item_id)
2685
    item = catalog_client.getItem(item_id)
2686
    if old_item.catalogItemId != item.catalogItemId:
2687
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
2688
 
5944 mandeep.dh 2689
    inventoryClient = InventoryClient().get_client()
5966 rajveer 2690
    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 2691
    __update_inventory_reservation(order)
3469 chandransh 2692
    #TODO: Check that this new item has the same price
2693
 
2694
    lineitem.item_id = item_id
2695
    lineitem.color = item.color
2696
 
3451 chandransh 2697
    session.commit()
3469 chandransh 2698
 
2699
    order = get_order(order_id)
3451 chandransh 2700
    return order
3469 chandransh 2701
 
2702
def change_warehouse(order_id, warehouse_id):
2703
    '''
2704
    Update the warehouse which will be used to fulfil this order.
2705
    '''
2706
    order = get_order(order_id)
6019 rajveer 2707
    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 2708
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
2709
 
2710
    if warehouse_id == order.warehouse_id:
2711
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
2712
 
2713
    lineitem = order.lineitems[0]
2714
    catalog_client = CatalogClient().get_client()
5944 mandeep.dh 2715
    inventoryClient = InventoryClient().get_client()
3469 chandransh 2716
    try:
5944 mandeep.dh 2717
        warehouse = inventoryClient.getWarehouse(warehouse_id)
3469 chandransh 2718
    except:
2719
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 2720
 
5147 mandeep.dh 2721
    if warehouse.billingWarehouseId is None:
2722
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 2723
 
5620 mandeep.dh 2724
    # If One gives a billing warehouse for warehouse shift, we should assign order to the GOOD warehouse
2725
    # present within it with maximum availability
2726
    if warehouse.id == warehouse.billingWarehouseId:
5944 mandeep.dh 2727
        warehouses = inventoryClient.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
5147 mandeep.dh 2728
        if warehouses:
5944 mandeep.dh 2729
            itemInventory = inventoryClient.getItemInventoryByItemId(lineitem.item_id)
5147 mandeep.dh 2730
            warehouse = warehouses[0]
2731
            maxAvailability = 0
2732
            for goodWarehouse in warehouses:
2733
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
2734
                    warehouse = goodWarehouse
2735
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
2736
 
2737
            # Use preferred vendor's warehouse if not available anywhere
2738
            if not maxAvailability:
2739
                item = catalog_client.getItem(lineitem.item_id)
2740
                if item.preferredVendor:
2741
                    for goodWarehouse in warehouses:
2742
                        if goodWarehouse.vendor.id == item.preferredVendor:
2743
                            warehouse = goodWarehouse
2744
        else:
2745
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
2746
 
6007 rajveer 2747
    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 2748
    __update_inventory_reservation(order)
2749
 
2750
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 2751
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 2752
    session.commit()
2753
    return order
3553 chandransh 2754
 
4647 rajveer 2755
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 2756
    '''
3994 chandransh 2757
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 2758
    '''
2759
    order = get_order(order_id)
2760
    try:
3581 chandransh 2761
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 2762
        order.delayReasonText = delayReasonText
4009 chandransh 2763
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
2764
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 2765
 
4842 rajveer 2766
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
2767
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 2768
 
3553 chandransh 2769
        session.commit()
4008 mandeep.dh 2770
 
2771
        try:
2772
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
2773
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
2774
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
2775
            session.commit()
2776
        except Exception as e:
4065 mandeep.dh 2777
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 2778
 
3553 chandransh 2779
        return True
2780
    except:
3994 chandransh 2781
        print sys.exc_info()[0]
3553 chandransh 2782
        return False
3956 chandransh 2783
 
2784
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
2785
    unprocessed_awbs = {}
2786
    for awb, amount in collected_amount_map.iteritems():
2787
        try:
2788
            order = Order.query.filter_by(airwaybill_no=awb).one()
2789
        except NoResultFound:
2790
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
2791
            continue
2792
        except MultipleResultsFound:
2793
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
2794
            continue
2795
 
2796
        if order.cod_reconciliation_timestamp:
2797
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
2798
            continue
2799
 
2800
        if order.status < OrderStatus.DELIVERY_SUCCESS:
2801
            #Order has not been delivered yet. No way we can receive the payment.
2802
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
2803
            continue
2804
 
4252 rajveer 2805
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
6318 rajveer 2806
        if abs(amount - (order.total_amount - order.gvAmount)) > 0.5:
3956 chandransh 2807
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
6318 rajveer 2808
            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 2809
            continue
2810
 
2811
        try:
2812
            payment_client = PaymentClient().get_client()
2813
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
2814
        except Exception:
2815
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
2816
            continue
2817
 
2818
        #Payment has been recorded now. We can update the order peacefully.
2819
        order.cod_reconciliation_timestamp = datetime.datetime.now()
2820
        session.commit()
3469 chandransh 2821
 
3956 chandransh 2822
    return unprocessed_awbs
4008 mandeep.dh 2823
 
2824
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 2825
    """
2826
    Returns the list of transaction ids that require some extra processing and
2827
    which belong to a particular category. This is currently used by CRM
2828
    application. If no such transaction ids are present, it returns an empty list.
2829
    """
2830
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 2831
 
4065 mandeep.dh 2832
    if category is not None:
2833
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 2834
 
4065 mandeep.dh 2835
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 2836
 
2837
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 2838
    """
2839
    Marks a particular transaction as processed for a particular cateogory.
2840
    It essentially deletes the transaction id record for a particular
2841
    processing type category (if present) from DB.
2842
    This is currently used by CRM application.
2843
    """
4008 mandeep.dh 2844
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
2845
    session.commit()
2846
 
4018 chandransh 2847
def get_item_wise_risky_orders_count():
2848
    """
2849
    Returns a map containing the number of risky orders keyed by item id. A risky order
2850
    is defined as one whose shipping date is about to expire.
2851
    """
2852
    item_wise_risky_orders_count = {}
4019 chandransh 2853
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 2854
    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()
2855
    for order in orders:
2856
        for lineitem in order.lineitems:
2857
            quantity = lineitem.quantity
2858
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
2859
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
2860
 
2861
            item_wise_risky_orders_count[lineitem.item_id] = quantity
2862
    return item_wise_risky_orders_count
2863
 
4324 mandeep.dh 2864
def update_shipment_address(order_id, address_id):
2865
    """
2866
    Updates shipment address of an order. Delivery and shipping date estimates
2867
    etc. are also updated here.
2868
 
2869
    Throws TransactionServiceException in case address change is not
2870
    possible due to certain reasons such as new pincode in address is
2871
    not serviceable etc.
2872
 
2873
    Parameters:
2874
     - orderId
2875
     - addressId
2876
    """
2877
    user_client = UserClient().get_client()
2878
    address     = user_client.getAddressById(address_id)
2879
    order       = get_order(order_id)
2880
 
4630 mandeep.dh 2881
    type = DeliveryType.PREPAID
2882
    if order.cod:
2883
        type = DeliveryType.COD
2884
 
4324 mandeep.dh 2885
    logistics_client = LogisticsClient().get_client()
5886 mandeep.dh 2886
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type)
4324 mandeep.dh 2887
 
2888
    # Check for new estimate. Raise exception if new address is not serviceable
2889
    if logistics_info.deliveryTime == -1:
2890
        raise TransactionServiceException(1, 'Location not serviceable')
2891
 
2892
    # COD services are not available everywhere
2893
    if order.cod:
4868 rajveer 2894
        if not logistics_info.codAllowed:
4324 mandeep.dh 2895
            raise TransactionServiceException(2, 'COD service not available')
2896
 
5593 mandeep.dh 2897
    if logistics_info.providerId != order.logistics_provider_id:
5887 mandeep.dh 2898
        logistics_info = logistics_client.getLogisticsInfo(address.pin, order.lineitems[0].item_id, type, PickUpType.COURIER)
5593 mandeep.dh 2899
        order.tracking_id = logistics_info.airway_billno
2900
        order.airwaybill_no = logistics_info.airway_billno
2901
        order.logistics_provider_id = logistics_info.providerId
2902
 
6525 rajveer 2903
    order.otg = logistics_info.otgAvailable
4324 mandeep.dh 2904
    current_time = datetime.datetime.now()
2905
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2906
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2907
 
2908
    order.customer_name         = address.name
2909
    order.customer_pincode      = address.pin
2910
    order.customer_address1     = address.line1
2911
    order.customer_address2     = address.line2
2912
    order.customer_city         = address.city
2913
    order.customer_state        = address.state
2914
    order.customer_mobilenumber = address.phone
2915
 
2916
    if order.cod:
2917
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2918
    else:
2919
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2920
 
2921
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
2922
    order.promised_shipping_time = order.expected_shipping_time
2923
    order.promised_delivery_time = order.expected_delivery_time 
2924
 
2925
    session.commit()
2926
 
4247 rajveer 2927
def mark_order_cancellation_request_received(orderId):
2928
    """
2929
    Mark order as cancellation request received. If customer sends request of cancellation of
2930
    a particular order, this method will be called. It will just change status of the order
2931
    depending on its current status. It also records the previous status, so that we can move
2932
    back to that status if cancellation request is denied.
2933
 
2934
    Parameters:
2935
     - orderId
2936
    """
4662 rajveer 2937
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2938
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
2939
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 2940
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2941
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
2942
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2943
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2944
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2945
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
2946
             }
4662 rajveer 2947
 
2948
    order = get_order(orderId)
4247 rajveer 2949
    if order.status not in status_transition.keys():
2950
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
2951
 
4662 rajveer 2952
 
4247 rajveer 2953
    order.previousStatus = order.status
2954
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
2955
    order.statusDescription = "Cancellation request received from user"
2956
    session.commit()
2957
 
4662 rajveer 2958
def mark_order_as_lost_in_transit(orderId):
2959
    """
2960
    Parameters:
2961
     - orderId
2962
    """
2963
    order = get_order(orderId)
4910 phani.kuma 2964
    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 2965
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
2966
    order.status = OrderStatus.LOST_IN_TRANSIT
2967
    order.statusDescription = "Lost in Transit"
2968
    session.commit()
2969
 
4258 rajveer 2970
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 2971
    """
4258 rajveer 2972
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
2973
    Changed transaction and all orders status to payment accepted.
4247 rajveer 2974
 
2975
    Parameters:
4258 rajveer 2976
     - transactionId
4247 rajveer 2977
    """
4258 rajveer 2978
    transaction = get_transaction(transactionId)
2979
    transaction.status = TransactionStatus.AUTHORIZED
2980
    for order in transaction.orders:
2981
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2982
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 2983
    session.commit()
2984
 
4259 anupam.sin 2985
def refund_transaction(transactionId, refundedBy, reason):
2986
    """
2987
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
2988
    need to be cancelled
2989
 
2990
    Parameters:
2991
     - transactionId
2992
    """
2993
    transaction = get_transaction(transactionId)
2994
    transaction.status = TransactionStatus.FAILED
2995
    for order in transaction.orders:
2996
        refund_order(order.id, refundedBy, reason)
2997
    session.commit()
2998
 
4247 rajveer 2999
def mark_order_cancellation_request_denied(orderId):
3000
    """
4283 anupam.sin 3001
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 3002
 
3003
    Parameters:
3004
     - orderId
3005
    """
3006
    order = get_order(orderId)
3007
    order.status = order.previousStatus
3008
    order.previousStatus = None
3009
    order.statusDescription = "Cancellation request denied"
3010
    session.commit()
3011
 
3012
def mark_order_cancellation_request_confirmed(orderId):
3013
    """
3014
    If we decide to to cancel order, CRM will call this method to move the status of order to
3015
    cancellation request confirmed. After this OM will be able to cancel the order.
3016
 
3017
    Parameters:
3018
     - orderId
3019
    """
3020
    order = get_order(orderId)
3021
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
3022
    order.statusDescription = "Cancellation request confirmed"
3023
    session.commit()
3024
 
4285 rajveer 3025
def accept_orders_for_item_id(itemId, inventory):
3026
    """
3027
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
3028
    given order is not a COD order, it also captures the payment if the same has not been captured.
3029
 
3030
    Parameters:
3031
     - itemId
3032
     - inventory
3033
    """
4938 rajveer 3034
    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 3035
    for order in orders:
4301 rajveer 3036
        if inventory > 0:
3037
            lineitem = order.lineitems[0]
3038
            if itemId == lineitem.item_id:
3039
                try:
3040
                    accept_order(order.id)
3041
                    inventory = inventory - lineitem.quantity
3042
                except:
3043
                    logging.info("Unable to accept the order")
3044
        else:
3045
            order_outofstock(order.id)
4285 rajveer 3046
    return
3047
 
4607 rajveer 3048
def get_slipped_sipping_date_orders():
4662 rajveer 3049
    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 3050
 
3051
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
3052
    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 3053
 
4369 rajveer 3054
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
3055
    if isReminder:
3056
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3057
    else:
3058
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3059
 
3060
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3061
    for order in orders:
3062
        lineitem = order.lineitems[0]
3063
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3064
            if estimate > 0:
3065
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
3066
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 3067
            order.statusDescription = "PO Raised"
4303 rajveer 3068
            quantity = quantity - lineitem.quantity
3069
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
3070
            session.commit()
3071
 
4369 rajveer 3072
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
3073
    if isReminder:
3074
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3075
    else:
3076
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3077
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3078
    for order in orders:
3079
        lineitem = order.lineitems[0]
3080
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3081
            if estimate > 0:
3082
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
3083
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 3084
            order.statusDescription = "Reversal Initiated"
4303 rajveer 3085
            quantity = quantity - lineitem.quantity
3086
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
3087
            session.commit()
3088
 
4369 rajveer 3089
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
3090
    if isReminder:
3091
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3092
    else:
3093
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3094
 
3095
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3096
    for order in orders:
3097
        lineitem = order.lineitems[0]
3098
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3099
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 3100
            order.statusDescription = "Not Available"
4303 rajveer 3101
            quantity = quantity - lineitem.quantity
3102
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
3103
            session.commit()
3104
 
3105
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 3106
    orderInv = OrderInventory.get_by(order_id=order.id)
3107
    if not orderInv:
3108
        orderInv = OrderInventory()
3109
        orderInv.order = order
4303 rajveer 3110
    orderInv.hotspotAction = hotspotAction  
3111
    orderInv.estimate = estimate
3112
    orderInv.itemId = itemId
3113
    orderInv.timestamp = datetime.datetime.now()
3114
    orderInv.quantity = quantity
3115
 
4556 mandeep.dh 3116
'''    
4369 rajveer 3117
def mark_orders_as_timeout(vendorId):
3118
    ret_timeouts = {}
3119
    orderInvs = OrderInventory.query.all()
3120
    for orderInv in orderInvs:
3121
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
3122
            if not ret_timeouts.has_key(orderInv.itemId):
3123
                timeout = TimeoutSummary()
3124
                ret_timeouts[orderInv.itemId] = timeout
3125
            else:
3126
                timeout = ret_timeouts.get(orderInv.itemId)
3127
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3128
                if timeout.poRaised:
3129
                    timeout.poRaised += 1
3130
                else:
3131
                    timeout.poRaised = 1
3132
 
3133
                if timeout.poEstimate:
3134
                    timeout.poEstimate += orderInv.estimate
3135
                else:
3136
                    timeout.poEstimate = orderInv.estimate
3137
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
3138
                orderInv.order.statusDescription = "PO Raised Timeout"
3139
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3140
                if timeout.reversalInitiated:
3141
                    timeout.reversalInitiated += 1
3142
                else:
3143
                    timeout.reversalInitiated = 1
3144
 
3145
                if timeout.reversalEstimate:
3146
                    timeout.reversalEstimate += orderInv.estimate
3147
                else:
3148
                    timeout.reversalEstimate = orderInv.estimate
3149
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
3150
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
3151
            else:
3152
                orderInv.delete()
3153
    session.commit()
3154
    return ret_timeouts
4556 mandeep.dh 3155
'''
3156
 
3157
 
3158
def mark_orders_as_timeout(vendorId):
3159
    ret_timeouts = {}
3160
    orderInvs = OrderInventory.query.all()
3161
    for orderInv in orderInvs:
3162
        if not ret_timeouts.has_key(orderInv.itemId):
3163
            timeout = TimeoutSummary()
3164
            ret_timeouts[orderInv.itemId] = timeout
3165
        else:
3166
            timeout = ret_timeouts.get(orderInv.itemId)
3167
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3168
            if timeout.poRaised:
3169
                timeout.poRaised += 1
3170
            else:
3171
                timeout.poRaised = 1
3172
 
3173
            if timeout.poEstimate:
3174
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
3175
            else:
3176
                timeout.poEstimate = orderInv.estimate
3177
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3178
            if timeout.reversalInitiated:
3179
                timeout.reversalInitiated += 1
3180
            else:
3181
                timeout.reversalInitiated = 1
3182
 
3183
            if timeout.reversalEstimate:
3184
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
3185
            else:
3186
                timeout.reversalEstimate = orderInv.estimate
3187
        orderInv.order.status = OrderStatus.INVENTORY_LOW
3188
        orderInv.order.statusDescription = "Low Inventory"
3189
        orderInv.delete()
3190
    session.commit()
3191
    return ret_timeouts
3192
 
4386 anupam.sin 3193
def get_order_for_awb(awb):
3194
    order = Order.get_by(airwaybill_no=awb)
3195
    if not order:
3196
        raise TransactionServiceException(108, "no such order")
3197
 
3198
    return order
4369 rajveer 3199
 
4910 phani.kuma 3200
def get_orders_for_provider_for_status(provider_id, order_status_list):
3201
    if not provider_id or not order_status_list:
4506 phani.kuma 3202
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 3203
    doa_provider = False
3204
    for order_status in order_status_list:
3205
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
3206
            doa_provider = True
3207
    if doa_provider:
3208
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 3209
    else:
4910 phani.kuma 3210
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 3211
    return query.all()
4386 anupam.sin 3212
 
4600 varun.gupt 3213
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 3214
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
3215
 
3216
    if vendor_id:
3217
        query = query.filter_by(vendorId = vendor_id)
3218
 
4600 varun.gupt 3219
    if billing_date_from:
3220
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 3221
 
4600 varun.gupt 3222
    if billing_date_to:
3223
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 3224
 
4600 varun.gupt 3225
    return query.all()
3226
 
5481 phani.kuma 3227
def get_billed_orders(vendor_id, onlyVendorNotPaid, billing_date_from, billing_date_to):
5386 phani.kuma 3228
    query = Order.query.filter(Order.billing_timestamp != None)
5481 phani.kuma 3229
 
3230
    if onlyVendorNotPaid:
5488 phani.kuma 3231
        query = query.filter_by(vendor_paid = False)
5481 phani.kuma 3232
 
5386 phani.kuma 3233
    if vendor_id != -1:
3234
        query = query.filter_by(vendorId = vendor_id)
3235
 
5481 phani.kuma 3236
    if billing_date_from:
3237
        query = query.filter(Order.billing_timestamp >= billing_date_from)
3238
 
3239
    if billing_date_to:
3240
        query = query.filter(Order.billing_timestamp <= billing_date_to)
3241
 
4885 varun.gupt 3242
    return query.all()
4875 varun.gupt 3243
 
4600 varun.gupt 3244
def save_bluedart_settlements(map_awb_and_amount):
3245
    payment_client = PaymentClient().get_client()
3246
 
3247
    for awb, amount in map_awb_and_amount.iteritems():
3248
        order = Order.get_by(airwaybill_no = awb)
3249
 
3250
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
3251
        settlement = PaymentSettlement()
3252
        settlement.paymentId = payment.paymentId
3253
        settlement.paymentGatewayId = payment.gatewayId
3254
        settlement.netCollection = amount
3255
        session.commit()
3256
 
4905 varun.gupt 3257
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 3258
    originalOrderId = None
3259
    if paymentGatewayId == 4:
3260
        cod_order = Order.get_by(id = referenceId)
3261
        if cod_order.originalOrderId:
3262
            originalOrderId = cod_order.originalOrderId
3263
        else:
3264
            originalOrderId = referenceId
4600 varun.gupt 3265
    settlement = PaymentSettlement()
3266
    settlement.settlementDate = settlementDate
3267
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 3268
    if originalOrderId is not None:
3269
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 3270
    settlement.referenceId = referenceId
4600 varun.gupt 3271
    settlement.serviceTax = serviceTax
3272
    settlement.otherCharges = otherCharges
3273
    settlement.netCollection = netCollection
3274
    session.commit()
3275
 
5386 phani.kuma 3276
def get_settlement_for_Prepaid(reference_id, is_refund = False):
3277
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 3278
 
5189 varun.gupt 3279
    if is_refund:
3280
        query = query.filter(PaymentSettlement.netCollection < 0)
3281
    else:
3282
        query = query.filter(PaymentSettlement.netCollection > 0)
3283
 
5386 phani.kuma 3284
    return query.first()
3285
 
3286
def get_settlement_for_Cod(orderId, is_refund = False):
3287
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 3288
 
5386 phani.kuma 3289
    if is_refund:
3290
        query = query.filter(PaymentSettlement.netCollection < 0)
3291
    else:
3292
        query = query.filter(PaymentSettlement.netCollection > 0)
3293
 
5189 varun.gupt 3294
    return query.first()
4600 varun.gupt 3295
 
3296
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
5551 phani.kuma 3297
    summary = EBSSettlementSummary.query.filter_by(settlementId = settlement_id).first()
5481 phani.kuma 3298
    if summary is None:
3299
        summary = EBSSettlementSummary()
3300
        summary.settlementId = settlement_id
3301
        summary.settlementDate = settlement_date
3302
        summary.transactionDateFrom = transaction_date_from
3303
        summary.transactionDateTo = transaction_date_to
3304
        summary.amount = amount
3305
        summary.detailsUploaded = False
3306
        session.commit()
4600 varun.gupt 3307
 
3308
def get_ebs_settlement_summaries():
3309
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
3310
    summary_map = {}
3311
 
3312
    for summary in summaries:
3313
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
3314
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
3315
 
3316
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
3317
 
3318
    return summary_map
3319
 
3320
def get_ebs_settlement_date(settlement_id):
3321
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3322
 
3323
    if summary:
3324
        return summary.settlementDate
3325
 
3326
def mark_ebs_settlement_uploaded(settlement_id):
3327
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3328
 
3329
    if summary:
3330
        summary.detailsUploaded = True
3331
        session.commit()
4715 varun.gupt 3332
 
3333
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
3334
    query = PaymentSettlement.query
4600 varun.gupt 3335
 
4715 varun.gupt 3336
    if settlement_date_from:
3337
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
3338
 
3339
    if settlement_date_to:
3340
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
3341
 
4749 varun.gupt 3342
    if is_refund is True:
3343
        query = query.filter(PaymentSettlement.netCollection < 0.0)
3344
    else:
3345
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 3346
 
4749 varun.gupt 3347
    return query.all()
4715 varun.gupt 3348
 
3349
def get_reshipped_order_ids(order_ids):
3350
    reshipped_order_ids = []
3351
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
3352
 
4749 varun.gupt 3353
def get_shipping_confirmation_email_body(order):
3354
 
3355
    html = """
3356
<html>
3357
<body>
3358
<div>
3359
    <p>Dear Customer,</p>
3360
    <p>
4885 varun.gupt 3361
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 3362
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
4749 varun.gupt 3363
    </p>
3364
    <p>
6655 rajveer 3365
        Expected delivery date for your order is $expected_delivery_date.
3366
        $otg_text 
4749 varun.gupt 3367
        The product can be delivered to you between business hours of 10am to 6pm. 
3368
        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.
3369
    </p>
3370
    <p>
5573 amit.gupta 3371
        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 3372
    </p>
5139 varun.gupt 3373
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 3374
    <p>
3375
        Warm Regards,<br />
6029 rajveer 3376
        $source_name Team
4749 varun.gupt 3377
    </p>
4750 varun.gupt 3378
</div>
4749 varun.gupt 3379
</body>
3380
</html>
3381
    """
5573 amit.gupta 3382
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}}
5139 varun.gupt 3383
    provider_name = logistics_providers[order.logistics_provider_id]['name']
3384
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
3385
 
5868 rajveer 3386
    lclient = LogisticsClient().get_client()
3387
    logistics_info = lclient.getLogisticsEstimation(order.lineitems[0].item_id, order.customer_pincode, DeliveryType.PREPAID)
4749 varun.gupt 3388
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 3389
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
4749 varun.gupt 3390
    product = "%s %s %s" % (order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number)
5868 rajveer 3391
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (logistics_info.deliveryTime - logistics_info.shippingTime)))
6666 rajveer 3392
    #update new expected timestamp
3393
    if order.cod:
3394
        new_expected_delivery_timestamp = new_expected_delivery_timestamp.replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3395
    else:
3396
        new_expected_delivery_timestamp = new_expected_delivery_timestamp.replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3397
    order.expected_delivery_time = new_expected_delivery_timestamp
3398
    session.commit()
3399
 
4885 varun.gupt 3400
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
6655 rajveer 3401
    otg_text = ""
3402
    if order.otg:
6662 rajveer 3403
        promised_delivery_date = order.promised_delivery_time.strftime("%A, %d %B %Y")
6655 rajveer 3404
        if new_expected_delivery_timestamp > order.promised_delivery_time:
6662 rajveer 3405
            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 3406
        elif new_expected_delivery_timestamp < order.promised_delivery_time:
6662 rajveer 3407
            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 3408
        else:            
6662 rajveer 3409
            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 3410
 
3411
    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 3412
    return Template(html).substitute(info)
4749 varun.gupt 3413
 
5832 rajveer 3414
def enqueue_shipping_confirmation_email(order):
4915 varun.gupt 3415
    # Calling helper service on production
3416
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5832 rajveer 3417
    try:
3418
        emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
3419
        emailBody = get_shipping_confirmation_email_body(order)
5866 rajveer 3420
        helperClient.saveUserEmailForSending([order.customer_email], None, emailSubject, emailBody, str(order.id), 'ShippingConfirmation', [], [])
5832 rajveer 3421
    except Exception as e:
3422
        print e
5139 varun.gupt 3423
 
4915 varun.gupt 3424
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 3425
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
3426
    query = query.filter(Order.created_timestamp >= start_date)
3427
    query = query.filter(Order.created_timestamp <= end_date)
3428
    return query.all()
4915 varun.gupt 3429
 
5067 varun.gupt 3430
def get_order_ids_for_status(status, start_datetime, end_datetime):
3431
    query = Order.query.filter(Order.status == status)
3432
    query = query.filter(Order.created_timestamp >= start_datetime)
3433
    query = query.filter(Order.created_timestamp <= end_datetime)
3434
    return query.all()
3435
 
5099 varun.gupt 3436
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 3437
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 3438
 
5139 varun.gupt 3439
    if paid_order.originalOrderId is None:
3440
        paid_order.vendor_paid = True
5099 varun.gupt 3441
        session.commit()
5139 varun.gupt 3442
 
3443
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
3444
            order.vendor_paid = True
3445
            session.commit()
3446
    else:
5208 varun.gupt 3447
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 3448
 
5208 varun.gupt 3449
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 3450
            order.vendor_paid = True
3451
            session.commit()
3452
 
3453
        original_order = Order.get_by(id = original_order_id)
3454
        if original_order:  original_order.vendor_paid = True
3455
        session.commit()
5348 anupam.sin 3456
 
3457
def update_COD_agent(agentEmailId, orderId):
3458
    order = Order.get_by(id=orderId)
3459
    if not order:
3460
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
3461
    agent = CodVerificationAgent()
3462
    agent.orderId = orderId
3463
    agent.verificationAgent = agentEmailId
3464
    session.commit()
3465
 
5099 varun.gupt 3466
 
5386 phani.kuma 3467
def update_order_only_as_paid_to_vendor(order_id):
3468
    paid_order = Order.get_by(id = order_id)
3469
    if paid_order is None:
3470
        raise TransactionServiceException(116, "No order found for the given order id")
3471
    paid_order.vendor_paid = True
3472
    session.commit()
3473
 
5208 varun.gupt 3474
def get_refunded_orders_marked_paid():
3475
    orderStatusGroup = OrderStatusGroups()
3476
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
3477
 
5447 anupam.sin 3478
def get_all_verification_agents(minOrderId, maxOrderId):
3479
    return CodVerificationAgent.query.filter(CodVerificationAgent.orderId >= minOrderId).filter(CodVerificationAgent.orderId <= maxOrderId).all()
3480
 
5527 anupam.sin 3481
def get_all_attributes_for_order_id(orderId):
3482
    return Attribute.query.filter(Attribute.orderId == orderId).all()
3483
 
3484
def set_order_attribute_for_transaction(transactionId, t_attribute):
3485
    for order in Order.query.filter_by(transaction_id = transactionId).all():
3486
        attribute = Attribute()
3487
        attribute.orderId = order.id
3488
        attribute.name = t_attribute.name
3489
        attribute.value = t_attribute.value
3490
        session.commit()
5593 mandeep.dh 3491
 
5558 mandeep.dh 3492
def accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
5944 mandeep.dh 3493
    inventoryClient = InventoryClient().get_client()
3494
    inventory = inventoryClient.getItemInventoryByItemId(itemId)
5684 mandeep.dh 3495
    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 3496
    for order in orders:
5593 mandeep.dh 3497
        lineitem = order.lineitems[0]
5558 mandeep.dh 3498
        if lineitem.item_id == itemId and lineitem.quantity <= quantity:
5944 mandeep.dh 3499
            warehouse = inventoryClient.getWarehouse(order.fulfilmentWarehouseId)
5684 mandeep.dh 3500
            if not warehouse.billingWarehouseId and warehouse.warehouseType == WarehouseType.THIRD_PARTY:
3501
                if (inventory.availability[fulfilmentWarehouseId] >= inventory.reserved[fulfilmentWarehouseId] + lineitem.quantity) and inventory.availability[order.fulfilmentWarehouseId] < inventory.reserved[order.fulfilmentWarehouseId]:
5966 rajveer 3502
                    inventoryClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3503
                    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 3504
                    order.fulfilmentWarehouseId = fulfilmentWarehouseId
5558 mandeep.dh 3505
                    quantity -= lineitem.quantity
5684 mandeep.dh 3506
                    session.commit()
5593 mandeep.dh 3507
                    if not quantity:
3508
                        break
5558 mandeep.dh 3509
 
6031 rajveer 3510
def get_recharge_order(rechargeOrderId):
6048 rajveer 3511
    return RechargeOrder.get_by(id = rechargeOrderId)
6031 rajveer 3512
 
3513
def get_recharge_orders(userId):
3514
    return RechargeOrder.query.filter_by(userId = userId).all()
3515
 
6279 rajveer 3516
def update_recharge_order_status(rechargeOrderId, rechargeOrderStatus, refundDate=None):
6031 rajveer 3517
    recharge_order = get_recharge_order(rechargeOrderId)
3518
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_FAILED:
3519
        recharge_order.status = RechargeOrderStatus.PAYMENT_FAILED
3520
        session.commit()
3521
        return True
6214 rajveer 3522
 
3523
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED:
3524
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
3525
        session.commit()
3526
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3527
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6214 rajveer 3528
        enqueue_recharge_info_email(recharge_order)
3529
        return True
3530
 
3531
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3532
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
6553 rajveer 3533
        recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
6214 rajveer 3534
        session.commit()
6285 rajveer 3535
        gvs = allocate_gift_voucher(recharge_order)
3536
        enqueue_recharge_info_email(recharge_order, gvs)
6214 rajveer 3537
        return True
3538
 
6279 rajveer 3539
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3540
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED
3541
        order.responseTimestamp = refundDate
3542
        session.commit()
3543
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3544
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6279 rajveer 3545
        enqueue_recharge_info_email(recharge_order)
3546
        return True
3547
 
6031 rajveer 3548
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6285 rajveer 3549
        gvs = {}
6206 rajveer 3550
        recharge_order.status = RechargeOrderStatus.PAYMENT_SUCCESSFUL
3551
        session.commit()
6031 rajveer 3552
        if recharge_order.walletAmount > 0:
3553
            wallet = get_user_wallet(recharge_order.userId)
3554
            if wallet and wallet.amount >= recharge_order.walletAmount:
3555
                update_amount_in_wallet(recharge_order.userId, -recharge_order.walletAmount, recharge_order.id)
3556
            else:
6441 rajveer 3557
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6031 rajveer 3558
                raise TransactionServiceException(103, 'Wallet amount has already been used')
3559
 
6092 rajveer 3560
        try:
3561
            if activate_recharge_txn(recharge_order):
3562
                recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
3563
                session.commit()
6285 rajveer 3564
                gvs = allocate_gift_voucher(recharge_order)
6092 rajveer 3565
                return True
3566
            else:
3567
                update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3568
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6092 rajveer 3569
                session.commit()
3570
                return False
3571
        except:
3572
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
3573
            transaction_requiring_extra_processing.category = 'RECHARGE_UNKNOWN'
3574
            transaction_requiring_extra_processing.transaction_id = recharge_order.transaction_id
6031 rajveer 3575
            session.commit()
3576
            return False
6102 rajveer 3577
        finally:
6285 rajveer 3578
            enqueue_recharge_info_email(recharge_order, gvs)
6102 rajveer 3579
 
6031 rajveer 3580
 
6285 rajveer 3581
def allocate_gift_voucher(recharge_order):            
3582
    totalAmount = recharge_order.totalAmount
3583
    gvs = {}
6438 rajveer 3584
    return gvs
6330 rajveer 3585
    if totalAmount >= 100:
3586
        totalAmount=500 if totalAmount >= 500 else totalAmount
6285 rajveer 3587
        try:
3588
            pc = PromotionClient().get_client()
6330 rajveer 3589
            enddate = datetime.datetime.now() + datetime.timedelta(days=45)
6285 rajveer 3590
            while totalAmount > 0:
6330 rajveer 3591
                gvAmount = totalAmount if totalAmount <= 250 else 250
6285 rajveer 3592
                totalAmount = totalAmount - gvAmount
6561 amit.gupta 3593
                gv = pc.createCoupon(26, to_java_date(enddate), recharge_order.userEmailId, gvAmount, False, 1, None)
6285 rajveer 3594
                gvs[gv] = gvAmount  
3595
        except:
3596
            print "Not able to create gift voucher for user " + recharge_order.userEmailId
3597
    return gvs     
3598
 
6048 rajveer 3599
def activate_recharge_txn(recharge_order):
3600
    if isinstance(recharge_order, MobileRechargeOrder):
3601
        rechargeType = 'MTP'
3602
        deviceNumber = recharge_order.mobileNumber
3603
        strProviderCode = get_provider_code(recharge_order.mobileOperatorId)
6161 rajveer 3604
        plan = recharge_order.rechargePlan
6048 rajveer 3605
    if isinstance(recharge_order, DTHRechargeOrder):
3606
        rechargeType = 'RCH'
3607
        deviceNumber = recharge_order.dthAccountNumber
3608
        strProviderCode = get_provider_code(recharge_order.dthOperatorId)
6161 rajveer 3609
        plan = ''
3610
    retStatus, retCode, spiceTID, description = RechargeService.rechargeDevice(recharge_order.id, rechargeType, strProviderCode, deviceNumber, recharge_order.totalAmount, plan)
6231 rajveer 3611
    recharge_order.spiceTID = spiceTID
3612
    recharge_order.responseTimestamp = datetime.datetime.now()
3613
    recharge_order.description = description
3614
    session.commit()
6092 rajveer 3615
    if retCode == '00' and retStatus == 'S':
3616
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
3617
        session.commit()
3618
        return True
6259 rajveer 3619
    elif retCode in ('STO', 'US', 'UP') and retStatus == 'S':
6231 rajveer 3620
        raise TransactionServiceException(111, "No response from operator within specified time")
6092 rajveer 3621
    else:
3622
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
6265 rajveer 3623
        if retCode in ('SVAI', 'SVIA', 'AI', 'IA', 'EAI', 'SVEAI'):
3624
            recharge_order.description = "Invalid Amount"
3625
        elif retCode in ('ECL', 'SVECL', 'SCL'):
3626
            recharge_order.description = "Customer Exceeded Daily Limit"
3627
        elif retCode in ('CI', 'ECI', 'ESP', 'SVCI', 'SVECI', 'SVESP', 'SV_ECI', 'SV ECI'):
6399 rajveer 3628
            recharge_order.description = "Invalid Device Number"
6092 rajveer 3629
        session.commit()
6048 rajveer 3630
        return False
6031 rajveer 3631
 
6092 rajveer 3632
 
6031 rajveer 3633
def get_user_wallet(userId):
3634
    wallet = UserWallet.get_by(userId = userId)
3635
    if not wallet:
3636
        wallet = UserWallet()
3637
        wallet.amount = 0
3638
        wallet.userId = userId
3639
    return wallet
3640
 
3641
def get_user_wallet_history(userId):
3642
    wallet = get_user_wallet(userId)
3643
    if wallet.id:
3644
        return UserWalletHistory.query.filter_by(wallet = wallet).all()
3645
    else:
3646
        return []
3647
 
6125 rajveer 3648
def get_provider(providerId):
3649
    return ServiceProvider.query.filter_by(id = providerId).one()
3650
 
6048 rajveer 3651
def get_provider_code(providerId):
3652
    return ServiceProvider.query.filter_by(id = providerId).one().code
6031 rajveer 3653
 
6310 anupam.sin 3654
def get_provider_by_code(providerCode):
3655
    return ServiceProvider.query.filter_by(code = providerCode).one()
6049 rajveer 3656
 
6206 rajveer 3657
def get_service_providers(recharge_type, only_active):
3658
    query = ServiceProvider.query.filter_by(type = recharge_type)
3659
    if only_active:
3660
        query = query.filter_by(status = only_active)
3661
    providers = query.all()
6048 rajveer 3662
    serviceProviders = {}
3663
    for provider in providers:
3664
        serviceProviders[provider.id] = provider.name
3665
    return serviceProviders
3666
 
6049 rajveer 3667
def get_service_provider_for_device(rechargeType, deviceNumber):
3668
    if rechargeType == RechargeType.MOBILE:
3669
        serviceType = 'MTP'
3670
    if rechargeType == RechargeType.DTH:
3671
        serviceType = 'RCH'
6048 rajveer 3672
 
6313 anupam.sin 3673
    provider = None
6537 rajveer 3674
    try:   
3675
        l = len(deviceNumber) 
3676
        if l < 10:
3677
            deviceNumber = deviceNumber + "0" * (10-l) 
6235 rajveer 3678
        providerCode, operatorCircle = RechargeService.checkServiceProviderApi(serviceType, deviceNumber)
6092 rajveer 3679
        if providerCode == 'SNS' or providerCode == '':
3680
            providerId = 0
3681
        else:
6310 anupam.sin 3682
            provider = get_provider_by_code(providerCode)
3683
            providerId = provider.id
6049 rajveer 3684
    except:
6092 rajveer 3685
        providerId = -1
6643 rajveer 3686
        operatorCircle = ""
6092 rajveer 3687
 
6289 anupam.sin 3688
    deviceNumberInfo = DeviceNumberInfo()
6336 anupam.sin 3689
    deviceNumberInfo.circleCode = operatorCircle
6289 anupam.sin 3690
    deviceNumberInfo.operatorId = providerId
6313 anupam.sin 3691
    if provider:
3692
        deviceNumberInfo.operatorName = provider.name
6289 anupam.sin 3693
    return deviceNumberInfo
6269 rajveer 3694
 
6591 anupam.sin 3695
def validate_recharge(rechargeType, deviceNumber, userSelectedProviderId, clientAddress):
3696
 
3697
    addressComponents = clientAddress.split('.')
3698
    n = 3
3699
    addressNumber = 0
3700
    for addressComponent in addressComponents :
3701
        addressNumber = addressNumber + (int(addressComponent) * pow(256, n))
3702
        n = n-1
3703
    matchingRow = BlockedIpRange.query.filter(BlockedIpRange.start <= addressNumber).filter(BlockedIpRange.end >= addressNumber).first()
3704
    #if a match is found then check if date has expired.
3705
    if matchingRow :
3706
        #if expiredOn is None that means this range is permanently blocked.
3707
        if matchingRow.expiredOn is None:
3708
            deniedIpAddress = DeniedIpAddress()
3709
            deniedIpAddress.ip = clientAddress
3710
            deniedIpAddress.deniedOn = datetime.datetime.now()
3711
            deniedIpAddress.deviceNumber = deviceNumber
3712
            deniedIpAddress.rechargeType = rechargeType
3713
            session.commit()
3714
            return "Oops! There seems to be a problem. Please try after some time."
3715
        else :
3716
            #if expired is not None and the blockage is still not expired then block the ip.
3717
            if matchingRow.expiredOn > datetime.datetime.now():
3718
                deniedIpAddress = DeniedIpAddress()
3719
                deniedIpAddress.ip = clientAddress
3720
                deniedIpAddress.deniedOn = datetime.datetime.now()
3721
                deniedIpAddress.deviceNumber = deviceNumber
3722
                deniedIpAddress.rechargeType = rechargeType
3723
                session.commit()
3724
                return "Oops! There seems to be a problem. Please try after some time."
3725
 
3726
 
6307 anupam.sin 3727
    deviceNumberInfo = get_service_provider_for_device(rechargeType, deviceNumber)
3728
    if deviceNumberInfo.operatorId == -1:
3729
        return "Oops! There seems to be a problem. Please try after some time."
6336 anupam.sin 3730
    circle = TelecomCircle.query.filter_by(code = deviceNumberInfo.circleCode).first()
6313 anupam.sin 3731
    if circle:
3732
        if not ServiceAvailability.query.filter_by(circleId = circle.id).filter_by(operatorId = userSelectedProviderId).first().isServiceAvailable :
3733
            if deviceNumberInfo.operatorName :
6314 anupam.sin 3734
                if circle.id == 8:
3735
                    return "We currently do not provide this service in J&K. We regret the inconvenience."
3736
                else :
3737
                    return "We are facing technical issues with " + deviceNumberInfo.operatorName + " in " + circle.name + " currently. Please try later." 
6316 anupam.sin 3738
            else :
6314 anupam.sin 3739
                return "We are facing technical issues with this operator in " + circle.name + " currently. Please try later." 
6271 rajveer 3740
    allcounts, successcounts  = get_previous_transactions(rechargeType, deviceNumber)
6269 rajveer 3741
    if allcounts >= 15 or successcounts >= 5:
3742
        return "You have exceeded daily limit for this mobile number."
3743
    return "SUCCESS"
6049 rajveer 3744
 
6271 rajveer 3745
def get_previous_transactions(rechargeType, deviceNumber):
3746
    limittime = datetime.datetime.now() - datetime.timedelta(hours=24)
3747
    if rechargeType == RechargeType.MOBILE:
3748
        allcounts = session.query(func.count(MobileRechargeOrder.mobileNumber)).filter(MobileRechargeOrder.mobileNumber == deviceNumber).filter(MobileRechargeOrder.creationTimestamp  > limittime).scalar()
3749
        successcounts = session.query(func.count(MobileRechargeOrder.mobileNumber)).filter(MobileRechargeOrder.mobileNumber == deviceNumber).filter(MobileRechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).filter(MobileRechargeOrder.creationTimestamp > limittime).scalar()
3750
    else:
3751
        allcounts = session.query(func.count(DTHRechargeOrder.dthAccountNumber)).filter(DTHRechargeOrder.dthAccountNumber == deviceNumber).filter(MobileRechargeOrder.creationTimestamp  > limittime).scalar()
3752
        successcounts = session.query(func.count(DTHRechargeOrder.dthAccountNumber)).filter(DTHRechargeOrder.dthAccountNumber == deviceNumber).filter(DTHRechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).filter(MobileRechargeOrder.creationTimestamp > limittime).scalar()
6269 rajveer 3753
    return allcounts, successcounts    
3754
 
6031 rajveer 3755
def update_amount_in_wallet(userId, amount, orderId):
3756
    if amount == 0:
3757
        return
3758
    wallet = get_user_wallet(userId)
3759
    wallet.amount = wallet.amount + amount
3760
 
3761
    history = UserWalletHistory()
3762
    history.amount = amount
3763
    history.orderId = orderId
3764
    history.wallet = wallet
3765
    history.timestamp = datetime.datetime.now()
3766
    session.commit()
6056 amit.gupta 3767
 
6094 rajveer 3768
def get_recharge_orders_for_device(deviceNumber):
3769
    orders = MobileRechargeOrder.query.filter_by(mobileNumber = deviceNumber).all()
3770
    if orders is None:
3771
        orders = DTHRechargeOrder.query.filter_by(dthAccountNumber = deviceNumber).all()
3772
    return orders
3773
 
6154 rajveer 3774
def get_recharge_orders_for_status(status):
3775
    if status == -1:
6161 rajveer 3776
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).all()
6154 rajveer 3777
    else:
6161 rajveer 3778
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = status).all()
6154 rajveer 3779
    return orders
3780
 
6188 rajveer 3781
def get_recharge_statistics():
3782
    rs = RechargeStatistics()
3783
    statusCounts = {}
3784
    operatorCounts = {}
3785
    currentOrders = {}
3786
    amounts = {}
3787
 
3788
    sorders = session.query(RechargeOrder.status, func.count(RechargeOrder.status)).group_by(RechargeOrder.status).all()
3789
    for sorder in sorders:
6190 rajveer 3790
        statusCounts[sorder[0]] = sorder[1]
6188 rajveer 3791
 
3792
    oorders = session.query(MobileRechargeOrder.mobileOperatorId, func.count(MobileRechargeOrder.mobileOperatorId)).group_by(MobileRechargeOrder.mobileOperatorId).all()
3793
    for oorder in oorders:
6190 rajveer 3794
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 3795
 
3796
    oorders = session.query(DTHRechargeOrder.dthOperatorId, func.count(DTHRechargeOrder.dthOperatorId)).group_by(DTHRechargeOrder.dthOperatorId).all()
3797
    for oorder in oorders:
6190 rajveer 3798
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 3799
 
6219 rajveer 3800
    forders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED).limit(20).all()
6188 rajveer 3801
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED)] = [order.to_thrift_object() for order in forders]
3802
    sorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_SUCCESSFUL).limit(20).all()
6197 rajveer 3803
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_SUCCESSFUL)] = [order.to_thrift_object() for order in sorders]
6216 rajveer 3804
    porders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.PAYMENT_SUCCESSFUL).limit(20).all()
3805
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.PAYMENT_SUCCESSFUL)] = [order.to_thrift_object() for order in porders]
6238 rajveer 3806
    rorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).limit(20).all()
3807
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)] = [order.to_thrift_object() for order in rorders]
6188 rajveer 3808
 
6190 rajveer 3809
    twa = session.query(func.sum(UserWallet.amount)).one()
3810
    tra = session.query(func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
3811
    gwa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId > 100000).one()
6278 rajveer 3812
    #tpa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId < 100000).one()
6482 rajveer 3813
    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()
3814
    tda = session.query(func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
3815
 
6346 rajveer 3816
    balance = RechargeService.getBalance()
6305 rajveer 3817
    amounts['(a) Total Payment Amount'] = tpa[0]
3818
    amounts['(b) Gift Wallet Amount'] = gwa[0]
3819
    amounts['(c) Total Wallet Amount'] = twa[0]
3820
    amounts['(d) Total Recharge Amount'] = tra[0]
3821
    amounts['(e) Account Balance'] = balance
6482 rajveer 3822
    amounts['(f) Discount Balance'] = tda[0]
6278 rajveer 3823
    #amounts['Total Payment Amount'] = tra[0] + twa[0] - gwa[0]
6524 rajveer 3824
    amounts['Saholic Mismatch = (a+b+f-c-d)'] = tpa[0] + gwa[0] + tda[0] - tra[0] - (twa[0] + 63774)
3825
    amounts['SpiceDeck Mismatch = (d-e)'] = tra[0] + balance - 750000 
6278 rajveer 3826
 
6337 rajveer 3827
    '''
6318 rajveer 3828
    if amounts['SpiceDeck Mismatch = (d-e)'] != -739:
3829
        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)']), "", [], [], [])
3830
    if amounts['Saholic Mismatch = (a+b-c-d)'] != -1919:
3831
        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 3832
    '''
6318 rajveer 3833
 
6188 rajveer 3834
    rs.statusCounts = statusCounts
3835
    rs.operatorCounts = operatorCounts    
3836
    rs.currentOrders = currentOrders
3837
    rs.amounts = amounts
3838
 
3839
    return rs
3840
 
3841
 
6159 rajveer 3842
def get_plans_for_operator(operator_id):
3843
    return RechargePlan.query.filter_by(operatorId = operator_id).all()
3844
 
6056 amit.gupta 3845
def get_recharge_orders_for_transaction(txId):
3846
    return RechargeOrder.query.filter_by(transaction_id = txId).first()
6102 rajveer 3847
 
6285 rajveer 3848
def enqueue_recharge_info_email(recharge_order, gvs={}):
6102 rajveer 3849
    status = ""
3850
    message = ""
3851
    html_header = """
3852
 
3853
    <html>
3854
    <body>
3855
    <div>
3856
        <p>
3857
            Hello $email,<br /><br />
6127 rajveer 3858
            Thanks for placing recharge order with us. Following are the details of your recharge order:
6102 rajveer 3859
        </p>
3860
        <div>
6136 rajveer 3861
            Order Id : $order_id <br/>
3862
            Order Date : $order_date <br/>
3863
            Order Amount : Rs. $order_amount <br/>
3864
            Order Status : $order_status <br/>
3865
            Device Number : $device_number <br/>
3866
            Service Provider : $service_provider <br/>
6102 rajveer 3867
        </div>
6348 rajveer 3868
    <br />
6102 rajveer 3869
    """
6288 rajveer 3870
 
3871
    FailureReasonMap = {}
3872
    FailureReasonMap["Invalid Amount"] = "the amount you tried seems to be invalid. Please try another amount."
3873
    FailureReasonMap["Customer Exceeded Daily Limit"] = "you have exceeded daily recharge limit for this number. Please try after 12 hours."
6399 rajveer 3874
    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 3875
 
3876
    failureReason = FailureReasonMap.get(recharge_order.description)
3877
    if failureReason is None:
3878
        failureReason = "of network failure."
6102 rajveer 3879
    if recharge_order.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3880
        status = "Recharge Successful"
3881
        message = ""
6444 rajveer 3882
        if recharge_order.couponAmount > 0:
3883
            message = message + "<b>You have used coupon " + recharge_order.couponCode + " and got discount of Rs. " + str(recharge_order.couponAmount) + ".</b>" 
3884
 
6102 rajveer 3885
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED:
3886
        status = "Recharge Failed"
6127 rajveer 3887
        message = """
6288 rajveer 3888
                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 3889
                """
6206 rajveer 3890
    elif recharge_order.status == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6102 rajveer 3891
        status = "Recharge Under Process"
6127 rajveer 3892
        message = """
6288 rajveer 3893
                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 3894
                """
6279 rajveer 3895
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3896
        status = "Recharge Failed, Amount Refunded"
3897
        message = """
3898
                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>
3899
                """
6285 rajveer 3900
    if len(gvs) > 0:
6340 rajveer 3901
        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 3902
        message = message + " <br />  <b>Voucher Code &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Amount</b>"
6285 rajveer 3903
        for gv in gvs.keys():
3904
            gvAmount = gvs.get(gv)
6330 rajveer 3905
            message = message + " <br />  <b>" + gv + "&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Rs. "  + str(gvAmount) + "</b>"
6285 rajveer 3906
 
6114 rajveer 3907
    message = message  + '<br />  In case of any problem, please  <a href="$source_url/contact-us">contact us</a>'
6102 rajveer 3908
 
6136 rajveer 3909
    html_header = html_header + message
6102 rajveer 3910
    html_footer = """
3911
    <p>
3912
        Best Wishes,<br />
3913
        $source_name Team
3914
    </p>
3915
    </div>
3916
    </body>
3917
    </html>
3918
    """
3919
 
6125 rajveer 3920
    if isinstance(recharge_order, MobileRechargeOrder):
3921
        deviceNumber = recharge_order.mobileNumber
3922
        providerName = get_provider(recharge_order.mobileOperatorId).name
3923
    if isinstance(recharge_order, DTHRechargeOrder):
3924
        deviceNumber = recharge_order.dthAccountNumber
3925
        providerName = get_provider(recharge_order.dthOperatorId).name
3926
 
6127 rajveer 3927
    display_order_id = recharge_order.idPrefix + str(recharge_order.id)
6102 rajveer 3928
    email = recharge_order.userEmailId
3929
    dt = datetime.datetime.strptime(str(recharge_order.creationTimestamp), "%Y-%m-%d %H:%M:%S")
3930
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
3931
 
6288 rajveer 3932
    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 3933
    email_footer = Template(html_footer).substitute(dict(source_url = source_url, source_name = source_name))
3934
 
3935
    try:
3936
        helper_client = HelperClient().get_client()
6643 rajveer 3937
        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 3938
        return True
3939
    except Exception as e:
3940
        print e
3941
        return False
3942
 
6307 anupam.sin 3943
def get_recharge_denominations(operator_id, circleCode, denomination_type):
3944
    circle_id = TelecomCircle.query.filter_by(code = circleCode).first().id
6289 anupam.sin 3945
    return RechargeDenomination.query.filter_by(operatorId = operator_id).filter_by(circleId = circle_id).filter_by(denominationType = denomination_type).all()
6371 rajveer 3946
 
3947
def update_availability_status(operatorId, circleId, isAvailable):
3948
    serviceAvailability = ServiceAvailability.query.filter_by(circleId = circleId).filter_by(operatorId = operatorId).first()
3949
    serviceAvailability.isServiceAvailable = isAvailable
3950
    session.commit()
3951
 
6389 rajveer 3952
def get_misc_charges(transactionId):
3953
    retCharges = {}
3954
    miscCharges = MiscCharges.get_by(transaction_id = transactionId)
3955
    if miscCharges:
6426 rajveer 3956
        retCharges[1] = miscCharges.chargeAmount 
6389 rajveer 3957
    return retCharges
6396 amit.gupta 3958
 
3959
def get_available_emi_schemes():
3960
    t_emi_schemes = []
3961
    emi_schemes = EmiScheme.query.all()
3962
    if emi_schemes:
3963
        t_emi_schemes = [to_t_emi_scheme(emi_scheme) for emi_scheme in emi_schemes]
3964
    return t_emi_schemes
6389 rajveer 3965
 
6507 anupam.sin 3966
def refund_recharge_order(rechargeOrderId):
3967
    try :
3968
        rechargeOrder = RechargeOrder.query.filter_by(id = rechargeOrderId).first()
3969
        wallet = UserWallet.query.filter_by(userId = rechargeOrder.userId).first()
3970
    except:
3971
        return False
3972
 
3973
    paidAmount = rechargeOrder.totalAmount - rechargeOrder.walletAmount - rechargeOrder.couponAmount
3974
    amountToRefund = 0
3975
    status = None
3976
    if (paidAmount <= wallet.amount) :
3977
        amountToRefund = paidAmount
3978
        status = RechargeOrderStatus.REFUNDED
3979
    else :
3980
        amountToRefund = wallet.amount
3981
        status = RechargeOrderStatus.PARTIALLY_REFUNDED
3982
 
3983
    update_amount_in_wallet(rechargeOrder.userId, -amountToRefund, rechargeOrderId)
3984
 
3985
    try:    
3986
        pc = PaymentClient().get_client()
3987
        if pc.refundPayment(rechargeOrder.transaction_id, amountToRefund, True) :
3988
            rechargeOrder.status = status
6515 anupam.sin 3989
            rechargeOrder.refundTimestamp = datetime.datetime.now()
6507 anupam.sin 3990
            session.commit()
3991
            return True
3992
        else :
3993
            update_amount_in_wallet(rechargeOrder.userId, amountToRefund, rechargeOrderId)
3994
 
3995
    except:
3996
        update_amount_in_wallet(rechargeOrder.userId, amountToRefund, rechargeOrderId)
3997
 
3998
    return False 
3999
 
4000
 
766 rajveer 4001
def close_session():
4002
    if session.is_active:
4003
        print "session is active. closing it."
2783 chandransh 4004
        session.close()
3376 rajveer 4005
 
4006
def is_alive():
4007
    try:
4008
        session.query(Transaction.id).limit(1).one()
4009
        return True
4010
    except:
6000 mandeep.dh 4011
        return False
4012
 
4013
if __name__ == '__main__':
4014
    print 'Inside main'
4015
    DataService.initialize()
6561 amit.gupta 4016
    '''a = MobileRechargeOrder()
4017
    session.commit()
6000 mandeep.dh 4018
    a.mobileNumber = 89564785666
6567 amit.gupta 4019
    session.commit()
4020
    '''