Subversion Repositories SmartDukaan

Rev

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