Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
94 ashish 1
'''
2
Created on 23-Mar-2010
3
 
4
@author: ashish
5
'''
6
from elixir import *
4748 mandeep.dh 7
from pydoc import Helper
8
from shop2020.clients.HelperClient import HelperClient
9
from shop2020.clients.TransactionClient import TransactionClient
10
from shop2020.config.client.ConfigClient import ConfigClient
94 ashish 11
from shop2020.model.v1.catalog.impl import DataService
4748 mandeep.dh 12
from shop2020.model.v1.catalog.impl.CategoryManager import CategoryManager
13
from shop2020.model.v1.catalog.impl.Convertors import to_t_item, \
3557 rajveer 14
    to_t_vendor_item_pricing, to_t_source
4748 mandeep.dh 15
from shop2020.model.v1.catalog.impl.DataService import Item, Warehouse, \
16
    ItemInventoryHistory, CurrentInventorySnapshot, ItemInfo, ItemChangeLog, \
17
    Category, EntityIDGenerator, VendorItemPricing, VendorItemMapping, Vendor, \
18
    SimilarItems, ProductNotification, Source, SourceItemPricing, AuthorizationLog, \
19
    MissingItemKey
20
from shop2020.thriftpy.model.v1.catalog.ttypes import InventoryServiceException, \
21
    status, ItemShippingInfo
22
from shop2020.thriftpy.model.v1.order.ttypes import AlertType
23
from shop2020.utils.EmailAttachmentSender import mail
2286 ankur.sing 24
from shop2020.utils.Utils import log_entry, to_py_date, log_risky_flag
621 chandransh 25
from sqlalchemy import desc, asc
3244 chandransh 26
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
3872 chandransh 27
from sqlalchemy.sql.expression import and_, or_, distinct, func
3086 rajveer 28
from string import Template
4748 mandeep.dh 29
from urllib2 import HTTPBasicAuthHandler
30
import datetime
31
import sys
3924 rajveer 32
import urllib2
94 ashish 33
 
34
def initialize():
35
    DataService.initialize()
36
 
3849 chandransh 37
def get_all_items_by_status(status, offset=0, limit=None):
38
    query = Item.query
4539 rajveer 39
    if status is not None:
3849 chandransh 40
        query = query.filter_by(status=status)
41
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
42
    if limit:
43
        query = query.limit(limit)
44
    items = query.all()
45
    return items
46
 
47
def get_all_items(is_active, offset=0, limit=None):
103 ashish 48
    if is_active:
3849 chandransh 49
        items = get_all_items_by_status(status.ACTIVE, offset, limit)
103 ashish 50
    else:
3849 chandransh 51
        items = get_all_items_by_status(None, offset, limit)
766 rajveer 52
    return items
53
 
3849 chandransh 54
def get_item_count_by_status(use_status, status):
55
    if use_status:
56
        return Item.query.filter_by(status=status).count()
103 ashish 57
    else:
3849 chandransh 58
        return Item.query.count()
103 ashish 59
 
635 rajveer 60
def get_item(item_id):
766 rajveer 61
    item = Item.get_by(id=item_id)
62
    return item
94 ashish 63
 
635 rajveer 64
def get_items_by_catalog_id(catalog_id):
447 rajveer 65
    query = Item.query.filter_by(catalog_item_id=catalog_id)
437 rajveer 66
    try:
635 rajveer 67
        items = query.all()
68
        return get_thrift_item_list(items)
1399 rajveer 69
    except Exception as ex:
70
        print ex
437 rajveer 71
        raise InventoryServiceException(109, "Item not found")
72
 
576 chandransh 73
def is_active(item_id):
2983 chandransh 74
    t_item_shipping_info = ItemShippingInfo()
576 chandransh 75
    try:
635 rajveer 76
        item = get_item(item_id)
3281 chandransh 77
        t_item_shipping_info.isRisky = item.risky
4708 anupam.sin 78
        warehouse_ids = None
79
        if item.isWarehousePreferenceSticky :
80
            warehouse_ids = [item.preferredWarehouse]
81
        availability = __get_item_availability(item, warehouse_ids)
3281 chandransh 82
        if item.risky and availability <= 0 and item.status == status.ACTIVE:
83
            add_status_change_log(item, status.PAUSED_BY_RISK)
84
            item.status = status.PAUSED_BY_RISK
85
            item.status_description = "This item is currently out of stock"
86
            session.commit()
3924 rajveer 87
            #This will clear cache from tomcat
88
            __clear_homepage_cache()
2983 chandransh 89
        t_item_shipping_info.isActive = (item.status == status.ACTIVE)
3281 chandransh 90
        t_item_shipping_info.quantity = availability
576 chandransh 91
    except InventoryServiceException:
2983 chandransh 92
        print "[ERROR] Unexpected error:", sys.exc_info()[0]
93
    return t_item_shipping_info
94
 
2035 rajveer 95
def get_item_status_description(itemId):
96
    item = get_item(itemId)
97
    return item.status_description
563 chandransh 98
 
94 ashish 99
def get_Warehouse(warehouse_id):
100
    return Warehouse.get_by(id=warehouse_id)
101
 
4332 anupam.sin 102
def get_Vendor(vendorId):
103
    return Vendor.get_by(id=vendorId)
104
 
122 ashish 105
def get_all_warehouses_by_status(status):
106
    if not status:
766 rajveer 107
        warehouses = Warehouse.query.all()
122 ashish 108
    else:
851 chandransh 109
        warehouses = Warehouse.query.filter_by(status=status).all()
110
    return warehouses
122 ashish 111
 
94 ashish 112
def get_all_warehouses_for_item(item_id):
635 rajveer 113
    item = get_item(item_id)
94 ashish 114
    if not item:
122 ashish 115
        raise InventoryServiceException(108, "Some unforeseen error while obtaining item")
116
    return item.get_all_warehouses
94 ashish 117
 
122 ashish 118
def get_all_items_for_warehouse(warehouse_id):
119
    warehouse = get_Warehouse(warehouse_id)
120
    if not warehouse:
121
        raise InventoryServiceException(108, "bad warehouse")
122
    return warehouse.all_items
123
 
94 ashish 124
def add_warehouse(warehouse):
103 ashish 125
    if not warehouse:
122 ashish 126
        raise InventoryServiceException(108, "Bad warehouse")
103 ashish 127
    if get_Warehouse(warehouse.id):
128
        #warehouse is already present.
122 ashish 129
        raise InventoryServiceException(101, "Warehouse already present")
103 ashish 130
 
94 ashish 131
    ds_warehouse = Warehouse()
132
    ds_warehouse.id = warehouse.id
133
    ds_warehouse.location = warehouse.location
122 ashish 134
    ds_warehouse.status = status.ACTIVE
103 ashish 135
    ds_warehouse.addedOn = datetime.datetime.now()
483 rajveer 136
    ds_warehouse.lastCheckedOn = datetime.datetime.now()
137
    ds_warehouse.tinNumber = warehouse.tinNumber
138
    ds_warehouse.pincode = warehouse.pincode
139
    if warehouse.vendorString:
140
        ds_warehouse.vendorString = warehouse.vendorString
94 ashish 141
    session.commit()
103 ashish 142
    return ds_warehouse.id
94 ashish 143
 
122 ashish 144
def update_item(item):
145
    if not item:
146
        raise InventoryServiceException(108, "Bad item in request")
147
 
148
    if not item.id:
609 chandransh 149
        raise InventoryServiceException(101, "Missing id for update")
122 ashish 150
 
2120 ankur.sing 151
    validate_item_prices(item)
2065 ankur.sing 152
 
635 rajveer 153
    ds_item = get_item(item.id)
122 ashish 154
 
155
    if not ds_item:
609 chandransh 156
        raise InventoryServiceException(101, "Item missing in our database")
122 ashish 157
 
963 chandransh 158
    if item.productGroup:
159
        ds_item.product_group = item.productGroup 
160
    if item.brand:
161
        ds_item.brand = item.brand
511 rajveer 162
    if item.modelNumber:
163
        ds_item.model_number = item.modelNumber
2497 ankur.sing 164
    ds_item.color = item.color
165
    ds_item.model_name = item.modelName
166
    ds_item.category = item.category
167
    ds_item.comments = item.comments
511 rajveer 168
 
2497 ankur.sing 169
    ds_item.catalog_item_id = item.catalogItemId
483 rajveer 170
 
2129 ankur.sing 171
    ds_item.mrp = item.mrp
172
    ds_item.sellingPrice = item.sellingPrice
2497 ankur.sing 173
 
2174 ankur.sing 174
    ds_item.weight = item.weight
2129 ankur.sing 175
 
2358 ankur.sing 176
    if ds_item.status != item.itemStatus:
2402 rajveer 177
        add_status_change_log(ds_item, item.itemStatus)
2358 ankur.sing 178
        ds_item.status = item.itemStatus
2035 rajveer 179
    if item.status_description:
180
        ds_item.status_description = item.status_description
122 ashish 181
 
511 rajveer 182
    if item.startDate:
2116 ankur.sing 183
        ds_item.startDate = to_py_date(item.startDate)
2497 ankur.sing 184
    else:
185
        ds_item.startDate = None
511 rajveer 186
    if item.retireDate:
2116 ankur.sing 187
        ds_item.retireDate = to_py_date(item.retireDate)
2497 ankur.sing 188
    else:
189
        ds_item.retireDate = None
511 rajveer 190
 
2497 ankur.sing 191
    ds_item.feature_id = item.featureId
192
    ds_item.feature_description = item.featureDescription
122 ashish 193
 
2129 ankur.sing 194
    ds_item.bestDealText = item.bestDealText
195
    ds_item.bestDealValue = item.bestDealValue
2065 ankur.sing 196
    ds_item.bestSellingRank = item.bestSellingRank
2497 ankur.sing 197
 
2065 ankur.sing 198
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 199
    ds_item.risky = item.risky
3359 chandransh 200
 
3459 chandransh 201
    if item.expectedDelay is not None:
3359 chandransh 202
        ds_item.expectedDelay = item.expectedDelay
203
 
204
    if item.preferredWarehouse:
205
        ds_item.preferredWarehouse = item.preferredWarehouse
4413 anupam.sin 206
 
207
    if item.defaultWarehouse:
208
        ds_item.defaultWarehouse = item.defaultWarehouse
4506 phani.kuma 209
 
210
    if item.preferredVendor:
211
        ds_item.preferredVendor = item.preferredVendor
4413 anupam.sin 212
 
213
    ds_item.isWarehousePreferenceSticky = item.isWarehousePreferenceSticky
3359 chandransh 214
 
2347 ankur.sing 215
    ds_item.updatedOn = datetime.datetime.now()
2065 ankur.sing 216
 
122 ashish 217
    session.commit();
218
    return ds_item.id
94 ashish 219
 
103 ashish 220
def add_item(item):
221
    if not item:
122 ashish 222
        raise InventoryServiceException(108, "Bad item in request")
635 rajveer 223
    if get_item(item.id):
122 ashish 224
        raise InventoryServiceException(101, "Item already exists")
2120 ankur.sing 225
 
226
    validate_item_prices(item)
227
 
103 ashish 228
    ds_item = Item()
963 chandransh 229
    if item.productGroup:
230
        ds_item.product_group = item.productGroup
231
    if item.brand:
232
        ds_item.brand = item.brand
515 rajveer 233
    if item.modelName:
234
        ds_item.model_name = item.modelName
235
    if item.modelNumber:
236
        ds_item.model_number = item.modelNumber
609 chandransh 237
    if item.color:
238
        ds_item.color = item.color
483 rajveer 239
    if item.category:
240
        ds_item.category = item.category
241
    if item.comments:
242
        ds_item.comments = item.comments
243
 
103 ashish 244
    ds_item.addedOn = datetime.datetime.now()
609 chandransh 245
    ds_item.updatedOn = datetime.datetime.now()
2116 ankur.sing 246
    if item.startDate:
247
        ds_item.startDate = to_py_date(item.startDate)
248
    if item.retireDate:
249
        ds_item.retireDate = to_py_date(item.retireDate)
609 chandransh 250
 
483 rajveer 251
    if item.mrp:
252
        ds_item.mrp = item.mrp
253
    if item.sellingPrice:
254
        ds_item.sellingPrice = item.sellingPrice
122 ashish 255
    if item.weight:
256
        ds_item.weight = item.weight
257
 
258
    if item.featureId:
259
        ds_item.feature_id = item.featureId
260
    if item.featureDescription:
261
        ds_item.feature_description = item.featureDescription
262
 
103 ashish 263
    if item.otherInfo:
264
        for k,v in item.otherInfo.iteritems():
265
            info = ItemInfo()
266
            info.key = k
267
            info.value = v
268
            ds_item.iteminfo.append(info)
2116 ankur.sing 269
 
103 ashish 270
    #check if categories present. If yes, add them to system
122 ashish 271
 
609 chandransh 272
    if item.bestDealValue:
273
        ds_item.bestDealValue = item.bestDealValue
274
    if item.bestDealText:
275
        ds_item.bestDealText = item.bestDealText
2116 ankur.sing 276
    if item.bestSellingRank:
277
        ds_item.bestSellingRank = item.bestSellingRank
278
    ds_item.defaultForEntity = item.defaultForEntity
2251 ankur.sing 279
    ds_item.risky = item.risky
609 chandransh 280
 
3467 chandransh 281
    if item.expectedDelay is not None:
3359 chandransh 282
        ds_item.expectedDelay = item.expectedDelay
3467 chandransh 283
    else:
284
        ds_item.expectedDelay = 0
3359 chandransh 285
 
286
    if item.preferredWarehouse:
287
        ds_item.preferredWarehouse = item.preferredWarehouse
288
 
2116 ankur.sing 289
    # Check if a similar item already exists in our database
4725 phani.kuma 290
    similar_item = Item.query.filter_by(brand=item.brand, model_number=item.modelNumber, model_name=item.modelName).first()
291
    print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2}".format(item.brand, item.modelNumber, item.modelName)
2116 ankur.sing 292
 
293
    if similar_item is None or similar_item.catalog_item_id is None:
294
        # If there is no similar item in the database from before,
295
        # use the entity_id_generator
296
        entity_id = EntityIDGenerator.query.first()
297
        ds_item.catalog_item_id = entity_id.id + 1
298
        ds_item.status = status.IN_PROCESS
299
        ds_item.status_description = "This item is in process."
300
        entity_id.id = entity_id.id  + 1
4725 phani.kuma 301
        if similar_item is not None and similar_item.catalog_item_id is None:
302
            similar_item.catalog_item_id = entity_id.id
2116 ankur.sing 303
    else:
304
        #If a similar item already exists for a product group, brand and model_number, set it as same.
305
        ds_item.catalog_item_id = similar_item.catalog_item_id
306
        ds_item.category = similar_item.category
4762 phani.kuma 307
        ds_item.product_group = similar_item.product_group
2116 ankur.sing 308
        ds_item.status = similar_item.status
309
        ds_item.status_description = similar_item.status_description
310
 
103 ashish 311
    session.commit();
3325 chandransh 312
    return ds_item.id
313
 
314
def update_inventory_history(warehouse_id, timestamp, availability):
315
    warehouse = get_Warehouse(warehouse_id)
316
    if not warehouse:
317
        raise InventoryServiceException(107, "Warehouse? Where?")
4368 rajveer 318
    vendors = get_vendors_for_warehouse(warehouse_id)
319
    if len(vendors) > 1:
320
        raise InventoryServiceException(110, "Multiple vendors found for warehouse !")
321
    vendor = vendors[0]
3325 chandransh 322
    time = datetime.datetime.now()
323
    for item_key, quantity in availability.iteritems():
324
        try:
325
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
326
            item = vendor_item_mapping.item
327
        except:
328
            continue  
329
        try:
330
            item_inventory_history = ItemInventoryHistory()
331
            item_inventory_history.warehouse = warehouse
332
            item_inventory_history.item = item
333
            item_inventory_history.timestamp = time
334
            item_inventory_history.availibility = quantity
335
        except:
336
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
337
    session.commit()
103 ashish 338
 
483 rajveer 339
def update_inventory(warehouse_id, timestamp, availability):
340
    warehouse = get_Warehouse(warehouse_id)
341
    if not warehouse:
342
        raise InventoryServiceException(107, "Warehouse? Where?")
343
 
344
    time = datetime.datetime.now()
345
    warehouse.lastCheckedOn = time
346
    warehouse.vendorString = timestamp
4368 rajveer 347
    vendors = get_vendors_for_warehouse(warehouse_id)
348
    if len(vendors) > 1:
349
        raise InventoryServiceException(110, "Multiple vendors found for warehouse !")
350
    vendor = vendors[0]
2368 ankur.sing 351
    session.commit()
1368 chandransh 352
    for item_key, quantity in availability.iteritems():
483 rajveer 353
        try:
1368 chandransh 354
            vendor_item_mapping = VendorItemMapping.query.filter_by(vendor=vendor, item_key=item_key).one();
355
            item = vendor_item_mapping.item
494 rajveer 356
        except:
4748 mandeep.dh 357
            print 'Could not find item with key: ' + item_key
358
            __send_mail_for_missing_key(item_key, warehouse_id)
359
            continue
494 rajveer 360
        try:
483 rajveer 361
            current_inventory_snapshot = CurrentInventorySnapshot.get_by(item=item, warehouse=warehouse)
362
            if not current_inventory_snapshot:
363
                current_inventory_snapshot = CurrentInventorySnapshot()
364
                current_inventory_snapshot.item = item
365
                current_inventory_snapshot.warehouse = warehouse
366
                current_inventory_snapshot.availibility = 0
871 chandransh 367
                current_inventory_snapshot.reserved = 0
483 rajveer 368
            # added the difference in the current inventory    
369
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
4400 rajveer 370
            try:
371
                if quantity > 0 and __get_item_reserved(item) > 0:
372
                    cl = TransactionClient().get_client()
4448 rajveer 373
                    #FIXME hardcoding for warehouse id 
374
                    cl.addAlert(AlertType.NEW_INVENTORY_ALERT, 5, "Inventory received for item " + item.brand + " " + item.model_name + " " + item.model_number + " " +  item.color)
4400 rajveer 375
            except:
376
                print "Not able to raise alert for incoming inventory" 
483 rajveer 377
        except:
378
            raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
2368 ankur.sing 379
        session.commit() 
380
        check_risky_item(item)
483 rajveer 381
 
4748 mandeep.dh 382
def __send_mail_for_missing_key(item_key, warehouse_id):
383
    if not MissingItemKey.get_by(itemKey = item_key):
384
        missingItemKey = MissingItemKey()
385
        missingItemKey.itemKey = item_key
386
        missingItemKey.warehouseId = warehouse_id
387
        helperClient = HelperClient().get_client()
388
        helperClient.saveUserEmailForSending('mandeep.dhir@shop2020.in', 'inventory@shop2020.in', 'Item-key not found while inventory sync', item_key + ' warehouse id: ' + str(warehouse_id), None, 'inventory')
389
        session.commit()
390
 
4320 rajveer 391
def add_inventory(itemId, warehouseId, quantity):
392
    current_inventory_snapshot = CurrentInventorySnapshot.get_by(item_id=itemId, warehouse_id=warehouseId)
393
    if not current_inventory_snapshot:
394
        current_inventory_snapshot = CurrentInventorySnapshot()
395
        current_inventory_snapshot.item_id = itemId
396
        current_inventory_snapshot.warehouse_id = warehouseId
397
        current_inventory_snapshot.availibility = 0
398
        current_inventory_snapshot.reserved = 0
399
    # added the difference in the current inventory    
400
    current_inventory_snapshot.availibility = current_inventory_snapshot.availibility + quantity
401
    session.commit() 
402
 
4431 phani.kuma 403
'''
94 ashish 404
def get_item_inventoy(item_id):
405
 
406
    inventory = Item.get_by(id=item_id).currentInventory
407
    if not inventory:
122 ashish 408
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
94 ashish 409
    return inventory
4431 phani.kuma 410
'''
94 ashish 411
 
635 rajveer 412
def get_item_inventory_by_item_id(item_id):
413
    inventory = Item.get_by(id=item_id).currentInventory
379 ashish 414
    if not inventory:
415
        raise InventoryServiceException(108, "Some unforeseen error while updating inventory")
416
    return inventory
417
 
103 ashish 418
 
419
def retire_warehouse(warehouse_id):
420
    if not warehouse_id:
122 ashish 421
        raise InventoryServiceException(101, "Bad warehouse id")
103 ashish 422
    warehouse = get_Warehouse(warehouse_id)
423
    if not warehouse:
122 ashish 424
        raise InventoryServiceException(108, "warehouse id not present")
425
    warehouse.status = status.DELETED;
103 ashish 426
    session.commit()
427
 
428
def retire_item(item_id):
429
    if not item_id:
122 ashish 430
        raise InventoryServiceException(101, "bad item id")
635 rajveer 431
    item = get_item(item_id)
103 ashish 432
    if not item:
122 ashish 433
        raise InventoryServiceException(108, "item id not present")
434
    item.status = status.PHASED_OUT
435
    item.retireDate = datetime.datetime.now()
103 ashish 436
    session.commit()
122 ashish 437
 
438
#need to implement threads based solution here
103 ashish 439
def start_item_on(item_id, timestamp):
440
    if not item_id:
122 ashish 441
        raise InventoryServiceException(101, "bad item id")
635 rajveer 442
    item = get_item(item_id)
103 ashish 443
    if not item:
122 ashish 444
        raise InventoryServiceException(108, "item id not present")
103 ashish 445
 
122 ashish 446
    item.status = status.ACTIVE
447
    item.startDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
448
    add_status_change_log(item, status.ACTIVE)
103 ashish 449
    session.commit()
450
 
122 ashish 451
#need to implement threads here
103 ashish 452
def retire_item_on(item_id, timestamp):
453
    if not item_id:
122 ashish 454
        raise InventoryServiceException(101, "bad item id")
635 rajveer 455
    item = get_item(item_id)
103 ashish 456
    if not item:
122 ashish 457
        raise InventoryServiceException(108, "item id not present")
103 ashish 458
 
122 ashish 459
    item.status = status.PHASED_OUT
460
    item.retireDate = datetime.datetime.fromtimestamp(to_py_date(timestamp))
461
    add_status_change_log(item, status.PHASED_OUT)
103 ashish 462
    session.commit()
463
 
464
def add_status_change_log(item, new_status):
465
    item_change_log = ItemChangeLog()
466
    item_change_log.new_status = new_status
467
    item_change_log.old_status = item.status
468
    item_change_log.timestamp = datetime.datetime.now()
469
    item_change_log.item = item
470
    session.commit()
471
 
472
def change_item_status(item_id, new_status):
473
    if not item_id:
122 ashish 474
        raise InventoryServiceException(101, "bad item id")
635 rajveer 475
    item = get_item(item_id)
103 ashish 476
    if not item:
122 ashish 477
        raise InventoryServiceException(108, "item id not present")
2116 ankur.sing 478
    add_status_change_log(item, new_status)
122 ashish 479
    item.status = new_status
2251 ankur.sing 480
    if item.status == status.PHASED_OUT:
481
        item.status_description = "This item has been phased out"
482
    elif item.status == status.DELETED:
483
        item.status_description = "This item has been deleted"
3924 rajveer 484
    elif item.status == status.PAUSED:
485
        item.status_description = "This item is currently out of stock"      
486
    elif item.status == status.PAUSED_BY_RISK:
487
        item.status_description = "This item is currently out of stock"
488
        #This will clear cache from tomcat
489
        __clear_homepage_cache()  
2251 ankur.sing 490
    elif item.status == status.ACTIVE:
491
        item.status_description = "This item is active"
492
    elif item.status == status.IN_PROCESS:
493
        item.status_description = "This item is in process"
494
    elif item.status == status.CONTENT_COMPLETE:
495
        item.status_description = "This item is in process"
103 ashish 496
    session.commit()
497
 
498
def get_item_availability_for_warehouse(warehouse_id, item_id):
499
    if not warehouse_id:
122 ashish 500
        raise InventoryServiceException(101, "bad warehouse_id")
103 ashish 501
    if not item_id:
122 ashish 502
        raise InventoryServiceException(101, "bad item_id")
103 ashish 503
 
504
    warehouse = get_Warehouse(warehouse_id)
505
    if not warehouse:
122 ashish 506
        raise InventoryServiceException(108, "warehouse does not exist")
635 rajveer 507
    item = get_item(item_id)
504 rajveer 508
 
103 ashish 509
    if not item:
766 rajveer 510
        raise InventoryServiceException(108, "item does not exist")
122 ashish 511
 
494 rajveer 512
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id)
504 rajveer 513
    query = query.filter_by(item_id = item.id)
494 rajveer 514
    try:
515
        current_inventory_snapshot = query.one()
871 chandransh 516
        return current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
494 rajveer 517
    except:
518
        return 0
519
    """
520
    current_inventory_snapshot = CurrentInventorySnapshot.query.filter(CurrentInventorySnapshot.warehouse_id == warehouse_id, CurrentInventorySnapshot.item_id == item_id).one()
103 ashish 521
    if not current_inventory_snapshot:
522
        return 0
523
    else:
524
        return current_inventory_snapshot.availibility
494 rajveer 525
    """
643 chandransh 526
 
2368 ankur.sing 527
def check_risky_item(item):
2251 ankur.sing 528
    if not item.risky:
529
        return
4406 anupam.sin 530
    availability = __get_item_availability(item, None)
2983 chandransh 531
    if availability <= 0:
2251 ankur.sing 532
        if item.status == status.ACTIVE:
2984 rajveer 533
            change_item_status(item.id, status.PAUSED_BY_RISK)
4318 rajveer 534
            try:
4374 rajveer 535
                mail("cnc.center@shop2020.in", "5h0p2o2o", ["chaitnaya.vats@shop2020.in", "abhishek.mathur@shop2020.in"], "Item is out of stock. ID: " + str(item.id)  + " " + item.brand +  " " + item.model_name + " " + item.model_number, " ", [])
4318 rajveer 536
            except:
537
                print "Unable to send the report"
2251 ankur.sing 538
    else:
2984 rajveer 539
        if item.status == status.PAUSED_BY_RISK:
2251 ankur.sing 540
            change_item_status(item.id, status.ACTIVE)
2368 ankur.sing 541
    session.commit()
2251 ankur.sing 542
 
4406 anupam.sin 543
'''
544
This method returns quantity of a particular item across all warehouses whose ids is provided
545
if warehouse_ids is null it checks for inventory in all warehouses.
546
'''
547
def __get_item_availability(item, warehouse_ids):
548
    if warehouse_ids is None:
549
        all_inventory = CurrentInventorySnapshot.query.filter_by(item = item).all()
550
        availability = 0
551
        reserved = 0
552
        for currInv in all_inventory:
553
            availability = availability + currInv.availibility
554
            reserved = reserved + currInv.reserved
555
        return availability - reserved
556
    else:
557
        total_availability = 0
558
        for warehouse_id in warehouse_ids:
559
            try:
560
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item.id).one()
561
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
562
            except Exception as e:
563
                print e
564
                availability = 0    
565
            total_availability = total_availability + availability
566
        return total_availability 
4400 rajveer 567
 
568
def __get_item_reserved(item):
569
    all_inventory = CurrentInventorySnapshot.query.filter_by(item = item).all()
570
    reserved = 0
571
    for currInv in all_inventory:
572
        reserved = reserved + currInv.reserved
573
    return reserved
2983 chandransh 574
 
871 chandransh 575
def reserve_item_in_warehouse(item_id, warehouse_id, quantity):    
576
    if not warehouse_id:
577
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 578
    item = get_item(item_id)
579
    if not item:
871 chandransh 580
        raise InventoryServiceException(101, "bad item_id")
581
 
582
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
583
    try:
584
        current_inventory_snapshot = query.one()
585
    except:
4103 chandransh 586
        current_inventory_snapshot = CurrentInventorySnapshot()
587
        current_inventory_snapshot.warehouse_id = warehouse_id
588
        current_inventory_snapshot.item_id = item_id
589
        current_inventory_snapshot.availibility = 0
590
        current_inventory_snapshot.reserved = 0
591
 
592
    current_inventory_snapshot.reserved = current_inventory_snapshot.reserved + quantity
593
    session.commit()
594
    check_risky_item(item)
595
    return True
871 chandransh 596
 
597
def reduce_reservation_count(item_id, warehouse_id, quantity):
598
    if not warehouse_id:
599
        raise InventoryServiceException(101, "bad warehouse_id")
2251 ankur.sing 600
    item = get_item(item_id)
601
    if not item:
871 chandransh 602
        raise InventoryServiceException(101, "bad item_id")
603
 
604
    query = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id)
605
    try:
606
        current_inventory_snapshot = query.one()
607
        current_inventory_snapshot.reserved = current_inventory_snapshot.reserved - quantity
4318 rajveer 608
        ##FIXME In case of our own warehouse reduce availability also
609
        if warehouse_id == 7:
4335 rajveer 610
            current_inventory_snapshot.availibility = current_inventory_snapshot.availibility - quantity
871 chandransh 611
        session.commit()
2368 ankur.sing 612
        check_risky_item(item)
871 chandransh 613
        return True
614
    except:
615
        print "Unexpected error:", sys.exc_info()[0]
616
        return False
617
 
2075 rajveer 618
def mark_item_as_content_complete(entity_id, category, brand, modelName, modelNumber):
2828 rajveer 619
    '''
620
    Get all the items for this entityID and update category, brand, modelName and modelNumber for all.
621
    Update Status for only IN_PROCESS items to CONTENT_COMPLETE
622
    '''
723 chandransh 623
    content_complete_status = status.CONTENT_COMPLETE
2828 rajveer 624
    items = Item.query.filter_by(catalog_item_id=entity_id).all()
723 chandransh 625
    current_timestamp = datetime.datetime.now()
626
    for item in items:
2828 rajveer 627
        if item.status == status.IN_PROCESS:
628
            item.status = content_complete_status
629
            item_change_log = ItemChangeLog()
630
            item_change_log.old_status = item.status
631
            item_change_log.new_status = content_complete_status
632
            item_change_log.timestamp = current_timestamp
633
            item_change_log.item = item
723 chandransh 634
 
4762 phani.kuma 635
        category_object = get_category(category)
636
        if category_object is not None:
637
            item.category = category
638
            item.product_group = category_object.display_name
2075 rajveer 639
        item.brand = brand
2081 rajveer 640
        item.model_name = modelName
641
        item.model_number = modelNumber
723 chandransh 642
        item.updatedOn = current_timestamp
643
    session.commit()
644
    return True
1294 chandransh 645
 
643 chandransh 646
def get_item_availability_for_location(warehouse_loc, item_id):
3355 chandransh 647
    """
648
    Determines the warehouse that should be used to fulfil an order for the given item.
4406 anupam.sin 649
    It first checks whether the preferred warehouse for that item is set or not. If set 
650
    and preference is sticky then that warehouse is used for fulfilment.
651
    If preference is not sticky then we see if item is available in the preferred WH,
652
    in which case that warehouse is used otherwise we use that warehouse which has the max
653
    availability. And if there is no inventory for that item in any warehouses then we use
654
    default warehouse.
655
    If preference is not set in that case we just find the warehouse with max availability
656
    and in case of zero inventory we use default warehouse
3355 chandransh 657
 
658
    Returns an ordered list of size 4 with following elements in the given order:
659
    1. Logistics location of the warehouse which was finally picked up to ship the order.
660
    2. Id of the warehouse which was finally picked up.
661
    3. Inventory size in the selected warehouse.
662
    4. Expected delay added by the category manager.
663
 
664
    Parameters:
665
     - warehouse_loc
666
     - item_id
667
    """
643 chandransh 668
    if warehouse_loc is None:
669
        raise InventoryServiceException(101, "Bad Warehouse Location")
670
    if not item_id:
1416 chandransh 671
        raise InventoryServiceException(101, "Bad Item id")
643 chandransh 672
 
1416 chandransh 673
    item = Item.get_by(id=item_id)
4406 anupam.sin 674
    logisticsLocation = warehouse_loc
675
    warehouses = Warehouse.query.filter_by(logisticsLocation=logisticsLocation).all()
643 chandransh 676
    warehouse_ids = [warehouse.id for warehouse in warehouses]
677
    warehouse_retid = -1
4406 anupam.sin 678
 
3503 chandransh 679
    total_availability = 0
4406 anupam.sin 680
    '''
681
    If warehouse preference is set and it is sticky then we should fulfil this order from this warehouse only.
682
    But we still need to calculate total availability across warehouses.
683
    '''
684
    if (item.isWarehousePreferenceSticky and item.preferredWarehouse is not None) :
685
        warehouse_retid = item.preferredWarehouse
686
        warehouse = Warehouse.get_by(id=warehouse_retid)
687
        logisticsLocation = warehouse.logisticsLocation
4476 anupam.sin 688
        total_availability = __get_item_availability(item, [warehouse_retid])
4406 anupam.sin 689
 
690
    #If preference is not sticky then this order should be fulfilled from preferred WH if inventory available
691
    #otherwise we should check for its availability elsewhere and fulfil this order from there, but if it is not available anywhere
692
    #then we should fulfil this order from its default warehouse.
693
 
694
    elif (not item.isWarehousePreferenceSticky and item.preferredWarehouse is not None) :
785 rajveer 695
        try:
4406 anupam.sin 696
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = item.preferredWarehouse, item_id = item_id).one()
871 chandransh 697
            availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
4317 varun.gupt 698
        except Exception as e:
699
            print e
785 rajveer 700
            availability = 0    
4406 anupam.sin 701
        if availability > 0:
702
            warehouse_retid = item.preferredWarehouse
4476 anupam.sin 703
            total_availability = availability
4406 anupam.sin 704
        else :
705
            [logisticsLocation, warehouse_retid, total_availability] = \
706
                        __get_warehouse_with_max_availability(warehouse_loc = warehouse_loc, \
707
                                                            warehouse_ids = warehouse_ids, item = item)
708
 
709
    else :
710
        [logisticsLocation, warehouse_retid, total_availability] = \
711
                        __get_warehouse_with_max_availability(warehouse_loc = warehouse_loc, \
712
                                                            warehouse_ids = warehouse_ids, item = item)
2341 chandransh 713
 
4406 anupam.sin 714
    if item.expectedDelay is None:
715
        print 'expectedDelay field for this item was Null. Resetting it to 0'
716
        item.expectedDelay = 0
717
 
718
    ## FIXME Assign warehouse 5 (9D2) for all the hotspot products.
719
    #if warehouse_retid in [warehouse.id for warehouse in get_warehouses_for_vendor(1)]:
4433 anupam.sin 720
    if int(warehouse_retid) in [1,2,3,4,5]:
4406 anupam.sin 721
        warehouse_retid = 5
722
        warehouse = Warehouse.get_by(id=warehouse_retid)
723
        logisticsLocation = warehouse.logisticsLocation  
724
 
725
    return [logisticsLocation, int(warehouse_retid), total_availability, int(item.expectedDelay)]
726
 
727
def __get_warehouse_with_max_availability(warehouse_loc, warehouse_ids, item):
728
 
729
    warehouse_retid = -1
730
    max_availability = 0
731
    total_availability = 0
732
 
733
    for warehouse_id in warehouse_ids:
734
            try:
735
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item.id).one()
736
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
737
            except Exception as e:
738
                print e
739
                availability = 0    
740
            if availability > max_availability:
741
                warehouse_retid = warehouse_id
742
                max_availability = availability
743
            total_availability = total_availability + availability
744
 
745
    #If no warehouse could be found, use the default warehouse for this item
643 chandransh 746
    if warehouse_retid == -1:
759 chandransh 747
        # This is the case when all warehouses have exhausted their
748
        # inventory of this item or no warehouse is available in this
749
        # location.
4406 anupam.sin 750
        warehouse_retid = int(item.defaultWarehouse)
2344 chandransh 751
        warehouse = Warehouse.get_by(id=warehouse_retid)
4406 anupam.sin 752
        warehouse_loc = warehouse.logisticsLocation
2341 chandransh 753
        try:
4406 anupam.sin 754
            current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_retid, item_id = item.id).one()
3503 chandransh 755
            max_availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
4317 varun.gupt 756
        except Exception as e:
757
            print e
3503 chandransh 758
            max_availability = 0
759
        total_availability = max_availability
643 chandransh 760
 
4406 anupam.sin 761
    return [warehouse_loc, warehouse_retid, total_availability]
762
'''    
763
def calculate_total_availability(warehouse_ids, item_id):
764
    total_availability = 0
765
    for warehouse_id in warehouse_ids:
766
            try:
767
                current_inventory_snapshot = CurrentInventorySnapshot.query.filter_by(warehouse_id = warehouse_id, item_id = item_id).one()
768
                availability = current_inventory_snapshot.availibility - current_inventory_snapshot.reserved
769
            except Exception as e:
770
                print e
771
                availability = 0    
772
            total_availability = total_availability + availability
773
    return total_availability
774
'''
2341 chandransh 775
 
122 ashish 776
def get_warehouses_for_item(item_id):
643 chandransh 777
 
122 ashish 778
    if not item_id:
779
        raise InventoryServiceException(101, "bad item_id")
635 rajveer 780
    item = get_item(item_id)
122 ashish 781
 
782
    if not item:
783
        raise InventoryServiceException(101, "bad item")
784
 
483 rajveer 785
    warehouses = item.currentInventory.warehouse
501 rajveer 786
    return warehouses
787
 
2404 chandransh 788
def get_child_categories(category):
789
    cm = CategoryManager()
2621 varun.gupt 790
    cat = cm.getCategory(category)
791
    return cat.children_category_ids if cat else None
2404 chandransh 792
 
626 chandransh 793
def get_best_sellers(start_index, stop_index, category=-1):
2404 chandransh 794
    '''
795
    Returns the Best Sellers between the start and the stop index in the given category
796
    '''
1926 rajveer 797
    query = get_best_sellers_query(category, None)
1098 chandransh 798
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 799
    return get_thrift_item_list(best_sellers)
800
 
2093 chandransh 801
def get_best_sellers_count(category=-1):
2404 chandransh 802
    '''
803
    Returns the number of best sellers in the given category
804
    '''
1926 rajveer 805
    count = get_best_sellers_query(category, None).count()
1120 rajveer 806
    if count is None:
807
        count = 0
766 rajveer 808
    return count
621 chandransh 809
 
1926 rajveer 810
def get_best_sellers_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 811
    '''
812
    Returns the Best sellers for the given brand and category between the start and the stop index.
813
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
814
    '''
1926 rajveer 815
    query = get_best_sellers_query(category, brand)
1098 chandransh 816
    best_sellers = query.all()[start_index:stop_index]
621 chandransh 817
    return [item.catalog_item_id for item in best_sellers]
1970 rajveer 818
 
1926 rajveer 819
def get_best_sellers_query(category, brand):
2404 chandransh 820
    '''
821
    Returns the query to be used for getting Best Sellers.
822
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
823
    '''
1098 chandransh 824
    query = Item.query.filter_by(status=status.ACTIVE).filter(Item.bestSellingRank != None)
626 chandransh 825
    if category != -1:
1970 rajveer 826
        all_categories = [category]
827
        child_categories = get_child_categories(category)
828
        if child_categories is not None:
829
            all_categories = all_categories + child_categories 
830
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 831
    if brand is not None:
832
        query = query.filter_by(brand=brand)
1098 chandransh 833
    query = query.order_by(asc(Item.bestSellingRank))
621 chandransh 834
    return query
609 chandransh 835
 
1098 chandransh 836
def get_best_deals(category=-1):
2404 chandransh 837
    '''
838
    Returns the Best deals in the given category. Ignores the category if it's passed as -1.
839
    '''
840
    query = get_best_deals_query(Item, category, None)
1098 chandransh 841
    items = query.all()
609 chandransh 842
    return get_thrift_item_list(items)
843
 
1098 chandransh 844
def get_best_deals_count(category=-1):
2404 chandransh 845
    '''
846
    Returns the count of best deals in the given category.
847
    Ignores the category if it's -1.
848
    '''
849
    count = get_best_deals_counting_query(func.count(distinct(Item.catalog_item_id)), category, None).scalar()
1120 rajveer 850
    if count is None:
851
        count = 0
766 rajveer 852
    return count
501 rajveer 853
 
1926 rajveer 854
def get_best_deals_catalog_ids(start_index, stop_index, brand, category=-1):
2404 chandransh 855
    '''
856
    Returns the catalog_item_ids of best deal items for the given brand and category.
857
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
858
    '''
859
    query = get_best_deals_query(Item, category, brand)
1098 chandransh 860
    best_deal_items = query.all()[start_index:stop_index]
861
    return [item.catalog_item_id for item in best_deal_items]
862
 
2404 chandransh 863
def get_best_deals_counting_query(obj, category, brand):
864
    '''
865
    Returns the query to be used to select the best deals in the given brand and category.
866
    Ignores the category if it's passed as -1 and the brand if it's passed as None. 
867
    '''
868
    query = session.query(obj).filter_by(status=status.ACTIVE).filter(Item.bestDealValue != None)
626 chandransh 869
    if category != -1:
1970 rajveer 870
        all_categories = [category]
871
        child_categories = get_child_categories(category)
872
        if child_categories is not None:
873
            all_categories = all_categories + child_categories 
874
        query = query.filter(Item.category.in_(all_categories))
1926 rajveer 875
    if brand is not None:
876
        query = query.filter_by(brand=brand)
2404 chandransh 877
    return query
878
 
879
def get_best_deals_query(obj, category, brand):
880
    '''
881
    Returns the query to be used to get the best deals in the given category and brand.
882
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
883
    '''
884
    query = get_best_deals_counting_query(obj, category, brand)
1098 chandransh 885
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.bestDealValue))
886
    return query
609 chandransh 887
 
1098 chandransh 888
def get_latest_arrivals(limit, category=-1):
2404 chandransh 889
    '''
890
    Returns up to limit number of Latest Arrivals in the given category.
891
    '''
2975 chandransh 892
    categories = []
893
    if category != -1:
894
        categories = [category]
895
    query = get_latest_arrivals_query(Item, categories, None)
1098 chandransh 896
    items = query.all()[0:limit]
609 chandransh 897
    return get_thrift_item_list(items)
598 chandransh 898
 
1098 chandransh 899
def get_latest_arrivals_count(limit, category=-1):
2404 chandransh 900
    '''
901
    Returns the number of latest arrivals which will be displayed on the website.
3016 chandransh 902
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 903
    '''
2975 chandransh 904
    categories = []
905
    if category != -1:
906
        categories = [category]
907
    count = get_latest_arrivals_counting_query(func.count(distinct(Item.catalog_item_id)), categories, None).scalar()
1120 rajveer 908
    if count is None:
909
        count = 0
910
    count = min(count, limit)
766 rajveer 911
    return count
602 chandransh 912
 
2975 chandransh 913
def get_latest_arrivals_catalog_ids(start_index, stop_index, brand, categories=[]):
2404 chandransh 914
    '''
915
    Returns the catalog_item_ids of the latest arrivals between the start and the stop index
3016 chandransh 916
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 917
    '''
2975 chandransh 918
    query = get_latest_arrivals_query(Item, categories, brand)
1098 chandransh 919
    latest_arrivals = query.all()[start_index:stop_index]
920
    return [item.catalog_item_id for item in latest_arrivals]
921
 
2975 chandransh 922
def get_latest_arrivals_counting_query(obj, categories, brand):
2404 chandransh 923
    '''
924
    Returns the query to be used to count Latest arrivals.
3016 chandransh 925
    To ignore the categories, pass the list as empty. To ignore brand, pass it as null.
2404 chandransh 926
    '''
927
    query = session.query(obj).filter_by(status=status.ACTIVE)
2975 chandransh 928
 
929
    all_categories = []
930
    for category in categories:
931
        all_categories.append(category)
1970 rajveer 932
        child_categories = get_child_categories(category)
2975 chandransh 933
        if child_categories:
934
            all_categories = all_categories + child_categories
935
    if all_categories: 
1970 rajveer 936
        query = query.filter(Item.category.in_(all_categories))
2975 chandransh 937
 
1926 rajveer 938
    if brand is not None:
939
        query = query.filter_by(brand=brand)
2404 chandransh 940
    return query
941
 
2975 chandransh 942
def get_latest_arrivals_query(obj, categories, brand):
2404 chandransh 943
    '''
944
    Returns the query to be used to retrieve Latest Arrivals.
945
    Ignores the category if it's passed as -1 and the brand if it's passed as None.
946
    '''
2975 chandransh 947
    query = get_latest_arrivals_counting_query(obj, categories, brand)
1098 chandransh 948
    query = query.group_by(Item.catalog_item_id).order_by(desc(Item.startDate))
949
    return query
609 chandransh 950
 
951
def get_thrift_item_list(items):
1098 chandransh 952
    return [to_t_item(item) for item in items if item != None]
635 rajveer 953
 
1155 rajveer 954
def generate_new_entity_id():
955
    generator =  EntityIDGenerator.query.one()
956
    id = generator.id + 1
957
    generator.id = id
958
    session.commit()
959
    return id
960
 
635 rajveer 961
def put_category_object(object):
962
    category = Category.get_by(id=1)
963
    if category is None:
964
        category = Category()
965
    category.object = object    
966
    session.commit()
967
    return True
968
 
969
def get_category_object():
766 rajveer 970
    object = Category.get_by(id=1).object
971
    return object
972
 
4283 anupam.sin 973
def get_item_pricing(item_id, vendorId):
1341 chandransh 974
    item = Item.query.filter_by(id=item_id).first()
975
    if item is None:
976
        raise InventoryServiceException(101, "Bad Item")
4307 anupam.sin 977
    '''
978
    if vendor id is -1 then we calculate an average transfer price to be populated
979
    at the time of order creation. This will be later updated with actual transfer price
980
    at the time of billing.
981
    '''
982
    if(vendorId == -1):
4543 anupam.sin 983
        total = 0
4307 anupam.sin 984
        try:
985
            item_pricings = VendorItemPricing.query.filter_by(item=item).all()
4315 anupam.sin 986
            if item_pricings:
4307 anupam.sin 987
                for item_pricing in item_pricings:
4543 anupam.sin 988
                    total += item_pricing.transfer_price
4315 anupam.sin 989
                avg = total / len(item_pricings)
990
                item_pricing.transfer_price = avg
4543 anupam.sin 991
            else:
992
                item_pricing = VendorItemPricing()
993
                item_pricing.transfer_price = item.sellingPrice
994
                vendor = Vendor()
995
                vendor.id = vendorId
996
                item_pricing.vendor = vendor
997
                item_pricing.item = item
998
 
999
            return item_pricing
4307 anupam.sin 1000
        except:
1001
            raise InventoryServiceException(101, "Item pricing not found ")
4283 anupam.sin 1002
    vendor = Vendor.get_by(id=vendorId)    
1341 chandransh 1003
    try:
1004
        item_pricing = VendorItemPricing.query.filter_by(vendor=vendor, item=item).one()
1347 chandransh 1005
        return item_pricing
3244 chandransh 1006
    except MultipleResultsFound:
1341 chandransh 1007
        raise InventoryServiceException(110, "Multiple pricing information present for Vendor: " + vendor.name + " and Item: " + str(item_id))
3244 chandransh 1008
    except NoResultFound:
1341 chandransh 1009
        raise InventoryServiceException(111, "Missing pricing information for Vendor: " + vendor.name + " and Item: " + str(item_id))
1010
 
1970 rajveer 1011
def add_category(t_category):
1012
    category = Category.get_by(id=t_category.id)
1013
    if category is None:
1014
        category = Category()
1015
    category.id = t_category.id 
1016
    category.label = t_category.label
1017
    category.description = t_category.description
4762 phani.kuma 1018
    category.display_name = t_category.display_name
1970 rajveer 1019
    category.parent_category_id = t_category.parent_category_id 
1020
    session.commit()
1021
    return True
1022
 
1023
def get_category(id):
1024
    return Category.query.filter_by(id=id).first()
1025
 
1026
def get_all_categories():
1027
    return Category.query.all()
1028
 
1991 ankur.sing 1029
 
1030
def get_all_item_pricing(item_id):
1031
    item = Item.query.filter_by(id=item_id).first()
1032
    if item is None:
1033
        raise InventoryServiceException(101, "Bad Item")
1034
    item_pricing = VendorItemPricing.query.filter_by(item=item).all()
1035
    return item_pricing
1036
 
2116 ankur.sing 1037
def get_item_mappings(item_id):
1038
    item = Item.query.filter_by(id=item_id).first()
1039
    if item is None:
1040
        raise InventoryServiceException(101, "Bad Item")
1041
    item_mappings = VendorItemMapping.query.filter_by(item=item).all()
1042
    return item_mappings
1043
 
1044
def add_vendor_pricing(vendorItemPricing):
1991 ankur.sing 1045
    if not vendorItemPricing:
1046
        raise InventoryServiceException(108, "Bad vendorItemPricing in request")
1047
    vendorId = vendorItemPricing.vendorId
1048
    itemId = vendorItemPricing.itemId
1049
 
1050
    try:
1051
        vendor = Vendor.query.filter_by(id=vendorId).one()
1052
    except:
1053
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
1054
 
1055
    try:
1056
        item = Item.query.filter_by(id=itemId).one()
1057
    except:
1058
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
1059
 
2120 ankur.sing 1060
    validate_vendor_prices(to_t_item(item), vendorItemPricing)
2065 ankur.sing 1061
 
1991 ankur.sing 1062
    try:
1063
        ds_vendorItemPricing = VendorItemPricing.query.filter(and_(VendorItemPricing.vendor==vendor, VendorItemPricing.item==item)).one()
1064
    except:
2116 ankur.sing 1065
        ds_vendorItemPricing = VendorItemPricing()
1066
        ds_vendorItemPricing.vendor = vendor
1067
        ds_vendorItemPricing.item = item
1991 ankur.sing 1068
 
1069
    if vendorItemPricing.mop:
1070
        ds_vendorItemPricing.mop = vendorItemPricing.mop
1071
    if vendorItemPricing.dealerPrice:
1072
        ds_vendorItemPricing.dealerPrice = vendorItemPricing.dealerPrice
1073
    if vendorItemPricing.transferPrice:
2065 ankur.sing 1074
        ds_vendorItemPricing.transfer_price = vendorItemPricing.transferPrice
1991 ankur.sing 1075
 
1076
    session.commit()
1077
    return
1078
 
2358 ankur.sing 1079
def add_vendor_item_mapping(key, vendorItemMapping):
2116 ankur.sing 1080
    if not vendorItemMapping:
1081
        raise InventoryServiceException(108, "Bad vendorItemMapping in request")
1082
    vendorId = vendorItemMapping.vendorId
1083
    itemId = vendorItemMapping.itemId
1084
 
1085
    try:
1086
        vendor = Vendor.query.filter_by(id=vendorId).one()
1087
    except:
1088
        raise InventoryServiceException(101, "Vendor not found for vendorId " + str(vendorId))
1089
 
1090
    try:
1091
        item = Item.query.filter_by(id=itemId).one()
1092
    except:
1093
        raise InventoryServiceException(101, "Item not found for vendorId " + str(itemId))
1094
 
1095
    try:
2358 ankur.sing 1096
        ds_vendorItemMapping = VendorItemMapping.query.filter(and_(VendorItemMapping.vendor==vendor, VendorItemMapping.item==item, VendorItemMapping.item_key==key)).one()
2116 ankur.sing 1097
    except:
1098
        ds_vendorItemMapping = VendorItemMapping()
1099
        ds_vendorItemMapping.vendor = vendor
1100
        ds_vendorItemMapping.item = item
1101
    ds_vendorItemMapping.item_key = vendorItemMapping.itemKey
1102
 
1103
    session.commit()
1104
    return
1105
 
2120 ankur.sing 1106
def validate_item_prices(item):
2129 ankur.sing 1107
    if item.mrp == None or item.sellingPrice == None or item.mrp == "" or item.sellingPrice == "":
1108
        return
1109
    if item.mrp < item.sellingPrice:
2120 ankur.sing 1110
        print "[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}, SP={5}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(item.sellingPrice))
1111
        raise InventoryServiceException(101, "[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}, SP={5}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(item.sellingPrice)))
2065 ankur.sing 1112
    return
2120 ankur.sing 1113
 
1114
def validate_vendor_prices(item, vendorPrices):
2129 ankur.sing 1115
    if item.mrp != None and item.mrp != "" and vendorPrices.mop != "" and item.mrp <  vendorPrices.mop:
2120 ankur.sing 1116
        print "[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(vendorPrices.mop), str(vendorPrices.vendorId))
1117
        raise InventoryServiceException(101, "[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(item.mrp), str(vendorPrices.mop), str(vendorPrices.vendorId)))
1118
    if vendorPrices.mop != "" and vendorPrices.transferPrice != "" and vendorPrices.transferPrice > vendorPrices.mop:
1119
        print "[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(vendorPrices.transferPrice), str(vendorPrices.mop), str(vendorPrices.vendorId))
1120
        raise InventoryServiceException(101, "[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}, Vendor={6}".format(item.productGroup, item.brand, item.modelNumber, item.color, str(vendorPrices.transferPrice), str(vendorPrices.mop), str(vendorPrices.vendorId)))
1121
    return
2065 ankur.sing 1122
 
1123
def get_all_vendors():
1124
    return Vendor.query.all()
1125
 
4725 phani.kuma 1126
def check_color_valid(color):
1127
    if color is not None:
1128
        color = color.strip().lower()
1129
        if color != '' and color != 'na' and color != 'blank' and color != '(blank)':
1130
            return True
1131
    return False
1132
 
1133
def check_similar_item(brand, model_number, model_name, color):
2129 ankur.sing 1134
    query = Item.query
2428 ankur.sing 1135
    query = query.filter_by(brand=brand)
1136
    query = query.filter_by(model_number=model_number)
4725 phani.kuma 1137
    query = query.filter_by(model_name=model_name)
1138
    similar_items = query.all()
1139
    item = None
1140
    # Check if a similar item already exists in our database
1141
    for old_item in similar_items:
1142
        if old_item.color != None and old_item.color.strip().lower() == color.strip().lower():
1143
            item = old_item
1144
            break
1145
 
1146
    # Check if a similar item already exists in our database with out valid color if similar item with same color is not found
2116 ankur.sing 1147
    if item is None:
4725 phani.kuma 1148
        for old_item in similar_items:
1149
            if not check_color_valid(old_item.color):
1150
                item = old_item
1151
                break
1152
    i = 0
1153
    color_of_similar_item = None
1154
    # Check if a similar item already exists in our database to be used to get catalog_item_id
1155
    for old_item in similar_items:
1156
        # get a similar item already existing in our database with valid color
1157
        if check_color_valid(old_item.color):
1158
            similar_item = old_item
1159
            color_of_similar_item = similar_item.color
1160
            break
1161
        i = i + 1
1162
        # get a similar item already existing in our database if similar item with valid color is not found
1163
        if i == len(similar_items):
1164
            similar_item = old_item
1165
            color_of_similar_item = similar_item.color
1166
 
1167
    # Check if a similar item that is obtained above is having a valid color
1168
    if check_color_valid(color_of_similar_item):
1169
        # if a similar item that is obtained above is having a valid color and new item is about to be created with out valid color it is not done.
1170
        # since for example if their is a item with red color in our database and we are creating a new item with no color for the same product which is wrong.
1171
        if item is None and not check_color_valid(color):
1172
            return similar_item.id
1173
 
1174
    if item is None:
2116 ankur.sing 1175
        return 0
1176
    else:
1177
        return item.id
2286 ankur.sing 1178
 
1179
def change_risky_flag(item_id, risky):
1180
    item = get_item(item_id)
1181
    if not item:
1182
        raise InventoryServiceException(101, "Item missing in our database")
1183
    try:
1184
        log_risky_flag(item_id, risky)
1185
    except:
1186
        print "Not able to log risky flag change"
1187
    item.risky = risky
4295 varun.gupt 1188
    if not risky and item.status == status.PAUSED_BY_RISK:
2368 ankur.sing 1189
        change_item_status(item.id, status.ACTIVE)
2286 ankur.sing 1190
    session.commit()
1191
 
4762 phani.kuma 1192
def get_items_by_category(categoryName):
1193
    if not categoryName:
1194
        raise InventoryServiceException(101, "Invalid category in request")
1195
    categories = ["Handsets", "Tablets", "Laptops"]
1196
    if categoryName == "Accessories":
1197
        query = Item.query.filter(and_(Item.product_group not in categories, Item.status != status.PHASED_OUT))
1198
    elif categoryName == "Handsets":
1199
        query = Item.query.filter(and_(Item.product_group in categories, Item.status != status.PHASED_OUT))
2358 ankur.sing 1200
    items = query.all()
1201
    return items
2116 ankur.sing 1202
 
2358 ankur.sing 1203
def get_risky_items():
1204
    items = Item.query.filter_by(risky=True).all()
1205
    return items
3008 rajveer 1206
 
2809 rajveer 1207
def get_similar_items_catalog_ids(start_index, stop_index, itemId):
3008 rajveer 1208
    query = SimilarItems.query.filter_by(item_id=itemId).limit(stop_index-start_index)
1209
    similar_items = query.all()
3289 rajveer 1210
    return_list = []
1211
    for similar_item in similar_items:
1212
        isActive = False
1213
        try:
1214
            all_items = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).all()
1215
        except:
1216
            continue
1217
        for item in all_items:
1218
            isActive = isActive or item.status == status.ACTIVE
1219
        if isActive:
1220
            return_list.append(similar_item.catalog_item_id)
1221
    return return_list
4423 phani.kuma 1222
 
1223
def get_all_similar_items_catalog_ids(itemId):
1224
    query = SimilarItems.query.filter_by(item_id=itemId)
1225
    similar_items = query.all()
1226
    return_list = []
1227
    for similar_item in similar_items:
1228
        item_query = Item.query.filter_by(catalog_item_id=similar_item.catalog_item_id).limit(1)
1229
        item = item_query.one()
1230
        return_list.append(item)
2809 rajveer 1231
 
4423 phani.kuma 1232
    return get_thrift_item_list(return_list)
1233
 
1234
def add_similar_item_catalog_id(itemId, catalog_item_id):
1235
    if not itemId or not catalog_item_id:
1236
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
1237
    items_for_entity = get_items_by_catalog_id(catalog_item_id)
1238
    if not len(items_for_entity):
1239
        raise InventoryServiceException(101, "catalogItemId does not exists in database")
1240
 
1241
    s_items = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1242
    if not len(s_items):
1243
        s_item = SimilarItems()
1244
        s_item.item_id=itemId
1245
        s_item.catalog_item_id=catalog_item_id
1246
        session.commit()
1247
        return items_for_entity[0]
1248
    else:
1249
        raise InventoryServiceException(101, "Already exists")
1250
 
1251
def delete_similar_item_catalog_id(itemId, catalog_item_id):
1252
    if not itemId or not catalog_item_id:
1253
        raise InventoryServiceException(101, "Bad itemId or catalogItemId in request")
1254
 
1255
    similar_item = SimilarItems.query.filter_by(item_id=itemId, catalog_item_id=catalog_item_id).all()
1256
    if len(similar_item):
1257
        similar_item[0].delete()
1258
    session.commit()
1259
    return True
1260
 
3079 rajveer 1261
def add_product_notification(itemId, email):
1262
    try:
3470 rajveer 1263
        try:
1264
            product_notification = ProductNotification.query.filter_by(item_id=itemId, email=email).one()
1265
        except:
1266
            product_notification = ProductNotification()
1267
            product_notification.email = email
1268
            product_notification.item_id = itemId
3079 rajveer 1269
        product_notification.addedOn = datetime.datetime.now()
1270
        session.commit()
1271
        return True
1272
    except:
1273
        return False
3086 rajveer 1274
 
1275
 
1276
def send_product_notifications():
1277
    product_notifications = ProductNotification.query.all()
1278
    for product_notification in product_notifications:
1279
        item = product_notification.item
4406 anupam.sin 1280
        availability = __get_item_availability(item, None)
3309 rajveer 1281
        if availability > 0 and item.status == status.ACTIVE:
3086 rajveer 1282
            __enque_product_notification_email(product_notification.email, __get_product_name(item) , product_notification.addedOn, __get_product_url(item), item.id)
1283
            product_notification.delete()
1284
    session.commit()
1285
    return True
1286
 
1287
def __get_product_name(item):
1288
    product_name = item.brand + " " + item.model_name + " " + item.model_number
1289
    color = item.color
1290
    if color is not None and color != 'NA':
1291
        product_name = product_name + " (" + color + ")"
3201 rajveer 1292
    product_name = product_name.replace("  "," ")
3086 rajveer 1293
    return product_name
1294
 
1295
 
1296
def __get_product_url(item):
1297
    product_url = "http://www.saholic.com/mobile-phones/" + item.brand + "-" + item.model_name + "-" + item.model_number + "-" + str(item.catalog_item_id)
1298
    product_url = product_url.replace("--","-")
1299
    product_url = product_url.replace(" ","")
1300
    return product_url
1301
 
3348 varun.gupt 1302
def get_all_brands_by_category(category_id):
1303
    catm = CategoryManager()
1304
    child_categories = catm.getCategory(category_id).children_category_ids
1305
    brands = session.query(distinct(Item.brand)).filter(Item.category.in_(child_categories)).all()
1306
 
1307
    return [brand[0] for brand in brands]
3086 rajveer 1308
 
1309
def __enque_product_notification_email(email, product, date, url, itemId):
1310
 
1311
    html = """
1312
        <html>
1313
        <body>
1314
        <div>
1315
        <p>
1316
            Hi,<br /><br />
1317
            The product requested by you on $date is now available on saholic.com.
1318
        </p>
1319
 
1320
        <p>    
1321
        <strong>Product: $product </strong>
1322
        </p>
1323
 
1324
        <p>
1325
        Click the link below to visit the product: 
1326
        <br/>
1327
        $url
1328
        </p>
1329
        <p>
1330
        Regards,<br/>
1331
        Saholic Customer Support Team<br/>
1332
        www.saholic.com<br/>
1333
        Email: help@saholic.com<br/>
1334
        </p>
1335
        </div>
1336
        </body>
1337
        </html>
1338
        """
1339
 
1340
    html = Template(html).substitute(dict(product=product,date=date,url=url))
3079 rajveer 1341
 
3086 rajveer 1342
    try:
1343
        helper_client = HelperClient().get_client()
1344
        helper_client.saveUserEmailForSending(email, "", "Product requested by you is available now.", html, str(itemId), "ProductNotification")
1345
    except Exception as e:
1346
        print e
1347
 
3557 rajveer 1348
def get_all_sources():
1349
    sources = Source.query.all()
1350
    return [to_t_source(source) for source in sources]
3086 rajveer 1351
 
3557 rajveer 1352
def get_item_pricing_by_source(itemId, sourceId):
1353
    item = Item.query.filter_by(id=itemId).first()
1354
    if item is None:
1355
        raise InventoryServiceException(101, "Bad Item")
1356
 
1357
    source = Source.query.filter_by(id=sourceId).first()
1358
    if source is None:
1359
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1360
 
1361
    item_pricing = SourceItemPricing.query.filter_by(source=source, item=item).first()
1362
    if item_pricing is None:
1363
        raise InventoryServiceException(101, "Pricing information not found for sourceId " + str(sourceId))
1364
    return item_pricing
1365
 
1366
def add_source_item_pricing(sourceItemPricing):
1367
    if not sourceItemPricing:
1368
        raise InventoryServiceException(108, "Bad sourceItemPricing in request")
1369
 
1370
    if not sourceItemPricing.sellingPrice:
4326 mandeep.dh 1371
        raise InventoryServiceException(101, "Selling Price is not defined for sourceId " + str(sourceItemPricing.sourceId))
3557 rajveer 1372
 
1373
    sourceId = sourceItemPricing.sourceId
1374
    itemId = sourceItemPricing.itemId
1375
 
1376
    item = Item.query.filter_by(id=itemId).first()
1377
    if item is None:
1378
        raise InventoryServiceException(101, "Bad Item")
1379
 
1380
    source = Source.query.filter_by(id=sourceId).first()
1381
    if source is None:
1382
        raise InventoryServiceException(101, "Source not found for sourceId " + str(sourceId))
1383
 
3564 rajveer 1384
    ds_sourceItemPricing = SourceItemPricing.get_by(source=source, item=item)
3557 rajveer 1385
    if ds_sourceItemPricing is None:
1386
        ds_sourceItemPricing = SourceItemPricing()
1387
        ds_sourceItemPricing.source = source
1388
        ds_sourceItemPricing.item = item
1389
 
1390
    if sourceItemPricing.mrp:
1391
        ds_sourceItemPricing.mrp = sourceItemPricing.mrp
1392
    ds_sourceItemPricing.sellingPrice = sourceItemPricing.sellingPrice
1393
 
1394
    session.commit()
1395
    return
1396
 
1397
def get_all_source_pricing(itemId):
1398
    item = Item.query.filter_by(id=itemId).first()
1399
    if item is None:
1400
        raise InventoryServiceException(101, "Bad Item")
1401
    source_pricing = SourceItemPricing.query.filter_by(item=item).all()
1402
    return source_pricing
1403
 
1404
 
1405
def get_item_for_source(item_id, sourceId):
1406
    item = get_item(item_id)
1407
    if sourceId == -1:
1408
        return item
1409
    try:
1410
        sip = get_item_pricing_by_source(item_id, sourceId)
1411
        item.sellingPrice = sip.sellingPrice
1412
        if sip.mrp:
1413
            item.mrp = sip.mrp
1414
    except:
1415
        print "No source pricing"
1416
    return item
1417
 
3872 chandransh 1418
def search_items(search_terms, offset, limit):
1419
    query = Item.query
1420
 
1421
    query_clause = []
1422
 
1423
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1424
 
1425
    for search_term in search_terms:
1426
        query_clause.append(Item.brand.like(search_term))
1427
        query_clause.append(Item.model_number.like(search_term))
1428
        query_clause.append(Item.model_name.like(search_term))
1429
 
1430
    query = query.filter(or_(*query_clause))
1431
 
1432
    query = query.order_by(Item.product_group, Item.brand, Item.model_number, Item.model_name).offset(offset)
1433
    if limit:
1434
        query = query.limit(limit)
1435
    items = query.all()
1436
    return items
1437
 
1438
def get_search_result_count(search_terms):
1439
    query = Item.query
1440
 
1441
    query_clause = []
1442
 
1443
    search_terms = ['%' + search_term + '%' for search_term in search_terms]
1444
 
1445
    for search_term in search_terms:
1446
        query_clause.append(Item.brand.like(search_term))
1447
        query_clause.append(Item.model_number.like(search_term))
1448
        query_clause.append(Item.model_name.like(search_term))
1449
 
1450
    query = query.filter(or_(*query_clause))
1451
 
1452
    return query.count()
1453
 
3924 rajveer 1454
def __clear_homepage_cache():
1455
    try:
1456
        # create a password manager
1457
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
1458
        # Add the username and password.
1459
        configclient = ConfigClient()
4310 rajveer 1460
        ips = configclient.get_property("production_servers_private_ips");
3924 rajveer 1461
        ips = ips.split(" ")
1462
 
1463
        for ip in ips:
4310 rajveer 1464
            try:
1465
                top_level_url = "http://" + ip + ":8080/"
1466
                password_mgr.add_password(None, top_level_url, "saholic", "shop2020")
1467
                handler = urllib2.HTTPBasicAuthHandler(password_mgr)
3924 rajveer 1468
 
4310 rajveer 1469
                opener = urllib2.build_opener(handler)
3924 rajveer 1470
 
4310 rajveer 1471
                # use the opener to fetch a URL
1472
                res = opener.open(top_level_url + "cache-admin/HomePageSnippets?_method=delete")
1473
                print "Successfully cleared home page cache" + res.read()
1474
            except:
1475
                print "Unable to clear home page cache" + res.read()
3924 rajveer 1476
    except:
1477
        print "Unable to clear cache, still should continue with other operations"
4024 chandransh 1478
 
4062 chandransh 1479
def get_pending_orders_inventory(vendor_id=1):
4024 chandransh 1480
    """
1481
    Returns a list of inventory stock for items for which there are pending orders.
1482
    """
4341 rajveer 1483
 
4368 rajveer 1484
    warehouse_ids = [warehouse.id for warehouse in get_warehouses_for_vendor(vendor_id)]
4064 chandransh 1485
    pending_items_inventory = []
1486
    if warehouse_ids:
1487
        pending_items_inventory = session.query(CurrentInventorySnapshot.item_id, func.sum(CurrentInventorySnapshot.availibility), func.sum(CurrentInventorySnapshot.reserved)).filter(CurrentInventorySnapshot.warehouse_id.in_(warehouse_ids)).group_by(CurrentInventorySnapshot.item_id).having(func.sum(CurrentInventorySnapshot.reserved) > 0).all()
4024 chandransh 1488
    return pending_items_inventory
4295 varun.gupt 1489
 
1490
def get_product_notifications(start_datetime):
1491
    '''
1492
    Returns a list of Product Notification objects each representing user requests for notification
1493
    '''
1494
    query = ProductNotification.query
3924 rajveer 1495
 
4295 varun.gupt 1496
    if start_datetime:
1497
        query = query.filter(ProductNotification.addedOn > start_datetime)
1498
 
1499
    notifications = query.order_by(desc('addedOn')).all()
1500
    return notifications
1501
 
1502
def get_product_notification_request_count(start_datetime):
1503
    '''
1504
    Returns list of items and the counts of product notification requests
1505
    '''
1506
    print start_datetime
1507
    query = session.query(ProductNotification, func.count(ProductNotification.email).label('count'))
1508
 
1509
    if start_datetime:
1510
        query = query.filter(ProductNotification.addedOn > start_datetime)
1511
 
1512
    counts = query.group_by(ProductNotification.item_id).order_by(desc('count')).all()
1513
    return counts
1514
 
766 rajveer 1515
def close_session():
1516
    if session.is_active:
1517
        print "session is active. closing it."
1399 rajveer 1518
        session.close()
3376 rajveer 1519
 
1520
def is_alive():
1521
    try:
1522
        session.query(Item.id).limit(1).one()
1523
        return True
1524
    except:
1525
        return False
4332 anupam.sin 1526
 
1527
def add_vendor(vendor):
1528
    if not vendor:
1529
        raise InventoryServiceException(108, "Bad vendor")
1530
    if get_Vendor(vendor.id):
1531
        #vendor is already present.
1532
        raise InventoryServiceException(101, "Vendor already present")
1533
 
1534
    ds_vendor = Vendor()
1535
    ds_vendor.id = vendor.id
1536
    ds_vendor.name = vendor.name
1537
    session.commit()
1538
    return ds_vendor.id
1539
 
1540
def add_warehouse_vendor_mapping(warehouse_id, VendorId):
1541
    return True
1542
 
1543
def get_vendors_for_warehouse(warehouse_id):
1544
    try:
1545
        warehouse = Warehouse.get_by(id=warehouse_id)
1546
        return warehouse.vendors
1547
    except:
1548
        raise InventoryServiceException(108, "Bad Warehouse Id")
1549
 
1550
def get_warehouses_for_vendor(vendorId):
1551
    try:
1552
        vendor = get_Vendor(vendorId)
1553
        return vendor.warehouses
1554
    except:
4649 phani.kuma 1555
        raise InventoryServiceException(108, "Bad Vendor Id")
1556
 
1557
def add_authorization_log_for_item(itemId, username, reason):
1558
    if not itemId or not username:
1559
        raise InventoryServiceException(101, "Bad itemId or Invalid username in request")
1560
    authorize_log = AuthorizationLog()
1561
    authorize_log.item_id = itemId
1562
    authorize_log.username = username
1563
    authorize_log.reason = reason
1564
    session.commit()
1565
    return True