Subversion Repositories SmartDukaan

Rev

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

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