Subversion Repositories SmartDukaan

Rev

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