Subversion Repositories SmartDukaan

Rev

Rev 6715 | Rev 6718 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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