Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
6903 anupam.sin 1
# -*- coding: utf-8 -*-
2
 
104 ashish 3
'''
4
Created on 29-Mar-2010
5
 
2536 chandransh 6
@author: Chandranshu
104 ashish 7
'''
2536 chandransh 8
 
4369 rajveer 9
from datetime import date, timedelta
7151 amit.gupta 10
from decimal import Decimal
11
from elixir import *
6424 rajveer 12
from math import ceil
5944 mandeep.dh 13
from random import randrange
7151 amit.gupta 14
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY
15
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
3499 mandeep.dh 16
from reportlab.lib.units import inch
2536 chandransh 17
from reportlab.pdfgen.canvas import Canvas
6980 anupam.sin 18
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, \
19
    BaseDocTemplate, Frame, PageTemplate
7151 amit.gupta 20
from reportlab.rl_config import defaultPageSize
5944 mandeep.dh 21
from shop2020.clients.AlertClient import AlertClient
3499 mandeep.dh 22
from shop2020.clients.CatalogClient import CatalogClient
23
from shop2020.clients.HelperClient import HelperClient
5944 mandeep.dh 24
from shop2020.clients.InventoryClient import InventoryClient
3499 mandeep.dh 25
from shop2020.clients.LogisticsClient import LogisticsClient
2747 chandransh 26
from shop2020.clients.PaymentClient import PaymentClient
7151 amit.gupta 27
from shop2020.clients.PromotionClient import PromotionClient
3499 mandeep.dh 28
from shop2020.clients.UserClient import UserClient
29
from shop2020.clients.WarehouseClient import WarehouseClient
7151 amit.gupta 30
from shop2020.config.client.ConfigClient import ConfigClient
3499 mandeep.dh 31
from shop2020.model.v1 import order
6048 rajveer 32
from shop2020.model.v1.order.impl import DataService, RechargeService
7198 amar.kumar 33
from shop2020.model.v1.order.impl.Convertors import to_t_emi_scheme, to_t_order
3499 mandeep.dh 34
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem, \
4435 mandeep.dh 35
    Order, BatchNoGenerator, InvoiceIDGenerator, TransactionRequiringExtraProcessing, \
5348 anupam.sin 36
    OrderInventory, Alert, PaymentSettlement, EBSSettlementSummary, \
7151 amit.gupta 37
    CodVerificationAgent, Attribute, RechargeVoucherTracker, EmiScheme, MiscCharges, \
38
    BlockedIpRange, DeniedIpAddress, InsuranceDetailForOrder, DocumentStore, \
39
    RechargeTransaction, HotspotStore, WalletForCompany, WalletHistoryForCompany, \
7285 rajveer 40
    FRC, OperatorSeries, SourceDetail, Company
7151 amit.gupta 41
from shop2020.model.v1.order.impl.model.BaseOrder import BaseOrder
42
from shop2020.model.v1.order.impl.model.DTHRechargeOrder import DTHRechargeOrder
6000 mandeep.dh 43
from shop2020.model.v1.order.impl.model.MobileRechargeOrder import \
44
    MobileRechargeOrder
7151 amit.gupta 45
from shop2020.model.v1.order.impl.model.RechargeDenomination import \
46
    RechargeDenomination
47
from shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrder
48
from shop2020.model.v1.order.impl.model.RechargePlan import RechargePlan
2687 chandransh 49
from shop2020.model.v1.order.impl.model.ReturnOrder import ReturnOrder
7151 amit.gupta 50
from shop2020.model.v1.order.impl.model.ServiceAvailability import \
51
    ServiceAvailability
52
from shop2020.model.v1.order.impl.model.ServiceProvider import ServiceProvider
53
from shop2020.model.v1.order.impl.model.TelecomCircle import TelecomCircle
54
from shop2020.model.v1.order.impl.model.UserWallet import UserWallet
55
from shop2020.model.v1.order.impl.model.UserWalletHistory import \
56
    UserWalletHistory
5944 mandeep.dh 57
from shop2020.thriftpy.alert.ttypes import MonitoredEntity, EntityType
5527 anupam.sin 58
from shop2020.thriftpy.logistics.ttypes import DeliveryType, PickUpType
6000 mandeep.dh 59
from shop2020.thriftpy.model.v1.catalog.ttypes import ItemType
5944 mandeep.dh 60
from shop2020.thriftpy.model.v1.inventory.ttypes import BillingType, \
61
    InventoryServiceException, WarehouseType, InventoryType
4435 mandeep.dh 62
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
63
    TransactionStatus, OrderStatus, DelayReason, ExtraTransactionProcessingType, \
7151 amit.gupta 64
    HotspotAction, TimeoutSummary, OrderStatusGroups, OrderType, RechargeOrderStatus, \
7293 anupam.sin 65
    RechargeType, RechargeStatistics, DeviceNumberInfo, EmiChargeType, PayMethod, OrderSource
5944 mandeep.dh 66
from shop2020.thriftpy.model.v1.user.ttypes import VoucherType
4421 mandeep.dh 67
from shop2020.thriftpy.payments.ttypes import PaymentException
5110 mandeep.dh 68
from shop2020.thriftpy.warehouse.ttypes import ScanType, \
69
    WarehouseServiceException
6000 mandeep.dh 70
from shop2020.utils.EmailAttachmentSender import mail, get_attachment_part
855 rajveer 71
from shop2020.utils.Utils import to_py_date, to_java_date
4008 mandeep.dh 72
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
3499 mandeep.dh 73
from sqlalchemy.sql import func
7151 amit.gupta 74
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
75
    between
3499 mandeep.dh 76
from string import Template
77
from textwrap import dedent
78
import datetime
5944 mandeep.dh 79
import httplib
3499 mandeep.dh 80
import logging
81
import os
4421 mandeep.dh 82
import sys
4435 mandeep.dh 83
import time
4421 mandeep.dh 84
import traceback
5806 rajveer 85
import urllib
7308 rajveer 86
import base64
6307 anupam.sin 87
 
5944 mandeep.dh 88
 
3499 mandeep.dh 89
logging.basicConfig(level=logging.DEBUG)
104 ashish 90
 
5966 rajveer 91
sourceId = int(ConfigClient().get_property("sourceid"))
92
mail_user = 'cnc.center@shop2020.in'
93
mail_password = '5h0p2o2o'
94
help_user = 'help@shop2020.in'
95
help_password = '5h0p2o2o'
6029 rajveer 96
source_url = 'www.saholic.com'
97
source_name = 'Saholic'
3499 mandeep.dh 98
 
4763 rajveer 99
PREPAID_SHIPPING_CUTOFF_TIME = 15
4019 chandransh 100
COD_SHIPPING_CUTOFF_TIME = 12
3499 mandeep.dh 101
 
2819 chandransh 102
PAGE_HEIGHT=defaultPageSize[1]
103
PAGE_WIDTH=defaultPageSize[0]
104
 
4763 rajveer 105
billedOrdersColorMap = {}
106
 
3499 mandeep.dh 107
ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT = {
4873 mandeep.dh 108
        OrderStatus.RTO_RESHIPPED    :  3,
109
        OrderStatus.RTO_IN_TRANSIT   : -5,
110
        OrderStatus.DELIVERY_SUCCESS :  1,
111
        OrderStatus.DOA_CERT_INVALID : -5
3499 mandeep.dh 112
}
113
 
5783 rajveer 114
delhi_pincodes = ['110001','110002','110003','110004','110005','110006','110007','110008','110009','110010','110011','110012','110013','110014','110015',\
115
                '110016','110017','110018','110019','110020','110021','110022','110023','110024','110025','110026','110027','110028','110029','110030',\
116
                '110031','110032','110033','110034','110035','110037','110038','110041','110042','110044','110045','110046','110047','110048','110049',\
117
                '110051','110052','110053','110054','110055','110056','110057','110058','110059','110060','110061','110062','110063','110064','110065',\
118
                '110066','110067','110068','110070','110071','110074','110075','110076','110078','110081','110082','110083','110084','110085','110086',\
119
                '110087','110088','110089','110091','110092','110093','110094','110095','110096','110101','110103','110104','110105','110106','110107',\
120
                '110108','110109','110110','110112','110113','110114','110115','110116','110117','110118','110119','110120','110122','110124','110125',\
121
                '110301','110302','110501','110502','110503','110504','110505','110510','110511','110512','110601','110602','110603','110604','110605',\
122
                '110606','110607','110608','110609']
123
 
104 ashish 124
def get_new_transaction():
125
    transaction = Transaction()
126
    transaction.createdOn = datetime.datetime.now()
738 chandransh 127
    transaction.status = TransactionStatus.INIT
104 ashish 128
    transaction.status_message = "New transaction"
483 rajveer 129
    return transaction
130
 
131
def create_order(t_order):
132
    order = Order()
133
    if t_order.warehouse_id:
134
        order.warehouse_id = t_order.warehouse_id
509 rajveer 135
    if t_order.logistics_provider_id:    
483 rajveer 136
        order.logistics_provider_id = t_order.logistics_provider_id
137
        order.airwaybill_no = t_order.airwaybill_no
138
        order.tracking_id = t_order.tracking_id
4009 chandransh 139
    if t_order.expected_shipping_time:
4019 chandransh 140
        order.expected_shipping_time = to_py_date(t_order.expected_shipping_time).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 141
        order.promised_shipping_time = order.expected_shipping_time
4009 chandransh 142
    if t_order.expected_delivery_time:
483 rajveer 143
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
4102 chandransh 144
        order.promised_delivery_time = order.expected_delivery_time
483 rajveer 145
    if t_order.customer_id:    
146
        order.customer_id = t_order.customer_id
147
        order.customer_name = t_order.customer_name
860 rajveer 148
        order.customer_city = t_order.customer_city
149
        order.customer_state = t_order.customer_state
483 rajveer 150
        order.customer_mobilenumber = t_order.customer_mobilenumber
151
        order.customer_pincode = t_order.customer_pincode
738 chandransh 152
        order.customer_address1 = t_order.customer_address1
153
        order.customer_address2 = t_order.customer_address2
483 rajveer 154
        order.customer_email = t_order.customer_email
155
    #new status and status description to be added    
716 rajveer 156
    order.status = t_order.status  
483 rajveer 157
    order.statusDescription = t_order.statusDescription
158
    order.total_amount = t_order.total_amount
6318 rajveer 159
    order.gvAmount = t_order.gvAmount
483 rajveer 160
    order.total_weight = t_order.total_weight
161
    if t_order.created_timestamp:
162
        order.created_timestamp = to_py_date(t_order.created_timestamp)
163
    else:
685 chandransh 164
        order.created_timestamp = datetime.datetime.now()
5555 rajveer 165
    order.pickupStoreId = t_order.pickupStoreId
7033 anupam.sin 166
    if t_order.insurer:
167
        order.insurer = t_order.insurer
168
        order.insuranceAmount = t_order.insuranceAmount
6903 anupam.sin 169
    if order.insurer > 0:
170
        insuranceDetail = InsuranceDetailForOrder()
171
        insuranceDetail.dob = t_order.dob
172
        insuranceDetail.guardianName = t_order.guardianName
173
        insuranceDetail.order = order
7190 amar.kumar 174
    if t_order.freebieItemId:
175
        order.freebieItemId = t_order.freebieItemId
7293 anupam.sin 176
    order.source = t_order.source
177
    order.advanceAmount = t_order.advanceAmount
178
    order.storeId = t_order.storeId
483 rajveer 179
    return order
180
 
181
def create_transaction(t_transaction):
182
    t_orders = t_transaction.orders
183
    if not t_orders:
184
        raise TransactionServiceException(101, "Orders missing from the transaction")
185
    transaction = get_new_transaction()
186
    transaction.customer_id = t_transaction.customer_id 
187
    transaction.shopping_cart_id = t_transaction.shoppingCartid
2219 varun.gupt 188
    transaction.coupon_code = t_transaction.coupon_code
2815 vikas 189
    transaction.session_source = t_transaction.sessionSource
190
    transaction.session_start_time = to_py_date(t_transaction.sessionStartTime)
3858 vikas 191
    transaction.first_source = t_transaction.firstSource
192
    transaction.first_source_start_time = to_py_date(t_transaction.firstSourceTime)
483 rajveer 193
 
6389 rajveer 194
    totalAmount = 0
483 rajveer 195
    for t_order in t_orders:
196
        order = create_order(t_order)
6389 rajveer 197
        totalAmount = totalAmount + order.total_amount
483 rajveer 198
        order.transaction = transaction 
199
        for line_item in t_order.lineitems:
200
            litem = LineItem()
716 rajveer 201
            litem.item_id = line_item.item_id
963 chandransh 202
            litem.productGroup = line_item.productGroup
483 rajveer 203
            litem.brand = line_item.brand
204
            if line_item.model_number:
205
                litem.model_number = line_item.model_number
206
            if line_item.model_name:    
207
                litem.model_name = line_item.model_name
908 chandransh 208
            if line_item.color:
209
                litem.color = line_item.color
483 rajveer 210
            if line_item.extra_info:
211
                litem.extra_info = line_item.extra_info
212
            litem.quantity = line_item.quantity
213
            litem.unit_price = line_item.unit_price
214
            litem.unit_weight = line_item.unit_weight
215
            litem.total_price = line_item.total_price
216
            litem.total_weight = line_item.total_weight
4283 anupam.sin 217
            '''litem.transfer_price = line_item.transfer_price'''
4172 rajveer 218
            litem.dealText = line_item.dealText
4295 varun.gupt 219
            litem.warranty_expiry_timestamp = to_py_date(line_item.warrantry_expiry_timestamp)
1976 varun.gupt 220
 
483 rajveer 221
            """
222
            if line_item.addedOn:
223
                litem.added_on = to_py_date(line_item.addedOn)
224
            else:
225
                litem.added_on = datetime.datetime.now()
226
            """
227
            litem.order = order
228
    session.commit()
6389 rajveer 229
 
230
    generateOtherCharges(transaction, t_transaction.emiSchemeId, totalAmount)
231
 
483 rajveer 232
    return transaction.id
233
 
6389 rajveer 234
def generateOtherCharges(transaction, emiSchemeId, totalAmount):
235
    emiScheme = EmiScheme.get_by(id=emiSchemeId)
236
    if not emiScheme:
237
        return
238
 
239
    if totalAmount < emiScheme.minAmount:
240
        return
241
 
242
    emiCharge = 0
243
    if emiScheme.chargeType == EmiChargeType.FIXED:
6424 rajveer 244
        emiCharge = ceil(emiScheme.chargeValue)
6389 rajveer 245
    if emiScheme.chargeType == EmiChargeType.PERCENTAGE:
6424 rajveer 246
        emiCharge = ceil(totalAmount*(emiScheme.chargeValue)/100)
6736 amit.gupta 247
 
248
    if transaction.coupon_code is not None and transaction.coupon_code != "":    
249
        try:
250
            promotion_client = PromotionClient().get_client()
251
            emis = promotion_client.getEmiDiscount(transaction.shopping_cart_id)
252
            if emis.has_key(emiSchemeId):
253
                discount = emis.get(emiSchemeId)
254
                if emiCharge > discount:
255
                    emiCharge -= discount
256
                else:
257
                    emiCharge = 0
258
        except:
259
            print "Could not get emi discounts from promotion"
260
 
6389 rajveer 261
    miscCharge = MiscCharges()
262
    miscCharge.transaction = transaction
263
    miscCharge.chargeType = 1 ##EMI charges
264
    miscCharge.chargeAmount = emiCharge
265
    session.commit()
266
 
483 rajveer 267
def get_transaction(transaction_id):
268
    transaction = Transaction.get_by(id=transaction_id)
269
    if not transaction:
270
        raise TransactionServiceException(108, "no such transaction")
271
 
272
    return transaction
273
 
274
def get_transactions_for_customer(customer_id, from_date, to_date, status):
275
    if not customer_id:
276
        raise TransactionServiceException(101, "bad customer id")
277
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 278
    if status is not None:
483 rajveer 279
        query = query.filter(Transaction.status == status)
280
    if from_date:
281
        query = query.filter(Transaction.createdOn >from_date)
282
    if to_date:
283
        query = query.filter(Transaction.createdOn < to_date)
284
    return query.all()
285
 
286
def get_transactions_for_shopping_cart_id(shopping_cart_id):
287
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
288
    return transactions
289
 
290
def get_transaction_status(transaction_id):
291
    if not transaction_id:
292
        raise TransactionServiceException(101, "bad transaction id")
293
 
294
    transaction = get_transaction(transaction_id)
295
 
296
    return transaction.status
297
 
7293 anupam.sin 298
def change_transaction_status(transaction_id, new_status, description, pickUp, orderType, source):
483 rajveer 299
    transaction = get_transaction(transaction_id)
300
    transaction.status = new_status
301
    transaction.status_message = description
5783 rajveer 302
    ## Assign runner in case of delhi pincodes
5784 rajveer 303
    if transaction.orders[0].pickupStoreId:
304
        logistics_client = LogisticsClient().get_client() 
305
        store = logistics_client.getPickupStore(transaction.orders[0].pickupStoreId)
306
        if delhi_pincodes.__contains__(store.pin):
5793 rajveer 307
            pickUp = PickUpType.RUNNER  
5783 rajveer 308
 
690 chandransh 309
    if new_status == TransactionStatus.FAILED:
310
        for order in transaction.orders:
311
            order.status = OrderStatus.PAYMENT_FAILED
2339 chandransh 312
            order.statusDescription = "Payment Failed"
4247 rajveer 313
    elif new_status == TransactionStatus.AUTHORIZED or new_status == TransactionStatus.FLAGGED:
690 chandransh 314
        for order in transaction.orders:
4247 rajveer 315
            if new_status == TransactionStatus.AUTHORIZED:
316
                order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
317
                order.statusDescription = "Submitted to warehouse"
318
            elif new_status == TransactionStatus.FLAGGED:
319
                order.status = OrderStatus.PAYMENT_FLAGGED
320
                order.statusDescription = "Payment flagged by gateway"
3092 chandransh 321
            order.cod = False
5527 anupam.sin 322
            order.orderType = orderType
743 rajveer 323
            #After we got payment success, we will set logistics info also 
324
            logistics_client = LogisticsClient().get_client()
325
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 326
            item_id = order.lineitems[0].item_id
5767 rajveer 327
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID, pickUp)
743 rajveer 328
 
1730 ankur.sing 329
            current_time = datetime.datetime.now()
330
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 331
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
6726 rajveer 332
            logistics_info.deliveryDelay = adjust_delivery_time(current_time, (logistics_info.shippingTime+logistics_info.deliveryDelay))
5110 mandeep.dh 333
 
6525 rajveer 334
            order.otg = logistics_info.otgAvailable
743 rajveer 335
            order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 336
            order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
743 rajveer 337
            order.logistics_provider_id = logistics_info.providerId
338
            order.airwaybill_no = logistics_info.airway_billno
339
            order.tracking_id = order.airwaybill_no
6726 rajveer 340
            order.courier_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryDelay)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4019 chandransh 341
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 342
            order.promised_shipping_time = order.expected_shipping_time
5165 rajveer 343
            order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3986 chandransh 344
            order.promised_delivery_time = order.expected_delivery_time 
871 chandransh 345
 
6718 rajveer 346
            if order.pickupStoreId:
347
                order.otg = False
348
 
5944 mandeep.dh 349
            inventory_client = InventoryClient().get_client()
5966 rajveer 350
            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 351
 
4316 anupam.sin 352
            try:
5944 mandeep.dh 353
                item_pricing = inventory_client.getItemPricing(item_id, -1)
4316 anupam.sin 354
                order.lineitems[0].transfer_price = item_pricing.transferPrice
6751 amar.kumar 355
                order.lineitems[0].nlc = item_pricing.nlc
4316 anupam.sin 356
            except:
357
                print "Not able to get transfer price. Skipping"
5944 mandeep.dh 358
 
359
            catalog_client = CatalogClient().get_client() 
5508 rajveer 360
            voucherAmount = catalog_client.getVoucherAmount(item_id, VoucherType.SPICEDECK_MOBILE)
361
            if voucherAmount:
5514 rajveer 362
                __create_recharge_voucher_tracker(order, voucherAmount, VoucherType.SPICEDECK_MOBILE)
5508 rajveer 363
 
3064 chandransh 364
    elif new_status == TransactionStatus.COD_IN_PROCESS:
365
        for order in transaction.orders:
4662 rajveer 366
            order.status = OrderStatus.COD_VERIFICATION_PENDING
3064 chandransh 367
            order.statusDescription = "Verification Pending"
368
            order.cod = True
5527 anupam.sin 369
            order.orderType = orderType
3064 chandransh 370
            #After we got payment success, we will set logistics info also 
371
            logistics_client = LogisticsClient().get_client()
372
            #FIXME line item is only one now. If multiple will come, need to fix.
373
            item_id = order.lineitems[0].item_id
5555 rajveer 374
            if order.pickupStoreId:
5885 mandeep.dh 375
                # Need to send prepaid awb number for store pick up orders
376
                logistics_info = logistics_client.getLogisticsEstimation(item_id, order.customer_pincode, DeliveryType.COD)
377
                prepaid_logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID, pickUp)
378
                logistics_info.airway_billno = prepaid_logistics_info.airway_billno
379
                logistics_info.providerId = prepaid_logistics_info.providerId
6525 rajveer 380
                # Will not provide OTG in pickup store
381
                order.otg = False
5555 rajveer 382
            else:
5767 rajveer 383
                logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.COD, pickUp)
6525 rajveer 384
                order.otg = logistics_info.otgAvailable
7293 anupam.sin 385
 
386
            if order.source == OrderSource.STORE:
387
                catalog_client = CatalogClient().get_client() 
388
                sourcePricing = catalog_client.getStorePricing(item_id)
389
                if order.total_amount > sourcePricing.maxPrice:
390
                    raise TransactionServiceException(199, "Order amount exceeded max price for item")
391
                elif order.total_amount > sourcePricing.minPrice:
392
                    order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
5885 mandeep.dh 393
 
3064 chandransh 394
            current_time = datetime.datetime.now()
395
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 396
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
6726 rajveer 397
            logistics_info.deliveryDelay = adjust_delivery_time(current_time, (logistics_info.shippingTime+logistics_info.deliveryDelay))
398
 
3064 chandransh 399
            order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 400
            order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
3064 chandransh 401
            order.logistics_provider_id = logistics_info.providerId
402
            order.airwaybill_no = logistics_info.airway_billno
403
            order.tracking_id = order.airwaybill_no
6726 rajveer 404
            order.courier_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryDelay)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4019 chandransh 405
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 406
            order.promised_shipping_time = order.expected_shipping_time
5165 rajveer 407
            order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3986 chandransh 408
            order.promised_delivery_time = order.expected_delivery_time
3064 chandransh 409
 
5944 mandeep.dh 410
            inventory_client = InventoryClient().get_client()
5966 rajveer 411
            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 412
 
4316 anupam.sin 413
            try:
5944 mandeep.dh 414
                item_pricing = inventory_client.getItemPricing(item_id, -1)
6751 amar.kumar 415
                order.lineitems[0].transfer_price = item_pricing.transferPrice
416
                order.lineitems[0].nlc = item_pricing.nlc        
4316 anupam.sin 417
            except:
418
                print "Not able to get transfer price. Skipping"
5508 rajveer 419
 
5944 mandeep.dh 420
            catalog_client = CatalogClient().get_client()
5508 rajveer 421
            voucherAmount = catalog_client.getVoucherAmount(item_id, VoucherType.SPICEDECK_MOBILE)
422
            if voucherAmount:
5514 rajveer 423
                __create_recharge_voucher_tracker(order, voucherAmount, VoucherType.SPICEDECK_MOBILE)
483 rajveer 424
    session.commit()
3499 mandeep.dh 425
 
3530 mandeep.dh 426
    try:
7308 rajveer 427
        if order.source == OrderSource.WEBSITE:    
428
            if new_status == TransactionStatus.COD_IN_PROCESS:
429
                transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
430
                transaction_requiring_extra_processing.category = 'COD_VERIFICATION'
431
                transaction_requiring_extra_processing.transaction_id = transaction_id
432
                session.commit()
433
            elif new_status == TransactionStatus.FLAGGED:
434
                transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
435
                transaction_requiring_extra_processing.category = 'PAYMENT_FLAGGED'
436
                transaction_requiring_extra_processing.transaction_id = transaction_id
437
                session.commit()
438
        elif order.source == OrderSource.STORE and order.status == OrderStatus.COD_VERIFICATION_PENDING:
439
            catalog_client = CatalogClient().get_client() 
440
            sourcePricing = catalog_client.getStorePricing(order.lineitems[0].item_id)
441
            content = "<html><body>"
442
            content += "<h2>Product:  " + str(order.lineitems[0]) + "</h2>"
443
            content += "<h2>Min Price: " +  str(sourcePricing.minPrice) + "</h2>"
444
            content += "<h2>Max Price: " +  str(sourcePricing.maxPrice) + "</h2>"
445
            content += "<h2>Recommended Price: " +  str(sourcePricing.recommendedPrice) + "</h2>"
446
            content += "<h2>Approval Requested for Price: " +  str(order.total_amount) + "</h2>"
447
            content += "<h3>Please click on link below to approve the order</h3>"
448
            content += "<a href='http://support.shop2020.in:8080/Support/price-approval?xszbg=" + base64.b64encode(str(order.id))  + "'>Click here for Approval</a>"
7310 rajveer 449
            content += "<br><br></body></html>"
7308 rajveer 450
            store = get_hotspot_store(order.storeId, "")
451
            helper_client = HelperClient().get_client()
452
            helper_client.saveUserEmailForSending(store.approvalEmail.split(';'), "", "Price approval requested for " + str(order.lineitems[0]) + " in store " + store.hotspotId , content, str(transaction_id), "PriceApproval", [], [])
453
 
3530 mandeep.dh 454
    except Exception as e:
4065 mandeep.dh 455
        print "Error inserting transaction Id: " + str(transaction_id) + " due to " + str(e)
3499 mandeep.dh 456
 
483 rajveer 457
    return True
458
 
5514 rajveer 459
def __create_recharge_voucher_tracker(order, amount, voucherType):
5508 rajveer 460
    rvt = RechargeVoucherTracker()
461
    rvt.order = order
462
    rvt.amount = amount
463
    rvt.voucherIssued = False
5514 rajveer 464
    rvt.voucherType = voucherType
5508 rajveer 465
 
3994 chandransh 466
def __get_holidays(start_time=0L, to_time=-1L):
467
    '''
468
    Get the list of all public holidays since start time including the
469
    day of start time if it's a holiday
470
    '''
471
    midnightTime = start_time.replace(hour=0, minute=0, second=0, microsecond=0)
1730 ankur.sing 472
    fromDate = to_java_date(midnightTime)
473
    logistics_client = LogisticsClient().get_client()
3994 chandransh 474
    #TODO: This list should be cached after the first call.
475
    #Calling logistics server is also unnecessary.
476
    holidays = logistics_client.getHolidays(fromDate, to_time)
477
    holidays = [to_py_date(holiday).date() for holiday in holidays]
478
    return holidays
479
 
480
def adjust_delivery_time(start_time, delivery_days):
481
    '''
482
    Returns the actual no. of days which will pass while 'delivery_days'
483
    no. of business days will pass since 'order_time'. 
484
    '''
485
    start_date = start_time.date()
486
    end_date = start_date + datetime.timedelta(days = delivery_days)
487
    holidays = __get_holidays(start_time)
1730 ankur.sing 488
 
3994 chandransh 489
    while start_date <= end_date:
490
        if start_date.weekday() == 6 or start_date in holidays:
1730 ankur.sing 491
            delivery_days = delivery_days + 1
3994 chandransh 492
            end_date = end_date + datetime.timedelta(days = 1)
4088 chandransh 493
        start_date = start_date + datetime.timedelta(days = 1)
3994 chandransh 494
 
1730 ankur.sing 495
    return delivery_days
496
 
6561 amit.gupta 497
def get_business_days_count(start_time, end_time):
498
    '''
499
    Returns business dates between two dates
500
    '''
501
    start_date = start_time.date()
502
    end_date  = end_time.date()
6669 amit.gupta 503
    diff = (end_date - start_date).days
6665 amit.gupta 504
    sundays = diff/7 + 1 if (start_date.weekday() + (diff%7) > 6) else diff/7 
6561 amit.gupta 505
    '''holidays = __get_holidays(start_time, end_time)'''
506
    logistics_client = LogisticsClient().get_client()
507
    #TODO: This list should be cached after the first call.
508
    #Calling logistics server is also unnecessary.
509
    holidays = logistics_client.getHolidays(to_java_date(start_time), to_java_date(end_time))
510
    non_business_days = len(holidays)
511
    for holiday in holidays:
6675 rajveer 512
        pyholiday = to_py_date(holiday).date()
513
        if pyholiday.weekday() == 6:
6561 amit.gupta 514
            sundays = sundays - 1
515
    return diff - (non_business_days + sundays)
516
 
517
 
1398 varun.gupt 518
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 519
    transaction = get_transaction(transaction_id)
6650 amit.gupta 520
    subject = source_name + " - Order Details"
521
    otgLink = ""
6660 amit.gupta 522
    inOrderOtg = "<div>On Time Guarantee<br><span style=color:red>We pay if we delay</span></div>"
6650 amit.gupta 523
    if len(transaction.orders) == 1:
524
        inOrderOtg = ""
525
        if transaction.orders[0].otg :
526
            subject = "Your Order is confirmed with On Time Guarantee We Pay if we Delay"
527
            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>'
528
 
5793 rajveer 529
    customer_name = "" 
1262 varun.gupt 530
    html_header = """
531
<html>
532
<body>
533
<div>
534
    <p>
5793 rajveer 535
        Hello $customer_name,<br /><br />
6650 amit.gupta 536
        Thanks for placing order with us.$otgLink Following are the details of your order:
1262 varun.gupt 537
    </p>
538
    <div>
539
        Order Date: $order_date
1569 varun.gupt 540
    </div>
1262 varun.gupt 541
    <div>
542
        <table>
5879 rajveer 543
        <tr><td colspan="6"><hr /></td></tr>
544
        <tr><td colspan="6" align="left"><b>Order Details</b></td></tr>
545
        <tr><td colspan="6"><hr /></td></tr>
1262 varun.gupt 546
        <tr>
2050 varun.gupt 547
            <th width="100">Order No.</th>
548
            <th>Product</th>
5879 rajveer 549
            <th width="100">Estimated Delivery Date</th>
2050 varun.gupt 550
            <th width="100">Quantity</th>
551
            <th width="100">Unit Price</th>
552
            <th width="100">Amount</th>
1262 varun.gupt 553
        </tr>
554
    """
1398 varun.gupt 555
    user_email = ""
1262 varun.gupt 556
    total_amount = 0.0
557
    html_table = ""
1569 varun.gupt 558
    order_date = datetime.datetime.now()
5676 rajveer 559
 
560
    orders = transaction.orders
561
    html_pickup_text = ""
562
    random_text = ""
5697 rajveer 563
    if orders[0].pickupStoreId:
5793 rajveer 564
        random_text = str(randrange(100000, 999999)) 
6650 amit.gupta 565
 
6654 amit.gupta 566
    first = True    
5676 rajveer 567
    for order in orders:
5793 rajveer 568
        customer_name = order.customer_name
1262 varun.gupt 569
        order_date = order.created_timestamp
1398 varun.gupt 570
        user_email = order.customer_email
6654 amit.gupta 571
        if first:
572
            first = False
573
            html_tr = "" 
574
        else:
6659 amit.gupta 575
            html_tr =  "<tr><td colspan=6>&nbsp;</td></tr>"
6654 amit.gupta 576
        html_tr += "<tr><td align='center'>" + str(order.id) + "</td>"
5676 rajveer 577
 
5879 rajveer 578
        sdt = datetime.datetime.strptime(str(orders[0].expected_delivery_time), "%Y-%m-%d %H:%M:%S")
579
        store_delivery_date = sdt.strftime("%d %B %Y")
580
 
5676 rajveer 581
        if order.pickupStoreId:
582
            attribute = Attribute()
583
            attribute.orderId = order.id
584
            attribute.name = "SECRET_CODE"
585
            attribute.value = random_text
586
            session.commit()
1262 varun.gupt 587
 
588
        for lineitem in order.lineitems:
2050 varun.gupt 589
            lineitem_total_price = round(lineitem.total_price, 2)
590
 
1276 chandransh 591
            html_tr += "<td>" + str(lineitem) + "</td>"
6561 amit.gupta 592
            if order.otg:
6650 amit.gupta 593
                html_tr += "<td align='center'><div>" + store_delivery_date + "</div>" + inOrderOtg + "</td>"
6561 amit.gupta 594
            else:
595
                html_tr += "<td align='center'>" + store_delivery_date + "</td>"
2050 varun.gupt 596
            html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
597
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
598
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
599
            total_amount += lineitem_total_price
1262 varun.gupt 600
            html_table += html_tr
7190 amar.kumar 601
        if order.freebieItemId:
602
            catalog_client = CatalogClient().get_client()
603
            item = catalog_client.getItem(order.freebieItemId)
7201 amar.kumar 604
            html_table += "<tr><td align='center'></td><td style='font-style:italic;' colspan='5'> Free Item: "+item.brand + " " + item.modelName + " " + item.modelNumber+"</td></tr>"
6906 rajveer 605
        if order.insurer:
606
            html_table += "<tr><td colspan=6>&nbsp;</td></tr>"
6927 rajveer 607
            html_table += "<tr><td align='center'></td><td style='font-style:italic;'>Insured Against Theft for 1 Year. <a href='http://www.saholic.com/static/insurance-terms'>Know More</a></td><td align='center'></td><td align='center'></td><td align='center'></td>"
6911 rajveer 608
            html_table += "<td align='center'>" + str(order.insuranceAmount) + "</td></tr>"
6927 rajveer 609
            total_amount += order.insuranceAmount
6422 rajveer 610
    emi_amount = 0
611
    miscCharges = get_misc_charges(transaction_id)
612
    if miscCharges.get(1):
613
        emi_amount = miscCharges.get(1)
614
 
1262 varun.gupt 615
    html_footer = """
5879 rajveer 616
        <tr><td colspan=6>&nbsp;</td></tr>
617
        <tr><td colspan=6><hr /></td></tr>
6422 rajveer 618
        """
619
    if emi_amount > 0:
6715 amit.gupta 620
        total_amount += emi_amount
6422 rajveer 621
        html_footer = html_footer + "<tr>\
622
                        <td colspan=5>EMI Processing Charges</td>\
623
                        <td> Rs. $emi_amount</td>\
624
                    </tr>"
625
 
626
    html_footer = html_footer + "<tr>\
627
                <td colspan=5>Total Amount</td>\
628
                <td> Rs. $total_amount</td>\
629
                </tr>\
630
            </table>\
631
        </div>"
5793 rajveer 632
 
6422 rajveer 633
 
5793 rajveer 634
    store_address = ""
635
    if orders[0].pickupStoreId:
636
        store = LogisticsClient().get_client().getPickupStore(orders[0].pickupStoreId)
637
        store_address = __get_store_address_html(store)
638
 
639
        html_pickup_text = html_pickup_text + """
640
        <h3>Steps to Pickup In Store</h3>
5879 rajveer 641
        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 642
        <br><i>$store_address</i><br>
643
        """
644
 
645
        if orders[0].cod:
646
            html_pickup_text = html_pickup_text + """
6318 rajveer 647
            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 648
            *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>
649
            <br>
6029 rajveer 650
            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 651
            </br><hr />
652
            """
653
        else:
654
            html_pickup_text = html_pickup_text + """
5879 rajveer 655
            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 656
            *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>
657
            <br>
6029 rajveer 658
            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 659
            </br><hr />
660
            """
661
 
5676 rajveer 662
    html_footer = html_footer + html_pickup_text + """
1262 varun.gupt 663
    <p>
664
        Best Wishes,<br />
6029 rajveer 665
        $source_name Team
1262 varun.gupt 666
    </p>
667
</div>
668
</body>
669
</html>
670
    """
1398 varun.gupt 671
 
1569 varun.gupt 672
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 673
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
5793 rajveer 674
 
675
    sdt = datetime.datetime.strptime(str(orders[0].expected_delivery_time), "%Y-%m-%d %H:%M:%S")
676
    store_delivery_date = sdt.strftime("%A, %d %B %Y")
677
 
6650 amit.gupta 678
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, source_url = source_url, otgLink = otgLink))
6422 rajveer 679
    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 680
 
1351 varun.gupt 681
    try:
682
        helper_client = HelperClient().get_client()
6906 rajveer 683
        helper_client.saveUserEmailForSending([user_email], "", subject, email_header + html_table + email_footer, str(transaction_id), "TransactionInfo", [], [])
5866 rajveer 684
 
1351 varun.gupt 685
        return True
686
    except Exception as e:
687
        print e
688
        return False
1262 varun.gupt 689
 
5802 rajveer 690
def enqueue_received_at_store_email(order):
691
    html_header = """
692
    <html>
693
    <body>
694
    <div>
695
        <p>
696
            Hello $customer_name,<br /><br />
697
            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:
698
        </p>
699
        <div>
700
            Order Date: $order_date
701
        </div>
702
        <div>
703
            <table>
704
            <tr><td colspan="5"><hr /></td></tr>
705
            <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
706
            <tr><td colspan="5"><hr /></td></tr>
707
            <tr>
708
                <th width="100">Order No.</th>
709
                <th>Product</th>
710
                <th width="100">Quantity</th>
711
                <th width="100">Unit Price</th>
712
                <th width="100">Amount</th>
713
            </tr>
714
    """
715
    total_amount = 0.0
716
    html_table = ""
717
 
718
    html_pickup_text = ""
719
    random_text = __get_secret_code(order.id)
720
 
721
    customer_name = order.customer_name
722
    order_date = order.created_timestamp
723
    user_email = order.customer_email
724
    html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
725
 
726
    for lineitem in order.lineitems:
727
        lineitem_total_price = round(lineitem.total_price, 2)
728
 
729
        html_tr += "<td>" + str(lineitem) + "</td>"
730
        html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
731
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
732
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
733
        total_amount += lineitem_total_price
734
        html_table += html_tr
735
 
736
    html_footer = """
737
        <tr><td colspan=5>&nbsp;</td></tr>
738
        <tr><td colspan=5><hr /></td></tr>
739
        <tr>
740
            <td colspan=4>Total Amount</td>
741
            <td> Rs. $total_amount</td>
742
        </tr>
743
        </table>
744
    </div>
745
    """
746
 
747
    store_address = ""
748
    if order.pickupStoreId:
749
        store = LogisticsClient().get_client().getPickupStore(order.pickupStoreId)
750
        store_address = __get_store_address_html(store)
751
 
752
        html_pickup_text = html_pickup_text + """
753
        <h3>Steps to Pickup In Store</h3>
754
        1) Please visit the following store selected by you on or before $order_expiry_date<br>
755
        <br><i>$store_address</i><br>
756
        """
757
 
758
        if order.cod:
759
            html_pickup_text = html_pickup_text + """
6318 rajveer 760
            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 761
            *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>
762
            <br>
6029 rajveer 763
            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 764
            </br><hr />
765
            """
766
        else:
767
            html_pickup_text = html_pickup_text + """
768
            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>
769
            *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>
770
            <br>
6029 rajveer 771
            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 772
            </br><hr />
773
            """
774
 
775
        html_footer = html_footer + html_pickup_text + """
776
        <p>
777
            Best Wishes,<br />
6029 rajveer 778
            $source_name Team
5802 rajveer 779
        </p>
780
        </div>
781
        </body>
782
        </html>
783
        """
784
 
785
    subject = "Your order for " + str(order.lineitems[0]) + " is ready for Pickup in Store"
786
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
787
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
788
 
789
    oetd = datetime.datetime.now() + datetime.timedelta(days=4)
790
    formated_order_expiry_date = oetd.strftime("%A, %d %B %Y")
791
 
792
 
6029 rajveer 793
    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 794
    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 795
 
796
    try:
5812 rajveer 797
        helper_client = HelperClient(host_key = "helper_service_server_host_prod").get_client()
6280 rajveer 798
        helper_client.saveUserEmailForSending([user_email], "", subject, email_header + html_table + email_footer, str(order.id), "ReceivedAtStore", [], [])
5802 rajveer 799
        return True
800
    except Exception as e:
801
        print e
802
        return False
803
 
5966 rajveer 804
def enqueue_delivery_success_mail(order):
5807 rajveer 805
    html_header = """
806
    <html>
807
    <body>
808
    <div>
809
        <p>
810
            Dear $customer_name,<br /><br />
811
    """
6561 amit.gupta 812
 
5807 rajveer 813
    if order.pickupStoreId:
814
        pickup_text = "Pickup Date: " + order.delivery_timestamp.strftime("%A, %d. %B %Y %I:%M%p")
815
        thank_you_html = """
816
        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>
817
 
6029 rajveer 818
        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 819
        """
820
    else:
821
        pickup_text = ""
6561 amit.gupta 822
        if order.otg:
823
 
824
            delayed = False
825
            fda = False
826
 
827
            if order.first_dlvyatmp_timestamp.date() < order.delivery_timestamp.date():
828
                fda = True
829
 
830
            fda_datetime = order.first_dlvyatmp_timestamp            
831
            fda_date = fda_datetime.date()
832
 
6711 amit.gupta 833
            if order.promised_delivery_time.date() < fda_date:
6561 amit.gupta 834
                delayed = True
835
 
836
            if not delayed and not fda:
837
                thank_you_html = """As Promised """ + str(order.lineitems[0]) +""" ordered by you has been <b>Delivered On Time.</b>""" 
838
            elif delayed:
839
                max_discount = 500
6711 amit.gupta 840
                delayedDays = get_business_days_count(order.promised_delivery_time, fda_datetime)
6561 amit.gupta 841
                max_discount = min(max_discount, order.lineitems[0].unit_price/10)
6686 anupam.sin 842
                discount = min(round(max_discount),delayedDays*50)  
6561 amit.gupta 843
                promotion_client = PromotionClient().get_client()
844
                endOn =  order.delivery_timestamp + datetime.timedelta(days = 30)
845
                endOn = to_java_date(endOn)
6688 anupam.sin 846
                arguments = "{\"endOn\":" + str(endOn) + ", \"emails\":[\"" + order.customer_email + "\"], \"couponType\":\"both\", \"usage_limit_for_user\":1, \"isCod\":False, \"discount\":" + str(discount) + "}"
6742 anupam.sin 847
                otgCoupon = promotion_client.createCoupon(28, '', arguments, False, "otg")
6691 amit.gupta 848
                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 849
                thank_you_html = Template(thank_you_html).substitute(dict(prodName=order.lineitems[0], delayedDays = delayedDays, discount = discount, otgCoupon = otgCoupon))
850
            elif fda:
851
                fdaFormattedString = order.first_dlvyatmp_timestamp.strftime("%A, %d. %B %Y")
852
                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.""" 
853
 
854
            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."""  
855
 
856
        else :
857
            thank_you_html = str(order.lineitems[0]) + """ ordered by you has been delivered. 
858
            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>
7198 amar.kumar 859
            """
860
 
861
    freebie_text = "<br/>"
862
    if order.freebieItemId:
863
        catalog_client = CatalogClient().get_client()
864
        item = catalog_client.getItem(order.freebieItemId)
865
        freebie_text = freebie_text = "We have also delivered " + item.brand + " " + item.modelName + "" + item.modelNumber +" as promised"
866
    else:
867
        freebie_orderId = get_order_attribute_value(order.id, "freebieOrderId")
868
        if freebie_orderId != "":
869
            line_items = get_line_items_for_order(int(freebie_orderId))
870
            freebie_order = get_order(int(freebie_orderId))
871
            freebie_text = freebie_text + " We wish to inform you that your freebie item " +line_items[0].brand + " " + line_items[0].model_name + " " + line_items[0].model_number + " will be sent as a separate order with OrderId : " + freebie_orderId + " and is expected to be delivered on " + freebie_order.expected_delivery_time.strftime("%A, %d %B %Y")+ "<br/>You can track the status of this order from My Orders section in saholic.com" 
5807 rajveer 872
 
873
    html_header = html_header + thank_you_html + """        
874
        </p>
875
        <div>
876
            Order Date: $order_date <br>
877
            $pickup_text
878
        </div>
879
        <div>
880
            <table>
881
            <tr><td colspan="5"><hr /></td></tr>
882
            <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
883
            <tr><td colspan="5"><hr /></td></tr>
884
            <tr>
885
                <th width="100">Order No.</th>
886
                <th>Product</th>
887
                <th width="100">Quantity</th>
888
                <th width="100">Unit Price</th>
889
                <th width="100">Amount</th>
890
            </tr>
891
    """
892
    total_amount = 0.0
893
    html_table = ""
5802 rajveer 894
 
5807 rajveer 895
    customer_name = order.customer_name
896
    order_date = order.created_timestamp
897
    user_email = order.customer_email
898
    html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
899
 
900
    for lineitem in order.lineitems:
901
        lineitem_total_price = round(lineitem.total_price, 2)
902
 
903
        html_tr += "<td>" + str(lineitem) + "</td>"
904
        html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
905
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
906
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
907
        total_amount += lineitem_total_price
908
        html_table += html_tr
6906 rajveer 909
    if order.insurer:
6915 anupam.sin 910
        html_table += "<tr><td align='center'></td><td style='font-style:italic;'>Insured Against Theft for 1 Year. <a href='http://www.saholic.com/static/insurance-terms'>Know More</a></td><td align='center'></td><td align='center'></td>"
6911 rajveer 911
        html_table += "<td align='center'>" + str(order.insuranceAmount) + "</td></tr>"
6947 rajveer 912
        html_table += "<tr><td align='center'></td><td style='font-style:italic;'>Please download and read attached policy document.</td><td align='center'></td><td align='center'></td></tr>"
6906 rajveer 913
        total_amount += order.insuranceAmount
914
 
5807 rajveer 915
    html_footer = """
916
        <tr><td colspan=5>&nbsp;</td></tr>
917
        <tr><td colspan=5><hr /></td></tr>
918
        <tr>
919
            <td colspan=4>Total Amount</td>
920
            <td> Rs. $total_amount</td>
921
        </tr>
922
        </table>
7198 amar.kumar 923
        $freebie_text
5807 rajveer 924
    </div>
925
    <p>
926
        Best Wishes,<br />
6029 rajveer 927
        $source_name Team
5807 rajveer 928
    </p>
929
    </div>
930
    </body>
931
    </html>
932
    """
933
 
934
    subject = "Your order for " + str(order.lineitems[0]) + " is now complete"
935
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
936
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
937
 
938
 
6029 rajveer 939
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, pickup_text = pickup_text, source_url = source_url))
7198 amar.kumar 940
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount, source_name = source_name, freebie_text = freebie_text))
5807 rajveer 941
 
942
    try:
5812 rajveer 943
        helper_client = HelperClient(host_key = "helper_service_server_host_prod").get_client()
6957 rajveer 944
        if order.insurer:
945
            helper_client.saveUserEmailForSending([user_email], "", subject, email_header + html_table + email_footer, str(order.id), "DeliverySuccess", [], ["pramit.singh@shop2020.in ","anupam.singh@shop2020.in","rajveer.singh@shop2020.in"])
946
        else:
947
            helper_client.saveUserEmailForSending([user_email], "", subject, email_header + html_table + email_footer, str(order.id), "DeliverySuccess", [], [])
5807 rajveer 948
        return True
949
    except Exception as e:
950
        print e
951
        return False
952
 
5802 rajveer 953
def __get_secret_code(order_id):
5855 rajveer 954
    return get_order_attribute_value(order_id, 'SECRET_CODE')
5806 rajveer 955
 
5833 rajveer 956
def get_order_attribute_value(order_id, attribute_name):
5808 rajveer 957
    existingAttribute = Attribute.query.filter(Attribute.orderId == order_id).filter(Attribute.name == attribute_name).first()
958
    if existingAttribute:
959
        return existingAttribute.value
5802 rajveer 960
    return ""
5806 rajveer 961
 
6019 rajveer 962
def change_jacket_number(order_id, jacket_number):
963
    order = get_order(order_id)
964
    if order.status == OrderStatus.BILLED:
965
        order.jacket_number = jacket_number
6047 rajveer 966
        session.commit()
6019 rajveer 967
        return True
968
    return False
969
 
970
def mark_order_as_rto_in_transit(order_id):
971
    order = get_order(order_id)
6032 rajveer 972
    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 973
        return False
974
    order.status = OrderStatus.RTO_IN_TRANSIT
975
    order.delivery_timestamp = datetime.datetime.now()
7151 amit.gupta 976
    order.statusDescription = "Order Returned to Origin"
6019 rajveer 977
    update_trust_level(order)
6032 rajveer 978
    session.commit()
6019 rajveer 979
    return True
980
 
483 rajveer 981
def get_order(order_id):
982
    order = Order.get_by(id=order_id)
983
    if not order:
984
        raise TransactionServiceException(108, "no such order")
985
 
986
    return order
987
 
4999 phani.kuma 988
def get_order_list(order_ids):
989
    orders = Order.query.filter(Order.id.in_(tuple(order_ids)))
990
    return orders
991
 
5386 phani.kuma 992
def get_order_list_for_vendor(order_ids, vendor_id):
993
    if vendor_id == -1:
994
        return get_order_list(order_ids)
995
    else:
996
        orders = Order.query.filter_by(vendorId = vendor_id).filter(Order.id.in_(tuple(order_ids)))
997
        return orders
998
 
3014 chandransh 999
def get_orders_for_customer(customer_id, from_date, to_date, statuses):
483 rajveer 1000
    if not customer_id:
1001
        raise TransactionServiceException(101, "bad customer id")
1002
    query = Order.query.filter(Order.customer_id == customer_id)
3014 chandransh 1003
    if statuses:
1004
        query = query.filter(Order.status.in_(tuple(statuses)))
483 rajveer 1005
    if from_date:
1006
        query = query.filter(Order.created_timestamp >from_date)
1007
    if to_date:
1008
        query = query.filter(Order.created_timestamp < to_date)
1009
    return query.all()
1010
 
1528 ankur.sing 1011
def get_order_for_customer(order_id, customer_id):
1012
    if not customer_id:
1013
        raise TransactionServiceException(101, "bad customer id")
1014
    order = get_order(order_id)
1015
    if order.customer_id != customer_id:
1016
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
1017
    return order
1018
 
4801 anupam.sin 1019
def get_all_orders(statuses, from_date, to_date, warehouse_id):
1020
    if not len(statuses):
1021
        raise TransactionServiceException(101, "Status list is empty")
1022
    query = Order.query.filter(Order.status.in_(statuses))
1023
    if warehouse_id:
1024
        query = query.filter(Order.warehouse_id == warehouse_id)
1025
        #raise TransactionServiceException(101, "bad warehouse id")
483 rajveer 1026
    if from_date:
1027
        query = query.filter(Order.created_timestamp >from_date)
1028
    if to_date:
1029
        query = query.filter(Order.created_timestamp < to_date)
1030
    return query.all()
1031
 
4133 chandransh 1032
def get_orders_in_batch(statuses=[], offset=0, limit=0, warehouse_id=None):
4296 rajveer 1033
    query = Order.query
1034
    if warehouse_id:
1035
        query = query.filter(Order.warehouse_id == warehouse_id)
4133 chandransh 1036
    if statuses:
1037
        query = query.filter(Order.status.in_(statuses))
1038
    query = query.offset(offset)
1039
    if limit:
1040
        query = query.limit(limit)
1041
    return query.all()
1042
 
1043
def get_order_count(statuses=[], warehouse_id=None):
1044
    if not warehouse_id:
1045
        raise TransactionServiceException(101, "bad warehouse id")
1046
    query = session.query(func.count(Order.id)).filter(Order.warehouse_id == warehouse_id)
1047
    if statuses:
1048
        query = query.filter(Order.status.in_(statuses))
1049
    return query.scalar()
1050
 
1382 varun.gupt 1051
def get_returnable_orders_for_customer(customer_id, limit = None):
1052
    if not customer_id:
1053
        raise TransactionServiceException(101, "bad customer id")
1054
 
1055
    query = Order.query.filter(Order.customer_id == customer_id)
1056
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
1057
    query = query.filter(Order.status != OrderStatus.REJECTED)
1058
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
1059
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
1060
    orders = query.all()
1061
    order_ids = [order.id for order in orders]
1062
    return order_ids
1063
 
1064
def get_cancellable_orders_for_customer(customer_id, limit = None):
1065
    if not customer_id:
1066
        raise TransactionServiceException(101, "bad customer id")
4815 phani.kuma 1067
    cancellableOrderStatuses = OrderStatusGroups().codCancellable
1382 varun.gupt 1068
    query = Order.query.filter(Order.customer_id == customer_id)
4815 phani.kuma 1069
    query = query.filter(Order.status.in_(cancellableOrderStatuses))
1382 varun.gupt 1070
    orders = query.all()
1071
    return [order.id for order in orders]
1072
 
995 varun.gupt 1073
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
1074
    if not warehouse_id:
1075
        raise TransactionServiceException(101, "bad warehouse id")
1076
 
1077
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
1078
 
1079
    if status:
1080
        query = query.filter(Order.status == status)
1081
 
1082
    if start_billing_date:
1083
        query = query.filter(Order.billing_timestamp >= start_billing_date)
1084
 
1085
    if end_billing_date:
1086
        query = query.filter(Order.billing_timestamp <= end_billing_date)
1087
 
1088
    return query.all()
1089
 
3451 chandransh 1090
def get_orders_by_shipping_date(from_shipping_date, to_shipping_date, provider_id, warehouse_id, cod):
1091
    query = Order.query.filter(Order.cod == cod)
3427 chandransh 1092
 
1093
    if warehouse_id and warehouse_id != -1:
1094
        query = query.filter(Order.warehouse_id == warehouse_id)
1095
 
1096
    if provider_id and provider_id != -1:
1097
        query = query.filter(Order.logistics_provider_id == provider_id)
1098
 
1099
    if from_shipping_date:
1100
        query = query.filter(Order.shipping_timestamp >= from_shipping_date)
1101
 
1102
    if to_shipping_date:
1103
        query = query.filter(Order.shipping_timestamp <= to_shipping_date)
1104
 
1105
    query = query.order_by(Order.airwaybill_no)
1106
 
1107
    return query.all()
1108
 
1528 ankur.sing 1109
def get_orders_for_transaction(transaction_id, customer_id):
1110
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
1111
 
1208 chandransh 1112
    if not orders:
1113
        raise TransactionServiceException(101, "No order for the transaction")
1114
    return orders
1115
 
1405 ankur.sing 1116
def get_undelivered_orders(provider_id, warehouse_id):
1117
    query = Order.query
1118
    if provider_id != -1:
1119
        query = query.filter_by(Order.logistics_provider_id == provider_id)
1120
    if warehouse_id != -1:
1121
        query = query.filter(Order.warehouse_id == warehouse_id)
1122
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
1123
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 1124
    #Get last midnight time instead of current time as courier company would have sent the 
1125
    #delivery records updated at least till midnight and not by the current time.
1126
    time_format = "%Y-%m-%d %H:%M:%S.%f"
1127
    t = time.strptime(str(datetime.datetime.now()), time_format)
1128
    midnightTime = datetime.datetime(*t[:3])
1129
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 1130
    orders = query.all()
1131
    return orders
1132
 
1208 chandransh 1133
def get_line_items_for_order(order_id):
1134
    query = LineItem.query.filter(LineItem.order_id == order_id)
1135
    return query.all()
1136
 
483 rajveer 1137
def change_order_status(self, orderId, status, description):
1138
    order = get_order(orderId)
1139
    order.status = status
1140
    order.statusDescription = description
1141
    session.commit()
3578 mandeep.dh 1142
    update_trust_level(order)
1143
    return True
3499 mandeep.dh 1144
 
3578 mandeep.dh 1145
def update_trust_level(order):
3530 mandeep.dh 1146
    try:
3578 mandeep.dh 1147
        trust_level_delta = 0
1148
        if order.cod == True:
1149
            trust_level_delta = ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT.get(order.status, 0)
1150
 
3530 mandeep.dh 1151
        if (trust_level_delta != 0):
1152
            user_client = UserClient().get_client()
1153
            user_client.increaseTrustLevel(order.customer_id, trust_level_delta)
1154
    except Exception as e:
1155
        print e
3499 mandeep.dh 1156
 
483 rajveer 1157
    return True
3064 chandransh 1158
 
1159
def verify_order(self, orderId):
1160
    logging.info("Verifying order no: " + str(orderId))
1161
    order = get_order(orderId)
4662 rajveer 1162
    if order.status == OrderStatus.COD_VERIFICATION_PENDING:
3064 chandransh 1163
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1164
        order.statusDescription = "Submitted for processing"
1165
        order.verification_timestamp = datetime.datetime.now()
1166
        session.commit()
1167
        logging.info("Successfully verified order no: " + str(orderId))
1168
        return True
1169
    else:
1170
        logging.warning("Verify called for order no." + str(orderId) +" which is not in verification pending state");
1171
        return False
1172
 
4285 rajveer 1173
def accept_order(orderId):
3064 chandransh 1174
    logging.info("Accepting order no: " + str(orderId))
921 rajveer 1175
    order = get_order(orderId)
5110 mandeep.dh 1176
    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 1177
        if not order.cod:
1178
            if order.transaction.status == TransactionStatus.AUTHORIZED:
4421 mandeep.dh 1179
                __capture_txn(order)
3010 chandransh 1180
        order.status = OrderStatus.ACCEPTED
1181
        order.statusDescription = "Order Accepted"
1182
        order.accepted_timestamp = datetime.datetime.now()
5530 mandeep.dh 1183
        __amend_fulfilment_warehouse(order)
6789 rajveer 1184
        __update_transfer_price(order, order.fulfilmentWarehouseId)
3010 chandransh 1185
        session.commit()
3064 chandransh 1186
        logging.info("Successfully accepted the order no.:" + str(orderId))
3010 chandransh 1187
        return True
1188
    else:
3064 chandransh 1189
        logging.warning("Accept called for the unacceptable order: " + str(orderId))
3010 chandransh 1190
        return False
921 rajveer 1191
 
4421 mandeep.dh 1192
def __capture_txn(order):
1193
    txnId = order.transaction_id
3010 chandransh 1194
    logging.info("Capturing payment for merchant txn:" + str(txnId))
4421 mandeep.dh 1195
    try:
1196
        payment_client = PaymentClient().get_client()
1197
        capture_result = payment_client.capturePayment(txnId)
1198
        if capture_result:
1199
            logging.info("Successfully captured payment for merchant txn:" + str(txnId))
7293 anupam.sin 1200
            change_transaction_status(txnId, TransactionStatus.IN_PROCESS, "Payment received", PickUpType.COURIER, order.orderType, order.source)
4421 mandeep.dh 1201
        else:
1202
            raise TransactionServiceException(115, "Payment capture failed.")
1203
    except PaymentException as e:
1204
        if e.error_code == 106:
1205
            order.status = OrderStatus.CAPTURE_IN_PROCESS
1206
            session.commit()
1207
            raise TransactionServiceException(122, "Unable to capture payment due to connection issue.")
1208
        else:
1209
            raise TransactionServiceException(115, "Payment capture failed.")
3010 chandransh 1210
 
5530 mandeep.dh 1211
def __amend_fulfilment_warehouse(order):
1212
    itemId = order.lineitems[0].item_id
5944 mandeep.dh 1213
    inventoryClient = InventoryClient().get_client()
1214
    inventory = inventoryClient.getItemInventoryByItemId(itemId)
5530 mandeep.dh 1215
    if not (inventory.availability.has_key(order.fulfilmentWarehouseId) and inventory.availability[order.fulfilmentWarehouseId]):
5944 mandeep.dh 1216
        for warehouse in inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, order.warehouse_id, 0):
5558 mandeep.dh 1217
            if inventory.availability.has_key(warehouse.id) and inventory.availability[warehouse.id] >= inventory.reserved[warehouse.id] + order.lineitems[0].quantity:
5966 rajveer 1218
                inventoryClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, sourceId, order.id, order.lineitems[0].quantity)
1219
                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 1220
                order.fulfilmentWarehouseId = warehouse.id
5530 mandeep.dh 1221
                break
1222
 
7190 amar.kumar 1223
def add_billing_details(orderId, invoice_number, serialNumbers, itemNumbers, freebieWarehouseId, billedBy, jacketNumber, billingType, fulfilmentWarehouseId, authorize):
4285 rajveer 1224
    if jacketNumber is None or jacketNumber <= 0:
2783 chandransh 1225
        raise TransactionServiceException(110, "Invalid jacket number")
1226
 
4285 rajveer 1227
    if billedBy is None or billedBy.strip() == "":
2783 chandransh 1228
        raise TransactionServiceException(110, "Invalid Biller")
1229
 
1149 chandransh 1230
    order = Order.get_by(id=orderId)
1231
    if not order:
2783 chandransh 1232
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
5110 mandeep.dh 1233
 
7190 amar.kumar 1234
    '''
1235
    First checking whether freebie can be billed or not otherwise wont proceed.
1236
    '''
7198 amar.kumar 1237
    if order.freebieItemId:
1238
        if billingType == BillingType.OURS or billingType == BillingType.OURS_EXTERNAL:
1239
            if freebieWarehouseId:
7190 amar.kumar 1240
                try:
7198 amar.kumar 1241
                    inventory_client = InventoryClient().get_client()
1242
                    warehouse = inventory_client.getWarehouse(freebieWarehouseId)
1243
 
7199 amar.kumar 1244
                    if warehouse.warehouseType!= WarehouseType.OURS or warehouse.inventoryType != InventoryType.GOOD:
7198 amar.kumar 1245
                        raise TransactionServiceException(110,'Billing of Freebie is only allowed from OURS_GOOD warehouses ')
1246
 
7190 amar.kumar 1247
                    warehouse_client = WarehouseClient().get_client()
1248
                    inventoryItem = warehouse_client.scanfreebie(orderId, order.freebieItemId, freebieWarehouseId, ScanType.SALE);
1249
 
1250
                    attr = Attribute()
1251
                    attr.orderId = orderId
1252
                    attr.name = "freebie_tp"
1253
                    attr.value = str(inventoryItem.unitPrice)
1254
 
1255
                    attr1 = Attribute()
1256
                    attr1.orderId = orderId
1257
                    attr1.name = "freebie_vendor"
1258
                    attr1.value = str(inventoryItem.supplierId)
5966 rajveer 1259
 
7190 amar.kumar 1260
                    inventory_client = InventoryClient().get_client()
1261
                    item_pricing = inventory_client.getItemPricing(order.freebieItemId, warehouse.vendor.id)
1262
                    attr2 = Attribute()
1263
                    attr2.orderId = orderId
1264
                    attr2.name = "freebie_nlc"
1265
                    attr2.value = str(item_pricing.nlc)
1266
                except Exception as e:
1267
                    print sys.exc_info()[0]
1268
                    print e.message
7198 amar.kumar 1269
                    raise TransactionServiceException(110,'Error in billing freebie for warehouseId ' + str(freebieWarehouseId))
1270
            else:
1271
                raise TransactionServiceException(110,'No warehouseId provided for billing of freebie ')
1272
        else:
1273
            raise TransactionServiceException(110,'Order with freebies associated with it cant be billed from an external warehouse ')
5110 mandeep.dh 1274
    lineitem = order.lineitems[0]
1275
    item_id = lineitem.item_id
5966 rajveer 1276
 
6007 rajveer 1277
#    inventoryClient = InventoryClient().get_client()
1278
#    if not inventoryClient.isOrderBillable(item_id, order.fulfilmentWarehouseId, sourceId, orderId):
1279
#        raise TransactionServiceException(101, "There are other orders to be billed before this order id " + str(orderId))
5966 rajveer 1280
 
5110 mandeep.dh 1281
    catalog_client = CatalogClient().get_client()
1282
    item = catalog_client.getItem(item_id)
4283 anupam.sin 1283
    if order.status == OrderStatus.ACCEPTED:
4285 rajveer 1284
        order.jacket_number = jacketNumber
6751 amar.kumar 1285
 
1286
        if itemNumbers:
1287
            lineitem.item_number = itemNumbers[0]    
7180 rajveer 1288
        if serialNumbers:
1289
            lineitem.serial_number = serialNumbers[0]                
1290
 
6787 rajveer 1291
        '''
6751 amar.kumar 1292
        if billingType == BillingType.EXTERNAL or billingType == BillingType.OURS_EXTERNAL:
4763 rajveer 1293
            if billedOrdersColorMap.has_key(orderId):
1294
                etpColor = billedOrdersColorMap.get(orderId)
1295
                ourColor = order.lineitems[0].color
4781 rajveer 1296
                if ourColor and etpColor != ourColor and not authorize:
4763 rajveer 1297
                    raise TransactionServiceException(777, "ETP color: " + etpColor + " and Order color: " + ourColor)
1298
                else:
1299
                    billedOrdersColorMap.pop(orderId)
6787 rajveer 1300
        '''
6751 amar.kumar 1301
 
1302
        if billingType == BillingType.EXTERNAL:            
1303
            order.invoice_number = invoice_number
1304
 
1305
        if billingType == BillingType.OURS or billingType == BillingType.OURS_EXTERNAL:
6757 rajveer 1306
            if ItemType.SERIALIZED == item.type and not (serialNumbers and serialNumbers[0]):
1307
                raise TransactionServiceException(110, "No Serial Number supplied")
1308
            if serialNumbers:
1309
                lineitem.serial_number = serialNumbers[0]
6969 amar.kumar 1310
 
4283 anupam.sin 1311
 
2842 chandransh 1312
        order.status = OrderStatus.BILLED
1313
        order.statusDescription = "Order Billed"
1314
        order.billing_timestamp = datetime.datetime.now()
4285 rajveer 1315
        order.billed_by = billedBy
4435 mandeep.dh 1316
 
5436 mandeep.dh 1317
        # Letting the billing process fail in cases where we are unable to 
4435 mandeep.dh 1318
        # fill in transfer price
1319
        try:
5944 mandeep.dh 1320
            inventory_client = InventoryClient().get_client()
1321
            warehouse = inventory_client.getWarehouse(fulfilmentWarehouseId)
1322
            item_pricing = inventory_client.getItemPricing(item_id, warehouse.vendor.id)
5110 mandeep.dh 1323
            lineitem.transfer_price = item_pricing.transferPrice
6751 amar.kumar 1324
            lineitem.nlc = item_pricing.nlc
6075 amit.gupta 1325
            lineitem.vatRate = catalog_client.getVatPercentageForItem(lineitem.item_id, lineitem.unit_price)
5110 mandeep.dh 1326
            order.vendorId = warehouse.vendor.id
4435 mandeep.dh 1327
        except InventoryServiceException as e:
1328
            print sys.exc_info()[0]
1329
            print e.message
5110 mandeep.dh 1330
            raise TransactionServiceException(110, 'Transfer price missing for itemId: ' + str(item_id) + ' and vendor: ' + str(warehouse.vendor.id))
4435 mandeep.dh 1331
 
5110 mandeep.dh 1332
        # For OUR warehouse, we need to scan out items for every billed order
1333
        if billingType == BillingType.OURS:
5530 mandeep.dh 1334
            for index, serialNumber in enumerate(serialNumbers):
5411 rajveer 1335
                try:
1336
                    warehouse_client = WarehouseClient().get_client()
5436 mandeep.dh 1337
                    # Fetching GOOD w/h corresponding to the virtual one here
5835 mandeep.dh 1338
                    if not warehouse.billingWarehouseId:
5950 mandeep.dh 1339
                        warehouse = inventory_client.getWarehouses(None, InventoryType.GOOD, warehouse.vendor.id, order.warehouse_id, 0)[0]
5436 mandeep.dh 1340
 
5411 rajveer 1341
                    if ItemType.SERIALIZED == item.type:
1342
                        inventoryItem = warehouse_client.getInventoryItem(serialNumber)
1343
                    else:
5661 mandeep.dh 1344
                        inventoryItem = warehouse_client.getNonSeralizedInventoryItem(itemNumbers[index], item_id, warehouse.id)
5411 rajveer 1345
 
1346
                    if (inventoryItem.itemId != item_id):
1347
                        catalog_client = CatalogClient().get_client()
1348
                        item = catalog_client.getItem(inventoryItem.itemId)
1349
                        scanItemString = " ".join([str(item.brand), str(item.modelName), str(item.modelNumber), str(item.color)])
1350
                        lineItemString = " ".join([str(lineitem.brand), str(lineitem.model_name), str(lineitem.model_number), str(lineitem.color)])
1351
                        raise TransactionServiceException(110, 'Trying to scan ' + scanItemString + ' instead of ' + lineItemString)
1352
 
1353
                    if ItemType.SERIALIZED == item.type:
5661 mandeep.dh 1354
                        inventoryItem = warehouse_client.scanSerializedItemForOrder(serialNumber, ScanType.SALE, orderId, warehouse.id, 1, order.warehouse_id)
5411 rajveer 1355
                    else:
5661 mandeep.dh 1356
                        inventoryItem = warehouse_client.scanForOrder(inventoryItem, ScanType.SALE, 1, order.id, warehouse.id, order.warehouse_id)
5411 rajveer 1357
 
1358
                    lineitem.transfer_price = inventoryItem.unitPrice
1359
                    order.vendorId = inventoryItem.supplierId
5636 amar.kumar 1360
                    catalog_client = CatalogClient().get_client()
5411 rajveer 1361
                except WarehouseServiceException as e:
1362
                    print sys.exc_info()[0]
1363
                    print 'Could not scan out orders due to: ' + e.message
1364
                    raise TransactionServiceException(110, e.message)
6763 amar.kumar 1365
        elif billingType == BillingType.OURS_EXTERNAL:
1366
            try:
6786 amar.kumar 1367
                if ItemType.SERIALIZED == item.type:
1368
                    serialNumber = serialNumbers[0]
1369
                else:
1370
                    serialNumber = ""
6763 amar.kumar 1371
                warehouse_client = WarehouseClient().get_client()
6768 amar.kumar 1372
                inventoryItem = warehouse_client.scanForOursExternalSale(lineitem.item_id, serialNumber, lineitem.item_number, invoice_number, order.fulfilmentWarehouseId, lineitem.transfer_price, order.id)
6763 amar.kumar 1373
                lineitem.transfer_price = inventoryItem.unitPrice
1374
                order.vendorId = inventoryItem.supplierId
1375
            except WarehouseServiceException as e:
1376
                print sys.exc_info()[0]
1377
                print 'Could not scan out orders due to: ' + e.message
1378
                raise TransactionServiceException(110, e.message)
5123 mandeep.dh 1379
        else:
1380
            if not warehouse.isAvailabilityMonitored:
5944 mandeep.dh 1381
                inventory_client = InventoryClient().get_client()
1382
                inventory_client.addInventory(item.id, warehouse.id, -1 * lineitem.quantity)
4365 mandeep.dh 1383
 
5110 mandeep.dh 1384
        __update_inventory_reservation(order)
5661 mandeep.dh 1385
        order.fulfilmentWarehouseId = warehouse.id
6969 amar.kumar 1386
        if billingType == BillingType.OURS or billingType == BillingType.OURS_EXTERNAL:
1387
            order.invoice_number = get_next_invoice_number(order.orderType)
4541 mandeep.dh 1388
        session.commit()
4283 anupam.sin 1389
        return True
1390
    else:
1391
        return False
1149 chandransh 1392
 
6751 amar.kumar 1393
def add_invoice_number(orderId, invoiceNumber, color, serialNumber, itemNumber):
4579 rajveer 1394
    order = Order.get_by(id=orderId)
1395
    if not order:
1396
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
1397
 
1398
    if order.status == OrderStatus.ACCEPTED:
1399
        order.invoice_number = invoiceNumber
4767 rajveer 1400
        if color:
6764 rajveer 1401
            billedOrdersColorMap[orderId] = color
6751 amar.kumar 1402
        if serialNumber:
6764 rajveer 1403
            order.lineitems[0].serial_number = serialNumber.strip() 
6751 amar.kumar 1404
        if itemNumber:
6764 rajveer 1405
            order.lineitems[0].item_number = itemNumber.strip()
4579 rajveer 1406
    session.commit()
1407
 
1220 chandransh 1408
def batch_orders(warehouseId):
1409
    if not warehouseId:
1410
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 1411
 
1412
    batchno_generator = BatchNoGenerator()
1413
    session.commit()
1220 chandransh 1414
    query = Order.query.filter_by(warehouse_id=warehouseId)
4592 mandeep.dh 1415
    query = query.filter(Order.status == OrderStatus.LOW_INV_PO_RAISED)
1220 chandransh 1416
    query = query.order_by(Order.created_timestamp)
1417
    pending_orders = query.all()
1225 chandransh 1418
 
1220 chandransh 1419
    serial_no = 1
1420
    for order in pending_orders:
1276 chandransh 1421
        order.batchNo = batchno_generator.id
1220 chandransh 1422
        order.serialNo = serial_no
1423
        serial_no += 1
1424
    session.commit() 
1425
    pending_orders = query.all()
1426
    return pending_orders
1427
 
1428
def order_outofstock(orderId):
1911 chandransh 1429
    '''
1430
    Mark order as out of stock
1431
    '''
1220 chandransh 1432
    order = get_order(orderId)
1433
    order.status = OrderStatus.INVENTORY_LOW
1434
    order.statusDescription = "Low Inventory"
1435
    order.outofstock_timestamp = datetime.datetime.now()
1436
    session.commit()
1437
    return True
1438
 
4789 rajveer 1439
def mark_orders_as_shipped_from_warehouse(warehouseId, providerId, cod, orderIds):
4410 rajveer 1440
    try:
1441
        current_timestamp = datetime.datetime.now()
5822 rajveer 1442
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(warehouse_id = warehouseId, logistics_provider_id = providerId, status = OrderStatus.BILLED).all()
4410 rajveer 1443
        for order in orders:
5822 rajveer 1444
            order.status = OrderStatus.SHIPPED_FROM_WH
1445
            order.statusDescription = "Order shipped from warehouse"
1446
            order.shipping_timestamp = current_timestamp
1447
            try:
1448
                print "Trying to schedule alert"
1449
                monitoredEntity = MonitoredEntity();
1450
                monitoredEntity.entityType=EntityType.COURIER;
1451
                monitoredEntity.eventType=OrderStatus.SHIPPED_FROM_WH;
1452
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1453
                adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1454
                sec = datetime.datetime.now()
1455
                #Warn alert time is taken as 16 hrs
1456
                warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=16))
1457
                #Critical alert time is taken as 26 hrs                    
1458
                critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=26))
1459
                monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1460
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1461
                monitoredEntity.description="warehouseId = " + str(warehouseId) + " providerId = " + str(providerId) + " orderId = "  + str(order.id);
1462
                alert_client = AlertClient().get_client()
1463
                alert_client.scheduleAlert(monitoredEntity)
1464
            except Exception as e:
1465
                print "Exception in scheduling alert in ShippedFromWarehouse method"
1466
                print e
759 chandransh 1467
        session.commit()
5832 rajveer 1468
 
4749 varun.gupt 1469
 
1470
        try:
5832 rajveer 1471
            for order in orders:
1472
                if order.pickupStoreId:
1473
                    send_mails_to_bdms(order)
1474
                else:
1475
                    enqueue_shipping_confirmation_email(order)
4749 varun.gupt 1476
        except Exception as e:
1477
            print e
5832 rajveer 1478
 
759 chandransh 1479
        return True
1480
    except:
1481
        return False
4410 rajveer 1482
 
5832 rajveer 1483
def send_mails_to_bdms(order):
5816 rajveer 1484
    logistics_client = LogisticsClient().get_client()
5832 rajveer 1485
    store = logistics_client.getPickupStore(order.pickupStoreId)
1486
    provider = logistics_client.getProvider(order.logistics_provider_id)
6029 rajveer 1487
    subject = source_name + " order " + str(order.id) +" shipped to store" 
5832 rajveer 1488
    raw_message = '''
1489
    Dear Sir,
5816 rajveer 1490
 
5832 rajveer 1491
    Order mentioned below is being shipped to your store. Customer will pick it from your store. 
1492
 
1493
    Store Id: %(store_id)s
1494
    Order Id: %(order_id)s 
1495
    Product: %(product)s
1496
    Delivery By: %(provider)s
5844 mandeep.dh 1497
    Payment Mode: %(payMode)s
1498
 
1499
    %(note)s
1500
 
5832 rajveer 1501
    Thanks and Regards
1502
    Sandeep Sachdeva
1503
    '''
1504
 
5844 mandeep.dh 1505
    payMode = 'Prepaid'
1506
    note = ''
1507
    if order.cod:
1508
        payMode = 'COD'
6318 rajveer 1509
        note = 'Note: Please collect Rs. ' + str(order.total_amount-order.gvAmount) + ' from customer'
5844 mandeep.dh 1510
 
5832 rajveer 1511
    message = dedent(raw_message) % { 'order_id' : str(order.id),
1512
                                     'store_id' : str(store.hotspotId),
1513
                                  'provider' : provider.name,
5844 mandeep.dh 1514
                                  'product' : str(order.lineitems[0]),
1515
                                  'payMode' : payMode,
1516
                                  'note'    : note
5832 rajveer 1517
                                  }
6643 rajveer 1518
    to_addresses = [store.email, store.bdmEmail, 'sandeep.sachdeva@shop2020.in', 'amit.sirohi@shop2020.in', 'manoj.kumar@shop2020.in']
5894 rajveer 1519
    cc = ['khushal.bhatia@spiceretail.co.in']
1520
    bcc = ['rajneesh.arora@spiceretail.co.in']
5966 rajveer 1521
    mail(mail_user, mail_password, to_addresses, subject, message, [], cc, bcc)
5816 rajveer 1522
 
5713 rajveer 1523
def mark_orders_as_returned_from_store(providerId, orderIds, awbs):
5676 rajveer 1524
    try:
1525
        current_timestamp = datetime.datetime.now()
5824 rajveer 1526
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(logistics_provider_id = providerId, status = OrderStatus.RET_PICKUP_REQUEST_RAISED).all()
5676 rajveer 1527
        for order in orders:
6943 amar.kumar 1528
            order.status = OrderStatus.RTO_IN_TRANSIT
5824 rajveer 1529
            order.statusDescription = "Order returned from store"
1530
            order.doa_pickup_timestamp = current_timestamp
1531
            #order.airwaybill_no = awbs[orderIds.index(order.id)]
1532
            order.tracking_id = awbs[orderIds.index(order.id)]
5676 rajveer 1533
        session.commit()
1534
 
1535
        return True
1536
    except:
1537
        return False    
1538
 
1539
def set_order_attributes(orderId, attributes):
5871 rajveer 1540
    for attribute in attributes :
1541
        existingAttribute = Attribute.query.filter(Attribute.orderId == orderId).filter(Attribute.name == attribute.name).first()
1542
        if existingAttribute:
1543
            existingAttribute.value = attribute.value
1544
        else :                
1545
            attr = Attribute()
1546
            attr.orderId = orderId
1547
            attr.name = attribute.name
1548
            attr.value = attribute.value
5791 anupam.sin 1549
    session.commit()
5724 rajveer 1550
 
1113 chandransh 1551
def mark_orders_as_picked_up(provider_id, pickup_details):
1552
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 1553
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 1554
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 1555
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1556
            continue
1113 chandransh 1557
        order.status = OrderStatus.SHIPPED_TO_LOGST
1558
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 1559
        order.pickup_timestamp = pickup_timestamp
5636 amar.kumar 1560
 
1561
        try:
1562
            monitoredEntity = MonitoredEntity();
1563
            monitoredEntity.entityType=EntityType.COURIER;
1564
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_LOGST
1565
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1566
            adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1567
            sec = datetime.datetime.now()
1568
            #Warn alert time is taken as 16 hrs
5821 amit.gupta 1569
            warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=15))
5744 amar.kumar 1570
            #Critical alert time is taken as 26 hrs                    
5821 amit.gupta 1571
            critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=20))
5744 amar.kumar 1572
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1573
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5819 amit.gupta 1574
            monitoredEntity.description="providerId = " + str(provider_id)
5636 amar.kumar 1575
            alert_client = AlertClient().get_client()
1576
            alert_client.updateMonitoredObject(monitoredEntity)
1577
        except Exception as e:
5801 amar.kumar 1578
            print "Exception in updating alert in MarkOrdersAsPickedUp method"
5636 amar.kumar 1579
            print e
1113 chandransh 1580
    session.commit()
1217 chandransh 1581
 
4910 phani.kuma 1582
def get_orders_not_picked_up(provider_id):
1132 chandransh 1583
    current_time = datetime.datetime.now()
1584
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4741 phani.kuma 1585
    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 1586
    return orders_not_picked_up
1587
 
1132 chandransh 1588
def mark_orders_as_delivered(provider_id, delivered_orders):
1589
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 1590
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 1591
        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 1592
            continue
6561 amit.gupta 1593
        timestamp, receiver = detail.split('|')
1594
        order.delivery_timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
1595
        if order.first_dlvyatmp_timestamp is None:
1596
            order.first_dlvyatmp_timestamp = order.delivery_timestamp
1597
        order.receiver = receiver
5555 rajveer 1598
        if order.pickupStoreId:
1599
            order.status = OrderStatus.DELIVERED_AT_STORE
1600
            order.statusDescription = "Order delivered At Store"
5762 amar.kumar 1601
            try:
1602
                monitoredEntity = MonitoredEntity();
1603
                monitoredEntity.entityType=EntityType.COURIER;
1604
                monitoredEntity.eventType=OrderStatus.RECEIVED_AT_STORE;
1605
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1606
                #adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1607
                sec = datetime.datetime.now()
1608
                #Critical alert time is taken as 26 hrs                    
1609
                critical_time = (sec + timedelta(hours=4))
1610
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1611
                monitoredEntity.description="deliveryTimeAtStore = " + str(order.delivery_timestamp) + " orderId = "  + str(order.id);
1612
                alert_client = AlertClient().get_client()
1613
                alert_client.updateMonitoredObject(monitoredEntity)
1614
            except Exception as e:
1615
                print e
5555 rajveer 1616
        else:
1617
            order.status = OrderStatus.DELIVERY_SUCCESS
1618
            order.statusDescription = "Order delivered"
5762 amar.kumar 1619
            update_trust_level(order)
6903 anupam.sin 1620
            if order.insuranceDetails:
6906 rajveer 1621
                try:
1622
                    update_insurance_details(order)
1623
                except:
1624
                    print "Error generating insurance file for order " + str(order.id)
1625
                    session.rollback()
1626
                    return
1627
 
6745 anupam.sin 1628
            if enqueue_delivery_success_mail(order) :
1629
                session.commit()
1630
            else :
1631
                session.rollback()
5762 amar.kumar 1632
            try:
1633
                alert_client = AlertClient().get_client()
1634
                alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1635
            except Exception as e:
5801 amar.kumar 1636
                print "Exception in scheduling alert in ShippedFromWarehouse method"
5762 amar.kumar 1637
                print e
5636 amar.kumar 1638
 
6906 rajveer 1639
def update_insurance_details(order):
1640
    order.insuranceDetails[0].startDate = order.delivery_timestamp
1641
    order.insuranceDetails[0].expiryDate = order.delivery_timestamp + timedelta(days = 365)
6947 rajveer 1642
    filename = "/tmp/" + str(order.id) + "-insurance-policy.pdf"
6906 rajveer 1643
    __generate_policy_doc(order, filename)
1644
    file = open(filename, "rb")
1645
    pdfFile = file.read()
1646
    doc = DocumentStore()
1647
    doc.docType = 1
1648
    doc.docSource = order.id
1649
    doc.document = pdfFile
1132 chandransh 1650
 
4712 rajveer 1651
def mark_order_as_delivered(orderId, deliveryTimestamp, receiver):
1652
    order = Order.get_by(id=orderId)
5555 rajveer 1653
    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 1654
        raise TransactionServiceException(101, "Either wrond order id or invalid state " + str(orderId))
5402 rajveer 1655
 
1656
    # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
1657
    if order.status == OrderStatus.BILLED and order.logistics_provider_id != 4:
5807 rajveer 1658
        raise TransactionServiceException(101, "Order is not marked for self pickup: " + str(orderId))
5402 rajveer 1659
 
5555 rajveer 1660
    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 1661
        order.delivery_timestamp = deliveryTimestamp
6631 amit.gupta 1662
        if order.first_dlvyatmp_timestamp is None:
6632 amit.gupta 1663
            order.first_dlvyatmp_timestamp = deliveryTimestamp
4712 rajveer 1664
        order.receiver = receiver
1665
    order.status = OrderStatus.DELIVERY_SUCCESS
1666
    order.statusDescription = "Order delivered"
1667
    update_trust_level(order)
6903 anupam.sin 1668
    if order.insuranceDetails:
6906 rajveer 1669
        try:
1670
            update_insurance_details(order)
1671
        except:
1672
            print "Error generating insurance file for order " + str(order.id)
1673
            session.rollback()
1674
            return
4712 rajveer 1675
    session.commit()
5713 rajveer 1676
 
5812 rajveer 1677
    if order.pickupStoreId and order.cod:
5806 rajveer 1678
        __push_collection_to_hotspot(order, "SALE")
1679
 
5966 rajveer 1680
    enqueue_delivery_success_mail(order)
5713 rajveer 1681
#    if order.pickupStoreId:
1682
#        payment_client = PaymentClient().get_client()
1683
#        payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
1684
#        payment_client = PaymentClient().get_client()
1685
#        payment_client.partiallyCapturePayment(order.transaction.id, order.total_amount, xferBy, xferTxnId, now())
1686
#        order.cod_reconciliation_timestamp = datetime.datetime.now()
1687
#        session.commit()
1688
 
5636 amar.kumar 1689
    try:
1690
        alert_client = AlertClient().get_client()
5744 amar.kumar 1691
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1692
    except Exception as e:
5801 amar.kumar 1693
        print "Exception in ending alert in MarkOrderAsDelivered method"
5636 amar.kumar 1694
        print e
1695
 
4712 rajveer 1696
 
5555 rajveer 1697
def mark_order_as_received_at_store(orderId, deliveryTimestamp):
1698
    order = Order.get_by(id=orderId)
1699
    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]:
1700
        order.status = OrderStatus.RECEIVED_AT_STORE
1701
        order.statusDescription = "Order received at store"
1702
        order.delivery_timestamp = deliveryTimestamp
1703
    session.commit()
5713 rajveer 1704
    try:
5762 amar.kumar 1705
        alert_client = AlertClient().get_client()
1706
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1707
    except Exception as e:
1708
        print e
1709
 
1710
    try:
5713 rajveer 1711
        enqueue_received_at_store_email(order)
1712
    except Exception as e:
1713
        print e
1714
 
1715
 
5555 rajveer 1716
 
4910 phani.kuma 1717
def mark_orders_as_rto(provider_id, returned_orders):
1135 chandransh 1718
    for awb, detail in returned_orders.iteritems():
1719
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
5713 rajveer 1720
        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 1721
            continue
1722
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 1723
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 1724
        order.delivery_timestamp, reason = detail.split('|')
1725
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 1726
        update_trust_level(order)
1911 chandransh 1727
    session.commit()
5636 amar.kumar 1728
    try:
1729
        alert_client = AlertClient().get_client()
5801 amar.kumar 1730
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1731
    except Exception as e:
5801 amar.kumar 1732
        print "Exception in ending alert in MarkOrderAsRTO method"
5636 amar.kumar 1733
        print e
1135 chandransh 1734
 
4910 phani.kuma 1735
def get_rto_orders(provider_id):
1736
    current_time = datetime.datetime.now()
1737
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1738
    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()
1739
    return rto_orders
1740
 
5555 rajveer 1741
def get_receive_pending_orders(storeId):
1742
    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()
1743
 
1744
def get_received_at_store_orders(storeId):
5676 rajveer 1745
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.RECEIVED_AT_STORE, OrderStatus.RET_PICKUP_REQUEST_RAISED))).all()
5555 rajveer 1746
 
5713 rajveer 1747
def get_orders_collection_at_store(storeId, fromDate, toDate, onlyCod):
1748
    query = Order.query.filter(Order.status == OrderStatus.DELIVERY_SUCCESS)
1749
    if storeId:
1750
        query = query.filter_by(pickupStoreId = storeId)
5720 rajveer 1751
    else:
1752
        query = query.filter(Order.pickupStoreId != 0)
5713 rajveer 1753
    if onlyCod:
1754
        query = query.filter_by(cod = onlyCod)
1755
    if fromDate:
1756
        query = query.filter(Order.delivery_timestamp >= fromDate)
1757
    if toDate:
1758
        query = query.filter(Order.delivery_timestamp <= toDate)
1759
    return query.all()
1760
 
1246 chandransh 1761
def update_non_delivery_reason(provider_id, undelivered_orders):
1762
    for awb, reason in undelivered_orders.iteritems():
1763
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4920 phani.kuma 1764
        if order == None or order.status == OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE:
2684 chandransh 1765
            continue
1766
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 1767
        order.statusDescription = reason
1768
    session.commit()
4910 phani.kuma 1769
 
1770
def get_non_delivered_orders_by_courier(provider_id):
4581 phani.kuma 1771
    current_time = datetime.datetime.now()
1772
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1773
    upto_datetime = today_datetime - datetime.timedelta(4)
4910 phani.kuma 1774
    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 1775
    return orders_not_delivered
1246 chandransh 1776
 
4910 phani.kuma 1777
def mark_orders_as_local_connected(provider_id, local_connected_orders):
1778
    for awb, timestamp in local_connected_orders.iteritems():
1779
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1780
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1781
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1782
            continue
1783
        order.status = OrderStatus.SHIPPED_TO_DESTINATION_CITY
1784
        order.statusDescription = "Left Out of Origin City"
5636 amar.kumar 1785
        current_time = datetime.datetime.now()
1786
        order.local_connected_timestamp = datetime.datetime(current_time.year, current_time.month, current_time.day)
1787
        try:
1788
            monitoredEntity = MonitoredEntity();
1789
            monitoredEntity.entityType=EntityType.COURIER;
1790
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_DESTINATION_CITY
1791
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1792
            #Warn alert time is taken as 23 hrs less than promised delivery time
5821 amit.gupta 1793
            warn_time = (order.expected_delivery_time-timedelta(hours = 15))
5744 amar.kumar 1794
            #Critical alert time is taken as 13 hrs less than promised delivery time                    
5821 amit.gupta 1795
            critical_time = (order.expected_delivery_time-timedelta(hours = 10))
5801 amar.kumar 1796
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1797
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1798
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1799
            alert_client = AlertClient().get_client()
1800
            alert_client.updateMonitoredObject(monitoredEntity)
1801
        except Exception as e:
5801 amar.kumar 1802
            print "Exception in updating alert in MarkOrderAsLocalConnected method"
5636 amar.kumar 1803
            print e
1804
        session.commit()
4910 phani.kuma 1805
 
1806
def get_orders_not_local_connected(provider_id):
1807
    current_time = datetime.datetime.now()
1808
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1809
    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()
1810
    return orders_pending_local_connection
1811
 
1812
def mark_orders_as_destinationCityReached(provider_id, destination_city_reached_orders):
1813
    for awb, timestamp in destination_city_reached_orders.iteritems():
1814
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1815
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY]:
1816
            continue
1817
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1818
        order.status = OrderStatus.REACHED_DESTINATION_CITY
1819
        order.statusDescription = "Reached Destination City"
1820
        order.reached_destination_timestamp = timestamp
5636 amar.kumar 1821
        try:
1822
            monitoredEntity = MonitoredEntity();
1823
            monitoredEntity.entityType=EntityType.COURIER;
1824
            monitoredEntity.eventType=OrderStatus.REACHED_DESTINATION_CITY
1825
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5764 amar.kumar 1826
            warn_time = (order.expected_delivery_time)
5801 amar.kumar 1827
            critical_time = (order.expected_delivery_time + timedelta(hours=12))
1828
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1829
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1830
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1831
            alert_client = AlertClient().get_client()
1832
            alert_client.updateMonitoredObject(monitoredEntity)
1833
        except Exception as e:
5801 amar.kumar 1834
            print "Exception in updating alert in MarkOrderAsDestCityReached method"
5636 amar.kumar 1835
            print e
4910 phani.kuma 1836
    session.commit()
1837
 
1838
def mark_orders_as_firstDeliveryAttempted(provider_id, first_atdl_orders):
1839
    for awb, detail in first_atdl_orders.iteritems():
1840
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1841
        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]:
1842
            continue
1843
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1844
        order.status = OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1845
        order.first_dlvyatmp_timestamp, reason = detail.split('|')
1846
        order.statusDescription = reason
5636 amar.kumar 1847
        try:
1848
            monitoredEntity = MonitoredEntity();
1849
            monitoredEntity.entityType=EntityType.COURIER;
1850
            monitoredEntity.eventType=OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1851
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1852
            adjustedDeliveryDaysfor1day = adjust_delivery_time(datetime.datetime.now(), 1);
1853
            adjustedDeliveryDaysfor2days = adjust_delivery_time(datetime.datetime.now(), 2);
1854
            sec = datetime.datetime.now()
1855
            #Warn alert time is taken as 16 hrs
1856
            warn_time = (sec + timedelta(days=(adjustedDeliveryDaysfor1day-1)) + timedelta(hours=24))
1857
            #Critical alert time is taken as 26 hrs                    
1858
            critical_time = (sec + timedelta(days=(adjustedDeliveryDaysfor2days-1)) + timedelta(hours=36))
1859
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1860
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1861
            monitoredEntity.description="providerId = " + str(provider_id) + " first attempt timestamp" + order.first_dlvyatmp_timestamp
1862
            alert_client = AlertClient().get_client()
1863
            alert_client.updateMonitoredObject(monitoredEntity)
1864
        except Exception as e:
5801 amar.kumar 1865
            print "Exception in updating alert in MarkOrdersAsFirstDeliveryAttempted method"
5636 amar.kumar 1866
            print e
4910 phani.kuma 1867
    session.commit()
1868
 
4783 phani.kuma 1869
def get_orders_not_met_expected_delivery_date():
1870
    current_time = datetime.datetime.now()
1871
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4910 phani.kuma 1872
    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 1873
    return orders_not_delivered
1874
 
4444 rajveer 1875
def get_alerts(type, warehouseId, status, timestamp):
1876
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
1877
    if type != -1 :
1878
        query = query.filter(Alert.type == type)
1879
    if status != -1 :
1880
        query = query.filter(Alert.status == status)
4394 rajveer 1881
    if timestamp:
1882
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 1883
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 1884
    return query.all()
1885
 
4447 rajveer 1886
def add_alert(type, warehouseId, description):
4394 rajveer 1887
    alert = Alert()
1888
    alert.type = type
1889
    alert.status = 1
1890
    alert.description = description
1891
    alert.timestamp = datetime.datetime.now()
4447 rajveer 1892
    alert.warehouseId = warehouseId
4444 rajveer 1893
    session.commit()
766 rajveer 1894
 
4444 rajveer 1895
def mark_alerts_as_seen(warehouseId):
1896
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
1897
    alerts = query.all()
1898
    for alert in alerts:
1899
        alert.status = 0    
1900
    session.commit()
1901
 
1596 ankur.sing 1902
def get_valid_order_count():
2851 chandransh 1903
    '''
1904
    Returns the number of orders which we processed. The reshipped orders are not
1905
    counted since there'll always be a new compensating order present.
1906
    '''
4682 rajveer 1907
    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 1908
 
1627 ankur.sing 1909
def get_cust_count_with_successful_txn():
2851 chandransh 1910
    '''
1911
    Returns the number of distinct customers who have done successful transactions.
1912
    It uses the sqlalchemy func module to construct an efficient query.
1913
    '''
1914
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 1915
 
1730 ankur.sing 1916
def get_valid_orders_amount_range():
2851 chandransh 1917
    '''
1918
    Returns a list containing the minimum and maximum amount across all
1919
    orders placed with us. No need to consider reshippped orders for min/max
1920
    amount of orders.
1921
    '''
1922
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 1923
 
5874 rajveer 1924
def get_valid_orders(limit, onlyStore):
2851 chandransh 1925
    '''
1926
    Returns the last limit number of valid orders placed with us. Ignored the
1927
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
1928
    less than 0. 
1929
    '''
1930
    if limit < 0:
1931
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
4662 rajveer 1932
    query = Order.query.filter(Order.status >= OrderStatus.COD_VERIFICATION_PENDING)
5874 rajveer 1933
    if onlyStore:
1934
        query = query.filter(Order.pickupStoreId != 0)
1886 ankur.sing 1935
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 1936
    if limit != 0:
1886 ankur.sing 1937
        query = query.limit(limit)
1938
    return query.all()
1939
 
5527 anupam.sin 1940
def get_next_invoice_number(orderType):
1941
    if OrderType.B2Cbulk == orderType:
1942
        orderType = OrderType.B2C
1943
    entity_id = InvoiceIDGenerator.query.filter(InvoiceIDGenerator.orderType == orderType).with_lockmode("update").one()
2783 chandransh 1944
    invoice_number = entity_id.id + 1
1945
    entity_id.id = invoice_number
1946
    return invoice_number
1947
 
2536 chandransh 1948
def toggle_doa_flag(order_id):
1949
    order = get_order(order_id)
1950
    if(order.doaFlag):
1951
        order.doaFlag = False
1952
    else:
1953
        order.doaFlag = True
1954
    session.commit()
1955
    return order.doaFlag
1956
 
4454 rajveer 1957
def mark_order_doa_request_received(orderId):
1958
    order = get_order(orderId)
1959
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1960
        return False
1961
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 1962
    order.statusDescription = "DOA Request Received"
4454 rajveer 1963
    session.commit()
1964
    return True
1965
 
1966
def mark_order_doa_request_authorized(orderId, isAuthorized):
1967
    order = get_order(orderId)
1968
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
1969
        return False
1970
    if isAuthorized:
1971
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 1972
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 1973
    else:
1974
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 1975
        order.statusDescription = "Order delivered"
4454 rajveer 1976
    session.commit()
1977
    return True
1978
 
4488 rajveer 1979
def mark_order_return_request_received(orderId):
1980
    order = get_order(orderId)
1981
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1982
        return False
1983
    order.status = OrderStatus.RET_REQUEST_RECEIVED
1984
    order.statusDescription = "Return Request Received"
1985
    session.commit()
1986
    return True
1987
 
1988
def mark_order_return_request_authorized(orderId, isAuthorized):
1989
    order = get_order(orderId)
1990
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
1991
        return False
1992
    if isAuthorized:
1993
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
1994
        order.statusDescription = "Return Request Authorized"
1995
    else:
1996
        order.status = OrderStatus.DELIVERY_SUCCESS
1997
        order.statusDescription = "Order delivered"
1998
    session.commit()
1999
    return True
2000
 
4579 rajveer 2001
def request_pickup_number(order_id, providerId):
2536 chandransh 2002
    order = get_order(order_id)
4495 rajveer 2003
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 2004
        return False
2005
 
4227 rajveer 2006
    subject = "Pickup request from " + order.customer_city
2536 chandransh 2007
    try:
5944 mandeep.dh 2008
        inventory_client = InventoryClient().get_client()
2009
        warehouse = inventory_client.getWarehouse(order.warehouse_id)
2536 chandransh 2010
 
2011
        logistics_client = LogisticsClient().get_client()
4579 rajveer 2012
        provider = logistics_client.getProvider(providerId)
3051 chandransh 2013
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 2014
        raw_message = '''
2015
        Dear Sir/Madam,
2016
 
2559 chandransh 2017
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 2018
 
6663 rajveer 2019
        Order Id: %(order_id)s
2536 chandransh 2020
        Pickup CODE: %(provider_code)s
2021
        Total Weight: %(order_weight)s kg
2022
 
2559 chandransh 2023
        Pickup Address:
2536 chandransh 2024
 
2025
        %(customer_address)s
2026
 
2027
        Delivery Address:
2028
 
2029
        %(warehouse_executive)s
2030
        %(warehouse_address)s
2031
        PIN %(warehouse_pin)s
2032
 
2033
        Thanks and Regards
4227 rajveer 2034
        Sandeep Sachdeva
2536 chandransh 2035
        '''
4579 rajveer 2036
 
2037
        if warehouse.id == 7:
7181 rajveer 2038
            executive = 'Shiv Kumar'
4579 rajveer 2039
        else:
4966 phani.kuma 2040
            executive = 'Dinesh Kumar'
4579 rajveer 2041
 
2559 chandransh 2042
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 2043
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
6663 rajveer 2044
                                          'order_id' : str(order_id),
2536 chandransh 2045
                                          'order_weight' : str(order.total_weight),
2046
                                          'customer_address' : __get_order_address(order),
4579 rajveer 2047
                                          'warehouse_executive' : executive,
2536 chandransh 2048
                                          'warehouse_address' : warehouse.location,
4966 phani.kuma 2049
                                          'warehouse_pin' : warehouse.pincode}
6645 anupam.sin 2050
        to_addresses = [to_addr,'amit.sirohi@shop2020.in', 'shrawan.choudhary@shop2020.in', 'ritesh.chauhan@shop2020.in']
4966 phani.kuma 2051
 
5966 rajveer 2052
        mail(mail_user, mail_password, to_addresses, subject, message)
4495 rajveer 2053
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
2054
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
2055
            order.statusDescription = "Pick up requested for RETURN"
2056
        else:
2057
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
2058
            order.statusDescription = "Pick up requested for DOA"
4815 phani.kuma 2059
        order.doa_logistics_provider_id = providerId
2536 chandransh 2060
        session.commit()
2061
        return True
2062
    except Exception as e:
2063
        print sys.exc_info()[0]
2064
        return False
2065
 
4602 rajveer 2066
def authorize_pickup(order_id, pickup_number, providerId):
2536 chandransh 2067
    order = get_order(order_id)
4495 rajveer 2068
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 2069
        return False
4815 phani.kuma 2070
    if order.doa_logistics_provider_id is not None:
2071
        providerId = order.doa_logistics_provider_id    #previously we are not storing this so data is taken from omdashboarduser
2536 chandransh 2072
    subject = 'Pickup details'
2073
    filename = "/tmp/" +  str(order.id) +".pdf" 
2074
    try:
5944 mandeep.dh 2075
        inventory_client = InventoryClient().get_client()
2076
        warehouse = inventory_client.getWarehouse(order.warehouse_id)
2536 chandransh 2077
 
2078
        logistics_client = LogisticsClient().get_client()
4602 rajveer 2079
        provider = logistics_client.getProvider(providerId)
2536 chandransh 2080
        provider_name = provider.name
2081
 
2082
        to_addr = order.customer_email
2083
        today = date.today().strftime("%d-%B-%Y (%A)")
2084
 
2085
        raw_message = '''
2086
        Dear Mr. %(customer_name)s,
2087
 
4815 phani.kuma 2088
        In reference to the return of order ID %(order_id)d, ''' + __generate_mail_body_for_authorize_pickup(order)
2089
        raw_message = raw_message + '''
2536 chandransh 2090
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
2091
        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.
2092
 
2093
        Pickup will happen from the below mentioned address:-
2094
 
2095
        %(customer_address)s
2096
 
2097
        Do let us know in case of any concerns
2098
 
2099
        Thanks & Regards
6029 rajveer 2100
        %(source_name)s Team
2536 chandransh 2101
        '''
2102
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
2103
                                         'order_id' : order_id,
2104
                                         'provider_name' : provider_name,
2105
                                         'date': today,
2106
                                         'pickup_request_no' : pickup_number,
6029 rajveer 2107
                                         'customer_address' : __get_order_address(order),
2108
                                         'source_name' : source_name}
2536 chandransh 2109
        print message
2110
        __generate_return_advice(order, warehouse, provider, filename)
5966 rajveer 2111
        mail(help_user, help_password, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 2112
        order.pickupRequestNo = pickup_number
4495 rajveer 2113
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
2114
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
2115
            order.statusDescription = "RETURN pick up confirmed"
2116
        else:
2117
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
2118
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 2119
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 2120
        session.commit()
2121
        return True
2122
    except Exception as e:
4234 rajveer 2123
        print sys.exc_info()
4506 phani.kuma 2124
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 2125
        return False
2126
    finally:
2127
        if os.path.exists(filename):
2128
            os.remove(filename)
2129
 
4815 phani.kuma 2130
def __generate_mail_body_for_authorize_pickup(order):
2131
    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.',
2132
                         '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.',
2133
                         '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.',
2134
                         'Sony Ericsson' : 'we request you to kindly pack the original DOA certificate and the invoice.',
2135
                         '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.',
2136
                         '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.',
2137
                         'Accessories' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original product and the invoice.'}
2138
    categories = ["Handsets", "Tablets", "Laptops"]
2139
    lineitem = order.lineitems[0]
2140
    brand = lineitem.brand
2141
    productGroup = lineitem.productGroup
2142
    searchkey = None
2143
    if productGroup not in categories:
2144
        searchkey = 'Accessories'
2145
    elif order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
2146
        searchkey = 'Handsets Return'
2147
    elif brand == 'Nokia':
2148
        searchkey = 'Nokia'
2149
    elif brand == 'Micromax':
2150
        searchkey = 'Micromax'
2151
    elif brand == 'Karbonn':
2152
        searchkey = 'Karbonn'
2153
    elif brand == 'Sony Ericsson':
2154
        searchkey = 'Sony Ericsson'
2155
    else:
2156
        searchkey = 'Others Handsets'
2157
    return brand_msgbody_map.get(searchkey)
2158
 
2764 chandransh 2159
def mark_doas_as_picked_up(provider_id, pickup_details):
2160
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 2161
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4452 rajveer 2162
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 2163
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
2164
            continue
2165
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
2166
        order.statusDescription = "DOA picked up by Courier Company"
2167
        order.doa_pickup_timestamp = doa_pickup_timestamp
2168
    session.commit()
2169
 
4910 phani.kuma 2170
def get_doas_not_picked_up(provider_id):
2764 chandransh 2171
    current_time = datetime.datetime.now()
2172
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 2173
    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 2174
    return orders_not_picked_up
2175
 
4741 phani.kuma 2176
def mark_return_orders_as_picked_up(provider_id, pickup_details):
2177
    for pickupNo, return_order_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 2178
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4741 phani.kuma 2179
        if order == None or order.status != OrderStatus.RET_PICKUP_CONFIRMED:
2180
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
2181
            continue
2182
        order.status = OrderStatus.RET_RETURN_IN_TRANSIT
2183
        order.statusDescription = "Return order picked up by Courier Company"
2184
        order.doa_pickup_timestamp = return_order_pickup_timestamp
2185
    session.commit()
2186
 
4910 phani.kuma 2187
def get_return_orders_not_picked_up(provider_id):
4741 phani.kuma 2188
    current_time = datetime.datetime.now()
2189
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 2190
    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 2191
    return orders_not_picked_up
2192
 
4479 rajveer 2193
def receive_return(order_id, receiveCondition):
2591 chandransh 2194
    order = get_order(order_id)
7199 amar.kumar 2195
    scanFreebie = False
4365 mandeep.dh 2196
 
4452 rajveer 2197
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 2198
        if receiveCondition == 0:
2199
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
2200
            order.statusDescription = "DOA package received"
2201
        elif receiveCondition == 1:
2202
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
2203
            order.statusDescription = "DOA received damaged"
2204
        elif receiveCondition == 2:
2205
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
2206
            order.statusDescription = "DOA lost in transit"
2764 chandransh 2207
        order.received_return_timestamp = datetime.datetime.now()
4495 rajveer 2208
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
2209
        if receiveCondition == 0:
2210
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
2211
            order.statusDescription = "RETURN package received"
2212
        elif receiveCondition == 1:
2213
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
2214
            order.statusDescription = "RETURN received damaged"
2215
        elif receiveCondition == 2:
2216
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
2217
            order.statusDescription = "RETURN lost in transit"
2218
        order.received_return_timestamp = datetime.datetime.now()
4484 rajveer 2219
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 2220
        if receiveCondition == 0:
2221
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 2222
            order.statusDescription = "Returned to origin"
4486 rajveer 2223
        elif receiveCondition == 1:
2224
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
2225
            order.statusDescription = "RTO received damaged"
2226
        elif receiveCondition == 2:
2227
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
2228
            order.statusDescription = "RTO lost in transit"
2764 chandransh 2229
        order.received_return_timestamp = datetime.datetime.now()
7199 amar.kumar 2230
        if order.freebieItemId:
2231
            scanFreebie = True
2616 chandransh 2232
    else:
2591 chandransh 2233
        return False
5110 mandeep.dh 2234
 
2235
    # For OUR warehouses, we need to scan in items for every return
5944 mandeep.dh 2236
    inventoryClient = InventoryClient().get_client()
2237
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
6763 amar.kumar 2238
    if warehouse.billingType == BillingType.OURS or warehouse.billingType == BillingType.OURS_EXTERNAL:
5361 mandeep.dh 2239
        scanMap = {
2240
            OrderStatus.RTO_RECEIVED_PRESTINE : ScanType.SALE_RET,
2241
            OrderStatus.RTO_RECEIVED_DAMAGED  : ScanType.SALE_RET_UNUSABLE,
2242
            OrderStatus.RTO_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT,
2243
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
2244
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
2245
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
2246
        }
5110 mandeep.dh 2247
 
5419 mandeep.dh 2248
        if scanMap.has_key(order.status):
2249
            scanType = scanMap[order.status]
5361 mandeep.dh 2250
            lineitem = order.lineitems[0]
5944 mandeep.dh 2251
            catalogClient = CatalogClient().get_client()
5361 mandeep.dh 2252
            item = catalogClient.getItem(lineitem.item_id)
2253
            warehouseClient = WarehouseClient().get_client()
6763 amar.kumar 2254
            if warehouse.billingType == BillingType.OURS or scanType != ScanType.SALE_RET:
2255
                if item.type == ItemType.SERIALIZED:
2256
                    warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
2257
                else:
2258
                    warehouseClient.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
2259
            if warehouse.billingType == BillingType.OURS_EXTERNAL and scanType == ScanType.SALE_RET:
2260
                warehouseClient.scanForOursExternalSaleReturn(order.id, lineitem.transfer_price)
7199 amar.kumar 2261
            if scanFreebie:
7292 amar.kumar 2262
                warehouseClient.scanfreebie(order.id, order.freebieItemId, 0, scanType)
5558 mandeep.dh 2263
    session.commit()
2591 chandransh 2264
    return True
2265
 
2266
def validate_doa(order_id, is_valid):
2267
    order = get_order(order_id)
4452 rajveer 2268
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 2269
        return False
2270
    if is_valid:
2609 chandransh 2271
        order.status = OrderStatus.DOA_CERT_VALID
2272
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 2273
    else:
2274
        order.status = OrderStatus.DOA_CERT_INVALID
2275
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 2276
        update_trust_level(order)
2591 chandransh 2277
    session.commit()
2278
    return True
2279
 
4495 rajveer 2280
def validate_return_product(order_id, is_usable):
2281
    order = get_order(order_id)
2282
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
2283
        return False
5110 mandeep.dh 2284
 
2285
    scanType = ScanType.SALE_RET_UNUSABLE
4495 rajveer 2286
    if is_usable:
2287
        order.status = OrderStatus.RET_PRODUCT_USABLE
2288
        order.statusDescription = "Return product usable"
5110 mandeep.dh 2289
        scanType = ScanType.SALE_RET
4495 rajveer 2290
    else:
2291
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
2292
        order.statusDescription = "Return product unusable"
2293
        update_trust_level(order)
2294
    session.commit()
5110 mandeep.dh 2295
 
2296
    # For OUR warehouses, we need to scan in items for every return
5944 mandeep.dh 2297
    inventoryClient = InventoryClient().get_client()
2298
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
6786 amar.kumar 2299
    if warehouse.billingType == BillingType.OURS or warehouse.billingType == BillingType.OURS_EXTERNAL:
5110 mandeep.dh 2300
        lineitem = order.lineitems[0]
5944 mandeep.dh 2301
        catalogClient = CatalogClient().get_client()
5361 mandeep.dh 2302
        item = catalogClient.getItem(lineitem.item_id)
5110 mandeep.dh 2303
        warehouse_client = WarehouseClient().get_client()
6786 amar.kumar 2304
        if warehouse.billingType == BillingType.OURS or scanType != ScanType.SALE_RET:
2305
            if item.type == ItemType.SERIALIZED:
2306
                warehouse_client.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
2307
            else:
2308
                warehouse_client.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
2309
        if scanType == ScanType.SALE_RET and warehouse.billingType == BillingType.OURS_EXTERNAL:
2310
            warehouse_client.scanForOursExternalSaleReturn(order.id, lineitem.transfer_price)        
4495 rajveer 2311
    return True
2312
 
2628 chandransh 2313
def reship_order(order_id):
2314
    """
4484 rajveer 2315
    If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
2628 chandransh 2316
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
4484 rajveer 2317
        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 2318
 
2319
    If the order is in DOA_CERT_VALID state, it does the following:
2320
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
2321
        2. Creates a return order for the warehouse executive to return the DOA material.
4452 rajveer 2322
        3. Marks the current order as the final DOA_VALID_RESHIPPED state.
2628 chandransh 2323
 
2324
    Returns the id of the newly created order.
2325
 
2326
    Throws an exception if the order with the given id couldn't be found.
2327
 
2328
    Parameters:
2329
     - orderId
2330
    """
2331
    order = get_order(order_id)
4484 rajveer 2332
    if order.status == OrderStatus.RTO_RECEIVED_PRESTINE:
4220 rajveer 2333
        new_order = __clone_order(order, True, order.cod)
4484 rajveer 2334
        order.status = OrderStatus.RTO_RESHIPPED
2628 chandransh 2335
        order.statusDescription = "Order Reshipped"
2336
        session.commit()
3578 mandeep.dh 2337
        update_trust_level(order)
6735 amar.kumar 2338
        __scan_for_reship_order(order_id, new_order)
4486 rajveer 2339
    elif order.status == OrderStatus.RTO_RECEIVED_DAMAGED:
2340
        new_order = __clone_order(order, False, order.cod)
2341
        ret_order = __create_return_order(order)
2342
        order.status = OrderStatus.RTO_DAMAGED_RESHIPPED
2343
        order.statusDescription = "Order Reshipped Received Damaged"
2344
        session.commit()
2345
    elif order.status == OrderStatus.RTO_LOST_IN_TRANSIT:
2346
        new_order = __clone_order(order, False, order.cod)
2347
        order.status = OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED
2348
        order.statusDescription = "Order Reshipped Lost In Transit"
2349
        session.commit()
4662 rajveer 2350
    elif order.status == OrderStatus.LOST_IN_TRANSIT:
2351
        new_order = __clone_order(order, False, order.cod)
2352
        order.status = OrderStatus.LOST_IN_TRANSIT_RESHIPPED
2353
        order.statusDescription = "Order Reshipped Lost In Transit"
2354
        session.commit()
2628 chandransh 2355
    elif order.status == OrderStatus.DOA_CERT_INVALID:
4220 rajveer 2356
        new_order = __clone_order(order, True, False)
2628 chandransh 2357
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
2358
        order.statusDescription = "Order Reshipped"
2359
        session.commit()
6735 amar.kumar 2360
        __scan_for_reship_order(order_id, new_order)
2628 chandransh 2361
    elif order.status == OrderStatus.DOA_CERT_VALID:
4220 rajveer 2362
        new_order = __clone_order(order, False, False)
2628 chandransh 2363
        ret_order = __create_return_order(order)
4452 rajveer 2364
        order.status = OrderStatus.DOA_VALID_RESHIPPED
2628 chandransh 2365
        order.statusDescription = "Order Reshipped"
2366
        session.commit()
4479 rajveer 2367
    elif order.status == OrderStatus.DOA_RECEIVED_DAMAGED:
2368
        new_order = __clone_order(order, False, False)
2369
        ret_order = __create_return_order(order)
2370
        order.status = OrderStatus.DOA_RESHIPPED_RCVD_DAMAGED
2371
        order.statusDescription = "Order Reshipped Received Damaged"
2372
        session.commit()
2373
    elif order.status == OrderStatus.DOA_LOST_IN_TRANSIT:
2374
        new_order = __clone_order(order, False, False)
2375
        order.status = OrderStatus.DOA_RESHIPPED_LOST_IN_TRANSIT
2376
        order.statusDescription = "Order Reshipped Lost In Transit"
2377
        session.commit()
4614 rajveer 2378
    elif order.status == OrderStatus.RET_PRODUCT_USABLE:
5620 mandeep.dh 2379
        new_order = __clone_order(order, False, False)
4614 rajveer 2380
        order.status = OrderStatus.RET_PRODUCT_USABLE_RESHIPPED
4495 rajveer 2381
        order.statusDescription = "Order Reshipped"
2382
        session.commit()
4614 rajveer 2383
    elif order.status == OrderStatus.RET_PRODUCT_UNUSABLE:
4495 rajveer 2384
        new_order = __clone_order(order, False, False)
2385
        ret_order = __create_return_order(order)
4614 rajveer 2386
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE_RESHIPPED
4495 rajveer 2387
        order.statusDescription = "Order Reshipped"
2388
        session.commit()
2389
    elif order.status == OrderStatus.RET_RECEIVED_DAMAGED:
2390
        new_order = __clone_order(order, False, False)
2391
        ret_order = __create_return_order(order)
2392
        order.status = OrderStatus.RET_RESHIPPED_RCVD_DAMAGED
2393
        order.statusDescription = "Order Reshipped Received Damaged"
2394
        session.commit()
2395
    elif order.status == OrderStatus.RET_LOST_IN_TRANSIT:
2396
        new_order = __clone_order(order, False, False)
2397
        order.status = OrderStatus.RET_RESHIPPED_LOST_IN_TRANSIT
2398
        order.statusDescription = "Order Reshipped Lost In Transit"
2399
        session.commit()
2628 chandransh 2400
    else:
2401
        raise TransactionServiceException(112, "This order can't be reshipped")
2402
 
2764 chandransh 2403
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 2404
    order.new_order_id = new_order.id
2405
    session.commit()
2406
 
2407
    return new_order.id
2408
 
6735 amar.kumar 2409
def __scan_for_reship_order(order_id, new_order):
2410
    inventoryClient = InventoryClient().get_client()
2411
    warehouse = inventoryClient.getWarehouse(new_order.warehouse_id)
2412
    if warehouse.billingType == BillingType.OURS:
2413
        warehouseClient = WarehouseClient().get_client()
2414
        inventoryItem = warehouseClient.getInventoryItemFromOrder(order_id)
2415
        warehouseClient.scanForOrder(inventoryItem, ScanType.SALE, new_order.lineitems[0].quantity, new_order.id, new_order.fulfilmentWarehouseId, new_order.warehouse_id)
7199 amar.kumar 2416
    if order.freebieItemId:
2417
        warehouseClient = WarehouseClient().get_client()
2418
        inventoryItem = warehouseClient.reshipfreebie(order_id, new_order.id, new_order.freebieItemId, ScanType.SALE)
6735 amar.kumar 2419
 
3226 chandransh 2420
def refund_order(order_id, refunded_by, reason):
2628 chandransh 2421
    """
4484 rajveer 2422
    If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2628 chandransh 2423
        1. Creates a refund request for batch processing.
2424
        2. Creates a return order for the warehouse executive to return the shipped material.
4484 rajveer 2425
        3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2628 chandransh 2426
 
2427
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2428
        1. Creates a refund request for batch processing.
3226 chandransh 2429
        2. Cancels the reservation of the item in the warehouse.
2430
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 2431
 
3226 chandransh 2432
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2433
        1. Cancels the reservation of the item in the warehouse.
2434
        2. Marks the current order as CANCELED.
2435
 
2436
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
2437
 
2438
    Returns True if it is successful, False otherwise.
2628 chandransh 2439
 
2440
    Throws an exception if the order with the given id couldn't be found.
2441
 
2442
    Parameters:
3226 chandransh 2443
     - order_id
2444
     - refunded_by
2445
     - reason
2628 chandransh 2446
    """
3414 chandransh 2447
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 2448
    order = get_order(order_id)
3186 chandransh 2449
 
3226 chandransh 2450
    if order.cod:
3414 chandransh 2451
        logging.info("Refunding COD order with status " + str(order.status))
4662 rajveer 2452
        status_transition = { OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2453
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2454
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2455
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2456
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2457
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2458
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2459
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2460
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2461
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2462
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2463
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2464
                     OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.COD_VERIFICATION_FAILED,
2465
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2466
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2467
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2468
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2469
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2470
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2471
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2472
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST
3366 chandransh 2473
                     }
2474
        if order.status not in status_transition.keys():
2475
            raise TransactionServiceException(114, "This order can't be refunded")
2476
 
5199 mandeep.dh 2477
        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 2478
            __update_inventory_reservation(order)
2479
            order.statusDescription = "Order Cancelled"
3415 chandransh 2480
        elif order.status == OrderStatus.BILLED:
3413 chandransh 2481
            __create_return_order(order)
2482
            order.statusDescription = "Order Cancelled"
4486 rajveer 2483
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
5386 phani.kuma 2484
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2485
                __create_return_order(order)
4486 rajveer 2486
            order.statusDescription = "RTO Refunded"
4662 rajveer 2487
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2488
            #__create_return_order(order)
4662 rajveer 2489
            order.statusDescription = "Lost in Transit Refunded"
4479 rajveer 2490
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2491
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2492
                __create_return_order(order)
3226 chandransh 2493
            __create_refund(order)
4495 rajveer 2494
            order.statusDescription = "DOA Refunded"
2495
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2496
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2497
                __create_return_order(order)
4495 rajveer 2498
            __create_refund(order)
2499
            order.statusDescription = "Return Refunded"
4247 rajveer 2500
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5199 mandeep.dh 2501
            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 2502
                __update_inventory_reservation(order)
2503
                order.statusDescription = "Order Cancelled on customer request"
2504
            elif order.previousStatus == OrderStatus.BILLED:
2505
                __create_return_order(order)
2506
                order.statusDescription = "Order Cancelled on customer request"
6668 amar.kumar 2507
                order.received_return_timestamp = datetime.datetime.now()
3226 chandransh 2508
    else:
4662 rajveer 2509
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2510
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2511
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2512
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2513
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2514
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2515
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2516
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2517
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2518
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2519
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2520
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2521
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2522
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2523
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2524
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2525
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2526
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2527
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2528
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
2529
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 2530
                     }
2531
        if order.status not in status_transition.keys():
2532
            raise TransactionServiceException(114, "This order can't be refunded")
2533
 
4495 rajveer 2534
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
5386 phani.kuma 2535
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2536
                __create_return_order(order)
3226 chandransh 2537
            __create_refund(order)
4495 rajveer 2538
            order.statusDescription = "RTO Refunded"
4662 rajveer 2539
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2540
            #__create_return_order(order)
4662 rajveer 2541
            __create_refund(order)
2542
            order.statusDescription = "Lost in Transit Refunded"
4495 rajveer 2543
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2544
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2545
                __create_return_order(order)
4495 rajveer 2546
            __create_refund(order)
2547
            order.statusDescription = "DOA Refunded"
2548
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2549
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2550
                __create_return_order(order)
4495 rajveer 2551
            __create_refund(order)
2552
            order.statusDescription = "Return Refunded"
5199 mandeep.dh 2553
        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 2554
            __update_inventory_reservation(order)
2555
            order.statusDescription = "Order Refunded"
4247 rajveer 2556
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5272 mandeep.dh 2557
            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 2558
                if order.previousStatus == OrderStatus.ACCEPTED:
2559
                    __create_refund(order)
4247 rajveer 2560
                __update_inventory_reservation(order)
2561
                order.statusDescription = "Order Cancelled on customer request"
2562
            elif order.previousStatus == OrderStatus.BILLED:
2563
                __create_return_order(order)
2564
                __create_refund(order)
2565
                order.statusDescription = "Order Cancelled on customer request"
6668 amar.kumar 2566
                order.received_return_timestamp = datetime.datetime.now()
4247 rajveer 2567
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
2568
            __update_inventory_reservation(order)
2569
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 2570
 
4873 mandeep.dh 2571
    # For orders that are cancelled after being billed, we need to scan in the scanned out
2572
    # inventory item and change availability accordingly
5944 mandeep.dh 2573
    inventoryClient = InventoryClient().get_client()
2574
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
6786 amar.kumar 2575
    if warehouse.billingType == BillingType.OURS or warehouse.billingType == BillingType.OURS_EXTERNAL:
4873 mandeep.dh 2576
        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]):
2577
            lineitem = order.lineitems[0]
5944 mandeep.dh 2578
            catalogClient = CatalogClient().get_client()
5177 mandeep.dh 2579
            item = catalogClient.getItem(lineitem.item_id)
5361 mandeep.dh 2580
            warehouseClient = WarehouseClient().get_client()
6786 amar.kumar 2581
            if warehouse.billingType == BillingType.OURS:
2582
                if ItemType.SERIALIZED == item.type:
2583
                    warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
2584
                else:
2585
                    warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
2586
            if warehouse.billingType == BillingType.OURS_EXTERNAL:
2587
                warehouseClient.scanForOursExternalSaleReturn(order.id, lineitem.transfer_price)            
4873 mandeep.dh 2588
 
3195 chandransh 2589
    order.status = status_transition[order.status]
2590
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 2591
    order.refunded_by = refunded_by
2592
    order.refund_reason = reason
4873 mandeep.dh 2593
 
2628 chandransh 2594
    session.commit()
2595
    return True
2596
 
3186 chandransh 2597
def __update_inventory_reservation(order):
3191 chandransh 2598
    '''
2599
    Reduce the reservation count for all line items of the given order.
2600
    '''
3186 chandransh 2601
    try:
5944 mandeep.dh 2602
        inventoryClient = InventoryClient().get_client()
3186 chandransh 2603
        for lineitem in order.lineitems:
5966 rajveer 2604
            inventoryClient.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3186 chandransh 2605
    except:
2606
        print "Unable to reduce reservation count"
2607
 
4220 rajveer 2608
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 2609
    current_time = datetime.datetime.now()
2610
    new_order = Order()
2611
    new_order.customer_id = order.customer_id
2612
    new_order.customer_name = order.customer_name
2613
    new_order.customer_city = order.customer_city
2614
    new_order.customer_state = order.customer_state
2615
    new_order.customer_mobilenumber = order.customer_mobilenumber
2616
    new_order.customer_pincode = order.customer_pincode
2617
    new_order.customer_address1 = order.customer_address1
2618
    new_order.customer_address2 = order.customer_address2
2619
    new_order.customer_email = order.customer_email
2620
    new_order.total_amount = order.total_amount
6318 rajveer 2621
    new_order.gvAmount = order.gvAmount
2628 chandransh 2622
    new_order.total_weight = order.total_weight
2623
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2624
    new_order.statusDescription = 'Submitted for Processing'
2625
    new_order.created_timestamp = current_time
5062 varun.gupt 2626
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 2627
 
2628
    new_order.transaction = order.transaction
4220 rajveer 2629
    new_order.cod = is_cod
5527 anupam.sin 2630
    new_order.orderType = order.orderType
7199 amar.kumar 2631
    new_order.freebieItemId = order.freebieItemId
2628 chandransh 2632
    for line_item in order.lineitems:
2633
        litem = LineItem()
2634
        litem.item_id = line_item.item_id
2635
        litem.productGroup = line_item.productGroup
2636
        litem.brand = line_item.brand
2637
        if line_item.model_number:
2638
            litem.model_number = line_item.model_number
2639
        if line_item.model_name:    
2640
            litem.model_name = line_item.model_name
2641
        if line_item.color:
2642
            litem.color = line_item.color
2643
        if line_item.extra_info:
2644
            litem.extra_info = line_item.extra_info
2645
        litem.quantity = line_item.quantity
2646
        litem.unit_price = line_item.unit_price
2647
        litem.unit_weight = line_item.unit_weight
2648
        litem.total_price = line_item.total_price
2649
        litem.total_weight = line_item.total_weight
2650
        litem.transfer_price = line_item.transfer_price
6751 amar.kumar 2651
        litem.nlc = line_item.nlc
4840 mandeep.dh 2652
        litem.dealText = line_item.dealText
6423 amit.gupta 2653
        litem.vatRate = line_item.vatRate
2628 chandransh 2654
        litem.order = new_order
6912 anupam.sin 2655
 
2656
    if order.insurer > 0:
2657
        new_order.insurer = order.insurer
2658
        new_order.insuranceAmount = order.insuranceAmount
2659
        newDetail = InsuranceDetailForOrder()
2660
        oldDetail = InsuranceDetailForOrder.get_by(order_id = order.id)
2661
        newDetail.dob = oldDetail.dob
2662
        newDetail.guardianName = oldDetail.guardianName
2663
        newDetail.order = new_order
2664
 
2628 chandransh 2665
    logistics_client = LogisticsClient().get_client()
2666
    item_id = new_order.lineitems[0].item_id
5785 mandeep.dh 2667
    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 2668
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2628 chandransh 2669
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
6726 rajveer 2670
    logistics_info.deliveryDelay = adjust_delivery_time(current_time, (logistics_info.shippingTime + logistics_info.deliveryDelay))
2628 chandransh 2671
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 2672
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 2673
    new_order.logistics_provider_id = logistics_info.providerId
2674
    new_order.airwaybill_no = logistics_info.airway_billno
2675
    new_order.tracking_id = new_order.airwaybill_no
6726 rajveer 2676
 
2677
    order.courier_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryDelay)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2678
    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 2679
    new_order.promised_delivery_time = new_order.expected_delivery_time
6629 anupam.sin 2680
    new_order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2681
    new_order.promised_shipping_time = new_order.expected_shipping_time
2682
 
2628 chandransh 2683
    if should_copy_billing_info:
5388 phani.kuma 2684
        new_order.vendorId = order.vendorId
2628 chandransh 2685
        new_order.invoice_number = order.invoice_number
2686
        new_order.billed_by = order.billed_by
2687
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 2688
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
5620 mandeep.dh 2689
        new_order.jacket_number = order.jacket_number
2690
        new_order.lineitems[0].serial_number = order.lineitems[0].serial_number
2691
        new_order.lineitems[0].item_number   = order.lineitems[0].item_number
2628 chandransh 2692
        new_order.accepted_timestamp = current_time
2693
        new_order.billing_timestamp = current_time    
2694
        new_order.status = OrderStatus.BILLED
2695
        new_order.statusDescription = 'Order Billed'
5966 rajveer 2696
    else:
2697
        session.commit()       
5944 mandeep.dh 2698
        inventoryClient = InventoryClient().get_client()
5966 rajveer 2699
        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 2700
 
2701
    return new_order
2702
 
2703
def __create_return_order(order):
2687 chandransh 2704
    ret_order = ReturnOrder(order)
2628 chandransh 2705
    return ret_order
2706
 
2707
def __create_refund(order):
4078 chandransh 2708
    payment_client = PaymentClient().get_client()
2709
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 2710
    return
2628 chandransh 2711
 
2536 chandransh 2712
def __get_order_address(order):
2713
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
2714
    if order.customer_address2:
2715
        address = address + order.customer_address2 + "\n"
2716
    address = address + order.customer_city + "\n"
2717
    address = address + order.customer_state + "\n"
2718
    address = address + "PIN " + order.customer_pincode + "\n"
2719
    address = address + "Phone: " + order.customer_mobilenumber
2720
    return address
2721
 
5767 rajveer 2722
def __get_store_address(store):
2723
    address = store.name + "\n" + store.line1 + "\n"
2724
    if store.line2:
2725
        address = address + store.line2 + "\n"
2726
    address = address + store.city + "\n"
2727
    address = address + store.state + "\n"
5802 rajveer 2728
    address = address + "PIN - " + store.pin + "\n"
5793 rajveer 2729
    if store.phone:
5802 rajveer 2730
        address = address + "Phone - " + store.phone + "\n"
5855 rajveer 2731
    address = address +  "Store timings - 11AM to 8PM (7 days)\n"
5767 rajveer 2732
    return address
2733
 
5793 rajveer 2734
def __get_store_address_html(store):
2735
    address = store.name + "<br>" + store.line1 + "<br>"
2736
    if store.line2:
2737
        address = address + store.line2 + "<br>"
2738
    address = address + store.city + "<br>"
2739
    address = address + store.state + "<br>"
5802 rajveer 2740
    address = address + "PIN - " + store.pin + "<br>"
5793 rajveer 2741
    if store.phone:
5802 rajveer 2742
        address = address + "Phone - " + store.phone + "<br>"
5855 rajveer 2743
    address = address +  "Store timings - 7 days: 11AM to 8PM  (7 days)<br>"
5793 rajveer 2744
    return address
2745
 
4815 phani.kuma 2746
def __generate_return_advice(order, warehouse, provider, filename):
2747
    if warehouse.id == 7:
7181 rajveer 2748
        executive = 'Shiv Kumar'
4815 phani.kuma 2749
    else:
4966 phani.kuma 2750
        executive = 'Dinesh Kumar'
2536 chandransh 2751
    pdf = Canvas(filename)
2752
    pdf.setFont('Times-Bold',16)
2753
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
2754
    address_text.textLine("To")
4815 phani.kuma 2755
    address_text.textLine(executive)
2536 chandransh 2756
    for line in warehouse.location.split("\n"):
2757
        address_text.textLine(line)
2758
    address_text.textLine("PIN " + warehouse.pincode)
2759
    pdf.drawText(address_text)
2760
 
2761
    pdf.setFont('Times-Roman',12)
2762
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 2763
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 2764
    lineitem = order.lineitems[0] 
4234 rajveer 2765
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 2766
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
2767
    order_text.textLine("Order ID : " + str(order.id))
2768
    pdf.drawText(order_text)
2769
    pdf.showPage()
2770
    pdf.save()
2771
    return filename
2772
 
5806 rajveer 2773
def __push_collection_to_hotspot(order, type):
2774
    try:
2775
        logistics_client = LogisticsClient().get_client()
2776
        store = logistics_client.getPickupStore(order.pickupStoreId)
2777
        store_string = "<store>" + store.hotspotId + "</store>"
2778
        order_string = "<orderno>" + str(order.id) + "</orderno>"
2779
        collection_type = "<Type>" + type + "</Type>"
5833 rajveer 2780
        payment_mode = get_order_attribute_value(order.id, "PAYMENT_MODE")
5806 rajveer 2781
        if type == "SALE":
6318 rajveer 2782
            amount = int(order.total_amount-order.gvAmount)
5806 rajveer 2783
            ts = order.delivery_timestamp
2784
        if type == "SALE RETURN":
6318 rajveer 2785
            amount = -int(order.total_amount-order.gvAmount)
5806 rajveer 2786
            ts = order.refund_timestamp
2787
        if payment_mode == "Cash":
2788
            cash_string = "<cash>" + str(amount) + "</cash>"
2789
            card_string = "<hdfc>0</hdfc>"
2790
        if payment_mode == "Card":
2791
            cash_string = "<cash>0</cash>"
2792
            card_string = "<hdfc>" + str(amount) + "</hdfc>"
2793
        date_string = "<date>" + ts.strftime("%Y%m%d") + "</date>"
2794
        time_string = "<time>" + ts.strftime("%H%M%S") + "</time>"
2795
 
7254 rajveer 2796
        conn = httplib.HTTPConnection("182.71.104.186")
5806 rajveer 2797
        XML="""
2798
        <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/">
2799
          <soap:Body>
2800
            <SaholicDataTransfer xmlns="http://tempuri.org/">
2801
        """
2802
 
2803
        XML = XML + store_string + order_string + collection_type + cash_string + card_string + date_string + time_string 
2804
 
2805
        footer = """
2806
            </SaholicDataTransfer>
2807
          </soap:Body>
2808
        </soap:Envelope>
2809
        """
2810
        XML = XML + footer
2811
 
2812
        params = urllib.urlencode({'op': 'SaholicDataTransfer'})
2813
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
2814
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
2815
        conn.send(XML)
2816
        response = conn.getresponse()
2817
        print response.status, response.reason
2818
        resp = response.read()
2819
        conn.close()
2820
        print resp
2821
        if "Saved Successfully" in resp:
2822
            return True
2823
        elif "Error in Saving Data" in resp:
2824
            return False
2825
        else: 
2826
            return False
2827
    except Exception as e:
2828
        print e
2829
        return False
2830
 
2697 chandransh 2831
def get_return_orders(warehouse_id, from_date, to_date):
2832
    query = ReturnOrder.query.filter_by(processedStatus = False)
2833
    if warehouse_id != -1:
2834
        query = query.filter_by(warehouseId = warehouse_id)
2835
    if from_date:
4118 chandransh 2836
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 2837
    if to_date:
4118 chandransh 2838
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 2839
    return [return_order.to_thrift_object() for return_order in query.all()]
2840
 
5481 phani.kuma 2841
def get_all_return_orders(onlyNotProcessed, from_date, to_date):
2842
    query = ReturnOrder.query
2843
    if onlyNotProcessed:
2844
        query = query.filter_by(processedStatus = False)
2845
    if from_date:
2846
        query = query.filter(ReturnOrder.createdAt >= from_date)
2847
    if to_date:
2848
        query = query.filter(ReturnOrder.createdAt <= to_date)
2849
    return [return_order.to_thrift_object() for return_order in query.all()]
2850
 
2700 chandransh 2851
def get_return_order(id):
2852
    ret_order = ReturnOrder.get_by(orderId = id)
2853
    if ret_order is None:
2854
        raise TransactionServiceException(116, "No return order found for the given order id")
2855
    return ret_order.to_thrift_object()
2856
 
2697 chandransh 2857
def process_return(ret_order_id):
2858
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
2859
    if ret_order is None:
2860
        raise TransactionServiceException(116, "No return order found for the given order id")
2861
    ret_order.processedStatus = True
2701 chandransh 2862
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 2863
    session.commit()
2864
 
4757 mandeep.dh 2865
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
2866
    """
2867
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
2868
    the quantities for which the PO is raised.
2869
 
2870
    Parameters:
2871
     - itemIdQuantityMap
2872
     - purchaseOrderId
2873
     - warehouseId
2874
    """
3451 chandransh 2875
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 2876
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 2877
    query = query.filter_by(purchase_order_id=None)
2878
    query = query.order_by(Order.created_timestamp)
2879
    pending_orders = query.all()
4586 mandeep.dh 2880
 
2881
    for order in pending_orders:
4757 mandeep.dh 2882
        lineitem = order.lineitems[0]
2883
        if itemIdQuantityMap.has_key(lineitem.item_id):
2884
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
2885
                order.status = OrderStatus.LOW_INV_PO_RAISED
2886
                order.statusDescription = 'In Process'
2887
                order.purchase_order_id = purchaseOrderId
2888
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 2889
 
2819 chandransh 2890
    session.commit()
2891
 
3451 chandransh 2892
def update_weight(order_id, weight):
3469 chandransh 2893
    '''
2894
    Update the weight of order
2895
    '''
3451 chandransh 2896
    order = get_order(order_id)
2897
    order.total_weight = weight
3469 chandransh 2898
    lineitem = order.lineitems[0]
2899
    lineitem.total_weight = weight
2900
    lineitem.unit_weight = weight
3451 chandransh 2901
 
3469 chandransh 2902
    session.commit()
2903
    return order
2904
 
2905
def change_product(order_id, item_id):
2906
    '''
2907
    Ship a product of a different color to the customer.
2908
    '''
2909
    order = get_order(order_id)
4662 rajveer 2910
    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 2911
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
2912
 
2913
    lineitem = order.lineitems[0]
3451 chandransh 2914
 
3469 chandransh 2915
    catalog_client = CatalogClient().get_client()
2916
 
2917
    old_item = catalog_client.getItem(lineitem.item_id)
2918
    item = catalog_client.getItem(item_id)
2919
    if old_item.catalogItemId != item.catalogItemId:
2920
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
2921
 
5944 mandeep.dh 2922
    inventoryClient = InventoryClient().get_client()
5966 rajveer 2923
    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 2924
    __update_inventory_reservation(order)
3469 chandransh 2925
    #TODO: Check that this new item has the same price
2926
 
2927
    lineitem.item_id = item_id
2928
    lineitem.color = item.color
2929
 
3451 chandransh 2930
    session.commit()
3469 chandransh 2931
 
2932
    order = get_order(order_id)
3451 chandransh 2933
    return order
3469 chandransh 2934
 
2935
def change_warehouse(order_id, warehouse_id):
2936
    '''
2937
    Update the warehouse which will be used to fulfil this order.
2938
    '''
2939
    order = get_order(order_id)
6019 rajveer 2940
    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 2941
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
2942
 
2943
    if warehouse_id == order.warehouse_id:
2944
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
2945
 
2946
    lineitem = order.lineitems[0]
2947
    catalog_client = CatalogClient().get_client()
5944 mandeep.dh 2948
    inventoryClient = InventoryClient().get_client()
3469 chandransh 2949
    try:
5944 mandeep.dh 2950
        warehouse = inventoryClient.getWarehouse(warehouse_id)
3469 chandransh 2951
    except:
2952
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 2953
 
6870 rajveer 2954
    if not warehouse.billingWarehouseId:
5147 mandeep.dh 2955
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 2956
 
5620 mandeep.dh 2957
    # If One gives a billing warehouse for warehouse shift, we should assign order to the GOOD warehouse
2958
    # present within it with maximum availability
2959
    if warehouse.id == warehouse.billingWarehouseId:
5944 mandeep.dh 2960
        warehouses = inventoryClient.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
5147 mandeep.dh 2961
        if warehouses:
5944 mandeep.dh 2962
            itemInventory = inventoryClient.getItemInventoryByItemId(lineitem.item_id)
5147 mandeep.dh 2963
            warehouse = warehouses[0]
2964
            maxAvailability = 0
2965
            for goodWarehouse in warehouses:
2966
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
2967
                    warehouse = goodWarehouse
2968
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
2969
 
2970
            # Use preferred vendor's warehouse if not available anywhere
2971
            if not maxAvailability:
2972
                item = catalog_client.getItem(lineitem.item_id)
2973
                if item.preferredVendor:
2974
                    for goodWarehouse in warehouses:
2975
                        if goodWarehouse.vendor.id == item.preferredVendor:
2976
                            warehouse = goodWarehouse
2977
        else:
2978
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
2979
 
6007 rajveer 2980
    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 2981
    __update_inventory_reservation(order)
6789 rajveer 2982
    if order.status == OrderStatus.ACCEPTED:
2983
        __update_transfer_price(order, warehouse.id)
5110 mandeep.dh 2984
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 2985
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 2986
    session.commit()
2987
    return order
3553 chandransh 2988
 
6789 rajveer 2989
def __update_transfer_price(order, warehouse_id):
2990
    lineitem = order.lineitems[0]
2991
    inventory_client = InventoryClient().get_client()
2992
    warehouse = inventory_client.getWarehouse(warehouse_id)
2993
    item_pricing = inventory_client.getItemPricing(lineitem.item_id, warehouse.vendor.id)
2994
    lineitem.transfer_price = item_pricing.transferPrice
2995
    lineitem.nlc = item_pricing.nlc
2996
 
4647 rajveer 2997
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 2998
    '''
3994 chandransh 2999
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 3000
    '''
3001
    order = get_order(order_id)
3002
    try:
3581 chandransh 3003
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 3004
        order.delayReasonText = delayReasonText
4009 chandransh 3005
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
3006
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 3007
 
4842 rajveer 3008
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
3009
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 3010
 
6726 rajveer 3011
        order.courier_delivery_time = order.courier_delivery_time + datetime.timedelta(days=adjust_delivery_time(order.courier_delivery_time, further_delay))
3012
 
3553 chandransh 3013
        session.commit()
4008 mandeep.dh 3014
 
3015
        try:
3016
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
3017
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
3018
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
3019
            session.commit()
3020
        except Exception as e:
4065 mandeep.dh 3021
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 3022
 
3553 chandransh 3023
        return True
3024
    except:
3994 chandransh 3025
        print sys.exc_info()[0]
3553 chandransh 3026
        return False
3956 chandransh 3027
 
3028
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
3029
    unprocessed_awbs = {}
3030
    for awb, amount in collected_amount_map.iteritems():
3031
        try:
3032
            order = Order.query.filter_by(airwaybill_no=awb).one()
3033
        except NoResultFound:
3034
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
3035
            continue
3036
        except MultipleResultsFound:
3037
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
3038
            continue
3039
 
3040
        if order.cod_reconciliation_timestamp:
3041
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
3042
            continue
3043
 
3044
        if order.status < OrderStatus.DELIVERY_SUCCESS:
3045
            #Order has not been delivered yet. No way we can receive the payment.
3046
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
3047
            continue
3048
 
4252 rajveer 3049
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
6318 rajveer 3050
        if abs(amount - (order.total_amount - order.gvAmount)) > 0.5:
3956 chandransh 3051
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
6318 rajveer 3052
            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 3053
            continue
3054
 
3055
        try:
3056
            payment_client = PaymentClient().get_client()
3057
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
3058
        except Exception:
3059
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
3060
            continue
3061
 
3062
        #Payment has been recorded now. We can update the order peacefully.
3063
        order.cod_reconciliation_timestamp = datetime.datetime.now()
3064
        session.commit()
3469 chandransh 3065
 
3956 chandransh 3066
    return unprocessed_awbs
4008 mandeep.dh 3067
 
3068
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 3069
    """
3070
    Returns the list of transaction ids that require some extra processing and
3071
    which belong to a particular category. This is currently used by CRM
3072
    application. If no such transaction ids are present, it returns an empty list.
3073
    """
3074
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 3075
 
4065 mandeep.dh 3076
    if category is not None:
3077
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 3078
 
4065 mandeep.dh 3079
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 3080
 
3081
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 3082
    """
3083
    Marks a particular transaction as processed for a particular cateogory.
3084
    It essentially deletes the transaction id record for a particular
3085
    processing type category (if present) from DB.
3086
    This is currently used by CRM application.
3087
    """
4008 mandeep.dh 3088
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
3089
    session.commit()
3090
 
4018 chandransh 3091
def get_item_wise_risky_orders_count():
3092
    """
3093
    Returns a map containing the number of risky orders keyed by item id. A risky order
3094
    is defined as one whose shipping date is about to expire.
3095
    """
3096
    item_wise_risky_orders_count = {}
4019 chandransh 3097
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 3098
    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()
3099
    for order in orders:
3100
        for lineitem in order.lineitems:
3101
            quantity = lineitem.quantity
3102
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
3103
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
3104
 
3105
            item_wise_risky_orders_count[lineitem.item_id] = quantity
3106
    return item_wise_risky_orders_count
3107
 
4324 mandeep.dh 3108
def update_shipment_address(order_id, address_id):
3109
    """
3110
    Updates shipment address of an order. Delivery and shipping date estimates
3111
    etc. are also updated here.
3112
 
3113
    Throws TransactionServiceException in case address change is not
3114
    possible due to certain reasons such as new pincode in address is
3115
    not serviceable etc.
3116
 
3117
    Parameters:
3118
     - orderId
3119
     - addressId
3120
    """
3121
    user_client = UserClient().get_client()
3122
    address     = user_client.getAddressById(address_id)
3123
    order       = get_order(order_id)
3124
 
4630 mandeep.dh 3125
    type = DeliveryType.PREPAID
3126
    if order.cod:
3127
        type = DeliveryType.COD
3128
 
4324 mandeep.dh 3129
    logistics_client = LogisticsClient().get_client()
5886 mandeep.dh 3130
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type)
4324 mandeep.dh 3131
 
3132
    # Check for new estimate. Raise exception if new address is not serviceable
3133
    if logistics_info.deliveryTime == -1:
3134
        raise TransactionServiceException(1, 'Location not serviceable')
3135
 
3136
    # COD services are not available everywhere
3137
    if order.cod:
4868 rajveer 3138
        if not logistics_info.codAllowed:
4324 mandeep.dh 3139
            raise TransactionServiceException(2, 'COD service not available')
3140
 
5593 mandeep.dh 3141
    if logistics_info.providerId != order.logistics_provider_id:
5887 mandeep.dh 3142
        logistics_info = logistics_client.getLogisticsInfo(address.pin, order.lineitems[0].item_id, type, PickUpType.COURIER)
5593 mandeep.dh 3143
        order.tracking_id = logistics_info.airway_billno
3144
        order.airwaybill_no = logistics_info.airway_billno
3145
        order.logistics_provider_id = logistics_info.providerId
3146
 
6525 rajveer 3147
    order.otg = logistics_info.otgAvailable
4324 mandeep.dh 3148
    current_time = datetime.datetime.now()
3149
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
3150
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
6726 rajveer 3151
    logistics_info.deliveryDelay = adjust_delivery_time(current_time, (logistics_info.shippingTime+logistics_info.deliveryDelay))
4324 mandeep.dh 3152
 
3153
    order.customer_name         = address.name
3154
    order.customer_pincode      = address.pin
3155
    order.customer_address1     = address.line1
3156
    order.customer_address2     = address.line2
3157
    order.customer_city         = address.city
3158
    order.customer_state        = address.state
3159
    order.customer_mobilenumber = address.phone
3160
 
3161
    if order.cod:
3162
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
6726 rajveer 3163
        order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3164
        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 3165
    else:
3166
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
6726 rajveer 3167
        order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3168
        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 3169
 
3170
    order.promised_shipping_time = order.expected_shipping_time
3171
    order.promised_delivery_time = order.expected_delivery_time 
3172
 
3173
    session.commit()
3174
 
4247 rajveer 3175
def mark_order_cancellation_request_received(orderId):
3176
    """
3177
    Mark order as cancellation request received. If customer sends request of cancellation of
3178
    a particular order, this method will be called. It will just change status of the order
3179
    depending on its current status. It also records the previous status, so that we can move
3180
    back to that status if cancellation request is denied.
3181
 
3182
    Parameters:
3183
     - orderId
3184
    """
4662 rajveer 3185
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 3186
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
3187
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 3188
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
3189
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
3190
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 3191
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
3192
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
3193
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
3194
             }
4662 rajveer 3195
 
3196
    order = get_order(orderId)
4247 rajveer 3197
    if order.status not in status_transition.keys():
3198
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
3199
 
4662 rajveer 3200
 
4247 rajveer 3201
    order.previousStatus = order.status
3202
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
3203
    order.statusDescription = "Cancellation request received from user"
3204
    session.commit()
3205
 
4662 rajveer 3206
def mark_order_as_lost_in_transit(orderId):
3207
    """
3208
    Parameters:
3209
     - orderId
3210
    """
3211
    order = get_order(orderId)
4910 phani.kuma 3212
    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 3213
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
3214
    order.status = OrderStatus.LOST_IN_TRANSIT
3215
    order.statusDescription = "Lost in Transit"
3216
    session.commit()
3217
 
4258 rajveer 3218
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 3219
    """
4258 rajveer 3220
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
3221
    Changed transaction and all orders status to payment accepted.
4247 rajveer 3222
 
3223
    Parameters:
4258 rajveer 3224
     - transactionId
4247 rajveer 3225
    """
4258 rajveer 3226
    transaction = get_transaction(transactionId)
3227
    transaction.status = TransactionStatus.AUTHORIZED
3228
    for order in transaction.orders:
3229
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
3230
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 3231
    session.commit()
3232
 
4259 anupam.sin 3233
def refund_transaction(transactionId, refundedBy, reason):
3234
    """
3235
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
3236
    need to be cancelled
3237
 
3238
    Parameters:
3239
     - transactionId
3240
    """
3241
    transaction = get_transaction(transactionId)
3242
    transaction.status = TransactionStatus.FAILED
3243
    for order in transaction.orders:
3244
        refund_order(order.id, refundedBy, reason)
3245
    session.commit()
3246
 
4247 rajveer 3247
def mark_order_cancellation_request_denied(orderId):
3248
    """
4283 anupam.sin 3249
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 3250
 
3251
    Parameters:
3252
     - orderId
3253
    """
3254
    order = get_order(orderId)
3255
    order.status = order.previousStatus
3256
    order.previousStatus = None
3257
    order.statusDescription = "Cancellation request denied"
3258
    session.commit()
3259
 
3260
def mark_order_cancellation_request_confirmed(orderId):
3261
    """
3262
    If we decide to to cancel order, CRM will call this method to move the status of order to
3263
    cancellation request confirmed. After this OM will be able to cancel the order.
3264
 
3265
    Parameters:
3266
     - orderId
3267
    """
3268
    order = get_order(orderId)
3269
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
3270
    order.statusDescription = "Cancellation request confirmed"
3271
    session.commit()
3272
 
4285 rajveer 3273
def accept_orders_for_item_id(itemId, inventory):
3274
    """
3275
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
3276
    given order is not a COD order, it also captures the payment if the same has not been captured.
3277
 
3278
    Parameters:
3279
     - itemId
3280
     - inventory
3281
    """
6782 rajveer 3282
    orders = Order.query.filter(Order.warehouse_id == 9).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 3283
    for order in orders:
4301 rajveer 3284
        if inventory > 0:
3285
            lineitem = order.lineitems[0]
3286
            if itemId == lineitem.item_id:
3287
                try:
3288
                    accept_order(order.id)
3289
                    inventory = inventory - lineitem.quantity
3290
                except:
3291
                    logging.info("Unable to accept the order")
3292
        else:
3293
            order_outofstock(order.id)
4285 rajveer 3294
    return
3295
 
6864 rajveer 3296
def move_orders_to_correct_warehouse():
3297
    orders = Order.query.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.promised_shipping_time).all()
3298
    logistics_client = LogisticsClient().get_client()
3299
    for order in orders:
3300
        lineitem = order.lineitems[0]
6870 rajveer 3301
        logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, lineitem.item_id, order.cod, PickUpType.COURIER)
6864 rajveer 3302
        if order.fulfilmentWarehouseId != logistics_info.fulfilmentWarehouseId:
6870 rajveer 3303
            try:
3304
                print "++++" + str(order.id) + "=" + str(order.fulfilmentWarehouseId) + "->"+ str(logistics_info.fulfilmentWarehouseId)
3305
                change_warehouse(order.id, logistics_info.fulfilmentWarehouseId)
3306
            except:
3307
                print "++++" + str(order.id)
6864 rajveer 3308
 
4607 rajveer 3309
def get_slipped_sipping_date_orders():
4662 rajveer 3310
    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 3311
 
3312
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
3313
    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 3314
 
4369 rajveer 3315
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
3316
    if isReminder:
3317
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3318
    else:
3319
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3320
 
3321
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3322
    for order in orders:
3323
        lineitem = order.lineitems[0]
3324
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3325
            if estimate > 0:
3326
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
3327
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 3328
            order.statusDescription = "PO Raised"
4303 rajveer 3329
            quantity = quantity - lineitem.quantity
3330
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
3331
            session.commit()
3332
 
4369 rajveer 3333
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
3334
    if isReminder:
3335
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3336
    else:
3337
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3338
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3339
    for order in orders:
3340
        lineitem = order.lineitems[0]
3341
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3342
            if estimate > 0:
3343
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
3344
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 3345
            order.statusDescription = "Reversal Initiated"
4303 rajveer 3346
            quantity = quantity - lineitem.quantity
3347
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
3348
            session.commit()
3349
 
4369 rajveer 3350
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
3351
    if isReminder:
3352
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3353
    else:
3354
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3355
 
3356
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3357
    for order in orders:
3358
        lineitem = order.lineitems[0]
3359
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3360
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 3361
            order.statusDescription = "Not Available"
4303 rajveer 3362
            quantity = quantity - lineitem.quantity
3363
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
3364
            session.commit()
3365
 
3366
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 3367
    orderInv = OrderInventory.get_by(order_id=order.id)
3368
    if not orderInv:
3369
        orderInv = OrderInventory()
3370
        orderInv.order = order
4303 rajveer 3371
    orderInv.hotspotAction = hotspotAction  
3372
    orderInv.estimate = estimate
3373
    orderInv.itemId = itemId
3374
    orderInv.timestamp = datetime.datetime.now()
3375
    orderInv.quantity = quantity
3376
 
4556 mandeep.dh 3377
'''    
4369 rajveer 3378
def mark_orders_as_timeout(vendorId):
3379
    ret_timeouts = {}
3380
    orderInvs = OrderInventory.query.all()
3381
    for orderInv in orderInvs:
3382
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
3383
            if not ret_timeouts.has_key(orderInv.itemId):
3384
                timeout = TimeoutSummary()
3385
                ret_timeouts[orderInv.itemId] = timeout
3386
            else:
3387
                timeout = ret_timeouts.get(orderInv.itemId)
3388
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3389
                if timeout.poRaised:
3390
                    timeout.poRaised += 1
3391
                else:
3392
                    timeout.poRaised = 1
3393
 
3394
                if timeout.poEstimate:
3395
                    timeout.poEstimate += orderInv.estimate
3396
                else:
3397
                    timeout.poEstimate = orderInv.estimate
3398
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
3399
                orderInv.order.statusDescription = "PO Raised Timeout"
3400
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3401
                if timeout.reversalInitiated:
3402
                    timeout.reversalInitiated += 1
3403
                else:
3404
                    timeout.reversalInitiated = 1
3405
 
3406
                if timeout.reversalEstimate:
3407
                    timeout.reversalEstimate += orderInv.estimate
3408
                else:
3409
                    timeout.reversalEstimate = orderInv.estimate
3410
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
3411
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
3412
            else:
3413
                orderInv.delete()
3414
    session.commit()
3415
    return ret_timeouts
4556 mandeep.dh 3416
'''
3417
 
3418
 
3419
def mark_orders_as_timeout(vendorId):
3420
    ret_timeouts = {}
3421
    orderInvs = OrderInventory.query.all()
3422
    for orderInv in orderInvs:
3423
        if not ret_timeouts.has_key(orderInv.itemId):
3424
            timeout = TimeoutSummary()
3425
            ret_timeouts[orderInv.itemId] = timeout
3426
        else:
3427
            timeout = ret_timeouts.get(orderInv.itemId)
3428
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3429
            if timeout.poRaised:
3430
                timeout.poRaised += 1
3431
            else:
3432
                timeout.poRaised = 1
3433
 
3434
            if timeout.poEstimate:
3435
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
3436
            else:
3437
                timeout.poEstimate = orderInv.estimate
3438
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3439
            if timeout.reversalInitiated:
3440
                timeout.reversalInitiated += 1
3441
            else:
3442
                timeout.reversalInitiated = 1
3443
 
3444
            if timeout.reversalEstimate:
3445
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
3446
            else:
3447
                timeout.reversalEstimate = orderInv.estimate
3448
        orderInv.order.status = OrderStatus.INVENTORY_LOW
3449
        orderInv.order.statusDescription = "Low Inventory"
3450
        orderInv.delete()
3451
    session.commit()
3452
    return ret_timeouts
3453
 
4386 anupam.sin 3454
def get_order_for_awb(awb):
3455
    order = Order.get_by(airwaybill_no=awb)
3456
    if not order:
3457
        raise TransactionServiceException(108, "no such order")
3458
 
3459
    return order
4369 rajveer 3460
 
4910 phani.kuma 3461
def get_orders_for_provider_for_status(provider_id, order_status_list):
3462
    if not provider_id or not order_status_list:
4506 phani.kuma 3463
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 3464
    doa_provider = False
3465
    for order_status in order_status_list:
3466
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
3467
            doa_provider = True
3468
    if doa_provider:
3469
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 3470
    else:
4910 phani.kuma 3471
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 3472
    return query.all()
4386 anupam.sin 3473
 
4600 varun.gupt 3474
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 3475
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
3476
 
3477
    if vendor_id:
3478
        query = query.filter_by(vendorId = vendor_id)
3479
 
4600 varun.gupt 3480
    if billing_date_from:
3481
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 3482
 
4600 varun.gupt 3483
    if billing_date_to:
3484
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 3485
 
4600 varun.gupt 3486
    return query.all()
3487
 
5481 phani.kuma 3488
def get_billed_orders(vendor_id, onlyVendorNotPaid, billing_date_from, billing_date_to):
5386 phani.kuma 3489
    query = Order.query.filter(Order.billing_timestamp != None)
5481 phani.kuma 3490
 
3491
    if onlyVendorNotPaid:
5488 phani.kuma 3492
        query = query.filter_by(vendor_paid = False)
5481 phani.kuma 3493
 
5386 phani.kuma 3494
    if vendor_id != -1:
3495
        query = query.filter_by(vendorId = vendor_id)
3496
 
5481 phani.kuma 3497
    if billing_date_from:
3498
        query = query.filter(Order.billing_timestamp >= billing_date_from)
3499
 
3500
    if billing_date_to:
3501
        query = query.filter(Order.billing_timestamp <= billing_date_to)
3502
 
4885 varun.gupt 3503
    return query.all()
4875 varun.gupt 3504
 
4600 varun.gupt 3505
def save_bluedart_settlements(map_awb_and_amount):
3506
    payment_client = PaymentClient().get_client()
3507
 
3508
    for awb, amount in map_awb_and_amount.iteritems():
3509
        order = Order.get_by(airwaybill_no = awb)
3510
 
3511
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
3512
        settlement = PaymentSettlement()
3513
        settlement.paymentId = payment.paymentId
3514
        settlement.paymentGatewayId = payment.gatewayId
3515
        settlement.netCollection = amount
3516
        session.commit()
3517
 
4905 varun.gupt 3518
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 3519
    originalOrderId = None
3520
    if paymentGatewayId == 4:
3521
        cod_order = Order.get_by(id = referenceId)
3522
        if cod_order.originalOrderId:
3523
            originalOrderId = cod_order.originalOrderId
3524
        else:
3525
            originalOrderId = referenceId
4600 varun.gupt 3526
    settlement = PaymentSettlement()
3527
    settlement.settlementDate = settlementDate
3528
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 3529
    if originalOrderId is not None:
3530
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 3531
    settlement.referenceId = referenceId
4600 varun.gupt 3532
    settlement.serviceTax = serviceTax
3533
    settlement.otherCharges = otherCharges
3534
    settlement.netCollection = netCollection
3535
    session.commit()
3536
 
5386 phani.kuma 3537
def get_settlement_for_Prepaid(reference_id, is_refund = False):
3538
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 3539
 
5189 varun.gupt 3540
    if is_refund:
3541
        query = query.filter(PaymentSettlement.netCollection < 0)
3542
    else:
3543
        query = query.filter(PaymentSettlement.netCollection > 0)
3544
 
5386 phani.kuma 3545
    return query.first()
3546
 
3547
def get_settlement_for_Cod(orderId, is_refund = False):
3548
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 3549
 
5386 phani.kuma 3550
    if is_refund:
3551
        query = query.filter(PaymentSettlement.netCollection < 0)
3552
    else:
3553
        query = query.filter(PaymentSettlement.netCollection > 0)
3554
 
5189 varun.gupt 3555
    return query.first()
4600 varun.gupt 3556
 
3557
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
5551 phani.kuma 3558
    summary = EBSSettlementSummary.query.filter_by(settlementId = settlement_id).first()
5481 phani.kuma 3559
    if summary is None:
3560
        summary = EBSSettlementSummary()
3561
        summary.settlementId = settlement_id
3562
        summary.settlementDate = settlement_date
3563
        summary.transactionDateFrom = transaction_date_from
3564
        summary.transactionDateTo = transaction_date_to
3565
        summary.amount = amount
3566
        summary.detailsUploaded = False
3567
        session.commit()
4600 varun.gupt 3568
 
3569
def get_ebs_settlement_summaries():
3570
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
3571
    summary_map = {}
3572
 
3573
    for summary in summaries:
3574
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
3575
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
3576
 
3577
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
3578
 
3579
    return summary_map
3580
 
3581
def get_ebs_settlement_date(settlement_id):
3582
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3583
 
3584
    if summary:
3585
        return summary.settlementDate
3586
 
3587
def mark_ebs_settlement_uploaded(settlement_id):
3588
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3589
 
3590
    if summary:
3591
        summary.detailsUploaded = True
3592
        session.commit()
4715 varun.gupt 3593
 
3594
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
3595
    query = PaymentSettlement.query
4600 varun.gupt 3596
 
4715 varun.gupt 3597
    if settlement_date_from:
3598
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
3599
 
3600
    if settlement_date_to:
3601
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
3602
 
4749 varun.gupt 3603
    if is_refund is True:
3604
        query = query.filter(PaymentSettlement.netCollection < 0.0)
3605
    else:
3606
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 3607
 
4749 varun.gupt 3608
    return query.all()
4715 varun.gupt 3609
 
3610
def get_reshipped_order_ids(order_ids):
3611
    reshipped_order_ids = []
3612
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
3613
 
4749 varun.gupt 3614
def get_shipping_confirmation_email_body(order):
3615
 
3616
    html = """
3617
<html>
3618
<body>
3619
<div>
3620
    <p>Dear Customer,</p>
3621
    <p>
4885 varun.gupt 3622
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 3623
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
7198 amar.kumar 3624
 
4749 varun.gupt 3625
    </p>
3626
    <p>
6655 rajveer 3627
        Expected delivery date for your order is $expected_delivery_date.
6675 rajveer 3628
        <br/>
3629
        $otg_text
7198 amar.kumar 3630
        $freebie_text
6675 rajveer 3631
        <br/> 
6716 rajveer 3632
        The product can be delivered to you between business hours of 10am to 6pm.
3633
        You can Check the current shipment updates for your product online at <a href="www.saholic.com/myaccount">Open Orders</a>.
4749 varun.gupt 3634
    </p>
3635
    <p>
5573 amit.gupta 3636
        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 3637
    </p>
5139 varun.gupt 3638
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 3639
    <p>
3640
        Warm Regards,<br />
6029 rajveer 3641
        $source_name Team
4749 varun.gupt 3642
    </p>
4750 varun.gupt 3643
</div>
4749 varun.gupt 3644
</body>
3645
</html>
3646
    """
5573 amit.gupta 3647
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}}
5139 varun.gupt 3648
    provider_name = logistics_providers[order.logistics_provider_id]['name']
3649
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
3650
 
5868 rajveer 3651
    lclient = LogisticsClient().get_client()
3652
    logistics_info = lclient.getLogisticsEstimation(order.lineitems[0].item_id, order.customer_pincode, DeliveryType.PREPAID)
4749 varun.gupt 3653
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 3654
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
6712 rajveer 3655
    product = str(order.lineitems[0])
5868 rajveer 3656
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (logistics_info.deliveryTime - logistics_info.shippingTime)))
6728 rajveer 3657
    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 3658
    #update new expected timestamp
3659
    if order.cod:
6705 amar.kumar 3660
        new_expected_delivery_timestamp = new_expected_delivery_timestamp.replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6728 rajveer 3661
        order.courier_delivery_time = new_courier_delivery_time.replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6666 rajveer 3662
    else:
6705 amar.kumar 3663
        new_expected_delivery_timestamp = new_expected_delivery_timestamp.replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6728 rajveer 3664
        order.courier_delivery_time = new_courier_delivery_time.replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6666 rajveer 3665
    order.expected_delivery_time = new_expected_delivery_timestamp
3666
    session.commit()
3667
 
4885 varun.gupt 3668
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
6655 rajveer 3669
    otg_text = ""
3670
    if order.otg:
6662 rajveer 3671
        promised_delivery_date = order.promised_delivery_time.strftime("%A, %d %B %Y")
6655 rajveer 3672
        if new_expected_delivery_timestamp > order.promised_delivery_time:
6712 rajveer 3673
            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 3674
        elif new_expected_delivery_timestamp < order.promised_delivery_time:
6662 rajveer 3675
            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 3676
        else:            
6662 rajveer 3677
            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 + '.'
7190 amar.kumar 3678
 
3679
    freebie_text = "<br/>"
3680
    if order.freebieItemId:
3681
        catalog_client = CatalogClient().get_client()
3682
        item = catalog_client.getItem(order.freebieItemId)
7198 amar.kumar 3683
        freebie_text = freebie_text = "We have also shipped you " + item.brand + " " + item.modelName + "" + item.modelNumber +" as promised<br/>"
7190 amar.kumar 3684
    else:
3685
        freebie_orderId = get_order_attribute_value(order.id, "freebieOrderId")
3686
        if freebie_orderId != "":
3687
            line_items = get_line_items_for_order(int(freebie_orderId))
7198 amar.kumar 3688
            freebie_order = get_order(int(freebie_orderId))
3689
            freebie_text = freebie_text + "We wish to inform you that your freebie item " +line_items[0].brand + " " + line_items[0].model_name + " " + line_items[0].model_number + " will be sent as a separate order with OrderId : " + freebie_orderId + " and is expected to be delivered on " + freebie_order.expected_delivery_time.strftime("%A, %d %B %Y")+ "<br/>"
3690
        else:
3691
            freebie_text = ""
6655 rajveer 3692
 
7190 amar.kumar 3693
    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, freebie_text = freebie_text)
4885 varun.gupt 3694
    return Template(html).substitute(info)
4749 varun.gupt 3695
 
5832 rajveer 3696
def enqueue_shipping_confirmation_email(order):
4915 varun.gupt 3697
    # Calling helper service on production
3698
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5832 rajveer 3699
    try:
3700
        emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
3701
        emailBody = get_shipping_confirmation_email_body(order)
6906 rajveer 3702
        helperClient.saveUserEmailForSending([order.customer_email], None, emailSubject, emailBody, str(order.id), 'ShippingConfirmation', [], [])
6687 rajveer 3703
 
5832 rajveer 3704
    except Exception as e:
3705
        print e
5139 varun.gupt 3706
 
4915 varun.gupt 3707
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 3708
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
3709
    query = query.filter(Order.created_timestamp >= start_date)
3710
    query = query.filter(Order.created_timestamp <= end_date)
3711
    return query.all()
4915 varun.gupt 3712
 
5067 varun.gupt 3713
def get_order_ids_for_status(status, start_datetime, end_datetime):
3714
    query = Order.query.filter(Order.status == status)
3715
    query = query.filter(Order.created_timestamp >= start_datetime)
3716
    query = query.filter(Order.created_timestamp <= end_datetime)
3717
    return query.all()
3718
 
5099 varun.gupt 3719
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 3720
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 3721
 
5139 varun.gupt 3722
    if paid_order.originalOrderId is None:
3723
        paid_order.vendor_paid = True
5099 varun.gupt 3724
        session.commit()
5139 varun.gupt 3725
 
3726
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
3727
            order.vendor_paid = True
3728
            session.commit()
3729
    else:
5208 varun.gupt 3730
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 3731
 
5208 varun.gupt 3732
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 3733
            order.vendor_paid = True
3734
            session.commit()
3735
 
3736
        original_order = Order.get_by(id = original_order_id)
3737
        if original_order:  original_order.vendor_paid = True
3738
        session.commit()
5348 anupam.sin 3739
 
3740
def update_COD_agent(agentEmailId, orderId):
3741
    order = Order.get_by(id=orderId)
3742
    if not order:
3743
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
3744
    agent = CodVerificationAgent()
3745
    agent.orderId = orderId
3746
    agent.verificationAgent = agentEmailId
3747
    session.commit()
3748
 
5099 varun.gupt 3749
 
5386 phani.kuma 3750
def update_order_only_as_paid_to_vendor(order_id):
3751
    paid_order = Order.get_by(id = order_id)
3752
    if paid_order is None:
3753
        raise TransactionServiceException(116, "No order found for the given order id")
3754
    paid_order.vendor_paid = True
3755
    session.commit()
3756
 
5208 varun.gupt 3757
def get_refunded_orders_marked_paid():
3758
    orderStatusGroup = OrderStatusGroups()
3759
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
3760
 
5447 anupam.sin 3761
def get_all_verification_agents(minOrderId, maxOrderId):
3762
    return CodVerificationAgent.query.filter(CodVerificationAgent.orderId >= minOrderId).filter(CodVerificationAgent.orderId <= maxOrderId).all()
3763
 
5527 anupam.sin 3764
def get_all_attributes_for_order_id(orderId):
3765
    return Attribute.query.filter(Attribute.orderId == orderId).all()
3766
 
3767
def set_order_attribute_for_transaction(transactionId, t_attribute):
3768
    for order in Order.query.filter_by(transaction_id = transactionId).all():
3769
        attribute = Attribute()
3770
        attribute.orderId = order.id
3771
        attribute.name = t_attribute.name
3772
        attribute.value = t_attribute.value
3773
        session.commit()
5593 mandeep.dh 3774
 
5558 mandeep.dh 3775
def accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
5944 mandeep.dh 3776
    inventoryClient = InventoryClient().get_client()
3777
    inventory = inventoryClient.getItemInventoryByItemId(itemId)
5684 mandeep.dh 3778
    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 3779
    for order in orders:
5593 mandeep.dh 3780
        lineitem = order.lineitems[0]
5558 mandeep.dh 3781
        if lineitem.item_id == itemId and lineitem.quantity <= quantity:
5944 mandeep.dh 3782
            warehouse = inventoryClient.getWarehouse(order.fulfilmentWarehouseId)
5684 mandeep.dh 3783
            if not warehouse.billingWarehouseId and warehouse.warehouseType == WarehouseType.THIRD_PARTY:
3784
                if (inventory.availability[fulfilmentWarehouseId] >= inventory.reserved[fulfilmentWarehouseId] + lineitem.quantity) and inventory.availability[order.fulfilmentWarehouseId] < inventory.reserved[order.fulfilmentWarehouseId]:
5966 rajveer 3785
                    inventoryClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3786
                    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 3787
                    order.fulfilmentWarehouseId = fulfilmentWarehouseId
5558 mandeep.dh 3788
                    quantity -= lineitem.quantity
5684 mandeep.dh 3789
                    session.commit()
5593 mandeep.dh 3790
                    if not quantity:
3791
                        break
5558 mandeep.dh 3792
 
6031 rajveer 3793
def get_recharge_order(rechargeOrderId):
6048 rajveer 3794
    return RechargeOrder.get_by(id = rechargeOrderId)
6031 rajveer 3795
 
3796
def get_recharge_orders(userId):
3797
    return RechargeOrder.query.filter_by(userId = userId).all()
3798
 
6279 rajveer 3799
def update_recharge_order_status(rechargeOrderId, rechargeOrderStatus, refundDate=None):
6031 rajveer 3800
    recharge_order = get_recharge_order(rechargeOrderId)
3801
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_FAILED:
3802
        recharge_order.status = RechargeOrderStatus.PAYMENT_FAILED
3803
        session.commit()
3804
        return True
6214 rajveer 3805
 
3806
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED:
3807
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
3808
        session.commit()
3809
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3810
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6214 rajveer 3811
        enqueue_recharge_info_email(recharge_order)
3812
        return True
3813
 
3814
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3815
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
6553 rajveer 3816
        recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
6214 rajveer 3817
        session.commit()
6285 rajveer 3818
        gvs = allocate_gift_voucher(recharge_order)
3819
        enqueue_recharge_info_email(recharge_order, gvs)
6214 rajveer 3820
        return True
3821
 
6279 rajveer 3822
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3823
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED
3824
        order.responseTimestamp = refundDate
3825
        session.commit()
3826
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3827
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6279 rajveer 3828
        enqueue_recharge_info_email(recharge_order)
3829
        return True
3830
 
6031 rajveer 3831
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6285 rajveer 3832
        gvs = {}
6206 rajveer 3833
        recharge_order.status = RechargeOrderStatus.PAYMENT_SUCCESSFUL
3834
        session.commit()
6031 rajveer 3835
        if recharge_order.walletAmount > 0:
3836
            wallet = get_user_wallet(recharge_order.userId)
3837
            if wallet and wallet.amount >= recharge_order.walletAmount:
3838
                update_amount_in_wallet(recharge_order.userId, -recharge_order.walletAmount, recharge_order.id)
3839
            else:
6441 rajveer 3840
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6031 rajveer 3841
                raise TransactionServiceException(103, 'Wallet amount has already been used')
3842
 
6092 rajveer 3843
        try:
3844
            if activate_recharge_txn(recharge_order):
3845
                recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
3846
                session.commit()
6285 rajveer 3847
                gvs = allocate_gift_voucher(recharge_order)
6092 rajveer 3848
                return True
3849
            else:
3850
                update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3851
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6092 rajveer 3852
                session.commit()
3853
                return False
3854
        except:
3855
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
3856
            transaction_requiring_extra_processing.category = 'RECHARGE_UNKNOWN'
3857
            transaction_requiring_extra_processing.transaction_id = recharge_order.transaction_id
6031 rajveer 3858
            session.commit()
3859
            return False
6102 rajveer 3860
        finally:
6285 rajveer 3861
            enqueue_recharge_info_email(recharge_order, gvs)
6102 rajveer 3862
 
6031 rajveer 3863
 
6285 rajveer 3864
def allocate_gift_voucher(recharge_order):            
3865
    totalAmount = recharge_order.totalAmount
3866
    gvs = {}
6438 rajveer 3867
    return gvs
6330 rajveer 3868
    if totalAmount >= 100:
3869
        totalAmount=500 if totalAmount >= 500 else totalAmount
6285 rajveer 3870
        try:
3871
            pc = PromotionClient().get_client()
6330 rajveer 3872
            enddate = datetime.datetime.now() + datetime.timedelta(days=45)
6285 rajveer 3873
            while totalAmount > 0:
6330 rajveer 3874
                gvAmount = totalAmount if totalAmount <= 250 else 250
6285 rajveer 3875
                totalAmount = totalAmount - gvAmount
6561 amit.gupta 3876
                gv = pc.createCoupon(26, to_java_date(enddate), recharge_order.userEmailId, gvAmount, False, 1, None)
6285 rajveer 3877
                gvs[gv] = gvAmount  
3878
        except:
3879
            print "Not able to create gift voucher for user " + recharge_order.userEmailId
3880
    return gvs     
3881
 
6048 rajveer 3882
def activate_recharge_txn(recharge_order):
3883
    if isinstance(recharge_order, MobileRechargeOrder):
3884
        rechargeType = 'MTP'
3885
        deviceNumber = recharge_order.mobileNumber
3886
        strProviderCode = get_provider_code(recharge_order.mobileOperatorId)
6161 rajveer 3887
        plan = recharge_order.rechargePlan
6048 rajveer 3888
    if isinstance(recharge_order, DTHRechargeOrder):
3889
        rechargeType = 'RCH'
3890
        deviceNumber = recharge_order.dthAccountNumber
3891
        strProviderCode = get_provider_code(recharge_order.dthOperatorId)
6161 rajveer 3892
        plan = ''
3893
    retStatus, retCode, spiceTID, description = RechargeService.rechargeDevice(recharge_order.id, rechargeType, strProviderCode, deviceNumber, recharge_order.totalAmount, plan)
6231 rajveer 3894
    recharge_order.spiceTID = spiceTID
3895
    recharge_order.responseTimestamp = datetime.datetime.now()
3896
    recharge_order.description = description
3897
    session.commit()
6092 rajveer 3898
    if retCode == '00' and retStatus == 'S':
3899
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
3900
        session.commit()
3901
        return True
6259 rajveer 3902
    elif retCode in ('STO', 'US', 'UP') and retStatus == 'S':
6231 rajveer 3903
        raise TransactionServiceException(111, "No response from operator within specified time")
6092 rajveer 3904
    else:
3905
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
6265 rajveer 3906
        if retCode in ('SVAI', 'SVIA', 'AI', 'IA', 'EAI', 'SVEAI'):
3907
            recharge_order.description = "Invalid Amount"
3908
        elif retCode in ('ECL', 'SVECL', 'SCL'):
3909
            recharge_order.description = "Customer Exceeded Daily Limit"
3910
        elif retCode in ('CI', 'ECI', 'ESP', 'SVCI', 'SVECI', 'SVESP', 'SV_ECI', 'SV ECI'):
6399 rajveer 3911
            recharge_order.description = "Invalid Device Number"
6092 rajveer 3912
        session.commit()
6048 rajveer 3913
        return False
6031 rajveer 3914
 
6092 rajveer 3915
 
6031 rajveer 3916
def get_user_wallet(userId):
3917
    wallet = UserWallet.get_by(userId = userId)
3918
    if not wallet:
3919
        wallet = UserWallet()
3920
        wallet.amount = 0
3921
        wallet.userId = userId
3922
    return wallet
3923
 
3924
def get_user_wallet_history(userId):
3925
    wallet = get_user_wallet(userId)
3926
    if wallet.id:
3927
        return UserWalletHistory.query.filter_by(wallet = wallet).all()
3928
    else:
3929
        return []
3930
 
6125 rajveer 3931
def get_provider(providerId):
3932
    return ServiceProvider.query.filter_by(id = providerId).one()
3933
 
6048 rajveer 3934
def get_provider_code(providerId):
3935
    return ServiceProvider.query.filter_by(id = providerId).one().code
6031 rajveer 3936
 
6310 anupam.sin 3937
def get_provider_by_code(providerCode):
3938
    return ServiceProvider.query.filter_by(code = providerCode).one()
6049 rajveer 3939
 
6206 rajveer 3940
def get_service_providers(recharge_type, only_active):
3941
    query = ServiceProvider.query.filter_by(type = recharge_type)
3942
    if only_active:
3943
        query = query.filter_by(status = only_active)
3944
    providers = query.all()
6048 rajveer 3945
    serviceProviders = {}
3946
    for provider in providers:
3947
        serviceProviders[provider.id] = provider.name
3948
    return serviceProviders
3949
 
6049 rajveer 3950
def get_service_provider_for_device(rechargeType, deviceNumber):
3951
    if rechargeType == RechargeType.MOBILE:
3952
        serviceType = 'MTP'
3953
    if rechargeType == RechargeType.DTH:
3954
        serviceType = 'RCH'
6048 rajveer 3955
 
6313 anupam.sin 3956
    provider = None
7120 rajveer 3957
    try:
3958
        series = OperatorSeries.get_by(series = int(deviceNumber))
3959
        if series:
7122 rajveer 3960
            providerId = series.operatorId
7120 rajveer 3961
            tc = TelecomCircle.get_by(id = series.circleId)
3962
            operatorCircle = tc.code
6092 rajveer 3963
        else:
7120 rajveer 3964
            l = len(deviceNumber)
3965
            if l < 10:
3966
                deviceNumber = deviceNumber + "0" * (10-l) 
3967
            providerCode, operatorCircle = RechargeService.checkServiceProviderApi(serviceType, deviceNumber)
3968
            if providerCode == 'SNS' or providerCode == '':
3969
                providerId = 0
3970
            else:
3971
                provider = get_provider_by_code(providerCode)
3972
                providerId = provider.id
6049 rajveer 3973
    except:
6092 rajveer 3974
        providerId = -1
6643 rajveer 3975
        operatorCircle = ""
6092 rajveer 3976
 
6289 anupam.sin 3977
    deviceNumberInfo = DeviceNumberInfo()
6336 anupam.sin 3978
    deviceNumberInfo.circleCode = operatorCircle
6289 anupam.sin 3979
    deviceNumberInfo.operatorId = providerId
6313 anupam.sin 3980
    if provider:
3981
        deviceNumberInfo.operatorName = provider.name
6289 anupam.sin 3982
    return deviceNumberInfo
6269 rajveer 3983
 
6591 anupam.sin 3984
def validate_recharge(rechargeType, deviceNumber, userSelectedProviderId, clientAddress):
3985
 
3986
    addressComponents = clientAddress.split('.')
3987
    n = 3
3988
    addressNumber = 0
3989
    for addressComponent in addressComponents :
3990
        addressNumber = addressNumber + (int(addressComponent) * pow(256, n))
3991
        n = n-1
3992
    matchingRow = BlockedIpRange.query.filter(BlockedIpRange.start <= addressNumber).filter(BlockedIpRange.end >= addressNumber).first()
3993
    #if a match is found then check if date has expired.
3994
    if matchingRow :
3995
        #if expiredOn is None that means this range is permanently blocked.
3996
        if matchingRow.expiredOn is None:
3997
            deniedIpAddress = DeniedIpAddress()
3998
            deniedIpAddress.ip = clientAddress
3999
            deniedIpAddress.deniedOn = datetime.datetime.now()
4000
            deniedIpAddress.deviceNumber = deviceNumber
4001
            deniedIpAddress.rechargeType = rechargeType
4002
            session.commit()
4003
            return "Oops! There seems to be a problem. Please try after some time."
4004
        else :
4005
            #if expired is not None and the blockage is still not expired then block the ip.
4006
            if matchingRow.expiredOn > datetime.datetime.now():
4007
                deniedIpAddress = DeniedIpAddress()
4008
                deniedIpAddress.ip = clientAddress
4009
                deniedIpAddress.deniedOn = datetime.datetime.now()
4010
                deniedIpAddress.deviceNumber = deviceNumber
4011
                deniedIpAddress.rechargeType = rechargeType
4012
                session.commit()
4013
                return "Oops! There seems to be a problem. Please try after some time."
4014
 
4015
 
6307 anupam.sin 4016
    deviceNumberInfo = get_service_provider_for_device(rechargeType, deviceNumber)
4017
    if deviceNumberInfo.operatorId == -1:
4018
        return "Oops! There seems to be a problem. Please try after some time."
6336 anupam.sin 4019
    circle = TelecomCircle.query.filter_by(code = deviceNumberInfo.circleCode).first()
6313 anupam.sin 4020
    if circle:
6734 anupam.sin 4021
        serviceAvailability = ServiceAvailability.query.filter_by(circleId = circle.id).filter_by(operatorId = userSelectedProviderId).first()
4022
        if serviceAvailability.permIsServiceAvailable == False or serviceAvailability.tempIsServiceAvailable == False :
4023
 
6313 anupam.sin 4024
            if deviceNumberInfo.operatorName :
6734 anupam.sin 4025
                if serviceAvailability.permIsServiceAvailable == False:
4026
                    return "We currently do not provide service for " + deviceNumberInfo.operatorName + " in " + circle.name + ". We regret the inconvenience."
6314 anupam.sin 4027
                else :
4028
                    return "We are facing technical issues with " + deviceNumberInfo.operatorName + " in " + circle.name + " currently. Please try later." 
6316 anupam.sin 4029
            else :
6734 anupam.sin 4030
                if serviceAvailability.permIsServiceAvailable == False:
4031
                    return "We currently do not provide service for this operator in " + circle.name + ". We regret the inconvenience."
4032
                else:
4033
                    return "We are facing technical issues with this operator in " + circle.name + " currently. Please try later." 
6719 anupam.sin 4034
    totalSuccessfulRechargeAmount = get_previous_transactions(clientAddress)
4035
    if totalSuccessfulRechargeAmount >= 3000 :
4036
        return "You have exceeded your daily recharge limit. Please try after 24 hours."
6269 rajveer 4037
    return "SUCCESS"
6049 rajveer 4038
 
6719 anupam.sin 4039
def get_previous_transactions(clientAddress):
6271 rajveer 4040
    limittime = datetime.datetime.now() - datetime.timedelta(hours=24)
6719 anupam.sin 4041
    totalSuccessfulRechargeAmount = session.query(func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == 5).filter(RechargeOrder.ipAddress == clientAddress).filter(RechargeOrder.creationTimestamp  > limittime).scalar()
4042
    return totalSuccessfulRechargeAmount    
6269 rajveer 4043
 
6031 rajveer 4044
def update_amount_in_wallet(userId, amount, orderId):
4045
    if amount == 0:
4046
        return
4047
    wallet = get_user_wallet(userId)
4048
    wallet.amount = wallet.amount + amount
4049
 
4050
    history = UserWalletHistory()
4051
    history.amount = amount
4052
    history.orderId = orderId
4053
    history.wallet = wallet
4054
    history.timestamp = datetime.datetime.now()
4055
    session.commit()
6056 amit.gupta 4056
 
6094 rajveer 4057
def get_recharge_orders_for_device(deviceNumber):
4058
    orders = MobileRechargeOrder.query.filter_by(mobileNumber = deviceNumber).all()
4059
    if orders is None:
4060
        orders = DTHRechargeOrder.query.filter_by(dthAccountNumber = deviceNumber).all()
4061
    return orders
4062
 
6154 rajveer 4063
def get_recharge_orders_for_status(status):
4064
    if status == -1:
6161 rajveer 4065
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).all()
6154 rajveer 4066
    else:
6161 rajveer 4067
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = status).all()
6154 rajveer 4068
    return orders
4069
 
6188 rajveer 4070
def get_recharge_statistics():
4071
    rs = RechargeStatistics()
4072
    statusCounts = {}
4073
    operatorCounts = {}
4074
    currentOrders = {}
4075
    amounts = {}
4076
 
4077
    sorders = session.query(RechargeOrder.status, func.count(RechargeOrder.status)).group_by(RechargeOrder.status).all()
4078
    for sorder in sorders:
6190 rajveer 4079
        statusCounts[sorder[0]] = sorder[1]
6188 rajveer 4080
 
4081
    oorders = session.query(MobileRechargeOrder.mobileOperatorId, func.count(MobileRechargeOrder.mobileOperatorId)).group_by(MobileRechargeOrder.mobileOperatorId).all()
4082
    for oorder in oorders:
6190 rajveer 4083
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 4084
 
4085
    oorders = session.query(DTHRechargeOrder.dthOperatorId, func.count(DTHRechargeOrder.dthOperatorId)).group_by(DTHRechargeOrder.dthOperatorId).all()
4086
    for oorder in oorders:
6190 rajveer 4087
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 4088
 
6219 rajveer 4089
    forders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED).limit(20).all()
6188 rajveer 4090
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED)] = [order.to_thrift_object() for order in forders]
4091
    sorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_SUCCESSFUL).limit(20).all()
6197 rajveer 4092
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_SUCCESSFUL)] = [order.to_thrift_object() for order in sorders]
6216 rajveer 4093
    porders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.PAYMENT_SUCCESSFUL).limit(20).all()
4094
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.PAYMENT_SUCCESSFUL)] = [order.to_thrift_object() for order in porders]
6238 rajveer 4095
    rorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).limit(20).all()
4096
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)] = [order.to_thrift_object() for order in rorders]
6188 rajveer 4097
 
6190 rajveer 4098
    twa = session.query(func.sum(UserWallet.amount)).one()
4099
    tra = session.query(func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
4100
    gwa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId > 100000).one()
6278 rajveer 4101
    #tpa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId < 100000).one()
6482 rajveer 4102
    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()
4103
    tda = session.query(func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
4104
 
6346 rajveer 4105
    balance = RechargeService.getBalance()
6305 rajveer 4106
    amounts['(a) Total Payment Amount'] = tpa[0]
4107
    amounts['(b) Gift Wallet Amount'] = gwa[0]
4108
    amounts['(c) Total Wallet Amount'] = twa[0]
4109
    amounts['(d) Total Recharge Amount'] = tra[0]
4110
    amounts['(e) Account Balance'] = balance
6482 rajveer 4111
    amounts['(f) Discount Balance'] = tda[0]
6278 rajveer 4112
    #amounts['Total Payment Amount'] = tra[0] + twa[0] - gwa[0]
6524 rajveer 4113
    amounts['Saholic Mismatch = (a+b+f-c-d)'] = tpa[0] + gwa[0] + tda[0] - tra[0] - (twa[0] + 63774)
4114
    amounts['SpiceDeck Mismatch = (d-e)'] = tra[0] + balance - 750000 
6278 rajveer 4115
 
6337 rajveer 4116
    '''
6318 rajveer 4117
    if amounts['SpiceDeck Mismatch = (d-e)'] != -739:
4118
        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)']), "", [], [], [])
4119
    if amounts['Saholic Mismatch = (a+b-c-d)'] != -1919:
4120
        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 4121
    '''
6318 rajveer 4122
 
6188 rajveer 4123
    rs.statusCounts = statusCounts
4124
    rs.operatorCounts = operatorCounts    
4125
    rs.currentOrders = currentOrders
4126
    rs.amounts = amounts
4127
 
4128
    return rs
4129
 
4130
 
6159 rajveer 4131
def get_plans_for_operator(operator_id):
4132
    return RechargePlan.query.filter_by(operatorId = operator_id).all()
4133
 
6056 amit.gupta 4134
def get_recharge_orders_for_transaction(txId):
4135
    return RechargeOrder.query.filter_by(transaction_id = txId).first()
6102 rajveer 4136
 
6285 rajveer 4137
def enqueue_recharge_info_email(recharge_order, gvs={}):
6102 rajveer 4138
    status = ""
4139
    message = ""
4140
    html_header = """
4141
 
4142
    <html>
4143
    <body>
4144
    <div>
4145
        <p>
4146
            Hello $email,<br /><br />
6127 rajveer 4147
            Thanks for placing recharge order with us. Following are the details of your recharge order:
6102 rajveer 4148
        </p>
4149
        <div>
6136 rajveer 4150
            Order Id : $order_id <br/>
4151
            Order Date : $order_date <br/>
4152
            Order Amount : Rs. $order_amount <br/>
4153
            Order Status : $order_status <br/>
4154
            Device Number : $device_number <br/>
4155
            Service Provider : $service_provider <br/>
6102 rajveer 4156
        </div>
6348 rajveer 4157
    <br />
6102 rajveer 4158
    """
6288 rajveer 4159
 
4160
    FailureReasonMap = {}
4161
    FailureReasonMap["Invalid Amount"] = "the amount you tried seems to be invalid. Please try another amount."
4162
    FailureReasonMap["Customer Exceeded Daily Limit"] = "you have exceeded daily recharge limit for this number. Please try after 12 hours."
6399 rajveer 4163
    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 4164
 
4165
    failureReason = FailureReasonMap.get(recharge_order.description)
4166
    if failureReason is None:
4167
        failureReason = "of network failure."
6102 rajveer 4168
    if recharge_order.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
4169
        status = "Recharge Successful"
4170
        message = ""
6444 rajveer 4171
        if recharge_order.couponAmount > 0:
4172
            message = message + "<b>You have used coupon " + recharge_order.couponCode + " and got discount of Rs. " + str(recharge_order.couponAmount) + ".</b>" 
4173
 
6102 rajveer 4174
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED:
4175
        status = "Recharge Failed"
6127 rajveer 4176
        message = """
6288 rajveer 4177
                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 4178
                """
6206 rajveer 4179
    elif recharge_order.status == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6102 rajveer 4180
        status = "Recharge Under Process"
6127 rajveer 4181
        message = """
6288 rajveer 4182
                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 4183
                """
6279 rajveer 4184
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
4185
        status = "Recharge Failed, Amount Refunded"
4186
        message = """
4187
                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>
4188
                """
6285 rajveer 4189
    if len(gvs) > 0:
6340 rajveer 4190
        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 4191
        message = message + " <br />  <b>Voucher Code &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Amount</b>"
6285 rajveer 4192
        for gv in gvs.keys():
4193
            gvAmount = gvs.get(gv)
6330 rajveer 4194
            message = message + " <br />  <b>" + gv + "&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Rs. "  + str(gvAmount) + "</b>"
6285 rajveer 4195
 
6114 rajveer 4196
    message = message  + '<br />  In case of any problem, please  <a href="$source_url/contact-us">contact us</a>'
6102 rajveer 4197
 
6136 rajveer 4198
    html_header = html_header + message
6102 rajveer 4199
    html_footer = """
4200
    <p>
4201
        Best Wishes,<br />
4202
        $source_name Team
4203
    </p>
4204
    </div>
4205
    </body>
4206
    </html>
4207
    """
4208
 
6125 rajveer 4209
    if isinstance(recharge_order, MobileRechargeOrder):
4210
        deviceNumber = recharge_order.mobileNumber
4211
        providerName = get_provider(recharge_order.mobileOperatorId).name
4212
    if isinstance(recharge_order, DTHRechargeOrder):
4213
        deviceNumber = recharge_order.dthAccountNumber
4214
        providerName = get_provider(recharge_order.dthOperatorId).name
4215
 
6127 rajveer 4216
    display_order_id = recharge_order.idPrefix + str(recharge_order.id)
6102 rajveer 4217
    email = recharge_order.userEmailId
4218
    dt = datetime.datetime.strptime(str(recharge_order.creationTimestamp), "%Y-%m-%d %H:%M:%S")
4219
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
4220
 
6288 rajveer 4221
    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 4222
    email_footer = Template(html_footer).substitute(dict(source_url = source_url, source_name = source_name))
4223
 
4224
    try:
4225
        helper_client = HelperClient().get_client()
6906 rajveer 4226
        helper_client.saveUserEmailForSending([email], "", source_name + " - Recharge Order Details", email_header + email_footer, str(recharge_order.id), "RechargeInfo", [], [])
6102 rajveer 4227
        return True
4228
    except Exception as e:
4229
        print e
4230
        return False
4231
 
6307 anupam.sin 4232
def get_recharge_denominations(operator_id, circleCode, denomination_type):
4233
    circle_id = TelecomCircle.query.filter_by(code = circleCode).first().id
6289 anupam.sin 4234
    return RechargeDenomination.query.filter_by(operatorId = operator_id).filter_by(circleId = circle_id).filter_by(denominationType = denomination_type).all()
6371 rajveer 4235
 
4236
def update_availability_status(operatorId, circleId, isAvailable):
4237
    serviceAvailability = ServiceAvailability.query.filter_by(circleId = circleId).filter_by(operatorId = operatorId).first()
6734 anupam.sin 4238
    serviceAvailability.tempIsServiceAvailable = isAvailable
6371 rajveer 4239
    session.commit()
4240
 
6389 rajveer 4241
def get_misc_charges(transactionId):
4242
    retCharges = {}
4243
    miscCharges = MiscCharges.get_by(transaction_id = transactionId)
4244
    if miscCharges:
6426 rajveer 4245
        retCharges[1] = miscCharges.chargeAmount 
6389 rajveer 4246
    return retCharges
6396 amit.gupta 4247
 
4248
def get_available_emi_schemes():
4249
    t_emi_schemes = []
4250
    emi_schemes = EmiScheme.query.all()
4251
    if emi_schemes:
4252
        t_emi_schemes = [to_t_emi_scheme(emi_scheme) for emi_scheme in emi_schemes]
4253
    return t_emi_schemes
6389 rajveer 4254
 
6507 anupam.sin 4255
def refund_recharge_order(rechargeOrderId):
4256
    try :
4257
        rechargeOrder = RechargeOrder.query.filter_by(id = rechargeOrderId).first()
4258
        wallet = UserWallet.query.filter_by(userId = rechargeOrder.userId).first()
4259
    except:
4260
        return False
4261
 
4262
    paidAmount = rechargeOrder.totalAmount - rechargeOrder.walletAmount - rechargeOrder.couponAmount
4263
    amountToRefund = 0
4264
    status = None
4265
    if (paidAmount <= wallet.amount) :
4266
        amountToRefund = paidAmount
4267
        status = RechargeOrderStatus.REFUNDED
4268
    else :
4269
        amountToRefund = wallet.amount
4270
        status = RechargeOrderStatus.PARTIALLY_REFUNDED
4271
 
4272
    update_amount_in_wallet(rechargeOrder.userId, -amountToRefund, rechargeOrderId)
4273
 
4274
    try:    
4275
        pc = PaymentClient().get_client()
4276
        if pc.refundPayment(rechargeOrder.transaction_id, amountToRefund, True) :
4277
            rechargeOrder.status = status
6515 anupam.sin 4278
            rechargeOrder.refundTimestamp = datetime.datetime.now()
6507 anupam.sin 4279
            session.commit()
4280
            return True
4281
        else :
4282
            update_amount_in_wallet(rechargeOrder.userId, amountToRefund, rechargeOrderId)
4283
 
4284
    except:
4285
        update_amount_in_wallet(rechargeOrder.userId, amountToRefund, rechargeOrderId)
4286
 
4287
    return False 
4288
 
6821 amar.kumar 4289
def get_physical_orders(from_date, to_date):
4290
    query = Order.query.filter(Order.created_timestamp >from_date).filter(Order.created_timestamp < to_date).filter(Order.status>=2)
4291
    return query.all()
4292
 
6507 anupam.sin 4293
 
766 rajveer 4294
def close_session():
4295
    if session.is_active:
4296
        print "session is active. closing it."
2783 chandransh 4297
        session.close()
3376 rajveer 4298
 
4299
def is_alive():
4300
    try:
4301
        session.query(Transaction.id).limit(1).one()
4302
        return True
4303
    except:
6000 mandeep.dh 4304
        return False
4305
 
6906 rajveer 4306
def get_document(docType, docSource):
4307
    document = DocumentStore.get_by(docType = docType, docSource = docSource)
4308
    if document:
4309
        return document.document
4310
    else:
7040 amar.kumar 4311
        return bin(0)
6906 rajveer 4312
 
7075 rajveer 4313
def retrieve_invoice(orderId, userId):
4314
    order = get_order(orderId)
4315
    if order.customer_id != userId:
4316
        return bin(0)
6988 rajveer 4317
    strOrderId = '0'*(10-len(str(orderId)))+str(orderId)
7072 rajveer 4318
    filename = "/SaholicInvoices/" + strOrderId[0:2] + "/" + strOrderId[2:4] + "/" + strOrderId[4:6] + "/" + str(orderId) + ".pdf"  
6988 rajveer 4319
    file = open(filename, "rb")
4320
    pdfFile = file.read()
4321
    return pdfFile
4322
 
6906 rajveer 4323
def myFirstPage(canvas, doc):
4324
    canvas.saveState()
6916 anupam.sin 4325
    canvas.setTitle("Theft-Insurance-Policy")
6906 rajveer 4326
    canvas.restoreState()
4327
 
4328
 
4329
def __generate_policy_doc(order, filename):
6903 anupam.sin 4330
    PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
4331
    styles = getSampleStyleSheet()
4332
    styles.add(ParagraphStyle(name='left', leftIndent=12,fontSize=11), alias='li')
4333
    styles.add(ParagraphStyle(name='bullet', bulletIndent=24, leftIndent=24), alias='bull')
6916 anupam.sin 4334
    styles.add(ParagraphStyle(name='insurerName', alignment=TA_CENTER, fontName="Times-Bold", fontSize=16), alias='iN')
4335
    styles.add(ParagraphStyle(name='insurerAdd', alignment=TA_CENTER, fontName="Helvetica",leading=15, fontSize=12), alias='iA')
4336
    styles.add(ParagraphStyle(name='subHeading', alignment=TA_CENTER, fontName="Helvetica", fontSize=13), alias='sH')
6903 anupam.sin 4337
 
6914 rajveer 4338
    invoiceNumber = str(order.invoice_number)
6906 rajveer 4339
    billing_timestamp = str(order.billing_timestamp.date()) 
6903 anupam.sin 4340
 
6906 rajveer 4341
    doc = SimpleDocTemplate(filename)
6916 anupam.sin 4342
    Story = [Spacer(0, 0)]
6903 anupam.sin 4343
    style = styles["Normal"]
6916 anupam.sin 4344
 
4345
 
4346
    file_name = os.path.dirname(os.path.realpath(__file__)) + '/../resources/nia-logo.jpg'
4347
    image = Image(file_name, width=100, height=100)
4348
    Story.append(image)
4349
    Story.append(Spacer(1,0.2*inch))
4350
 
4351
    text = ("""<u>The New India Assurance Company Limited</u>""") 
4352
    p = Paragraph(text, styles['insurerName'])
4353
    Story.append(p)
4354
    Story.append(Spacer(1,0.2*inch))
4355
 
4356
    text = ("""DO-IX, 35/1, Fortune Park, 1st Floor, Park Road, Tasker Town, Shivajinagar, Bangalore  560051""") 
4357
    p = Paragraph(text, styles['insurerAdd'])
4358
    Story.append(p)
4359
    Story.append(Spacer(1,0.3*inch))
4360
 
4361
    text = ("""MOBILE HAND SET INSURANCE – THEFT & BURGLARY RISKS ONLY""")
4362
    p = Paragraph(text, styles['subHeading'])
4363
    Story.append(p)
4364
    Story.append(Spacer(1,1*inch))
4365
 
6903 anupam.sin 4366
    text = ("""<u><b>Subject Matter Of Insurance</b></u> : <i>New Mobile Handsets</i> alone and <i>Tablets with 'Voice Calls'</i> only. 
4367
    Sold 'online' by <b>Spice Online Retail Private Limited, New Delhi</b>, to its customers.""") 
4368
    p = Paragraph(text, style)
4369
    Story.append(p)
4370
    Story.append(Spacer(1,0.2*inch))
4371
    text = ("""Insurer will indemnify the Insured in the event of Theft/Burglary of <i>Mobile Handsets</i> 
6914 rajveer 4372
    alone and <i>Tablets with 'Voice Calls'</i> only sold as per Invoice No. %s
6903 anupam.sin 4373
    dated %s and insured with THE NEW INDIA ASSURANCE COMPANY LIMITED, BANGALORE, as per Policy No. 671700/46/12/2400000008,  
4374
    for a period of 12 months from the date and time of delivery of Mobile Handset to the customer.""" % (invoiceNumber, billing_timestamp)) 
4375
    p = Paragraph(text, style)
4376
    Story.append(p)
4377
    Story.append(Spacer(1,0.2*inch))
4378
    text = ("""<b>WARRANTY</b> -  Warranted that the Mobile Handset sold during the Policy Period of 25/02/2013 to 24/02/2014
4379
             are only covered irrespective of date of delivery to the customer""")
4380
    p = Paragraph(text, style)
4381
    Story.append(p)
4382
    Story.append(Spacer(1,0.2*inch))
6915 anupam.sin 4383
    text = ("<b>INSURER</b> -The New India Assurance company limited.")
6903 anupam.sin 4384
    p = Paragraph(text, style)
4385
    Story.append(p)
4386
    Story.append(Spacer(1,0.2*inch))
4387
    text = ("<b>INSURED</b> - Purchaser of the Mobile Handset OR his/her spouse or children. If the Purchaser is a ‘Company’, user is the duly authorised person.") 
4388
    p = Paragraph(text, style)
4389
    Story.append(p)
4390
    Story.append(Spacer(1,0.2*inch))
4391
    text = ("<b>GEOGRAPHICAL LIMIT</b> – World-wide") 
4392
    p = Paragraph(text, style)
4393
    Story.append(p)
4394
    Story.append(Spacer(1,0.2*inch))
4395
    text = ("<b>RISK COVERAGE</b> – Theft and/or burglary only") 
4396
    p = Paragraph(text, style)
4397
    Story.append(p)
6916 anupam.sin 4398
    Story.append(Spacer(1,0.4*inch))
6915 anupam.sin 4399
    text = ("Terms and Conditions of Insurance:") 
4400
    p = Paragraph(text, styles["h2"])
4401
    Story.append(p)
4402
    Story.append(Spacer(1,0.1*inch))
4403
    text = ("""Insurance Premium paid will not be refunded.""")
4404
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4405
    Story.append(p)
4406
    Story.append(Spacer(1,0.1*inch))
6921 anupam.sin 4407
    text = ("""Claims will be settled by UIB on behalf of The New India Assurance Co. Ltd.<br></br>
4408
            Saholic.com will not be responsible for claim approval and disbursement.""")
4409
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4410
    Story.append(p)
4411
    Story.append(Spacer(1,0.1*inch))
6915 anupam.sin 4412
    text = ("""Insurance will be invalidated for returned products.""")
4413
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4414
    Story.append(p)
6921 anupam.sin 4415
    Story.append(Spacer(1,0.3*inch))
6903 anupam.sin 4416
    text = ("Exclusions:") 
4417
    p = Paragraph(text, styles["h2"])
4418
    Story.append(p)
4419
    Story.append(Spacer(1,0.1*inch))
4420
    text = ("Insurer is not liable") 
4421
    p = Paragraph(text, styles["left"])
4422
    Story.append(p)
4423
    Story.append(Spacer(1,0.1*inch))
4424
    text = ("If the handset is not connected to Mobile Service Provider Network")
4425
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4426
    Story.append(p)
4427
    Story.append(Spacer(1,0.1*inch))
4428
    text = ("Caused by incorrect storage, poor care and maintenance, careless use, negligence.")
4429
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4430
    Story.append(p)
4431
    Story.append(Spacer(1,0.1*inch))
4432
    text = ("Due to mysterious disappearance, forgotten or misplaced or Lost or if handset is left unattended at any point of time.")
4433
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4434
    Story.append(p)
4435
    Story.append(Spacer(1,0.1*inch))
4436
    text = ("Caused by war, war like operation, act of foreign enemy, civil war, rebellion, civil commotion, military usurped power, seizure, capture, confiscation, arrests, restrains and detainment by order of any Government or any other Authority.")
4437
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4438
    Story.append(p)
4439
    Story.append(Spacer(1,0.1*inch))
4440
    text = ("Caused whilst engaging in criminal acts.")
4441
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4442
    Story.append(p)
4443
    Story.append(Spacer(1,0.1*inch))
4444
    text = ("Caused by consequential loss or damage of whatsoever nature or any costs incurred in connection with claim under this policy, including postage, transit costs and reconnection cost.")
4445
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4446
    Story.append(p)
4447
    Story.append(Spacer(1,0.1*inch))
4448
    text = ("Loss of mobile handset due to theft from an unattended vehicle unless the vehicle is of  fully enclosed saloon type having at time all the doors/windows and other opening securely locked and properly fastened.")
4449
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4450
    Story.append(p)
4451
    Story.append(Spacer(1,0.1*inch))
4452
    text = ("Loss of mobile handset due to theft from the building unless there is visible forcible entry/exit into/from the building.")
4453
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4454
    Story.append(p)
4455
    Story.append(Spacer(1,0.1*inch))
4456
    text = ("If the documents are found to be tampered; non-disclosure of material fact, fraud/misrepresentation.")
4457
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4458
    Story.append(p)
4459
    Story.append(Spacer(1,0.1*inch))
4460
    text = ("The policy is not transferable.")
4461
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4462
    Story.append(p)
4463
    Story.append(Spacer(1,0.2*inch))
4464
 
4465
    text = ("Claim Procedure:") 
4466
    p = Paragraph(text, styles["h2"])
4467
    Story.append(p)
4468
    Story.append(Spacer(1,0.1*inch))
4469
    text = ("""For Theft or Burglary of the handset immediate intimation to be given
4470
     to the police within 48 hours of occurrence of incident and proper documents to be obtained 
4471
     and inform the service provider within 48 hours about theft of handset in order to block the SIM services.""")
4472
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4473
    Story.append(p)
4474
    Story.append(Spacer(1,0.1*inch))
4475
    text = ("""To intimate Insurance Company about the loss of Mobile Handset within 48 hours 
6915 anupam.sin 4476
     through Call Centre No.022-49107910 OR through e-mail <u>saholic.claims@universalinsurance.co.in</u> OR through 
6903 anupam.sin 4477
     written communication to <i>Universal Insurance brokers (UIB) No.304, Commerce House, 9/1,Cunningham Road, Bangalore – 560052</i>.""")
4478
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4479
    Story.append(p)
4480
    Story.append(Spacer(1,0.1*inch))
6915 anupam.sin 4481
    text = ("""Claim documents can be downloaded through UIB Website <u>http://www.universalinsurance.co.in/mobileinsurance/claiminfo.html</u>
4482
    <br></br>To know or track your claim please contact Call Centre No. 022-49107910 of Universal Insurance brokers (UIB). """)
6903 anupam.sin 4483
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4484
    Story.append(p)
4485
    Story.append(Spacer(1,0.1*inch))
4486
    text = ("""All the completed claim documents to reach ‘Universal Insurance Brokers (UIB)’ office 
4487
    at <i>No.304, Commerce House, 9/1, Cunningham Road, Bangalore – 560052</i> <b>within 21 days</b>.""")
4488
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4489
    Story.append(p)
4490
    Story.append(Spacer(1,0.2*inch))
4491
 
4492
 
4493
    text = ("Excess(Minimum Deduction):") 
4494
    p = Paragraph(text, styles["h2"])
4495
    Story.append(p)
4496
    Story.append(Spacer(1,0.1*inch))
4497
    text = ("""The excess will be 5% of the value of each claim subject to a minimum of Rs.500/-""")
4498
    p = Paragraph(text, styles["left"])
4499
    Story.append(p)
4500
    Story.append(Spacer(1,0.2*inch))
4501
 
4502
    text = ("Depreciation:") 
4503
    p = Paragraph(text, styles["h2"])
4504
    Story.append(p)
4505
    Story.append(Spacer(1,0.1*inch))
4506
 
4507
    text = ("For 0 – 60 days, 15%")
4508
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4509
    Story.append(p)
4510
    Story.append(Spacer(1,0.1*inch))
4511
 
4512
    text = ("61-150 days, 30%")
4513
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4514
    Story.append(p)
4515
    Story.append(Spacer(1,0.1*inch))
4516
 
4517
    text = ("151 – 365 days, 45%")
4518
    p = Paragraph(text, styles["bullet"], bulletText='\xe2\x80\xa2')
4519
    Story.append(p)
4520
    Story.append(Spacer(1,0.4*inch))
4521
 
4522
    text = ("<i>Insurance is a subject matter of solicitation.</i>")
4523
    p = Paragraph(text, style)
4524
    Story.append(p)
4525
    Story.append(Spacer(1,0.2*inch))
4526
 
6906 rajveer 4527
    doc.build(Story, onFirstPage=myFirstPage)
6980 anupam.sin 4528
 
4529
def drawLine(Story, style):
4530
    Story.append(Paragraph('-'*40, style))
6915 anupam.sin 4531
 
6980 anupam.sin 4532
def generateHotSpotInvoice():
4533
 
4534
    ##########TO BE PASSED TO THIS METHOD####################################
4535
    #########################################################################
4536
    filename = "/home/anupam/test.pdf"                             ##########
4537
    itemCode = "SPICEMI450WHT"                                     ##########
4538
    lotNumber = "12345678901234"                                   ##########
4539
    itemName = "Spice Stellar Craze Mi-450 White"                  ##########
4540
    qty = 1                                                        ##########
4541
    unitPrice = 3099.50                                            ##########
4542
    vat = 310.23                                                   ##########
4543
    billingTime = datetime.datetime.now()                          ##########
4544
    invNum = "885182994"                                           ##########
4545
    counter = 1                                                    ##########
4546
    ourInvoiceNum = "209809"                                       ##########
4547
    customerId = "12345678909"                                     ##########
4548
    customerName = "ANUPAM PRATAP SINGH"                           ##########
4549
    telNum = ""                                                    ##########
4550
    #########################################################################
4551
 
4552
    PAGE_HEIGHT=defaultPageSize[1];
4553
    styles = getSampleStyleSheet()
4554
    styles.add(ParagraphStyle(name='prologue', alignment=TA_CENTER, fontName="Courier", rightIndent = 5, fontSize=10), alias='sH')
4555
    styles.add(ParagraphStyle(name='text', alignment=TA_JUSTIFY, fontName="Courier", fontSize=10), alias='text')
4556
    styles.add(ParagraphStyle(name='line', alignment=TA_CENTER, fontName="Courier", fontSize=10), alias='line')
4557
    styles.add(ParagraphStyle(name='epilogue', alignment=TA_CENTER, fontName="Courier", leftIndent = 30, rightIndent=36, fontSize=10), alias='ep')
4558
 
4559
    Story = []
4560
    prologueStyle = styles["prologue"]
4561
    lineStyle = styles["line"]
4562
    textStyle = styles["text"]
4563
    epilogueStyle = styles["epilogue"]
4564
 
4565
    doc = BaseDocTemplate(filename,showBoundary=0)
4566
 
4567
    #Two Columns
4568
    frame1 = Frame(58, doc.bottomMargin, doc.width/2 + 25, doc.height + 7, id='col1')
4569
 
4570
 
4571
 
4572
    Story.append(Paragraph("""Spice Retail Limited<br></br>
4573
        C/O,PIBCO LIMITED,Basement,Punjsons<br></br>
4574
        2,Kalkaji Industrial Area,New Delhi<br></br>
4575
          .<br></br>
4576
        TIN NO. 07430284979<br></br>
4577
        Service Tax No:AAACM0294PST001<br></br>
4578
        D U P L I C A T E<br></br>
4579
        I N V O I C E<br></br>""", prologueStyle))
4580
    drawLine(Story, lineStyle)
4581
 
4582
    Story.append(Paragraph('{0:7s}{1:>11s}{2:  %d/%m/%Y  %H:%M:%S}'.format("INV NO:", invNum, billingTime).replace(" ", "&nbsp;"), textStyle))
4583
    Story.append(Paragraph("{0:8s}{1:>5d}{2:>11s}{3:>11s}".format('COUNTER:', counter, "CASHIER:", "SUPERADMIN").replace(" ", "&nbsp;"), textStyle))
4584
    Story.append(Paragraph("MN INV NO&amp;DT: {0:<13s}{1:%d/%m/%Y}   ".format(ourInvoiceNum, billingTime).replace(" ", "&nbsp;"), textStyle))
4585
    drawLine(Story, lineStyle)
4586
 
4587
    Story.append(Paragraph("{0:<13s}{1:<27s}".format("CUSTOMER ID:", customerId).replace(" ", "&nbsp;"), textStyle))
4588
    Story.append(Paragraph("{0:<6s}{1:<34s}".format("NAME:", customerName + " " + ourInvoiceNum).replace(" ", "&nbsp;"), textStyle))
4589
    Story.append(Paragraph("{0:<9s}{1:<31s}".format("TEL NO.:", telNum).replace(" ", "&nbsp;"), textStyle))
4590
    drawLine(Story, lineStyle)
4591
 
4592
    Story.append(Paragraph("ITEM" + "&nbsp;"*12 + "LOT NUMBER<br></br>" + \
4593
                            "&nbsp;ITEM NAME<br></br>" + \
4594
                            "&nbsp;"*5 + "QTY" + "&nbsp;"*21 + "AMOUNT(INR)", textStyle))
4595
    drawLine(Story, lineStyle)
4596
 
4597
    Story.append(Paragraph(('{0:<16s}{1:24s}').format(itemCode, lotNumber).replace(' ', '&nbsp;'),textStyle))
4598
    Story.append(Paragraph((' {0:<39s}').format(itemName).replace(' ', '&nbsp;'),textStyle))
4599
    Story.append(Paragraph(('{0:<3d}{1:>10s}{2:13.2f}{3:14.2f}').format(qty, 'PCS', unitPrice, qty*unitPrice).replace(' ', '&nbsp;'),textStyle))
4600
    Story.append(Paragraph(('{0:<3s}{1:37.2f}').format("VAT", vat).replace(' ', '&nbsp;'),textStyle))
4601
    Story.append(Paragraph(('{0:<10s}{1:30.2f}').format("ITEM TOTAL", vat + unitPrice*qty).replace(' ', '&nbsp;'),textStyle))
4602
 
4603
    drawLine(Story, lineStyle)
4604
    Story.append(Paragraph(('{0:13s}{1:>12s}{2:15.2f}').format("GROSS TOTAL:","INR", vat + unitPrice*qty).replace(' ', '&nbsp;'),textStyle))
4605
    drawLine(Story, lineStyle)
4606
 
4607
    Story.append(Paragraph(('{0:13s}{1:>12s}{2:15.2f}').format("NET TOTAL:","INR", vat + unitPrice*qty).replace(' ', '&nbsp;'),textStyle))
4608
    Story.append(Paragraph(('{0:13s}{1:>12s}{2:15.2f}').format("NET VAT:","INR", vat).replace(' ', '&nbsp;'),textStyle))
4609
    drawLine(Story, lineStyle)
4610
 
4611
    Story.append(Paragraph(('{0:13s}{1:>12s}{2:15.2f}').format("SPICE ONLINE:","INR", vat + unitPrice*qty).replace(' ', '&nbsp;'),textStyle))
4612
    drawLine(Story, lineStyle)
4613
 
4614
    Story.append(Paragraph(('{0:16s}{1:>4d}').format("NUMBER OF ITEMS:",qty,).replace(' ', '&nbsp;'),textStyle))
4615
    Story.append(Paragraph(('{0:16s}{1:>9.6f}').format("TOTAL ITEMS    :",qty,).replace(' ', '&nbsp;'),textStyle))
4616
 
4617
    Story.append(Paragraph("Goods once Sold Will not be taken back.<br></br>All Disputes subject to Delhi Jurisdiction",epilogueStyle))
4618
 
4619
 
4620
    doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1]), ])
4621
 
4622
    #start the construction of the pdf
4623
    doc.build(Story)
4624
 
6985 anupam.sin 4625
def change_shipping_address(orderId, line1, line2, city, state, pin):
4626
    order = Order.get_by(id = orderId)
4627
    if order:
4628
        order.customer_address1 = line1
4629
        order.customer_address2 = line2
4630
        order.customer_city = city
4631
        order.customer_state = state
4632
        order.customer_pin = pin
4633
        session.commit()
4634
        return True
4635
    return False
4636
 
7084 rajveer 4637
def get_recharge_transactions(storeId):
4638
    query = RechargeTransaction.query.filter(RechargeTransaction.storeId == storeId)
4639
    return query.all()
4640
 
7151 amit.gupta 4641
def get_recharge_trans(storeId, startdate,enddate, status):
4642
    if startdate == -1:
4643
        startdate = None
4644
    if enddate == -1:
4645
        enddate = None
4646
    if storeId== 0:
4647
        storeId = None
4648
    if status == 0:
4649
        status = None    
4650
 
4651
    query = RechargeTransaction.query
4652
    if storeId is not None:
4653
        query = query.filter(RechargeTransaction.storeId == storeId)
4654
    if status is not None:
4655
        query = query.filter(RechargeTransaction.status == status)
7169 anupam.sin 4656
 
4657
    if status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED :
4658
        query.filter(cast(RechargeTransaction.responseTime, DATE) == enddate)
7151 amit.gupta 4659
 
7169 anupam.sin 4660
    else :
4661
        if startdate is not None and enddate is not None:
4662
            startdate = to_py_date(startdate).date()
4663
            enddate = to_py_date(enddate).date()
4664
            if startdate == enddate:
4665
                query = query.filter(cast(RechargeTransaction.transactionTime, DATE) == enddate)
4666
            elif enddate < startdate:
4667
                query = query.filter(between(cast(RechargeTransaction.transactionTime, DATE), enddate, startdate))
4668
            else:
4669
                query = query.filter(between(cast(RechargeTransaction.transactionTime, DATE), startdate, enddate))
4670
        elif startdate is not None:
4671
            startdate = to_py_date(startdate).date()
4672
            query = query.filter(cast(RechargeTransaction.transactionTime, DATE) >= startdate)
4673
        elif enddate is not None:
4674
            enddate = to_py_date(enddate).date()
4675
            query = query.filter(cast(RechargeTransaction.transactionTime, DATE) <= enddate)
4676
 
7151 amit.gupta 4677
    return query.all()    
4678
 
7243 rajveer 4679
def update_recharge_transaction_status(id, status):
7127 rajveer 4680
    rechargeTransaction = RechargeTransaction.get_by(id=id)
7163 rajveer 4681
    if status in (RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_FAILED):
4682
        rechargeTransaction.status = status
7243 rajveer 4683
        rechargeTransaction.responseTime = datetime.datetime.now() 
7127 rajveer 4684
 
4685
        store = HotspotStore.get_by(id=rechargeTransaction.storeId)
4686
        wallet = WalletForCompany.get_by(companyId=store.companyId)
4687
        wh = WalletHistoryForCompany()
4688
        wh.walletId = wallet.id
4689
        wh.amount = rechargeTransaction.amount
4690
        wh.transactionTime = rechargeTransaction.responseTime
4691
        wh.openingBal = wallet.amount
4692
        wh.closingBal = wallet.amount + wh.amount
4693
        wh.referenceNumber = rechargeTransaction.id 
4694
        wh.description = "Credited amount"
4695
 
4696
        wallet.amount = wallet.amount + rechargeTransaction.amount
4697
        store.availableLimit = store.availableLimit + rechargeTransaction.amount
4698
        store.collectedAmount = store.collectedAmount - rechargeTransaction.amount + rechargeTransaction.discount
4699
        session.commit()
7163 rajveer 4700
 
4701
    if status == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
4702
        rechargeTransaction.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
4703
        rechargeTransaction.invoiceNumber = get_next_invoice_number(OrderType.RCH4HOTSPOT)
4704
        session.commit()
4705
 
4706
 
7073 anupam.sin 4707
def create_recharge_transaction(t_recharge):
7163 rajveer 4708
    dt = datetime.datetime.now() - datetime.timedelta(minutes=10)
4709
    txns = RechargeTransaction.query.filter(RechargeTransaction.deviceNum == t_recharge.deviceNum).filter(RechargeTransaction.transactionTime > dt).all()
4710
    if txns:
4711
        raise TransactionServiceException(898, "In last 10 minutes you had already recharged this mobile number. Please try after sometime.")
7073 anupam.sin 4712
    rechargeTransaction = RechargeTransaction()
4713
    rechargeTransaction.amount = t_recharge.amount
7096 anupam.sin 4714
    rechargeTransaction.circleId = t_recharge.circleId
7073 anupam.sin 4715
    rechargeTransaction.deviceNum = t_recharge.deviceNum
4716
    rechargeTransaction.deviceType = t_recharge.deviceType
4717
    rechargeTransaction.discount = t_recharge.discount
4718
    rechargeTransaction.email = t_recharge.email
4719
    rechargeTransaction.name = t_recharge.name
4720
    rechargeTransaction.cafNum = t_recharge.cafNum
4721
    rechargeTransaction.simNum = t_recharge.simNum
4722
    rechargeTransaction.isFrc = t_recharge.isFrc
4723
    rechargeTransaction.status = RechargeOrderStatus.INIT
4724
    rechargeTransaction.storeId = t_recharge.storeId
4725
    rechargeTransaction.transactionTime = datetime.datetime.now()
7075 rajveer 4726
    rechargeTransaction.operatorId = t_recharge.operatorId
4727
    rechargeTransaction.plan = t_recharge.plan
7080 anupam.sin 4728
    rechargeTransaction.ipAddress = t_recharge.ipAddress
7096 anupam.sin 4729
    rechargeTransaction.paymentAmount = t_recharge.paymentAmount
7139 amit.gupta 4730
    rechargeTransaction.payMethod = t_recharge.payMethod
7075 rajveer 4731
 
4732
    store = HotspotStore.get_by(id=rechargeTransaction.storeId)
7304 rajveer 4733
    if not rechargeTransaction.circleId:
4734
        rechargeTransaction.circleId = store.circleId
4735
 
7075 rajveer 4736
    wallet = WalletForCompany.get_by(companyId=store.companyId)
4737
    if store.availableLimit < rechargeTransaction.amount or wallet.amount < rechargeTransaction.amount:
4738
        raise TransactionServiceException(898, "Either wallet amount for company or available limit for store is less than recharge amount.")
7249 rajveer 4739
 
7075 rajveer 4740
    wh = WalletHistoryForCompany()
4741
    wh.walletId = wallet.id
4742
    wh.amount = -rechargeTransaction.amount
4743
    wh.transactionTime = rechargeTransaction.transactionTime
4744
    wh.openingBal = wallet.amount
4745
    wh.closingBal = wallet.amount + wh.amount
4746
    wh.description = "Debited amount"
4747
 
4748
    wallet.amount = wallet.amount - rechargeTransaction.amount
4749
    store.availableLimit = store.availableLimit - rechargeTransaction.amount
7076 rajveer 4750
    store.collectedAmount = store.collectedAmount + rechargeTransaction.amount - rechargeTransaction.discount 
7075 rajveer 4751
    session.commit()
4752
 
7249 rajveer 4753
    wh.referenceNumber = rechargeTransaction.id
4754
    session.commit()
4755
 
4756
 
7101 rajveer 4757
    strProviderCode = get_provider_code(rechargeTransaction.operatorId)
4758
    if rechargeTransaction.deviceType == 1:
4759
        rtype = 'MTP'
4760
    else:
4761
        rtype = 'RCH'
4762
    retStatus, retCode, spiceTID, description = RechargeService.rechargeDevice(rechargeTransaction.id, rtype, strProviderCode, rechargeTransaction.deviceNum, rechargeTransaction.amount, rechargeTransaction.plan)
7075 rajveer 4763
    rechargeTransaction.spiceTID = spiceTID
4764
    rechargeTransaction.responseTime = datetime.datetime.now()
4765
    rechargeTransaction.description = description
4766
    if retCode == '00' and retStatus == 'S':
4767
        rechargeTransaction.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
7096 anupam.sin 4768
        rechargeTransaction.invoiceNumber = get_next_invoice_number(OrderType.RCH4HOTSPOT)
7075 rajveer 4769
 
4770
    elif retCode in ('STO', 'US', 'UP') and retStatus == 'S':
4771
        rechargeTransaction.status = RechargeOrderStatus.RECHARGE_UNKNOWN
4772
    else:
4773
        rechargeTransaction.status = RechargeOrderStatus.RECHARGE_FAILED
4774
        if retCode in ('SVAI', 'SVIA', 'AI', 'IA', 'EAI', 'SVEAI'):
4775
            rechargeTransaction.description = "Invalid Amount"
4776
        elif retCode in ('ECL', 'SVECL', 'SCL'):
4777
            rechargeTransaction.description = "Customer Exceeded Daily Limit"
4778
        elif retCode in ('CI', 'ECI', 'ESP', 'SVCI', 'SVECI', 'SVESP', 'SV_ECI', 'SV ECI'):
4779
            rechargeTransaction.description = "Invalid Device Number"
4780
 
4781
        store = HotspotStore.get_by(id=rechargeTransaction.storeId)
4782
        wallet = WalletForCompany.get_by(companyId=store.companyId)
4783
        wh = WalletHistoryForCompany()
4784
        wh.walletId = wallet.id
4785
        wh.amount = rechargeTransaction.amount
4786
        wh.transactionTime = rechargeTransaction.responseTime
4787
        wh.openingBal = wallet.amount
4788
        wh.closingBal = wallet.amount + wh.amount
4789
        wh.referenceNumber = rechargeTransaction.id 
4790
        wh.description = "Credited amount"
4791
 
4792
        wallet.amount = wallet.amount + rechargeTransaction.amount
4793
        store.availableLimit = store.availableLimit + rechargeTransaction.amount
7076 rajveer 4794
        store.collectedAmount = store.collectedAmount - rechargeTransaction.amount + rechargeTransaction.discount
7075 rajveer 4795
 
4796
    session.commit()
4797
 
7073 anupam.sin 4798
    return rechargeTransaction
4799
 
7080 anupam.sin 4800
def get_frcs(circleId, operatorId):
7267 anupam.sin 4801
    query = FRC.query.filter(FRC.circleId == circleId)
4802
    if(operatorId > 0):
4803
        query = query.filter(FRC.operatorId == operatorId)
4804
 
4805
    frcs = query.all()
4806
 
7096 anupam.sin 4807
    if frcs is None:
4808
        return []
4809
    return frcs
7080 anupam.sin 4810
 
4811
def get_recharge_transaction(rechargeId):
4812
    recharge = RechargeTransaction.get_by(id = rechargeId)
4813
    if not recharge:
4814
        raise TransactionServiceException(108, "no such transaction")
4815
    return recharge
4816
 
7096 anupam.sin 4817
def get_hotspot_store(id, hotspotid):
4818
    store = None
4819
    if id > 0:
4820
        store = HotspotStore.query.filter(HotspotStore.id == id).first()
4821
    elif len(hotspotid) > 0:
4822
        store = HotspotStore.query.filter(HotspotStore.hotspotId == hotspotid).first()
4823
    else:
4824
        raise TransactionServiceException(119, 'No such store')
4825
    if store:
4826
        return store
4827
    else:
4828
        raise TransactionServiceException(119, 'No such store')
4829
 
4830
def get_circle(id, code):
4831
    circle = None
4832
    if id > 0:
4833
        circle = TelecomCircle.get_by(id = id)
4834
    elif len(code) > 0:
4835
        circle = TelecomCircle.get_by(code = code)
4836
    else:
4837
        raise TransactionServiceException(119, 'No such circle')
4838
    if circle:
4839
        return circle
4840
    else:
4841
        raise TransactionServiceException(119, 'No such circle')
4842
 
7109 anupam.sin 4843
def retrieve_hotspot_recharge_invoice(id):
4844
    recharge = RechargeTransaction.get_by(id = id)
7139 amit.gupta 4845
    filename = "/tmp/recharge" + str(recharge.invoiceNumber) + ".pdf"
7109 anupam.sin 4846
    operator = ServiceProvider.get_by(id = recharge.operatorId).name
4847
    amount = recharge.amount
4848
    telNum = "+91 " + str(recharge.deviceNum)
4849
    customerName = recharge.name
4850
    invNum = str(recharge.invoiceNumber)
4851
    billingTime = recharge.responseTime
7151 amit.gupta 4852
    payMethod = recharge.payMethod
4853
    return __printRechargeInvoice(filename, operator, amount, telNum, customerName, invNum, billingTime, payMethod)
7109 anupam.sin 4854
 
7190 amar.kumar 4855
def split_freebie_order(order_id, splitReason, shippingDate):
4856
    order = get_order(order_id)
4857
    freebie_order = Order()
4858
 
4859
    freebie_order.transaction = order.transaction
4860
 
4861
    freebie_order.customer_id = order.customer_id
4862
    freebie_order.customer_email = order.customer_email
4863
    freebie_order.customer_name = order.customer_name
4864
    freebie_order.customer_pincode = order.customer_pincode
4865
    freebie_order.customer_address1 = order.customer_address1
4866
    freebie_order.customer_address2 = order.customer_address2
4867
    freebie_order.customer_city = order.customer_city
4868
    freebie_order.customer_state = order.customer_state
4869
    freebie_order.customer_mobilenumber = order.customer_mobilenumber
4870
    freebie_order.total_weight = order.total_weight
4871
    freebie_order.total_amount = 0.01
4872
    freebie_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
4873
    freebie_order.statusDescription = "In Process";
4874
    freebie_order.created_timestamp = datetime.datetime.now()
4875
    freebie_order.cod = 0
4876
    freebie_order.orderType = OrderType.B2C
4877
    freebie_order.pickupStoreId = 0
4878
    freebie_order.otg = 0
4879
    freebie_order.insurer = 0
4880
    freebie_order.insuranceAmount = 0
4881
 
4882
    logistics_client = LogisticsClient().get_client()
4883
    logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, 1, DeliveryType.PREPAID, PickUpType.COURIER)
4884
    freebie_order.logistics_provider_id = logistics_info.providerId;
4885
    freebie_order.tracking_id = logistics_info.airway_billno
4886
    freebie_order.airwaybill_no = logistics_info.airway_billno
4887
    freebie_order.expected_delivery_time = (to_py_date(shippingDate)+datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)  
4888
    freebie_order.promised_delivery_time = order.promised_delivery_time
4889
    freebie_order.expected_shipping_time = to_py_date(shippingDate)
4890
    freebie_order.promised_shipping_time = order.promised_shipping_time
4891
 
4892
    inventory_client = InventoryClient().get_client()
7198 amar.kumar 4893
    item_availability = inventory_client.getItemAvailabilityAtLocation(order.freebieItemId,1)
7190 amar.kumar 4894
    freebie_order.warehouse_id = item_availability[2]
7303 amar.kumar 4895
    freebie_order.fulfilmentWarehouseId = item_availability[0]
7190 amar.kumar 4896
 
4897
    catalog_client = CatalogClient().get_client()
4898
    item = catalog_client.getItem(order.freebieItemId)
4899
    freebie_order.total_weight = item.weight
4900
 
4901
    litem = LineItem()
4902
    litem.item_id = item.id
4903
    litem.productGroup = item.productGroup
4904
    litem.brand = item.brand
4905
    litem.model_number = item.modelNumber
4906
    litem.model_name = item.modelName
4907
    litem.color = item.color
4908
    litem.extra_info = "Freebie Order for Order ID " + str(order.id)
4909
    litem.quantity = 1
4910
    litem.unit_price = 0.01
4911
    litem.unit_weight = item.weight
4912
    litem.total_price = 0.01
4913
    litem.total_weight = item.weight
4914
    litem.vatRate = 5.0
4915
 
4916
    freebie_order.lineitems.append(litem)
7198 amar.kumar 4917
    order.freebieItemId = 0
7190 amar.kumar 4918
    session.commit()
7198 amar.kumar 4919
    order.lineitems[0].extra_info = "Parent Order for Order ID " + str(freebie_order.id)
7190 amar.kumar 4920
 
7198 amar.kumar 4921
    inventory_client = InventoryClient().get_client()   
4922
    inventory_client.reserveItemInWarehouse(freebie_order.lineitems[0].item_id, item_availability[0], sourceId, freebie_order.id, to_java_date(freebie_order.created_timestamp), to_java_date(freebie_order.promised_shipping_time), 1)
7190 amar.kumar 4923
    parentOrderAttribute = Attribute()
4924
    parentOrderAttribute.orderId = freebie_order.id
4925
    parentOrderAttribute.name = "parentOrderIdForFreebie"
4926
    parentOrderAttribute.value = str(order.id)
4927
 
4928
    freebieOrderAttribute = Attribute()
4929
    freebieOrderAttribute.orderId = order.id
4930
    freebieOrderAttribute.name = "freebieOrderId"
4931
    freebieOrderAttribute.value = str(freebie_order.id)
4932
    session.commit()
4933
 
7198 amar.kumar 4934
    return to_t_order(freebie_order)
7190 amar.kumar 4935
 
7151 amit.gupta 4936
def __printRechargeInvoice(filename, operator, amount, telNum, customerName, invNum, billingTime, payMethod): 
7109 anupam.sin 4937
    PAGE_HEIGHT=defaultPageSize[1];
4938
    styles = getSampleStyleSheet()
4939
    styles.add(ParagraphStyle(name='prologue', alignment=TA_CENTER, fontName="Courier", rightIndent = 5, fontSize=10), alias='sH')
4940
    styles.add(ParagraphStyle(name='text', alignment=TA_JUSTIFY, fontName="Courier", fontSize=10), alias='text')
4941
    styles.add(ParagraphStyle(name='line', alignment=TA_CENTER, fontName="Courier", fontSize=10), alias='line')
4942
    styles.add(ParagraphStyle(name='epilogue', alignment=TA_CENTER, fontName="Courier", leftIndent = 30, rightIndent=36, fontSize=10), alias='ep')
7096 anupam.sin 4943
 
7109 anupam.sin 4944
    Story = []
4945
    prologueStyle = styles["prologue"]
4946
    lineStyle = styles["line"]
4947
    textStyle = styles["text"]
4948
    epilogueStyle = styles["epilogue"]
7096 anupam.sin 4949
 
7109 anupam.sin 4950
    doc = BaseDocTemplate(filename,showBoundary=0)
4951
 
4952
    #Two Columns
4953
    frame1 = Frame(58, doc.bottomMargin, doc.width/2 + 25, doc.height + 7, id='col1')
4954
 
4955
 
4956
 
4957
    Story.append(Paragraph("""Spice Retail Limited<br></br>
4958
        C/O,PIBCO LIMITED,Basement,Punjsons<br></br>
4959
        2,Kalkaji Industrial Area,New Delhi<br></br>
4960
          .<br></br>
4961
        TIN NO. 07430284979<br></br>
4962
        Service Tax No:AAACM0294PST001<br></br><br></br><br></br>""", prologueStyle))
4963
    drawLine(Story, lineStyle)
4964
 
4965
    Story.append(Paragraph('{0:7s}{1:>11s}{2:  %d/%m/%Y  %H:%M:%S}'.format("INV NO:", invNum, billingTime).replace(" ", "&nbsp;"), textStyle))
4966
    drawLine(Story, lineStyle)
4967
 
4968
    Story.append(Paragraph("{0:<6s}{1:<34s}".format("NAME:", customerName).replace(" ", "&nbsp;"), textStyle))
4969
    Story.append(Paragraph("{0:<9s}{1:<31s}".format("TEL NO.:", telNum).replace(" ", "&nbsp;"), textStyle))
7151 amit.gupta 4970
    Story.append(Paragraph("{0:<9s}{1:<31s}".format("PAYMENT MODE:", PayMethod._VALUES_TO_NAMES[payMethod]).replace(" ", "&nbsp;"), textStyle))
7109 anupam.sin 4971
    drawLine(Story, lineStyle)
4972
 
4973
    Story.append(Paragraph(('{0:<16s}{1:>13s}{2:11.2f}').format(operator, "RECHARGE", amount).replace(' ', '&nbsp;'),textStyle))
4974
    drawLine(Story, lineStyle)
4975
    doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1]), ])
4976
 
4977
    #start the construction of the pdf
4978
    doc.build(Story)
4979
 
4980
    try:
4981
        fileToSend = open(filename, "rb")
4982
        pdfFile = fileToSend.read()
4983
    except:
4984
        return bin(0)
4985
 
4986
    return pdfFile
4987
 
7172 anupam.sin 4988
def get_recharge_transactions_by_number(number, storeId):
7169 anupam.sin 4989
    query = RechargeTransaction.query.filter(RechargeTransaction.deviceNum == number)
7172 anupam.sin 4990
    query = query.filter(RechargeTransaction.storeId == storeId)
7169 anupam.sin 4991
    return query.all()
4992
 
4993
def update_hotspot_store_password(storeId, password):
4994
    store = None
4995
    if password is None:
4996
        return False
4997
    if storeId:
4998
        store = HotspotStore.query.filter(HotspotStore.id == storeId).first()
4999
    if store:
5000
        store.password = password
5001
        session.commit()
5002
        return True
5003
    return False
5004
 
7263 anupam.sin 5005
def get_source_detail(source):
5006
    detail = SourceDetail.get_by(id=source)
5007
    if not detail:
5008
        raise TransactionServiceException(108, "no such source")
5009
    return detail
5010
 
7267 anupam.sin 5011
def get_all_circles():
5012
    circles = TelecomCircle.query.all();
5013
    if not circles:
5014
        circles = []
5015
    return circles 
5016
 
5017
def delete_frcs(frcIdsToDelete):
5018
    toReturn = False
5019
    if frcIdsToDelete:
5020
        for frcId in frcIdsToDelete:
5021
            frc = FRC.get_by(id = frcId)
5022
            if frc:
5023
                frc.delete()
5024
                toReturn = True
5025
        session.commit()
5026
        return toReturn
5027
    else:
5028
        return toReturn
5029
 
7285 rajveer 5030
def topup_company_wallet(companyId, amount):
5031
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
5032
    company = Company.get_by(id = companyId)
5033
    wh = WalletHistoryForCompany()
5034
    wh.walletId = wallet.id
5035
    wh.openingBal = wallet.amount
5036
    wh.closingBal = wallet.amount +  amount
5037
    wh.amount = amount
5038
    wh.transactionTime = datetime.datetime.now()
5039
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
5040
    wh.description = "Wallet Credited"
5041
 
5042
    wallet.amount += amount
5043
    session.commit()
5044
    mail("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "Ashwani.Kumar@spiceretail.co.in","parveen.mittal@spiceretail.co.in","pardeep.panwar@spiceretail.co.in","gagan.sharma@spiceretail.co.in","j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in", "amit.tyagi@spiceretail.co.in"] , company.name + " wallet topped up by " +  str(amount) + " rupees.", "", [], [], [])
5045
    return wallet.amount
7267 anupam.sin 5046
 
7285 rajveer 5047
def get_wallet_balance_for_company(companyId):
5048
    return WalletForCompany.get_by(companyId = companyId).amount
5049
 
6915 anupam.sin 5050
if __name__ == '__main__':
6980 anupam.sin 5051
    print 'helllo'