Subversion Repositories SmartDukaan

Rev

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