Subversion Repositories SmartDukaan

Rev

Rev 18618 | Rev 18647 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 18618 Rev 18634
Line 40... Line 40...
40
    RechargeTransaction, HotspotStore, WalletForCompany, WalletHistoryForCompany, \
40
    RechargeTransaction, HotspotStore, WalletForCompany, WalletHistoryForCompany, \
41
    FRC, OperatorSeries, SourceDetail, Company, EbayOrder, AmazonFbaSalesSnapshot, \
41
    FRC, OperatorSeries, SourceDetail, Company, EbayOrder, AmazonFbaSalesSnapshot, \
42
    AmazonOrder, StoreOrderDetail, EdcBank, StoreOrderCollection, \
42
    AmazonOrder, StoreOrderDetail, EdcBank, StoreOrderCollection, \
43
    HotspotServiceMatrix, SnapdealOrder, FlipkartOrder, DataInsuranceDetailForOrder, \
43
    HotspotServiceMatrix, SnapdealOrder, FlipkartOrder, DataInsuranceDetailForOrder, \
44
    AmazonFbaOrderReturns, FlipkartAdvantageOrder, InvoiceCounterGenerator, \
44
    AmazonFbaOrderReturns, FlipkartAdvantageOrder, InvoiceCounterGenerator, \
45
    TransactionShipmentSequence, HsOrder
45
    TransactionShipmentSequence, HsOrder, Creditor, UserSanction, CreditHistory, LoanHistory
46
from shop2020.model.v1.order.impl.model.BaseOrder import BaseOrder
46
from shop2020.model.v1.order.impl.model.BaseOrder import BaseOrder
47
from shop2020.model.v1.order.impl.model.DTHRechargeOrder import DTHRechargeOrder
47
from shop2020.model.v1.order.impl.model.DTHRechargeOrder import DTHRechargeOrder
48
from shop2020.model.v1.order.impl.model.MobileRechargeOrder import \
48
from shop2020.model.v1.order.impl.model.MobileRechargeOrder import \
49
    MobileRechargeOrder
49
    MobileRechargeOrder
50
from shop2020.model.v1.order.impl.model.RechargeDenomination import \
50
from shop2020.model.v1.order.impl.model.RechargeDenomination import \
Line 68... Line 68...
68
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
68
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
69
    TransactionStatus, OrderStatus, DelayReason, ExtraTransactionProcessingType, \
69
    TransactionStatus, OrderStatus, DelayReason, ExtraTransactionProcessingType, \
70
    HotspotAction, TimeoutSummary, OrderStatusGroups, OrderType, RechargeOrderStatus, \
70
    HotspotAction, TimeoutSummary, OrderStatusGroups, OrderType, RechargeOrderStatus, \
71
    RechargeType, RechargeStatistics, DeviceNumberInfo, EmiChargeType, PayMethod, \
71
    RechargeType, RechargeStatistics, DeviceNumberInfo, EmiChargeType, PayMethod, \
72
    OrderSource, StorePaymentStatus, ProductCondition, TaxType, \
72
    OrderSource, StorePaymentStatus, ProductCondition, TaxType, \
73
    AmazonFCWarehouseLocation, RechargeMode
73
    AmazonFCWarehouseLocation, RechargeMode, CreditTxnType, CreditHistory as TCreditHistory, \
-
 
74
    LoanHistory as TLoanHistory
74
from shop2020.thriftpy.model.v1.user.ttypes import VoucherType, CouponCategory, \
75
from shop2020.thriftpy.model.v1.user.ttypes import VoucherType, CouponCategory, \
75
    User, Sex
76
    User, Sex
76
from shop2020.thriftpy.payments.ttypes import PaymentException
77
from shop2020.thriftpy.payments.ttypes import PaymentException
77
from shop2020.thriftpy.utils.ttypes import UserSmsInfo, SmsType
78
from shop2020.thriftpy.utils.ttypes import UserSmsInfo, SmsType
78
from shop2020.thriftpy.warehouse.ttypes import ScanType, \
79
from shop2020.thriftpy.warehouse.ttypes import ScanType, \
Line 135... Line 136...
135
        OrderStatus.RTO_IN_TRANSIT   : -5,
136
        OrderStatus.RTO_IN_TRANSIT   : -5,
136
        OrderStatus.DELIVERY_SUCCESS :  1,
137
        OrderStatus.DELIVERY_SUCCESS :  1,
137
        OrderStatus.DOA_CERT_INVALID : -5
138
        OrderStatus.DOA_CERT_INVALID : -5
138
}
139
}
139
 
140
 
-
 
141
creditTxnMultiplierMap = {
-
 
142
    CreditTxnType.BLOCKED : 1,
-
 
143
    CreditTxnType.BLOCK_REVERSED : -1, 
-
 
144
    CreditTxnType.LOAN : -1,
-
 
145
    CreditTxnType.CORRECTION : 1                  
-
 
146
}
-
 
147
 
-
 
148
loanTxnMultplierMap = {
-
 
149
    CreditTxnType.LOAN : 1, 
-
 
150
    CreditTxnType.LOAN_CANCELLED : -1, 
-
 
151
    CreditTxnType.PAID : -1,
-
 
152
    CreditTxnType.CORRECTION : -1
-
 
153
}
-
 
154
 
140
 
155
 
141
stateIdMap = {}
156
stateIdMap = {}
142
def fetchStateMaster():
157
def fetchStateMaster():
143
    global stateIdMap
158
    global stateIdMap
144
    if stateIdMap:
159
    if stateIdMap:
Line 409... Line 424...
409
        
424
        
410
    if new_status == TransactionStatus.FAILED:
425
    if new_status == TransactionStatus.FAILED:
411
        for order in transaction.orders:
426
        for order in transaction.orders:
412
            order.status = OrderStatus.PAYMENT_FAILED
427
            order.status = OrderStatus.PAYMENT_FAILED
413
            order.statusDescription = "Payment Failed"
428
            order.statusDescription = "Payment Failed"
414
    elif new_status == TransactionStatus.AUTHORIZED or new_status == TransactionStatus.FLAGGED:
429
    elif new_status == TransactionStatus.AUTHORIZED or new_status == TransactionStatus.FLAGGED:                    
415
        if transaction.payment_option == capitalFloatPayMethod:
430
        if transaction.payment_option == capitalFloatPayMethod:
416
            pass
431
            total_amount = 0
-
 
432
            singleOrder = transaction.orders[0]
-
 
433
            for order in transaction.orders:
-
 
434
                total_amount = total_amount + order.total_amount + order.shippingCost - order.gvAmount
417
            
435
            
-
 
436
            creditObj = __creditHistoryObj(singleOrder.customer_id, 1, transaction.id, total_amount, CreditTxnType.BLOCKED, str(transaction.id))
-
 
437
            creditTxns = []
-
 
438
            creditTxns.append(creditObj)
-
 
439
            process_credit_transaction(transaction.id, singleOrder.customer_id, 1, creditTxns)
-
 
440
 
418
        for order in transaction.orders:
441
        for order in transaction.orders:
419
            if new_status == TransactionStatus.AUTHORIZED:
442
            if new_status == TransactionStatus.AUTHORIZED:
420
                order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
443
                order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
421
                order.statusDescription = "Submitted to warehouse"
444
                order.statusDescription = "Submitted to warehouse"
422
            elif new_status == TransactionStatus.FLAGGED:
445
            elif new_status == TransactionStatus.FLAGGED:
Line 2308... Line 2331...
2308
                    print "Exception in scheduling alert in ShippedFromWarehouse method"
2331
                    print "Exception in scheduling alert in ShippedFromWarehouse method"
2309
                    print e
2332
                    print e
2310
    
2333
    
2311
    for logisticsTxnId, ordersList in logisticsTxnIdOrdersMap.iteritems():
2334
    for logisticsTxnId, ordersList in logisticsTxnIdOrdersMap.iteritems():
2312
        if enqueue_delivery_success_mail(logisticsTxnId, ordersList) :
2335
        if enqueue_delivery_success_mail(logisticsTxnId, ordersList) :
-
 
2336
            order = orderList[0]
-
 
2337
            if order.transaction.payment_option == capitalFloatPayMethod:
-
 
2338
                total_amount = 0
-
 
2339
                for ordObj in orderList:
-
 
2340
                    total_amount = total_amount + ordObj.total_amount + ordObj.shippingCost - ordObj.gvAmount
-
 
2341
                creditObj = __creditHistoryObj(order.customer_id, 1, order.transaction.id, total_amount, CreditTxnType.LOAN, order.logisticsTransactionId)
-
 
2342
                creditTxns = []
-
 
2343
                creditTxns.append(creditObj)
-
 
2344
                try:
-
 
2345
                    process_credit_transaction(order.transaction.id, order.customer_id, 1, creditTxns)
-
 
2346
                except:
-
 
2347
                    traceback.print_exc()
-
 
2348
                    session.rollback()
-
 
2349
                    return
2313
            session.commit()
2350
            session.commit()
2314
        else :
2351
        else :
2315
            session.rollback()              
2352
            session.rollback()              
2316
    
2353
    
2317
 
2354
 
Line 2345... Line 2382...
2345
                logisticsTxnIdOrdersMap[order.logisticsTransactionId]= orderList
2382
                logisticsTxnIdOrdersMap[order.logisticsTransactionId]= orderList
2346
    else:
2383
    else:
2347
        grouppedOrdersList.append(singleOrder)
2384
        grouppedOrdersList.append(singleOrder)
2348
        logisticsTxnIdOrdersMap[str(singleOrder.id)]= grouppedOrdersList
2385
        logisticsTxnIdOrdersMap[str(singleOrder.id)]= grouppedOrdersList
2349
        
2386
        
-
 
2387
    for logisticsTxnId, ordersList in logisticsTxnIdOrdersMap.iteritems():
-
 
2388
        order = orderList[0]
-
 
2389
        if order.transaction.payment_option == capitalFloatPayMethod:
-
 
2390
            total_amount = 0
-
 
2391
            for ordObj in orderList:
-
 
2392
                total_amount = total_amount + ordObj.total_amount + ordObj.shippingCost - ordObj.gvAmount
-
 
2393
            creditObj = __creditHistoryObj(order.customer_id, 1, order.transaction.id, total_amount, CreditTxnType.LOAN, order.logisticsTransactionId)
-
 
2394
            creditTxns = []
-
 
2395
            creditTxns.append(creditObj)
-
 
2396
            try:
-
 
2397
                process_credit_transaction(order.transaction.id, order.customer_id, 1, creditTxns)
-
 
2398
            except:
-
 
2399
                traceback.print_exc()
-
 
2400
                session.rollback()
-
 
2401
                return
-
 
2402
        
-
 
2403
        
2350
    for order in grouppedOrdersList:            
2404
    for order in grouppedOrdersList:            
2351
        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]:
2405
        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]:
2352
            raise TransactionServiceException(101, "Either wrong order id or invalid state " + str(orderId))
2406
            raise TransactionServiceException(101, "Either wrong order id or invalid state " + str(orderId))
2353
       
2407
       
2354
        # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
2408
        # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
Line 2972... Line 3026...
2972
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
3026
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
2973
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
3027
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
2974
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
3028
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
2975
        }
3029
        }
2976
        if orderCurrentStatus == OrderStatus.RTO_IN_TRANSIT:
3030
        if orderCurrentStatus == OrderStatus.RTO_IN_TRANSIT:
-
 
3031
            order = grouppedOrdersList[0]
-
 
3032
            
-
 
3033
            if order.transaction.payment_option == capitalFloatPayMethod:
-
 
3034
                total_amount = 0
-
 
3035
                for ordObj in grouppedOrdersList:
-
 
3036
                    total_amount = total_amount + ordObj.total_amount + ordObj.shippingCost - ordObj.gvAmount
-
 
3037
                if not order.delivery_timestamp:
-
 
3038
                    creditObj = __creditHistoryObj(order.customer_id, 1, order.transaction.id, total_amount, CreditTxnType.BLOCK_REVERSED, order.logisticsTransactionId)
-
 
3039
                    creditTxns = []
-
 
3040
                    creditTxns.append(creditObj)
-
 
3041
                    try:
-
 
3042
                        process_credit_transaction(order.transaction.id, order.customer_id, 1, creditTxns)
-
 
3043
                    except:
-
 
3044
                        traceback.print_exc()
-
 
3045
                        session.rollback()
-
 
3046
                        return False
-
 
3047
                else:
-
 
3048
                    loanObj = __loanHistoryObj(order.customer_id, 1, order.transaction.id, total_amount, CreditTxnType.CORRECTION, order.logisticsTransactionId)
-
 
3049
                    loanTxns = []
-
 
3050
                    loanTxns.append(loanObj)
-
 
3051
                    try:
-
 
3052
                        process_loan_transaction(order.transaction.id, order.customer_id, 1, loanTxns)
-
 
3053
                    except:
-
 
3054
                        traceback.print_exc()
-
 
3055
                        session.rollback()
-
 
3056
                        return False
-
 
3057
                
2977
            for orderObj in grouppedOrdersList:
3058
            for orderObj in grouppedOrdersList:
2978
                if scanMap.has_key(orderObj.status):
3059
                if scanMap.has_key(orderObj.status):
2979
                    scanType = scanMap[orderObj.status]
3060
                    scanType = scanMap[orderObj.status]
2980
                    lineitem = orderObj.lineitems[0]
3061
                    lineitem = orderObj.lineitems[0]
2981
                    catalogClient = CatalogClient().get_client()
3062
                    catalogClient = CatalogClient().get_client()
Line 3398... Line 3479...
3398
            elif order.previousStatus == OrderStatus.BILLED:
3479
            elif order.previousStatus == OrderStatus.BILLED:
3399
                __create_return_order(order)
3480
                __create_return_order(order)
3400
                __create_refund(order)
3481
                __create_refund(order)
3401
                order.statusDescription = "Order Cancelled on customer request"
3482
                order.statusDescription = "Order Cancelled on customer request"
3402
                order.received_return_timestamp = datetime.datetime.now()
3483
                order.received_return_timestamp = datetime.datetime.now()
-
 
3484
            
-
 
3485
            if order.transaction.payment_option == capitalFloatPayMethod:
-
 
3486
                total_amount = order.total_amount + order.shippingCost - order.gvAmount
-
 
3487
                creditObj = __creditHistoryObj(order.customer_id, 1, order.transaction.id, total_amount, CreditTxnType.BLOCK_REVERSED, order.logisticsTransactionId)
-
 
3488
                creditTxns = []
-
 
3489
                creditTxns.append(creditObj)
-
 
3490
                try:
-
 
3491
                    process_credit_transaction(order.transaction.id, order.customer_id, 1, creditTxns)
-
 
3492
                except:
-
 
3493
                    traceback.print_exc()
-
 
3494
                    session.rollback()
-
 
3495
                    return False  
-
 
3496
            
3403
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
3497
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
3404
            __update_inventory_reservation(order)
3498
            __update_inventory_reservation(order)
3405
            order.statusDescription = "Order Cancelled due to payment flagged"
3499
            order.statusDescription = "Order Cancelled due to payment flagged"
3406
 
3500
 
3407
    # For orders that are cancelled after being billed, we need to scan in the scanned out
3501
    # For orders that are cancelled after being billed, we need to scan in the scanned out
Line 8135... Line 8229...
8135
    
8229
    
8136
    for ordObj in grouppedOrders:
8230
    for ordObj in grouppedOrders:
8137
        if ordObj.id not in orderIds:
8231
        if ordObj.id not in orderIds:
8138
            errorString = errorString + "Order Id:- " +str(ordObj.id) +" "
8232
            errorString = errorString + "Order Id:- " +str(ordObj.id) +" "
8139
    
8233
    
8140
    errorString = errorString.strip()
-
 
8141
    if len(errorString)>0:
8234
    if len(errorString)>0:
8142
        raise TransactionServiceException(301, missingString + errorString)
8235
        raise TransactionServiceException(301, missingString + errorString)
8143
            
8236
                
8144
    
-
 
8145
    #inventoryDbConnection = getDbConnection("192.168.190.114","root", "shop2020", "inventory") 
8237
    #inventoryDbConnection = getDbConnection("192.168.190.114","root", "shop2020", "inventory") 
8146
    try:
8238
    try:
8147
        warehouseDbConnection = getDbConnection("localhost","root", "shop2020", "warehouse")
8239
        warehouseDbConnection = getDbConnection("localhost","root", "shop2020", "warehouse")
8148
    except:
8240
    except:
8149
        raise TransactionServiceException(302, "Unable to connect to Warehouse System")
8241
        raise TransactionServiceException(302, "Unable to connect to Warehouse System")
Line 8255... Line 8347...
8255
            
8347
            
8256
            try:
8348
            try:
8257
                if not inventory_client.isAlive():
8349
                if not inventory_client.isAlive():
8258
                    inventory_client = InventoryClient().get_client()
8350
                    inventory_client = InventoryClient().get_client()
8259
                warehouse = inventory_client.getWarehouse(order.fulfilmentWarehouseId)
8351
                warehouse = inventory_client.getWarehouse(order.fulfilmentWarehouseId)
8260
                if order.productCondition == ProductCondition.GOOD:
8352
                if order.productCondition == ProductCondition.BAD:
8261
                    item_pricing = inventory_client.getItemPricing(item_id, warehouse.vendor.id)
8353
                    item_pricing = inventory_client.getItemPricing(item_id, warehouse.vendor.id)
8262
                    lineitem.transfer_price = item_pricing.transferPrice
8354
                    lineitem.transfer_price = item_pricing.transferPrice
8263
                    lineitem.nlc = item_pricing.nlc
8355
                    lineitem.nlc = item_pricing.nlc
8264
                if order.taxType == TaxType.CFORM:
8356
                if order.taxType == TaxType.CFORM:
8265
                    lineitem.vatRate = 2
8357
                    lineitem.vatRate = 2
Line 8297... Line 8389...
8297
                        warehouse = inventory_client.getWarehouses(None, InventoryType.GOOD, warehouse.vendor.id, order.warehouse_id, 0)[0]
8389
                        warehouse = inventory_client.getWarehouses(None, InventoryType.GOOD, warehouse.vendor.id, order.warehouse_id, 0)[0]
8298
                    
8390
                    
8299
                    whCursor = warehouseDbConnection.cursor()
8391
                    whCursor = warehouseDbConnection.cursor()
8300
                    ''' Good Serialized'''
8392
                    ''' Good Serialized'''
8301
                    if ItemType.SERIALIZED == item.type:
8393
                    if ItemType.SERIALIZED == item.type:
8302
                        for serialNumber in serialNumbers:
8394
                        for serialNumber in serialNumbers: 
8303
                            serialNumber = serialNumber.strip()
8395
                            serialNumber = serialNumber.strip()
8304
                            if len(serialNumber) ==0:
8396
                            if len(serialNumber) ==0:
8305
                                raise TransactionServiceException(315, "Serial Number not Specified. Order Id:- "+str(order.id))  
8397
                                raise TransactionServiceException(315, "Serial Number not Specified. Order Id:- "+str(order.id))
8306
                            invItemSql = "select i.id, i.itemId, i.itemNumber, i.serialNumber, i.initialQuantity, i.currentQuantity, i.purchaseId, i.purchaseReturnId, i.currentWarehouseId, i.lastScanType, i.transferStatus, physicalWarehouseId, po.supplierId, l.unitPrice, l.nlc from inventoryItem i join purchase p on i.purchaseId = p.id join purchaseorder po on p.purchaseOrder_id = po.id join lineitem l on (i.itemId = l.itemId and po.id =l.purchaseOrder_id) where i.serialNumber ='%s' order by i.id desc limit 1"%(serialNumber)
8398
                            invItemSql = "select i.id, i.itemId, i.itemNumber, i.serialNumber, i.initialQuantity, i.currentQuantity, i.purchaseId, i.purchaseReturnId, i.currentWarehouseId, i.lastScanType, i.transferStatus, physicalWarehouseId, po.supplierId, l.unitPrice, l.nlc from inventoryItem i join purchase p on i.purchaseId = p.id join purchaseorder po on p.purchaseOrder_id = po.id join lineitem l on (i.itemId = l.itemId and po.id =l.purchaseOrder_id) where i.serialNumber ='%s' order by i.id desc limit 1"%(serialNumber)
8307
                            whCursor.execute(invItemSql)
8399
                            whCursor.execute(invItemSql)
8308
                            invItem = whCursor.fetchone()
8400
                            invItem = whCursor.fetchone()
8309
                            if invItem is None:
8401
                            if invItem is None:
8310
                                if warehouseDbConnection.open:
8402
                                if warehouseDbConnection.open:
Line 8447... Line 8539...
8447
                    whCursor = warehouseDbConnection.cursor()
8539
                    whCursor = warehouseDbConnection.cursor()
8448
                    if ItemType.SERIALIZED == item.type:
8540
                    if ItemType.SERIALIZED == item.type:
8449
                        for serialNumber in serialNumbers:
8541
                        for serialNumber in serialNumbers:
8450
                            serialNumber = serialNumber.strip()
8542
                            serialNumber = serialNumber.strip()
8451
                            if len(serialNumber) ==0:
8543
                            if len(serialNumber) ==0:
8452
                                raise TransactionServiceException(315, "Serial Number not Specified. Order Id:- "+str(order.id))  
8544
                                raise TransactionServiceException(315, "Serial Number not Specified. Order Id:- "+str(order.id)) 
8453
                            invItemSql = "select i.id, i.itemId, i.itemNumber, i.serialNumber, i.initialQuantity, i.currentQuantity, i.purchaseId, i.purchaseReturnId, i.currentWarehouseId, i.lastScanType, i.transferStatus, physicalWarehouseId, po.supplierId, l.unitPrice, l.nlc from inventoryItem i join purchase p on i.purchaseId = p.id join purchaseorder po on p.purchaseOrder_id = po.id join lineitem l on (i.itemId = l.itemId and po.id =l.purchaseOrder_id) where i.serialNumber ='%s' order by i.id desc limit 1"%(serialNumber)
8545
                            invItemSql = "select i.id, i.itemId, i.itemNumber, i.serialNumber, i.initialQuantity, i.currentQuantity, i.purchaseId, i.purchaseReturnId, i.currentWarehouseId, i.lastScanType, i.transferStatus, physicalWarehouseId, po.supplierId, l.unitPrice, l.nlc from inventoryItem i join purchase p on i.purchaseId = p.id join purchaseorder po on p.purchaseOrder_id = po.id join lineitem l on (i.itemId = l.itemId and po.id =l.purchaseOrder_id) where i.serialNumber ='%s' order by i.id desc limit 1"%(serialNumber)
8454
                            whCursor.execute(invItemSql)
8546
                            whCursor.execute(invItemSql)
8455
                            invItem = whCursor.fetchone()
8547
                            invItem = whCursor.fetchone()
8456
                            if invItem is None:
8548
                            if invItem is None:
8457
                                if warehouseDbConnection.open:
8549
                                if warehouseDbConnection.open:
Line 8865... Line 8957...
8865
def verify_orders_for_transaction(transactionId):
8957
def verify_orders_for_transaction(transactionId):
8866
    transaction = get_transaction(transactionId)
8958
    transaction = get_transaction(transactionId)
8867
    for order in transaction.orders:
8959
    for order in transaction.orders:
8868
        __verify_order(order)
8960
        __verify_order(order)
8869
    return True
8961
    return True
-
 
8962
 
-
 
8963
def get_creditor_info(creditorId):
-
 
8964
    return Creditor.get_by(id=creditorId)
-
 
8965
 
-
 
8966
def update_creditor_info(creditor):
-
 
8967
    t_creditor = get_creditor_info(creditor.id)
-
 
8968
    t_creditor.active = creditor.active
-
 
8969
    if t_creditor.name != creditor.name:
-
 
8970
        t_creditor.name = creditor.name
-
 
8971
    session.commit()
-
 
8972
    return True
-
 
8973
 
-
 
8974
def get_user_sanction_details(userId, creditorId):
-
 
8975
    us_query = UserSanction.query
-
 
8976
    if userId:
-
 
8977
        us_query = us_query.filter(UserSanction.user_id == userId)
-
 
8978
    if creditorId:
-
 
8979
        us_query = us_query.filter(UserSanction.creditor_id == creditorId)
-
 
8980
    return us_query.all()
-
 
8981
 
-
 
8982
def update_user_sanction(userSanction):
-
 
8983
    userS = UserSanction.get_by(id=userSanction.id)
-
 
8984
    if userS is None:
-
 
8985
        return False
-
 
8986
    else:
-
 
8987
        userS.credit_blocked = userSanction.credit_blocked
-
 
8988
        userS.loan = userSanction.loan
-
 
8989
        userS.active = userSanction.active
-
 
8990
        session.commit()
-
 
8991
        return True
8870
    
8992
    
-
 
8993
def __get_user_sanction(sanctionId):
-
 
8994
    return UserSanction.get_by(id=sanctionId)
-
 
8995
 
-
 
8996
def get_credit_history_records(paymentId, userId, creditorId, creditTxnType):
-
 
8997
    credit_hs_query = CreditHistory.query
-
 
8998
    if paymentId:
-
 
8999
        credit_hs_query = credit_hs_query.filter(CreditHistory.payment_id==paymentId)
-
 
9000
    if userId:
-
 
9001
        credit_hs_query = credit_hs_query.filter(CreditHistory.user_id==userId)
-
 
9002
    if creditorId:
-
 
9003
        credit_hs_query = credit_hs_query.filter(CreditHistory.creditor_id==creditorId)
-
 
9004
    if creditTxnType:
-
 
9005
        credit_hs_query = credit_hs_query.filter(CreditHistory.credit_type==CreditTxnType._VALUES_TO_NAMES[creditTxnType])
-
 
9006
    return credit_hs_query.all()
-
 
9007
 
-
 
9008
def process_credit_transaction(paymentId, userId, creditorId, creditTxns):
-
 
9009
    userSanctions = get_user_sanction_details(userId, creditorId)
-
 
9010
    if userSanctions is None or len(userSanctions)==0:
-
 
9011
        logging.info("No Credit Sanction Details Availble. UserId:- "+str(userId)+ " Creditor Id:- "+ str(creditorId))
-
 
9012
        raise TransactionServiceException(221, "No Credit Sanction Details Availble. UserId:- "+str(userId)+ " Creditor Id:- "+ str(creditorId))
-
 
9013
    
-
 
9014
    userSanction = userSanctions[0]
-
 
9015
    availableCredit =  userSanction.credit_limit - (userSanction.credit_blocked + userSanction.loan)
-
 
9016
        
-
 
9017
    amountToReversed = 0
-
 
9018
    amountToLoan = 0
-
 
9019
    amountToBlocked = 0
-
 
9020
    
-
 
9021
    creditHistoryTotal = 0
-
 
9022
    
-
 
9023
    allCreditTxns = get_credit_history_records(paymentId, userId, creditorId, None)
-
 
9024
    for credit_txn in allCreditTxns:
-
 
9025
        creditHistoryTotal = creditHistoryTotal + credit_txn.amount
-
 
9026
        
-
 
9027
    if creditHistoryTotal < 0:
-
 
9028
        logging.info("Error: Credit History is Negative. Payment Id:- "+str(paymentId))
-
 
9029
        raise TransactionServiceException(222, "Error: Credit History is Negative. Payment Id:- "+str(paymentId))
-
 
9030
    
-
 
9031
    for creditTxn in creditTxns:
-
 
9032
        if creditTxn.credit_type in [CreditTxnType.BLOCK_REVERSED]:
-
 
9033
            amountToReversed = amountToReversed + creditTxn.amount
-
 
9034
        if creditTxn.credit_type in [CreditTxnType.LOAN]:
-
 
9035
            amountToLoan = amountToLoan + creditTxn.amount
-
 
9036
        if creditTxn.credit_type in [CreditTxnType.BLOCKED]:
-
 
9037
            amountToBlocked = amountToBlocked + creditTxn.amount   
-
 
9038
    
-
 
9039
    if amountToLoan > userSanction.credit_blocked:
-
 
9040
        logging.info("Error: Not Enough Credit to Process For Loan. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(creditTxns[0].shipping_id))
-
 
9041
        raise TransactionServiceException(224, "Error: Not Enough Credit to Process For Loan. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(creditTxns[0].shipping_id))
-
 
9042
    
-
 
9043
    if amountToReversed > userSanction.credit_blocked:
-
 
9044
        logging.info("Error: Not Enough Credit to Process For Reversal. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(creditTxns[0].shipping_id))
-
 
9045
        raise TransactionServiceException(225, "Error: Not Enough Credit to Process For Reversal. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(creditTxns[0].shipping_id))
-
 
9046
    
-
 
9047
    if amountToBlocked > availableCredit:
-
 
9048
        logging.info("Error: Not Enough Credit to be Blocked. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(creditTxns[0].shipping_id))
-
 
9049
        raise TransactionServiceException(226, "Error: Not Enough Credit to be Blocked. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(creditTxns[0].shipping_id))
-
 
9050
    
-
 
9051
    for creditTxn in creditTxns:
-
 
9052
        creditHistoryRec = CreditHistory.get_by(payment_id=paymentId,shipping_id=creditTxn.shipping_id)
-
 
9053
        if creditHistoryRec is None:
-
 
9054
            creditHistoryRec = CreditHistory()
-
 
9055
            creditHistoryRec.user_id = userId
-
 
9056
            creditHistoryRec.creditor_id = creditorId
-
 
9057
            creditHistoryRec.payment_id = paymentId
-
 
9058
            creditHistoryRec.amount = creditTxn.amount * creditTxnMultiplierMap.get(creditTxn.credit_type) 
-
 
9059
            creditHistoryRec.credit_type = CreditTxnType._VALUES_TO_NAMES[creditTxn.credit_type]
-
 
9060
            creditHistoryRec.shipping_id = creditTxn.shipping_id
-
 
9061
            userSanction.credit_blocked = userSanction.credit_blocked + (creditTxn.amount * creditTxnMultiplierMap.get(creditTxn.credit_type))
-
 
9062
            if creditTxn.credit_type in [CreditTxnType.LOAN]:
-
 
9063
                userSanction.loan = userSanction.loan + creditTxn.amount
-
 
9064
                loanHistoryRec = LoanHistory()
-
 
9065
                loanHistoryRec.user_id = userId
-
 
9066
                loanHistoryRec.creditor_id = creditorId
-
 
9067
                loanHistoryRec.payment_id = paymentId
-
 
9068
                loanHistoryRec.amount = creditTxn.amount * loanTxnMultplierMap.get(creditTxn.credit_type)
-
 
9069
                loanHistoryRec.credit_type = CreditTxnType._VALUES_TO_NAMES[creditTxn.credit_type]
-
 
9070
                loanHistoryRec.loan_id = creditTxn.loan_id
-
 
9071
                loanHistoryRec.due_date = datetime.datetime.now()+timedelta(days=30)
-
 
9072
        else:
-
 
9073
            logging.info("Error: Entry already existed for "+str(paymentId) + " Shipping Id:- "+str(creditTxns.shipping_id) +" Credit Txn Type:- "+CreditTxnType._VALUES_TO_NAMES[creditTxn.credit_type]+ " in Credit History ")
-
 
9074
            raise TransactionServiceException(227, "Error: Entry already existed for "+str(paymentId) + " Shipping Id:- "+str(creditTxns.shipping_id) +" Credit Txn Type:- "+CreditTxnType._VALUES_TO_NAMES[creditTxn.credit_type]+ " in Credit History ")
-
 
9075
    session.commit()   
-
 
9076
    return True
-
 
9077
            
-
 
9078
def get_loan_payable_for_user_to_creditor(userId, creditorId, dueDate):
-
 
9079
    loanhistoryRecords = LoanHistory.query.filter(and_(LoanHistory.user_id==userId, LoanHistory.creditor_id==creditorId, LoanHistory.due_date<to_py_date(dueDate), LoanHistory.updated is None)).all()
-
 
9080
    loanAmount = 0
-
 
9081
    for loanHistory in loanhistoryRecords:
-
 
9082
        loanAmount = loanAmount + loanHistory.amount
-
 
9083
    return loanAmount
-
 
9084
 
-
 
9085
def get_loan_history_records(paymentId, userId, creditorId, creditTxnType):
-
 
9086
    loan_hs_query = LoanHistory.query
-
 
9087
    if paymentId:
-
 
9088
        loan_hs_query = loan_hs_query.filter(LoanHistory.payment_id==paymentId)
-
 
9089
    if userId:
-
 
9090
        loan_hs_query = loan_hs_query.filter(LoanHistory.user_id==userId)
-
 
9091
    if creditorId:
-
 
9092
        loan_hs_query = loan_hs_query.filter(LoanHistory.creditor_id==creditorId)
-
 
9093
    if creditTxnType:
-
 
9094
        loan_hs_query = loan_hs_query.filter(LoanHistory.credit_type==CreditTxnType._VALUES_TO_NAMES[creditTxnType])
-
 
9095
    return loan_hs_query.all()
-
 
9096
 
-
 
9097
def process_loan_transaction(paymentId, userId, creditorId, loantxns):
-
 
9098
    userSanctions = get_user_sanction_details(userId, creditorId)
-
 
9099
    if userSanctions is None or len(userSanctions)==0:
-
 
9100
        logging.info("No Credit Sanction Details Availble. UserId:- "+str(userId)+ " Creditor Id:- "+ str(creditorId))
-
 
9101
        raise TransactionServiceException(227, "No Credit Sanction Details Availble. UserId:- "+str(userId)+ " Creditor Id:- "+ str(creditorId))
-
 
9102
    
-
 
9103
    userSanction = userSanctions[0]
-
 
9104
        
-
 
9105
    amountToLoan = 0
-
 
9106
    amountToLoanPaid = 0
-
 
9107
    amountToCorrected = 0
-
 
9108
    
-
 
9109
    loanHistoryTotal = 0
-
 
9110
 
-
 
9111
    allLoanTxns = get_loan_history_records(paymentId, userId, creditorId, None)
-
 
9112
    for loan_txn in allLoanTxns:
-
 
9113
        loanHistoryTotal = loanHistoryTotal + loan_txn.amount
8871
        
9114
        
-
 
9115
    if loanHistoryTotal < 0:
-
 
9116
        logging.info("Error: Loan History is Negative. Payment Id:- "+str(paymentId))
-
 
9117
        raise TransactionServiceException(228, "Error: Loan History is Negative. Payment Id:- "+str(paymentId))
-
 
9118
    
-
 
9119
    for loanTxn in loantxns:
-
 
9120
        if loanTxn.credit_type in [CreditTxnType.LOAN]:
-
 
9121
            amountToLoan = amountToLoan + loanTxn.amount
-
 
9122
        if loanTxn.credit_type in [CreditTxnType.PAID]:
-
 
9123
            amountToLoanPaid = amountToLoanPaid + loanTxn.amount
-
 
9124
        if loanTxn.credit_type in [CreditTxnType.CORRECTION]:
-
 
9125
            amountToCorrected = amountToCorrected + loanTxn.amount
-
 
9126
    
-
 
9127
    if amountToLoan > userSanction.loan:
-
 
9128
        logging.info("Error: Loan required is more than specified. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(loantxns[0].loan_id))
-
 
9129
        raise TransactionServiceException(229, "Error: Loan required is more than specified. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(loantxns[0].loan_id))
-
 
9130
    
-
 
9131
    if amountToLoanPaid > userSanction.loan:
-
 
9132
        logging.info("Error: Can't Pay more than Loan Amount. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(loantxns[0].loan_id))
-
 
9133
        raise TransactionServiceException(230, "Error: Can't Pay more than Loan Amount. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(loantxns[0].loan_id))
-
 
9134
    
-
 
9135
    if amountToCorrected > userSanction.loan:
-
 
9136
        logging.info("Error: Correction Amount More than loan Amount. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(loantxns[0].loan_id))
-
 
9137
        raise TransactionServiceException(231, "Error: Correction Amount More than loan Amount. Payment Id:- "+str(paymentId) + " Shipping Id:- "+str(loantxns[0].loan_id))    
-
 
9138
    
-
 
9139
    for loanTxn in loantxns:
-
 
9140
        if loanTxn.credit_type in [CreditTxnType.PAID]:
-
 
9141
            loanHistoryRecords = LoanHistory.query.filter(LoanHistory.loan_id==loanTxn.loan_id).filter(LoanHistory.payment_id==paymentId).all()
-
 
9142
            loanTotalHistory = 0
-
 
9143
            for loanHistoryRec in loanHistoryRecords:
-
 
9144
                loanTotalHistory = loanTotalHistory + loanHistoryRec.amount
-
 
9145
            if loanTotalHistory < 0:
-
 
9146
                logging.info("Error: Loan Already Paid or Closed for "+str(paymentId) + " Loan Id:- "+str(loanTxn.loan_id) +" Loan Txn Type:- "+CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type])
-
 
9147
                raise TransactionServiceException(227, "Error: Loan Already Paid or Closed for "+str(paymentId) + " Loan Id:- "+str(loanTxn.loan_id) +" Loan Txn Type:- "+CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type])
-
 
9148
            else:
-
 
9149
                loanHistoryRec = LoanHistory()
-
 
9150
                loanHistoryRec.user_id = userId
-
 
9151
                loanHistoryRec.creditor_id = creditorId
-
 
9152
                loanHistoryRec.payment_id = paymentId
-
 
9153
                loanHistoryRec.amount = loanTxn.amount * loanTxnMultplierMap.get(loanTxn.credit_type)
-
 
9154
                loanHistoryRec.credit_type = CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type]
-
 
9155
                loanHistoryRec.loan_id = loanTxn.loan_id
-
 
9156
                loanRec = LoanHistory.get_by(payment_id=paymentId,loan_id=loanTxn.loan_id, credit_type='LOAN')
-
 
9157
                userSanction.loan = userSanction.loan + (loanTxn.amount * loanTxnMultplierMap.get(loanTxn.credit_type))
-
 
9158
        else:
-
 
9159
            loanHistoryRec = LoanHistory.get_by(payment_id=paymentId,loan_id=loanTxn.loan_id, credit_type=CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type])
-
 
9160
            if loanHistoryRec is None:
-
 
9161
                loanHistoryRec = LoanHistory()
-
 
9162
                loanHistoryRec.user_id = userId
-
 
9163
                loanHistoryRec.creditor_id = creditorId
-
 
9164
                loanHistoryRec.payment_id = paymentId
-
 
9165
                loanHistoryRec.amount = loanTxn.amount * loanTxnMultplierMap.get(loanTxn.credit_type)
-
 
9166
                loanHistoryRec.credit_type = CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type]
-
 
9167
                loanHistoryRec.loan_id = loanTxn.loan_id
-
 
9168
                if loanTxn.credit_type in [CreditTxnType.LOAN]:
-
 
9169
                    loanHistoryRec.due_date = datetime.datetime.now()+timedelta(days=30)
-
 
9170
                if loanTxn.credit_type in [CreditTxnType.CORRECTION]:
-
 
9171
                    loanRec = LoanHistory.get_by(payment_id=paymentId,loan_id=loanTxn.loan_id, credit_type='LOAN')
-
 
9172
                    loanRec.updated = datetime.datetime.now()
-
 
9173
                    userSanction.loan = userSanction.loan + (loanTxn.amount * loanTxnMultplierMap.get(loanTxn.credit_type))
-
 
9174
            else:
-
 
9175
                logging.info("Error: Entry already existed for "+str(paymentId) + " Loan Id:- "+str(loanTxn.loan_id) +" Loan Txn Type:- "+CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type])
-
 
9176
                raise TransactionServiceException(227, "Error: Entry already existed for "+str(paymentId) + " Loan Id:- "+str(loanTxn.loan_id) +" Loan Txn Type:- "+CreditTxnType._VALUES_TO_NAMES[loanTxn.credit_type])
-
 
9177
    session.commit()   
-
 
9178
    return True
-
 
9179
    
-
 
9180
def __loanHistoryObj(user_id, creditor_id, paymentId, amount, credit_type, loan_id):
-
 
9181
    loanobj = TLoanHistory()
-
 
9182
    loanobj.user_id = user_id
-
 
9183
    loanobj.creditor_id = creditor_id    
-
 
9184
    loanobj.payment_id = paymentId
-
 
9185
    loanobj.amount = amount
-
 
9186
    loanobj.credit_type = credit_type
-
 
9187
    loanobj.loan_id = loan_id
-
 
9188
    return loanobj
-
 
9189
 
-
 
9190
def __creditHistoryObj(user_id, creditor_id, paymentId, amount, credit_type, shipping_id):
-
 
9191
    creditObj = TCreditHistory()
-
 
9192
    creditObj.user_id = user_id
-
 
9193
    creditObj.creditor_id = creditor_id
-
 
9194
    creditObj.payment_id = paymentId
-
 
9195
    creditObj.amount = amount
-
 
9196
    creditObj.credit_type = credit_type
-
 
9197
    creditObj.shipping_id = shipping_id
-
 
9198
    return creditObj
-
 
9199
 
8872
if __name__ == '__main__':
9200
if __name__ == '__main__':
8873
    print get_orders_by_mobile_number("9650889334")
9201
    print get_orders_by_mobile_number("9650889334")