Subversion Repositories SmartDukaan

Rev

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