Subversion Repositories SmartDukaan

Rev

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