Subversion Repositories SmartDukaan

Rev

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