Subversion Repositories SmartDukaan

Rev

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