Subversion Repositories SmartDukaan

Rev

Rev 23686 | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on 29-Mar-2010

@author: ashish
'''
from elixir import session
from shop2020.model.v1.order.impl import DataService, RedExpressUpdateService, \
    RechargeService
from shop2020.model.v1.order.impl.Convertors import to_t_transaction, to_t_alert, \
    to_t_order, to_t_lineitem, to_t_payment_settlement, to_t_verification_agent, \
    to_t_attribute, to_t_rechargeTransaction, to_t_frc, to_t_hotspot, \
    to_t_sourcedetail, to_t_amazonorder, to_t_storeOrderDetail, \
    to_t_storeOrderCollection, to_t_hotspotServiceMatrix, to_t_ebayOrder, \
    to_t_amazonFbaSalesSnapshot, to_t_snapdealOrder, to_t_flipkartOrder, \
    to_t_amazonFbaOrderReturn, to_t_flipkartAdvantageOrder, to_t_hsOrder, \
    to_t_Creditor, to_t_CreditHistory, to_t_UserSanction, to_t_LoanHistory, \
    to_t_PaginatedCreditHistory, to_t_PaginatedLoanHistory, \
    to_t_PaginatedUserSanction, to_t_returnOrderInfo, to_t_returnTransaction, \
    to_t_rPickupRequest, to_t_OutstandingPayments, to_t_ShipmentLogisticsCostDetail, \
    to_t_pmsa
from shop2020.model.v1.order.impl.DataAccessors import create_transaction, \
    get_transactions_for_customer, get_transaction_status, get_line_items_for_order, \
    get_transaction, get_transactions_for_shopping_cart_id, \
    change_transaction_status, get_orders_for_customer, get_orders_for_transaction, \
    get_order, get_returnable_orders_for_customer, \
    get_cancellable_orders_for_customer, get_orders_by_billing_date, get_all_orders, \
    change_order_status, get_alerts, add_alert, add_billing_details, close_session, \
    mark_orders_as_picked_up, mark_orders_as_delivered, mark_orders_as_rto, \
    order_outofstock, batch_orders, update_non_delivery_reason, \
    enqueue_transaction_info_email, get_undelivered_orders, get_order_for_customer, \
    get_valid_order_count, get_cust_count_with_successful_txn, \
    get_valid_orders_amount_range, get_valid_orders, toggle_doa_flag, \
    request_pickup_number, authorize_pickup, receive_return, validate_doa, \
    reship_order, refund_order, get_return_orders, process_return, get_return_order, \
    mark_doas_as_picked_up, verify_order, is_alive, get_orders_by_shipping_date, \
    update_weight, change_warehouse, change_product, add_delay_reason, \
    reconcile_cod_collection, get_transactions_requiring_extra_processing, \
    mark_transaction_as_processed, get_item_wise_risky_orders_count, \
    accept_order_for_item, get_orders_in_batch, get_order_count, \
    get_ebs_settlement_summaries, mark_order_cancellation_request_received, \
    mark_order_cancellation_request_denied, refund_transaction, \
    mark_order_cancellation_request_confirmed, \
    mark_transaction_as_payment_flag_removed, mark_orders_as_po_raised, \
    mark_orders_as_reversal_initiated, mark_orders_as_not_available, \
    update_shipment_address, mark_orders_as_timeout, get_order_for_awb, \
    mark_orders_as_shipped_from_warehouse, mark_alerts_as_seen, \
    mark_order_doa_request_received, mark_order_doa_request_authorized, \
    mark_order_return_request_received, mark_order_return_request_authorized, \
    add_invoice_number, get_reshipped_order_ids, validate_return_product, \
    get_orders_for_provider_for_status, save_ebs_settlement_summary, \
    get_ebs_settlement_date, save_payment_settlements, mark_ebs_settlement_uploaded, \
    get_billed_orders_for_vendor, get_settlement_for_Prepaid, \
    get_settlements_by_date, get_slipped_sipping_date_orders, \
    mark_order_as_lost_in_transit, get_cancelled_orders, mark_order_as_delivered, \
    mark_return_orders_as_picked_up, update_orders_as_PORaised, \
    get_order_distribution_by_status, get_orders_not_met_expected_delivery_date, \
    mark_orders_as_local_connected, mark_orders_as_destinationCityReached, \
    mark_orders_as_firstDeliveryAttempted, get_non_delivered_orders_by_courier, \
    get_orders_not_local_connected, get_doas_not_picked_up, \
    get_return_orders_not_picked_up, get_orders_not_picked_up, get_rto_orders, \
    get_order_list, get_order_ids_for_status, update_orders_as_paid_to_vendor, \
    update_COD_agent, get_refunded_orders_marked_paid, get_settlement_for_Cod, \
    get_order_list_for_vendor, update_order_only_as_paid_to_vendor, \
    get_all_verification_agents, get_all_attributes_for_order_id, \
    set_order_attribute_for_transaction, get_billed_orders, get_all_return_orders, \
    mark_order_as_received_at_store, get_receive_pending_orders, \
    get_received_at_store_orders, mark_orders_as_returned_from_store, \
    set_order_attributes, get_orders_collection_at_store, get_order_attribute_value, \
    change_jacket_number, mark_order_as_rto_in_transit, get_recharge_order, \
    get_recharge_orders, update_recharge_order_status, activate_recharge_txn, \
    get_user_wallet, get_user_wallet_history, get_service_providers, \
    get_service_provider_for_device, get_recharge_orders_for_transaction, \
    get_recharge_orders_for_device, get_recharge_orders_for_status, \
    get_plans_for_operator, get_recharge_statistics, validate_recharge, \
    get_recharge_denominations, update_availability_status, get_misc_charges, \
    get_available_emi_schemes, refund_recharge_order, create_recharge_transaction, \
    get_physical_orders, get_document, retrieve_invoice, change_shipping_address, \
    get_recharge_transactions, get_recharge_transaction, get_frcs, get_hotspot_store, \
    get_circle, retrieve_hotspot_recharge_invoice, get_recharge_trans, \
    split_freebie_order, get_recharge_transactions_by_number, \
    update_hotspot_store_password, get_source_detail, get_all_circles, delete_frcs, \
    topup_company_wallet, get_wallet_balance_for_company, add_amazon_order, \
    update_amazon_order_status, get_amazon_order, get_amazon_orders_shipped, \
    get_amazon_orders_cancelled, get_orders_for_store, \
    get_store_order_advance_invoice, add_frc, add_series, get_store_order_detail, \
    save_store_order_detail, get_all_edc_banks, save_refund_amounts_for_store_order, \
    get_collections_for_store, get_amazon_orders_to_acknowledge, \
    change_amazon_order_status, update_timestamp_for_amazon_order, \
    update_source_detail_timestamp, get_amazon_order_by_amazonorderid, \
    get_orders_by_mobile_number, get_orders_by_amazon_id, change_courier_provider, \
    convert_store_to_normal, update_freebie_item, update_order_AWB, \
    get_hotspot_service_matrices, get_orders_by_vendor, \
    get_orders_count_created_after_timestamp_for_source, \
    get_min_created_timestamp_undelivered_orders_for_source, \
    get_recharge_order_status, get_recharge_transaction_status, \
    accept_package_orders, get_group_orders_by_logistics_txn_id, \
    add_billing_details_for_groupped_orders, get_invoice_format_logistics_txn_id, \
    split_bulk_order, move_orders_to_correct_warehouse, \
    verify_orders_for_transaction, get_creditor_info, update_creditor_info, \
    get_user_sanction_details, update_user_sanction, get_credit_history_records, \
    process_credit_transaction, get_loan_payable_for_user_to_creditor, \
    get_loan_history_records, process_loan_transaction, \
    get_credit_history_records_paginated, get_loan_history_records_paginated, \
    get_user_sanction_details_paginated, get_orders_in_batch_as_promised_shipping, \
    set_order_attribute_for_master_order_id, update_master_order_awb, \
    add_or_update_shipment_logistics_cost_details, get_return_order_info, \
    get_return_orders_info_map, update_return_order_info, \
    bulk_update_return_order_info, get_return_orders_as_per_warehouse, \
    create_return_transaction, get_return_transactions_for_customer, \
    get_return_transaction, change_return_transaction_status, \
    create_return_pickup_request, update_return_pickup_request, \
    get_return_orders_for_return_transaction, receive_return_pickup, \
    validate_return_pickup, process_return_pickup, mark_return_transaction_complete, \
    refund_return_transaction_payment, get_eligible_orders_for_return, \
    get_eligible_return_orders_for_pickup, validate_return_transaction, \
    get_return_pickup_request, mark_return_not_required_orders_as_processed, \
    get_all_return_orders_for_return_pickup_request, unaccept_order, \
    get_outstanding_payments, mark_payment_settled, get_seller_info, \
    get_warehouse_address, get_buyer_by_warehouse, add_shipment_delay, \
    refund_return_order, get_cost_detail_for_logistics_txn_id, \
    add_shipment_logistic_detail, create_payment, calculate_payment_amount, \
    add_amount_in_wallet, get_billed_orders_for_manifest_gen, register_rsa, \
    add_sales_associate, search_pmsa, get_pmsa_user, update_pmsa_user, \
    get_pending_pmsa, get_pmsa_users, get_stats_for_associates, credit_user_wallet, \
    is_private_deal_transaction, add_invoice_details_to_orders, \
    mark_order_for_registered_gst_invoice, is_shipment_cod, \
    get_intransit_orders_on_date, get_intransit_orders_on_date_by_item_id, \
    add_price_drop
from shop2020.model.v1.order.impl.DataService import DtrBatchCreditTracker
from shop2020.model.v1.order.impl.ObsoleteDataAccessors import create_ebay_order, \
    get_ebay_order_by_orderId, get_ebay_order_by_sales_rec_number, get_ebay_order, \
    update_ebay_order, ebay_order_exists, update_order_for_ebay, split_ebay_order, \
    add_or_update_amazon_fba_sales_snapshot, get_amazon_fba_sales_snapshot_for_days, \
    get_amazon_fba_sales_latest_snapshot_for_item, create_snapdeal_order, \
    get_snapdeal_order, snapdeal_order_exists, update_latest_fba_prices_for_item, \
    flipkart_order_exists, create_flipkart_order, get_flipkart_order, \
    get_flipkart_order_by_subOrderId, update_flipkart_order_dates_and_awb, \
    update_snapdeal_orders_status, update_flipkart_orders_status, \
    bulk_add_or_update_amazon_fba_sales_snapshot, get_created_orders_for_flipkart, \
    change_easyship_mfn_order_txn_status, update_amazon_fba_order_returns, \
    get_all_amazon_fba_order_returns, get_total_sale_returns_fba_skus_curent_time, \
    get_amazon_fba_sales_latest_snapshot_for_item_location_wise, \
    get_verification_pending_orders_fk, get_fa_order_by_fk_order_id, \
    get_all_fa_orders_list, add_update_fa_orders_bulk, flipkart_fa_order_exists, \
    create_homeshop_order, get_homeshop_order, homeshop_order_exists
from shop2020.model.v1.order.impl.model.DTHRechargeOrder import DTHRechargeOrder
from shop2020.model.v1.order.impl.model.DigitalTransaction import \
    DigitalTransaction
from shop2020.model.v1.order.impl.model.MobileRechargeOrder import \
    MobileRechargeOrder
from shop2020.model.v1.order.impl.model.UserWalletHistory import \
    UserWalletHistory
from shop2020.model.v1.order.script.RechargeUnknownReport import order_list
from shop2020.model.v1.user.impl.Converters import to_t_address
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
    RechargeType, AmazonOrdersToAcknowledge, WalletReferenceType
from shop2020.utils.Utils import to_py_date, get_fdate_tdate, to_java_date
import datetime
import json
import traceback



class OrderServiceHandler:
    
    def __init__(self, dbname='transaction', db_hostname='localhost'):
        """
        Constructor
        """
        DataService.initialize(dbname, db_hostname)
        
    def createTransaction(self, transaction):
        """
        Parameters:
         - transaction
        """
        try:
            return create_transaction(transaction)
        finally:
            close_session()
        
    def getTransaction(self, id):
        """
            Get transaction methods.
        
        Parameters:
         - id
        """
        try:
            transaction = get_transaction(id)
            return to_t_transaction(transaction)
        finally:
            close_session()
            
    def getTransactionsForCustomer(self, customerId, from_date, to_date, status):
        """
        Parameters:
         - customerId
         - from_date
         - to_date
         - status
        """
        try:
            current_from_date, current_to_date = get_fdate_tdate(from_date, to_date)
                    
            transactions = get_transactions_for_customer(customerId, current_from_date, current_to_date, status)
            t_transaction = []
            for transaction in transactions:
                t_transaction.append(to_t_transaction(transaction))
            return t_transaction
        finally:
            close_session()

    def getTransactionsForShoppingCartId(self, shoppingCartId):
        """
        Parameters:
            - shoppingCartId
        """
        try:
            transactions = get_transactions_for_shopping_cart_id(shoppingCartId)
            t_transaction = []
            for transaction in transactions:
                t_transaction.append(to_t_transaction(transaction))
            return t_transaction
        finally:
            close_session()
    
    def getTransactionStatus(self, transactionId):
        """
        Parameters:
         - transactionId
        """
        try:
            return get_transaction_status(transactionId)
        finally:
            close_session()
                
    def changeTransactionStatus(self, transactionId, status, description, pickUp, orderType, source):
        """
        Parameters:
         - transactionId
         - status
         - description
         - selfPickup
        """
        try:
            return change_transaction_status(transactionId, status, description, pickUp, orderType, source)
        finally:
            close_session()
            
    def getOrdersForTransaction(self, transactionId, customerId):
        """
        Returns list of orders for given transaction Id. Also filters based on customer Id so that
        only user who owns the transaction can view its order details.
        
        Parameters:
         - transactionId
         - customerId
        """
        try:
            orders = get_orders_for_transaction(transactionId, customerId)
            return [to_t_order(order) for order in orders]    
        finally:
            close_session()
            
    def getAllOrders(self, statuses, from_date, to_date, warehouse_id):
        """
        Parameters:
         - status
         - from_date
         - to_date
         - warehouse_id
        """
        try:
            current_from_date, current_to_date = get_fdate_tdate(from_date, to_date)        
            orders = get_all_orders(statuses, current_from_date, current_to_date, warehouse_id)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()

    def getOrdersInBatch(self, statuses, offset, limit, warehouse_id, source):
        """
        Returns at most 'limit' orders with the given statuses for the given warehouse starting from the given offset.
        Pass the status as null and the limit as 0 to ignore them.
    
        Parameters:
         - statuses
         - offset
         - limit
         - warehouse_id
        """
        try:
            orders = get_orders_in_batch(statuses, offset, limit, warehouse_id, source)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()

    def getOrderCount(self, statuses, warehouseId, source):
        """
        Returns the count of orders with the given statuses assigned to the given warehouse.
    
        Parameters:
         - statuses
         - warehouseId
        """
        try:
            return get_order_count(statuses, warehouseId, source)
        finally:
            close_session()
    
    def getOrdersByBillingDate(self, status, start_billing_date, end_billing_date, warehouse_id):
        """
        Parameters:
         - status
         - start_billing_date
         - end_billing_date
         - warehouse_id
        """
        try:
            current_start_billing_date, current_end_billing_date = get_fdate_tdate(start_billing_date, end_billing_date)
            orders = get_orders_by_billing_date(status, current_start_billing_date, current_end_billing_date, warehouse_id)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
    
    def getOrdersByShippingDate(self, fromShippingDate, toShippingDate, providerId, warehouseId, cod):
        """
        Returns orders for a particular provider and warehouse which were shipped between the given dates.
        Returned orders comprise of COD orders if cod parameter is true. It comprises of prepaid orders otherwise.
        Pass providerId and warehouseId as -1 to ignore both these parameters.
        
        Parameters:
         - fromShippingDate
         - toShippingDate
         - providerId
         - warehouseId
         - cod
        """
        try:
            from_shipping_date, to_shipping_date = get_fdate_tdate(fromShippingDate, toShippingDate)
            orders = get_orders_by_shipping_date(from_shipping_date, to_shipping_date, providerId, warehouseId, cod)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
    
    def getReturnableOrdersForCustomer(self, customerId, limit = None):
        """
        Parameters:
         - customerId
         - limit
        """
        try:
            return get_returnable_orders_for_customer(customerId, limit)
        finally:
            close_session()
            
    def getCancellableOrdersForCustomer(self, customerId, limit = None):
        """
        Parameters:
         - customerId
         - limit
        """
        try:
            return get_cancellable_orders_for_customer(customerId, limit)
        finally:
            close_session()
    
    def changeOrderStatus(self, orderId, status, description):
        """
        Parameters:
         - orderId
         - status
         - description
         - 
        """
        try:
            return change_order_status(self, orderId, status, description)
        finally:
            close_session()

    def verifyOrder(self, orderId):
        """
        Marks the given order as SUBMITTED_FOR_PROCESSING and updates the verified
        timestamp. It is intended to be used for COD orders but can be harmlessly
        used for all other orders as well.
        Throws an exception if no such order exists.
        
        Parameters:
         - orderId
        """
        try:
            return verify_order(orderId)
        finally:
            close_session()

    def acceptOrder(self, orderId):
        """
        Marks the given order as ACCEPTED and updates the accepted timestamp. If the
        given order is not a COD order, it also captures the payment if the same has
        not been captured.
        Throws an exception if no such order exists.
        
        Parameters:
         - orderId
        """
        try:
            return accept_package_orders([orderId])
        finally:
            close_session()

    def unacceptOrder(self, orderId):
        """
        Rollsback to Processing State
        
        Parameters:
         - orderId
        """
        try:
            return unaccept_order(orderId)
        finally:
            close_session()
    
    def getOrdersForCustomer(self, customerId, from_date, to_date, statuses):
        """
        Returns list of orders for the given customer created between the given dates and having the given statuses.
        Pass and empty list to ignore filtering on statuses.
        
        Parameters:
         - customerId
         - from_date
         - to_date
         - statuses
        """
        try:
            current_from_date, current_to_date = get_fdate_tdate(from_date, to_date)
            
            orders = get_orders_for_customer(customerId, current_from_date, current_to_date, statuses)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
    
    def getOrderForCustomer(self, orderId, customerId):
        """
        Returns an order for the order Id. Also checks if the order belongs to the customer whose Id is passed.
        Throws exception if either order Id is invalid or order does not below to the customer whose Id is passed.
        
        Parameters:
         - customerId
         - orderId
        """
        try:
            return to_t_order(get_order_for_customer(orderId, customerId))
        finally:
            close_session()
            
    def getOrder(self, id):
        """
        Parameters:
         - id
        """
        try:
            return to_t_order(get_order(id))
        finally:
            close_session()
    
    def getOrderList(self, order_ids):
        """
        Parameters:
         - order_ids
        """
        try:
            orders = get_order_list(order_ids)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
    
    def getOrderListForVendor(self, order_ids, vendorId):
        """
        Parameters:
         - order_ids
         - vendorId
        """
        try:
            orders = get_order_list_for_vendor(order_ids, vendorId)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
    
    def getLineItemsForOrder(self, orderId):
        """
        Parameters:
         - orderId
        """
        try:
            lineitems = get_line_items_for_order(orderId)
            t_lineitems = []
            for lineitem in lineitems:
                t_lineitems.append(to_t_lineitem(lineitem))
            return t_lineitems
        finally:
            close_session()

    def addBillingDetails(self, orderId, invoice_number, serialNumber, itemNumber, freebieWarehouseId, billedBy, jacketNumber, billingType, vendorId, authorize):
        """
        Adds jacket number and serial no. to the order. Doesn't update the serial no. if a -1 is supplied.
        Also marks the order as billed and sets the billing timestamp.
        Return false if it doesn't find the order with the given ID.
        
        Parameters:
         - orderId
         - jacketNumber
         - serialNumber
         - itemNumber
         - freebieWarehouseId
         - billedBy
        """
        try:
            return add_billing_details(orderId, invoice_number, serialNumber, itemNumber, freebieWarehouseId, billedBy, jacketNumber, billingType, vendorId, authorize)
        finally:
            close_session()

    def addInvoiceNumber(self, orderId, invoiceNumber, color, serialNumber, itemNumber):
        """
        Add the invoice number to the order.
        
        Parameters:
         - orderId
         - invoice_number
        """
        try:
            add_invoice_number(orderId, invoiceNumber, color, serialNumber, itemNumber)
        finally:
            close_session()

    def batchOrders(self, warehouseId):
        """
        Create a batch of all the pending orders for the given warehouse.
        The returned list is orderd by created_timestamp.
        If there are no pending orders, an empty list is returned.
        
        Parameters:
         - warehouseId
        """
        try:
            pending_orders = batch_orders(warehouseId)
            return [to_t_order(order) for order in pending_orders]
        finally:
            close_session()
        
    def markOrderAsOutOfStock(self, orderId):
        """
        Mark the given order as out of stock. Throws an exception if the order with the given Id couldn't be found.
        
        
        Parameters:
         - orderId
        """
        try:
            return order_outofstock(orderId)
        finally:
            close_session()
    
    def markOrdersAsShippedFromWarehouse(self, warehouseId, providerId, cod, orderIds):
        """
        Depending on the third parameter, marks either all prepaid or all cod orders BILLED by the
        given warehouse and were picked up by the given provider as SHIPPED_FROM_WH.
        
        Parameters:
         - warehouseId
         - providerId
         - cod
        """
        try:
            return mark_orders_as_shipped_from_warehouse(warehouseId, providerId, cod, orderIds)
        finally:
            close_session()

    def markOrdersAsReturnedFromStore(self, providerId, orderIds, awbs):
        """
        Parameters:
         - providerId
         - orderIds
         - awbs
        """
        try:
            return mark_orders_as_returned_from_store(providerId, orderIds, awbs)
        finally:
            close_session()
    
    def setOrderAttributes(self, orderId, attributes):
        """
        sets attributes for an order

        Parameters:
         - orderId
         - attributes
        """
        try:
            return set_order_attributes(orderId, attributes)
        finally:
            close_session()


    def markOrdersAsPickedUp(self, providerId, pickupDetails):
        """
        Marks all SHIPPED_FROM_WH orders of the previous day for a provider as SHIPPED_TO_LOGISTICS.
        Raises an exception if we encounter report for an AWB number that we did not ship.
        
        Parameters:
         - providerId
         - pickupDetails
        """
        try:
            mark_orders_as_picked_up(providerId, pickupDetails)
        finally:
            close_session()

    def getOrdersNotPickedUp(self, providerId):
        """
        Returns a list of orders that were shipped from warehouse but did not appear in the pick-up report.
        
        Parameters:
         - providerId
        """
        try:
            orders_not_picked_up = get_orders_not_picked_up(providerId)
            return [to_t_order(order) for order in orders_not_picked_up]
        finally:
            close_session()

    def markOrdersAsDelivered(self, providerId, deliveredOrders):
        """
        Marks all orders with AWBs in the given map as delivered. Also sets the delivery timestamp and
        the name of the receiver.
        Raises an exception if we encounter report for an AWB number that we did not ship.
        
        Parameters:
         - providerId
         - deliveredOrders
        """
        try:
            mark_orders_as_delivered(providerId, deliveredOrders)
        finally:
            close_session()

    def markOrderAsDelivered(self, orderId, deliveryTimestamp, receiver):
        """
        Attributes:
         - orderId
         - deliveryTimestamp
         - receiver
        """
        try:
            mark_order_as_delivered(orderId, to_py_date(deliveryTimestamp), receiver)
        finally:
            close_session()


    def markOrderAsReceivedAtStore(self, orderId, deliveryTimestamp):
        """
        Attributes:
         - orderId
         - deliveryTimestamp
        """
        try:
            mark_order_as_received_at_store(orderId, to_py_date(deliveryTimestamp))
        finally:
            close_session()
    
    def getReceivePendingOrders(self, storeId):
        """
        Attributes:
         - storeId
        """
        try:
            orders = get_receive_pending_orders(storeId)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()

    def getReceivedAtStoreOrders(self, storeId):
        """
        Attributes:
         - storeId
        """
        try:
            orders = get_received_at_store_orders(storeId)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
    
    def getOrdersCollectionAtStore(self, storeId, fromDate, toDate, onlyCod):
        """
        Parameters:
         - storeId
         - fromDate
         - toDate
         - onlyCod
        """
        try:
            orders = get_orders_collection_at_store(storeId, to_py_date(fromDate), to_py_date(toDate), onlyCod)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()

    def markAsRTOrders(self, providerId, returnedOrders):
        """
        Mark all orders with AWBs in the given map as RTO. Also sets the delivery timestamp.
        Raises an exception if we encounter report for an AWB number that we did not ship.
        
        Parameters:
         - providerId
         - returnedOrders
        """
        try:
            mark_orders_as_rto(providerId, returnedOrders)
        finally:
            close_session()

    def getRTOrders(self, providerId):
        """
        Returns a list of orders that were returned by courier.
        
        Parameters:
         - providerId
        """
        try:
            rto_orders = get_rto_orders(providerId)
            return [to_t_order(order) for order in rto_orders]
        finally:
            close_session()

    def updateNonDeliveryReason(self, providerId, undeliveredOrders):
        """
        Update the status description of orders whose AWB numbers are keys of the Map.
        
        Parameters:
         - providerId
         - undelivered_orders
        """
        try:
            update_non_delivery_reason(providerId, undeliveredOrders)
        finally:
            close_session()

    def getNonDeliveredOrdersbyCourier(self, providerId):
        """
        Returns a list of orders that were picked up or shipped four days ago but did not get delivered.
        
        Parameters:
         - providerId
        """
        try:
            orders_not_delivered = get_non_delivered_orders_by_courier(providerId)
            return [to_t_order(order) for order in orders_not_delivered]
        finally:
            close_session()

    def markOrdersAsLocalConnected(self, providerId, local_connected_orders):
        """
        Mark all orders with AWBs in the given map as local connected. Also sets the local connected timestamp.
        
        Parameters:
         - providerId
         - local_connected_orders
        """
        try:
            mark_orders_as_local_connected(providerId, local_connected_orders)
        finally:
            close_session()

    def getOrdersNotLocalConnected(self, providerId):
        """
        Returns a list of orders that were picked up or shipped but pending local connection.
        
        Parameters:
         - providerId
        """
        try:
            orders_pending_local_connection = get_orders_not_local_connected(providerId)
            return [to_t_order(order) for order in orders_pending_local_connection]
        finally:
            close_session()

    def markOrdersAsDestinationCityReached(self, providerId, destination_city_reached_orders):
        """
        Mark all orders with AWBs in the given map as reached destination city. Also sets the reached destination timestamp.
        
        Parameters:
         - providerId
         - destination_city_reached_orders
        """
        try:
            mark_orders_as_destinationCityReached(providerId, destination_city_reached_orders)
        finally:
            close_session()

    def markOrdersAsFirstDeliveryAttempted(self, providerId, first_atdl_orders):
        """
        Mark all orders with AWBs in the given map as first delivery attempt made. Also sets the first delivery attempted timestamp.
        
        Parameters:
         - providerId
         - first_atdl_orders
        """
        try:
            mark_orders_as_firstDeliveryAttempted(providerId, first_atdl_orders)
        finally:
            close_session()

    def getUndeliveredOrdersExpectedDeliveryDateNotMet(self):
        """
        Returns the list of orders whose expected delivery date has passed but have not been
        delivered yet.
        Returns an empty list if no such orders exist.
        """
        try:
            orders_not_delivered = get_orders_not_met_expected_delivery_date()
            return [to_t_order(order) for order in orders_not_delivered]
        finally:
            close_session()

    def getUndeliveredOrders(self, providerId, warehouseId):
        """
        Returns the list of orders whose delivery time has passed but have not been
        delivered yet for the given provider and warehouse. To get a complete list of
        undelivered orders, pass them as -1.
        Returns an empty list if no such orders exist.
        
        Parameters:
         - providerId
         - warehouseId
        """
        try:
            undelivered_orders = get_undelivered_orders(providerId, warehouseId)
            return [to_t_order(order) for order in undelivered_orders]
        finally:
            close_session()
    
    def enqueueTransactionInfoEmail(self, transactionId):
        """
        Save the email containing order details to be sent to customer later by batch job
        
        Parameters:
         - transactionId
        """
        try:
            return enqueue_transaction_info_email(transactionId)
        finally:
            close_session()
    
    def getAlerts(self, type, warehouseId, status, timestamp):
        """
        Parameters:
         - type
         - warehouseId
         - status
         - timestamp
        """
        try:
            alerts = get_alerts(type, warehouseId, status, timestamp)
            
            t_alerts = []
            for alert in alerts:
                t_alerts.append(to_t_alert(alert)) 
            
            return t_alerts
        finally:
            close_session()

    def addAlert(self, type, warehouseId, description):
        """
        Parameters:
         - type
         - description
         - warehouseId
        """
        try:
            add_alert(type, warehouseId, description)
        finally:
            close_session()

    def markAlertsAsSeen(self, warehouseId):
        """
        Parameters:
         - warehouseId
        """
        try:
            mark_alerts_as_seen(warehouseId)
        finally:
            close_session()
        pass

    def getValidOrderCount(self, ):
        """
        Return the number of valid orders. (OrderStatus >= OrderStatus.SUBMITTED_FOR_PROCESSING)
        """
        try:
            return get_valid_order_count()
        finally:
            close_session()
    
    def getNoOfCustomersWithSuccessfulTransaction(self, ):
        """
        Returns the number of distinct customers who have done successful transactions
        """
        try:
            return get_cust_count_with_successful_txn()
        finally:
            close_session()


    def getValidOrdersAmountRange(self, ):
        """
        Returns the minimum and maximum amounts of a valid order. (OrderStatus >= OrderStatus.SUBMITTED_FOR_PROCESSING)
        List contains two values, first minimum amount and second maximum amount.
        """
        try:
            return get_valid_orders_amount_range()
        finally:
            close_session()

    def getValidOrders(self, limit, onlyStore):
        """
        Returns list of Orders in descending order by Order creation date. List is restricted to limit Orders.
        If limit is passed as 0, then all valid Orders are returned.
        
        Parameters:
         - limit
         - onlyStore
        """
        try:
            return [to_t_order(order) for order in get_valid_orders(limit, onlyStore)]
        finally:
            close_session()
    
    def toggleDOAFlag(self, orderId):
        """
        Toggle the DOA flag of an order. This should be used to flag an order for follow-up and unflag it when the follow-up is complete.
        Returns the final flag status.
        Throws an exception if the order with the given id couldn't be found or if the order status is not DELVIERY_SUCCESS.
        
        Parameters:
         - orderId
        """
        try:
            return toggle_doa_flag(orderId)
        finally:
            close_session()

    def markOrderDoaRequestReceived(self, orderId):
        """
        Once user raise the request for a DOA, order status will be changed from DELVIERY_SUCCESS to DOA_REQUEST_RECEIVED
    
        Parameters:
         - orderId
        """
        try:
            return mark_order_doa_request_received(orderId)
        finally:
            close_session()

    def markOrderDoaRequestAuthorized(self, orderId, isAuthorized,  fromStore, isReship):
        """
        CRM person can authorize or deny the request reised by customer. If he authorizes order will change from DOA_REQUEST_RECEIVED
        to DOA_REQUEST_AUTHORIZED. If he denies, status will be changed back to DELVIERY_SUCCESS.
    
        Parameters:
         - orderId
         - isAuthorized
        """
        try:
            return mark_order_doa_request_authorized(orderId, isAuthorized, fromStore, isReship)
        finally:
            close_session()

    def markOrderReturnRequestReceived(self, orderId):
        """
        Once user raise the request for a DOA, order status will be changed from DELVIERY_SUCCESS to RET_REQUEST_RECEIVED
    
        Parameters:
         - orderId
        """
        try:
            return mark_order_return_request_received(orderId)
        finally:
            close_session()

    def markOrderReturnRequestAuthorized(self, orderId, isAuthorized, fromStore, isReship):
        """
        CRM person can authorize or deny the request reised by customer. If he authorizes order will change from RET_REQUEST_RECEIVED
        to RET_REQUEST_AUTHORIZED. If he denies, status will be changed back to DELVIERY_SUCCESS.
    
        Parameters:
         - orderId
         - isAuthorized
        """
        try:
            return mark_order_return_request_authorized(orderId, isAuthorized, fromStore, isReship)
        finally:
            close_session()

    def requestPickupNumber(self, orderId, providerId):
        """
        Sends out an email to the account manager of the original courier provider used to ship the order.
        If the order status was DELIVERY_SUCCESS, it is changed to be DOA_PICKUP_REQUEST_RAISED.
        If the order status was DOA_PICKUP_REQUEST_RAISED, it is left unchanged.
        For any other status, it returns false.
        Throws an exception if the order with the given id couldn't be found.
        
        Parameters:
         - orderId
        """
        try:
            return request_pickup_number(orderId, providerId)
        finally:
            close_session()

    def authorizePickup(self, orderId, pickupNumber, providerId):
        """
        If the order status is DOA_PICKUP_REQUEST_RAISED, it does the following
            1. Sends out an email to the customer with the dispatch advice that he has to print as an attachment.
            2. Changes order status to be DOA_PICKUP_AUTHORIZED.
            3. Returns true
        If the order is any other status, it returns false.
        Throws an exception if the order with the given id couldn't be found.
        
        Parameters:
         - orderId
         - pickupNumber
        """
        try:
            return authorize_pickup(orderId, pickupNumber, providerId)
        finally:
            close_session()    
   
    def markDoasAsPickedUp(self, providerId, pickupDetails):
        """
        Marks all DOA_PICKUP_AUTHORIZED orders of the previous day for a provider as DOA_RETURN_IN_TRANSIT.
        
        Parameters:
         - providerId
         - pickupDetails
        """
        try:
            mark_doas_as_picked_up(providerId, pickupDetails)
        finally:
            close_session()

    def getDoasNotPickedUp(self, providerId):
        """
        Returns a list of orders that were authorized for pickup but did not appear in the pick-up report.
        
        Parameters:
         - providerId
        """
        try:
            orders_not_picked_up = get_doas_not_picked_up(providerId)
            return [to_t_order(order) for order in orders_not_picked_up]
        finally:
            close_session()

    def markReturnOrdersAsPickedUp(self, providerId, pickupDetails):
        """
        Marks all RET_PICKUP_CONFIRMED orders of the previous day for a provider as RET_RETURN_IN_TRANSIT.
        
        Parameters:
         - providerId
         - pickupDetails
        """
        try:
            mark_return_orders_as_picked_up(providerId, pickupDetails)
        finally:
            close_session()

    def getReturnOrdersNotPickedUp(self, providerId):
        """
        Returns a list of orders that were authorized for pickup but did not appear in the pick-up report.
        
        Parameters:
         - providerId
        """
        try:
            orders_not_picked_up = get_return_orders_not_picked_up(providerId)
            return [to_t_order(order) for order in orders_not_picked_up]
        finally:
            close_session()

    def receiveReturn(self, orderId, receiveCondition, receiveFreebie, serialNumbers):
        """
        If the order status is DOA_PICKUP_CONFIRMED or DOA_RETURN_IN_TRANSIT, marks the order status as DOA_RECEIVED_PRESTINE and returns true.
        If the order is in any other state, it returns false.
        Throws an exception if the order with the given id couldn't be found.
        
        Parameters:
         - orderId
        """
        try:
            return receive_return(orderId, receiveCondition, receiveFreebie, serialNumbers)
        finally:
            close_session()

    def validateDoa(self, orderId, isValid):
        """
        Used to validate the DOA certificate for an order in the DOA_RECEIVED_PRESTINE state. If the certificate is valid,
        the order state is changed to DOA_CERT_PENDING.
        If the certificate is invalid, the order state is changed to DOA_CERT_INVALID.
        If the order is in any other state, it returns false.
        Throws an exception if the order with the given id couldn't be found.
        
        Parameters:
         - orderId
         - isValid
        """
        try:
            return validate_doa(orderId, isValid)
        finally:
            close_session()

    def validateReturnProduct(self, orderId, isUsable):
        """
        Parameters:
         - orderId
         - isUsable
        """
        try:
            return validate_return_product(orderId, isUsable)
        finally:
            close_session()

    def reshipOrder(self, orderId):
        """
        If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
            1. Creates a new order for processing in the BILLED state. All billing information is saved.
            2. Marks the current order as one of the final states RTO_RESHIPPED and DOA_INVALID_RESHIPPED depending on what state the order started in.
            
        If the order is in DOA_CERT_VALID state, it does the following:
            1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
            2. Creates a return order for the warehouse executive to return the DOA material.
            3. Marks the current order as the final DOA_VALID_RESHIPPED state.
        
        Returns the id of the newly created order.
        
        Throws an exception if the order with the given id couldn't be found.
        
        Parameters:
         - orderId
        """
        try:
            return reship_order(orderId)
        finally:
            close_session()

    def refundOrder(self, orderId, refundedBy, reason):
        """
        If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
            1. Creates a refund request for batch processing.
            2. Creates a return order for the warehouse executive to return the shipped material.
            3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
        
        If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
            1. Creates a refund request for batch processing.
            2. Cancels the reservation of the item in the warehouse.
            3. Marks the current order as the REFUNDED final state.
        
        For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
            1. Cancels the reservation of the item in the warehouse.
            2. Marks the current order as CANCELED.
            
        In all cases, it updates the reason for cancellation or refund and the person who performed the action.
         
        Returns True if it is successful, False otherwise.
        
        Throws an exception if the order with the given id couldn't be found.
        
        Parameters:
         - orderId
         - refundedBy
         - reason
        """
        try:
            return refund_order(orderId, refundedBy, reason)
        finally:
            close_session()

    def getReturnOrders(self, warehouseId, fromDate, toDate):
        """
        Get all return orders created between the from and to dates for the given warehouse.
        Ignores the warehouse if it is passed as -1.
        
        Parameters:
         - warehouseId
         - fromDate
         - toDate
        """
        try:
            from_date, to_date = get_fdate_tdate(fromDate, toDate)
            return get_return_orders(warehouseId, from_date, to_date)
        finally:
            close_session()
    
    def getAllReturnOrders(self, onlyNotProcessed, fromDate, toDate):
        """
        Get all return orders created between the from and to dates for the given warehouse.
        Ignores the warehouse if it is passed as -1.
        
        Parameters:
         - warehouseId
         - fromDate
         - toDate
        """
        try:
            from_date, to_date = get_fdate_tdate(fromDate, toDate)
            return get_all_return_orders(onlyNotProcessed, from_date, to_date)
        finally:
            close_session()
    
    def getReturnOrder(self, id):
        """
        Returns the ReturnOrder corresponding to the given id.
        Throws an exception if the return order with the given id couldn't be found.
        
        Parameters:
         - id
        """
        try:
            return get_return_order(id)
        finally:
            close_session()
    
    def processReturn(self, returnOrderId):
        """
        Marks the return order with the given id as processed. Raises an exception if no such return order exists.
        
        Parameters:
         - returnOrderId
        """
        try:
            process_return(returnOrderId)
        finally:
            close_session()

    def updateOrdersAsPORaised(self, itemIdQuantityMap, purchaseOrderId, warehouseId):
        """
        Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
        the quantities for which the PO is raised.

        Parameters:
         - itemIdQuantityMap
         - purchaseOrderId
         - warehouseId
        """
        try:
            update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId)
        finally:
            close_session()

    def updateWeight(self, orderId, weight):
        """
        Set the weight of the given order to the provided value. Will attempt to update the weight of the item in the catalog as well.
        
        Parameters:
         - orderId
         - weight
        """
        try:
            order = update_weight(orderId, weight)
            return to_t_order(order)
        finally:
            close_session()
    
    def changeItem(self, orderId, itemId):
        """
        Change the item to be shipped for this order. Also adjusts the reservation in the inventory accordingly.
        Currently, it also ensures that only a different color of the given item is shipped.
    
        Parameters:
         - orderId
         - itemId
        """
        try:
            order = change_product(orderId, itemId)
            return to_t_order(order)
        finally:
            close_session()
    
    def changeCourierProvider(self, orderId, providerId):
        try:
            order = change_courier_provider(orderId, providerId)
            return to_t_order(order)
        finally:
            close_session()
            

    def shiftToWarehouse(self, orderId, warehouseId):
        """
        Moves the given order to the given warehouse. Also adjusts the inventory reservations accordingly.
    
        Parameters:
         - orderId
         - warehouseId
        """
        try:
            order = change_warehouse(orderId, warehouseId)
            return to_t_order(order)
        finally:
            close_session()
            
    def addDelayReason(self, orderId, delayReason, furtherDelay, delayReasonText):
        """
        Adds the given delay reason to the given order.
        Increases the expected delivery time of the given order by the given no. of days.
        Raises an exception if no order with the given id can be found.
    
        Parameters:
         - orderId
         - delayReason
        """
        try:
            return add_delay_reason(orderId, delayReason, furtherDelay, delayReasonText)
        finally:
            close_session()
    
    def reconcileCodCollection(self, collectedAmountMap, xferBy, xferTxnId, xferDate):
        """
        Marks the COD orders with given AWB nos. as having been processed.
        Updates the captured amount for the corresponding payment.
    
        Returns a map of AWBs which were not processed and the associated reason. An AWB is not processed if:
        1. There is no order corresponding to an AWB number.
        2. The captured amount for a payment exceeds the total payment.
        3. The order corresponding to an AWB no. is in a state prior to DELIVERY_SUCCESS.
    
        Parameters:
         - collectedAmountMap
         - xferBy
         - xferTxnId
         - xferDate
        """
        try:
            return reconcile_cod_collection(collectedAmountMap, xferBy, xferTxnId, xferDate)
        finally:
            close_session()

    def getTransactionsRequiringExtraProcessing(self, category):
        """
        Returns the list of transactions that require some extra processing and
        which belong to a particular category. This is currently used by CRM
        application.
        """
        try:
            return get_transactions_requiring_extra_processing(category)
        finally:
            close_session()

    def markTransactionAsProcessed(self, transactionId, category):
        """
        Marks a particular transaction as processed for a particular category.
        It essentially deletes the transaction if it is processed for a particular
        category. This is currently used by CRM application.
        """
        try:
            return mark_transaction_as_processed(transactionId, category)
        finally:
            close_session()
            
    def getItemWiseRiskyOrdersCount(self, ):
        """
        Returns a map containing the number of risky orders keyed by item id. A risky order
        is defined as one whose shipping date is about to expire.
        """
        try:
            return get_item_wise_risky_orders_count()
        finally:
            close_session()
    
    def markOrderCancellationRequestReceived(self, orderId):
        """
        Mark order as cancellation request received. If customer sends request of cancellation of
        a particular order, this method will be called. It will just change status of the order
        depending on its current status. It also records the previous status, so that we can move
        back to that status if cancellation request is denied.
    
        Parameters:
         - orderId
        """
        try:
            return mark_order_cancellation_request_received(orderId)
        finally:
            close_session()
    

    def markOrderAsLostInTransit(self, orderId):
        """
        Parameters:
         - orderId
        """
        try:
            return mark_order_as_lost_in_transit(orderId)
        finally:
            close_session()
            
    def markTransactionAsPaymentFlagRemoved(self, transactionId):
        """
        If we and/or payment gateway has decided to accept the payment, this method needs to be called.
        Changed transaction and all orders status to payment accepted.
    
        Parameters:
         - transactionId
        """
        try:
            return mark_transaction_as_payment_flag_removed(transactionId)
        finally:
            close_session()
            
    def refundTransaction(self, transactionId, refundedBy, reason):
        """
        This method is called when a flagged payment is deemed unserviceable and the corresponding orders
        need to be cancelled
    
        Parameters:
         - transactionId
        """
        try:
            return refund_transaction(transactionId, refundedBy, reason)
        finally:
            close_session()

    def markOrderCancellationRequestDenied(self, orderId):
        """
        If we decide to not to cancel order, we will move the order ro previous status.
    
        Parameters:
         - orderId
        """
        try:
            return mark_order_cancellation_request_denied(orderId)
        finally:
            close_session()
    
    def markOrderCancellationRequestConfirmed(self, orderId):
        """
        If we decide to to cancel order, CRM will call this method to move the status of order to
        cancellation request confirmed. After this OM will be able to cancel the order.
    
        Parameters:
         - orderId
        """
        try:
            return mark_order_cancellation_request_confirmed(orderId)
        finally:
            close_session()

    def updateShipmentAddress(self, orderId, addressId):
        """
        Updates shipment address of an order. Delivery and shipping date estimates
        etc. are also updated here.

        Throws TransactionServiceException in case address change is not
        possible due to certain reasons such as new pincode in address is
        not serviceable etc.

        Parameters:
         - orderId
         - addressId
        """
        try:
            update_shipment_address(orderId, addressId)
        finally:
            close_session()

    def acceptOrdersForItemId(self, itemId, inventory):
        return False



    def markOrdersAsPORaised(self, vendorId, itemId, quantity, estimate, isReminder):
        """
        Parameters:
         - vendorId
         - itemId
         - quantity
         - estimate
         - isReminder
        """
        try:
            return mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder)
        finally:
            close_session()

    def markOrdersAsReversalInitiated(self, vendorId, itemId, quantity, estimate, isReminder):
        """
        Parameters:
         - vendorId
         - itemId
         - quantity
         - estimate
         - isReminder
        """
        try:
            return mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder)
        finally:
            close_session()

    def markOrdersAsNotAvailabke(self, vendorId, itemId, quantity, estimate, isReminder):
        """
        Parameters:
         - vendorId
         - itemId
         - quantity
         - estimate
         - isReminder
        """
        try:
            return mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder)
        finally:
            close_session()


    def markOrdersAsTimeout(self, vendorId):
        """
        Parameters:
         - vendorId
        """
        try:
            return mark_orders_as_timeout(vendorId)
        finally:
            close_session()
            
    def getOrderForAwb(self, awb):
        """
        Parameters:
         - AirwayBill Number
        """
        ret_Orders =[]
        
        try:
            orderList = get_order_for_awb(awb)
            for order in orderList:
                ret_Orders.append(to_t_order(order))
            return ret_Orders
        finally:
            close_session()

    def getOrdersForProviderForStatus(self, provider_id, order_status_list):
        """
        Parameters:
         - provider id
         - order status
        """
        try:
            orders_of_provider_by_status = get_orders_for_provider_for_status(provider_id, order_status_list)
            return [to_t_order(order) for order in orders_of_provider_by_status if order != None]
        finally:
            close_session()
    
    def getBilledOrdersForVendor(self, vendorId, billingDateFrom, billingDateTo):
        '''
        Parameters:
         - vendorId
         - billingDateFrom
         - billingDateTo
        '''
        try:
            return [to_t_order(order) for order in get_billed_orders_for_vendor(vendorId, to_py_date(billingDateFrom), to_py_date(billingDateTo))]
        finally:
            close_session()
    
    def getSlippedSippingDateOrders(self):
        try:
            return [to_t_order(order) for order in get_slipped_sipping_date_orders()]
        finally:
            close_session()
            
    def getCancelledOrders(self, cancelDateFrom, cancelDateTo):
        try:
            return [to_t_order(order) for order in get_cancelled_orders(to_py_date(cancelDateFrom), to_py_date(cancelDateTo))]
        finally:
            close_session()
            
    def getEBSSettlementSummaries(self):
        try:
            return get_ebs_settlement_summaries()
        finally:
            close_session()

    def saveEBSSettlementSummary(self, settlementId, settlementDate, transactionDateFrom, transactionDateTo, amount):
        try:
            save_ebs_settlement_summary(settlementId, to_py_date(settlementDate), to_py_date(transactionDateFrom), to_py_date(transactionDateTo), amount)
        finally:
            close_session()
    
    def getSettlementForPrepaid(self, referenceId, isRefund):
        '''
        Parameters:
         - referenceId
         - isRefund
        '''
        try:
            return to_t_payment_settlement(get_settlement_for_Prepaid(referenceId, isRefund))
        finally:
            close_session()
    
    def getSettlementForCod(self, orderId, isRefund):
        '''
        Parameters:
         - orderId
         - isRefund
        '''
        try:
            return to_t_payment_settlement(get_settlement_for_Cod(orderId, isRefund))
        finally:
            close_session()
    
    def getEBSSettlementDate(self, settlementId):
        try:
            return to_java_date(get_ebs_settlement_date(settlementId))
        finally:
            close_session()
    
    def savePaymentSettlements(self, settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
        try:
            save_payment_settlements(to_py_date(settlementDate), paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection)
        finally:
            close_session()
    
    def markEBSSettlementUploaded(self, settlementId):
        try:
            mark_ebs_settlement_uploaded(settlementId)
        finally:
            close_session()
    
    def getSettlementsByDate(self, settlementDateFrom, settlementDateTo, isRefund):
        try:
            settlements = get_settlements_by_date(to_py_date(settlementDateFrom), to_py_date(settlementDateTo), isRefund)
            return [to_t_payment_settlement(settlement) for settlement in settlements]
        finally:
            close_session()
    
    def getReshippedOrderIds(self, orderIds):
        try:
            return get_reshipped_order_ids(orderIds)
        finally:
            close_session()
    
    def getBilledOrders(self, vendorId, onlyVendorNotPaid, billingDateFrom, billingDateTo):
        try:
            from_date, to_date = get_fdate_tdate(billingDateFrom, billingDateTo)
            return [to_t_order(order) for order in get_billed_orders(vendorId, onlyVendorNotPaid, from_date, to_date)]
        finally:
            close_session()
    
    def getStatusDistributionOfOrders(self, startDate, endDate):
        try:
            distribution = {}
            
            for status, count in get_order_distribution_by_status(to_py_date(startDate), to_py_date(endDate)):
                distribution[status] = count
            
            return distribution
        finally:
            close_session()
    
    def getOrderIdsForStatus(self, status, startDatetime, endDatetime):
        try:
            orders = get_order_ids_for_status(status, to_py_date(startDatetime), to_py_date(endDatetime))
            return [order.id for order in orders]
        finally:
            close_session()
    
    def updateOrderAsPaidToVendor(self, orderId):
        try:
            update_orders_as_paid_to_vendor(orderId)
        finally:
            close_session()
    
    def updateCODAgent(self, agentEmailId, orderId):
        try:
            update_COD_agent(agentEmailId, orderId)
        finally:
            close_session()
    
    def updateOrderOnlyAsPaidToVendor(self, orderId):
        try:
            update_order_only_as_paid_to_vendor(orderId)
        finally:
            close_session()
    
    def getRefundedOrdersMarkedPaid(self):
        try:
            return [to_t_order(order) for order in get_refunded_orders_marked_paid()]
        finally:
            close_session()
            
    def getAllVerificationAgents(self, minOrderId, maxOrderId):
        try:
            return [to_t_verification_agent(codAgent) for codAgent in get_all_verification_agents(minOrderId, maxOrderId)]
        finally:
            close_session()
            
    def getAllAttributesForOrderId(self, orderId):
        try:
            return [to_t_attribute(attribute) for attribute in get_all_attributes_for_order_id(orderId)]
        finally:
            close_session()
            
    def setOrderAttributeForTransaction(self, transactionId, attribute):
        try:
            set_order_attribute_for_transaction(transactionId, attribute)                    
        finally:
            close_session()

    def acceptOrderForItem(self, itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
        return False
        """
        Accepts appropriate order for an item in a given billingWarehouse. Usually
        invoked while scanning IN of items.

        Parameters:
         - itemId
         - quantity
         - fulfilmentWarehouseId
         - billingWarehouseId
        """
        try:
            accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId)
        finally:
            close_session()

    def getOrderAttributeValue(self, orderId, attributeName):
        """
        Parameters:
         - orderId
         - attributeName
        """
        try:
            return get_order_attribute_value(orderId, attributeName)
        finally:
            close_session()

    def changeJacketNumber(self, orderId, jacketNumber):
        """
        Parameters:
         - orderId
         - jacketNumber
        """
        try:
            return change_jacket_number(orderId, jacketNumber)
        finally:
            close_session()

    def markOrderAsRtoInTransit(self, orderId):
        """
        Parameters:
         - orderId
        """
        try:
            return mark_order_as_rto_in_transit(orderId)
        finally:
            close_session()        
            
    def createRechargeOrder(self, thriftRechargeOrder):
        """
        Parameters:
         - thriftRechargeOrder
        """
        try:
            if thriftRechargeOrder is None or thriftRechargeOrder.rechargeType is None:
                raise TransactionServiceException(102, 'Order or the type is Null')
            
            rechargeOrder = None
            if thriftRechargeOrder.rechargeType == RechargeType.MOBILE:
                rechargeOrder = MobileRechargeOrder()
            elif thriftRechargeOrder.rechargeType == RechargeType.DTH:
                rechargeOrder = DTHRechargeOrder()
            
            if rechargeOrder is None:
                raise TransactionServiceException(102, 'Unsupported recharge type')

            transaction = DigitalTransaction()
            transaction.createdOn = datetime.datetime.now()
            transaction.userId = thriftRechargeOrder.userId
            transaction.orders = [rechargeOrder]
            
            rechargeOrder.from_thrift_object(thriftRechargeOrder)
            session.commit()
            return rechargeOrder.to_thrift_object()
        except:
            raise TransactionServiceException(103, 'Invalid values passed')
        finally:
            self.closeSession()

    def getRechargeOrder(self, rechargeOrderId):
        """
        Parameters:
         - rechargeOrderId
        """
        try:
            return get_recharge_order(rechargeOrderId).to_thrift_object()
        finally:
            self.closeSession()
    
    def getRechargeOrders(self, userId):
        """
        Parameters:
         - userId
        """
        try:
            return [order.to_thrift_object() for order in get_recharge_orders(userId)]
        finally:
            self.closeSession()
    
    def getPaginatedRechargeOrders(self, userId, offset, limit):
        try:
            return [order.to_thrift_object() for order in get_recharge_orders(userId, offset, limit)]
        finally:
            self.closeSession()
            
    def updateRechargeOrderStatus(self, rechargeOrderId, rechargeOrderStatus):
        """
        Parameters:
         - rechargeOrderId
         - rechargeOrderStatus
        """
        try:
            return update_recharge_order_status(rechargeOrderId, rechargeOrderStatus)
        finally:
            self.closeSession()
            
    def activateRechargeTxn(self, rechargeOrderId):
        """
        Parameters:
         - rechargeOrderId
        """
        try:
            return True
            activate_recharge_txn(rechargeOrderId)
        finally:
            self.closeSession()
    
    def getUserWallet(self, userId):
        """
        Parameters:
         - userId
        """
        try:
            return get_user_wallet(userId).to_thrift_object()
        finally:
            self.closeSession()
            
            
    def getLatestUserWalletHistory(self, userId, offset, limit):
        try:
            return [userWalletHistory.to_thrift_object() for userWalletHistory in get_user_wallet_history(userId, offset, limit)]
        finally:
            self.closeSession()
    
    def getUserWalletHistory(self, userId):
        """
        Parameters:
         - userId
        """
        try:
            return [userWalletHistory.to_thrift_object() for userWalletHistory in get_user_wallet_history(userId)]
        finally:
            self.closeSession()

    def getServiceProviders(self, rechargeType, onlyActive):
        """
        Parameters:
         - rechargeType
         - onlyActive
        """
        
        try:
            return get_service_providers(rechargeType, onlyActive)
        finally:
            self.closeSession()
            
    def getServiceProviderForDevice(self, rechargeType, deviceNumber):
        """
        Parameters:
         - deviceNumber
        """
        try:
            return get_service_provider_for_device(rechargeType, deviceNumber)
        finally:
            self.closeSession()
    
    def validateRecharge(self, rechargeType, deviceNumber, userSelectedProviderId, clientAddress):
        """
        Parameters:
         - deviceNumber
        """
        try:
            return validate_recharge(rechargeType, deviceNumber, userSelectedProviderId, clientAddress)
        finally:
            self.closeSession()
    
    def getRechargeOrdersForTransaction(self, txId):
        """
        Parameters:
         - transactionId
        """
        try:
            return get_recharge_orders_for_transaction(txId).to_thrift_object()
        finally:
            self.closeSession()
     
    def getRechargeOrdersForDevice(self, deviceNumber):
        """
        Parameters:
        - deviceNumber
        """
        try:
            return [order.to_thrift_object() for order in get_recharge_orders_for_device(deviceNumber)]
        finally:
            self.closeSession()
    
    def getRechargeOrdersForStatus(self, status):
        """
        Parameters:
        - status
        """
        try:
            return [order.to_thrift_object() for order in get_recharge_orders_for_status(status)]
        finally:
            self.closeSession()
            
    def getPlansForOperator(self, operatorId):
        """
        Parameters:
        - operatorId
        """
        try:
            return [plan.to_thrift_object() for plan in get_plans_for_operator(operatorId)]
        finally:
            self.closeSession()
        
    
#    def addAmountToWallet(self, userId, orderId, amount):
#        """
#        Parameters:
#        - userId
#        - orderId
#        - amount
#        """
#        try:
#            update_amount_in_wallet(userId, amount, orderId, 0)
#        finally:
#            self.closeSession()
                 
    def getRechargeStatistics(self):
        """
        Parameters:
        """
        try:
            return get_recharge_statistics()
        finally:
            self.closeSession()
            
    def getRechargeDenominations(self, operatorId, circleCode, denominationType):
        try:
            returnList = []
            rechargeDenominations = get_recharge_denominations(operatorId, circleCode, denominationType)
            for rechargeDenomination in rechargeDenominations:
                returnList.append(rechargeDenomination.to_thrift_object())
            return returnList
        finally:
            self.closeSession() 
    
    def updateAvailabilityStatus(self, operatorId, circleId, isAvailable):
        try:
            update_availability_status(operatorId, circleId, isAvailable)
        finally:
            self.closeSession() 
            
    def getAvailableEmiSchemes(self):
        try:
            return get_available_emi_schemes()
        finally:
            self.closeSession()
            
    def getMiscCharges(self, transactionId):
        try:
            return get_misc_charges(transactionId)
        finally:
            self.closeSession()
            
    def refundRechargeOrder (self, rechargeOrderId):
        try:
            return refund_recharge_order(rechargeOrderId)
        finally:
            self.closeSession()
    
    def getPhysicalOrders(self, start_date, end_date):
        try:
            return [to_t_order(order) for order in get_physical_orders(to_py_date(start_date), to_py_date(end_date))]
        finally:
            self.closeSession()
            
    def getDocument(self, docType, docSource):
        try:
            return get_document(docType, docSource)
        finally:
            self.closeSession()
            
    def retrieveInvoice(self, orderId, userId):
        try:
            return retrieve_invoice(orderId,userId)
        finally:
            self.closeSession()
    
    def receiveUpdatesForRedExpress(self, awbNumber):
        try:
            return RedExpressUpdateService.get_updates_for_user(awbNumber)
        finally:
            self.closeSession()
    
    def changeShippingAddress(self, orderId, line1, line2, city, state, pin):
        try:
            return change_shipping_address(orderId, line1, line2, city, state, pin)
        finally:
            self.closeSession()
    
    def createRechargeTransaction(self, t_rechargeTransaction):
        try:
            return to_t_rechargeTransaction(create_recharge_transaction(t_rechargeTransaction))
        finally:
            self.closeSession()

    def getRechargeTransactions(self, storeId):
        try:
            return [to_t_rechargeTransaction(txn) for txn in get_recharge_transactions(storeId)]
        finally:
            self.closeSession()

    def getRechargeTrans(self, storeId, startdate, enddate, status):
        try:
            return [to_t_rechargeTransaction(txn) for txn in get_recharge_trans(storeId,startdate, enddate, status)]
        finally:
            self.closeSession()

    def getRechargeTransaction(self, rechargeId):
        try:
            return to_t_rechargeTransaction(get_recharge_transaction(rechargeId))
        finally:
            self.closeSession()
            
    def getFRCs(self, circleId, operatorId):
        try:
            return [to_t_frc(frc) for frc in get_frcs(circleId, operatorId)]
        finally:
            self.closeSession()
            
    def getHotspotStore(self, id, hotspotid):
        try:
            return to_t_hotspot(get_hotspot_store(id, hotspotid))
        finally:
            self.closeSession()
            
    def getTelecomCircle(self, id, code):
        try:
            return get_circle(id, code).to_thrift_object()
        finally:
            self.closeSession()
            
    def retrieveHotspotRechargeInvoice(self, rechargeId):
        try:
            return retrieve_hotspot_recharge_invoice(rechargeId)
        finally:
            self.closeSession()
        
    def splitFreebieOrder(self, orderId, splitReason, shippingDate):
        try:
            return split_freebie_order(orderId, splitReason, shippingDate)
        finally:
            self.closeSession()
            
    def getRechargeTransactionsByNumber(self, number, storeId):
        try:
            return [to_t_rechargeTransaction(txn) for txn in get_recharge_transactions_by_number(number, storeId)]
        finally:
            self.closeSession()
            
    def updateHotspotStorePassword(self, storeId, password):
        try:
            return update_hotspot_store_password(storeId, password)
        finally:
            self.closeSession()
            
    def getSourceDetail(self, source):
        try:
            return to_t_sourcedetail(get_source_detail(source))
        finally:
            self.closeSession()
        
    def getAllCircles(self):
        try:
            return [circle.to_thrift_object() for circle in get_all_circles()]
        finally:
            self.closeSession()
            
    def deleteFrcs(self, frcIdsToDelete):
        try:
            return delete_frcs(frcIdsToDelete)
        finally:
            self.closeSession()
         
    def topupCompanyWallet(self, companyId, amount):
        try:
            return topup_company_wallet(companyId, amount)
        finally:
            self.closeSession()
        
    def getWalletBalanceForCompany(self, companyId):
        try:
            return get_wallet_balance_for_company(companyId)
        finally:
            self.closeSession()
            
    def addAmazonOrder(self,amazonOrder):
        try:
            add_amazon_order(amazonOrder)
        except:
            self.closeSession()
            
    def updateAmazonOrderStatus(self,orderId,status):
        try:
            return update_amazon_order_status(orderId,status)
        finally:
            self.closeSession()
        
    def getAmazonOrdersShipped(self):
        try:
            ordersShipped = get_amazon_orders_shipped()
        finally:
            self.closeSession()
            return ordersShipped
    
    def getAmazonOrdersCancelled(self,interval):
        ordersCancelled=None
        try:
            ordersCancelled = get_amazon_orders_cancelled(interval)
        except:
            ordersCancelled=None
        finally:
            self.closeSession()
            return ordersCancelled
    
    def getAmazonOrder(self,orderId):
        result = None
        try:
            result = to_t_amazonorder(get_amazon_order(orderId))
        finally:
            self.closeSession()
            return result
        
    def getAmazonOrderByAmazonOrderId(self,amazonOrderId):
        result = []
        try:
            for amazonOrder in get_amazon_order_by_amazonorderid(amazonOrderId): 
                result.append(to_t_amazonorder(amazonOrder))
        except:
            return None
        finally:
            self.closeSession()
            return result

    def getOrdersForStore(self, id, storeId, startDate, endDate, statuses):
        try:
            return [to_t_order(order) for order in get_orders_for_store(id, storeId, to_py_date(startDate), to_py_date(endDate), statuses)]
        finally:
            self.closeSession()
    
    def getStoreOrderAdvanceInvoice(self, orderId, storeId):
        try:
            return get_store_order_advance_invoice(orderId, storeId)
        finally:
            self.closeSession()

    def getSaholicRechargeBalance(self):
        try:
            return RechargeService.getBalance()
        finally:
            self.closeSession()
            
    def addFrc(self, circle, operatorId, denomination, maxDiscount):
        try:
            return add_frc(circle, operatorId, denomination, maxDiscount)
        except:
            return False
        finally:
            self.closeSession()
            
    def addSeries(self, circle, operatorId, series):
        try:
            return add_series(circle, operatorId, series)
        except:
            return "Error Occured. Try Again."
        finally:
            self.closeSession()
            
    def saveStoreOrderDetail(self, storeOrderDetail):
        try:
            return save_store_order_detail(storeOrderDetail)
        except:
            return False
        finally:
            self.closeSession()
            
     
    def getStoreOrderDetail(self, orderId, storeId):
        try:
            return to_t_storeOrderDetail(get_store_order_detail(orderId, storeId))
        finally:
            self.closeSession()
            
    def getAllEdcBanks(self):
        try:
            return get_all_edc_banks()
        finally:
            self.closeSession()
            
    def saveRefundAmountsForStoreOrder(self, orderId, storeId, cashRefundAmount, cardRefundAmount):
        try:
            return save_refund_amounts_for_store_order(orderId, storeId, cashRefundAmount, cardRefundAmount)
        finally:
            self.closeSession()
        
    def getCollectionsForStore(self, storeId, startDate, endDate):
        try:
            return [to_t_storeOrderCollection(collection) for collection in get_collections_for_store(storeId, startDate, endDate)]
        finally:
            self.closeSession()
            
    def getAmazonOrdersToAcknowledge(self, source):
        try:
            ordersack = []
            for amazonOrderId,amazonOrderCode,status,txnid,count in get_amazon_orders_to_acknowledge(source):
                orderack = AmazonOrdersToAcknowledge()
                orderack.amazonOrderId = amazonOrderId
                orderack.amazonOrderItemId = amazonOrderCode
                orderack.status = status
                orderack.transaction_id = txnid
                orderack.count = count
                ordersack.append(orderack)
            return ordersack    
        except:
            return None
        finally:
            self.closeSession()   
                
    def changeAmazonOrderStatus(self,amazonOrderCode,status):
        try:
            change_amazon_order_status(amazonOrderCode,status) 
        finally:
            self.closeSession()
    
    def updateTimestampForAmazonOrder(self,orderDeliveryMap):
        try:
            return update_timestamp_for_amazon_order(orderDeliveryMap)
        except:
            return False
        finally:
            self.closeSession()
            
    def updateSourceDetailTimestamp(self,id,lastUpdatedOn):
        try:
            return update_source_detail_timestamp(id,lastUpdatedOn)
        except:
            return False
        finally:
            self.closeSession()   
            
    def getOrdersByMobileNumber(self, mobileNumber):
        try:
            orders = get_orders_by_mobile_number(mobileNumber)
            return [to_t_order(order) for order in orders]
        finally:
            self.closeSession()
        
    def getOrdersByAmazonOrderCode(self, amazonId):
        try:
            orders = get_orders_by_amazon_id(amazonId)
            return [to_t_order(order) for order in orders]
        finally:
            self.closeSession()
            
    def convertStoreToNormal(self, orderId):
        try:
            return convert_store_to_normal(orderId)
        except:
            return False
        finally:
            self.closeSession()
            
    def updateFreebieItem(self, orderId, newFreebieItemId):
        try:
            return to_t_order(update_freebie_item(orderId, newFreebieItemId))
        finally:
            self.closeSession()
            
    def getHotspotServiceMatrices(self):
        try:
            return [to_t_hotspotServiceMatrix(hotpotServiceMatrix) for hotpotServiceMatrix in get_hotspot_service_matrices()]
        finally:
            self.closeSession()
            
    def updateOrderAWB(self, orderId, airwayBillNo):
        try:
            return to_t_order(update_order_AWB(orderId, airwayBillNo))
        finally:
            close_session()
    def getOrdersByVendor(self, vendors, statuses):
        try:
            return [to_t_order(order) for order in get_orders_by_vendor(vendors, statuses)]
        finally:
            close_session()
    
    def createEbayOrder(self, ebayOrder):
        try:
            create_ebay_order(ebayOrder)
        finally:
            close_session()
    def getEbayOrderByOrderId(self, orderId):
        try:
            return to_t_ebayOrder(get_ebay_order_by_orderId(orderId))
        finally:
            close_session()
     
    def getEbayOrderBySalesRecNumber(self, salesRecordNumber):
        try:
            return to_t_ebayOrder(get_ebay_order_by_sales_rec_number(salesRecordNumber))
        finally:
            close_session()
            
    def getEbayOrder(self, salesRecordNumber, listingId, paisaPayId):
        try:
            return [to_t_ebayOrder(order) for order in get_ebay_order(salesRecordNumber, listingId, paisaPayId)]
        finally:
            close_session()
    
    def updateEbayOrder(self, ebayOrder):
        try:
            update_ebay_order(ebayOrder)
        finally:
            close_session()
    
    def ebayOrderExists(self, salesRecNumber, ebayListingId):
        try:
            return ebay_order_exists(salesRecNumber, ebayListingId)
        finally:
            close_session()
    
    def updateOrderForEbay(self, order):
        try:
            update_order_for_ebay(order)
        finally:
            close_session()
            
    def splitEbayOrder(self, orderId, splitOrderQty, splitOrderItemId, usePowerShip):
        try:
            return to_t_order(split_ebay_order(orderId, splitOrderQty, splitOrderItemId, usePowerShip))
        finally:
            close_session()
    
    def addOrUpdateAmazonFbaSalesSnapshot(self,amazonfbasalessnapshot):
        try:
            add_or_update_amazon_fba_sales_snapshot(amazonfbasalessnapshot)
        finally:
            close_session()
    
    def getAmazonFbaSalesSnapshotForDays(self,days):
        fbasalessnapshot = []
        try:
            snapshots = get_amazon_fba_sales_snapshot_for_days(days)
            for snapshot in snapshots:
                fbasalessnapshot.append(to_t_amazonFbaSalesSnapshot(snapshot)) 
            return fbasalessnapshot
        except:
            return None
        finally:
            close_session()
            
    def getAmazonFbaSalesLatestSnapshotForItem(self,item_id):
        try:
            return to_t_amazonFbaSalesSnapshot(get_amazon_fba_sales_latest_snapshot_for_item(item_id))
        except:
            return None
        finally:
            close_session()
 
    def createSnapdealOrder(self, snapdeal_order):
        try:
            create_snapdeal_order(snapdeal_order)
        finally:
            close_session()
     
    def getSnapdealOrder(self, orderId, reference_code, suborder_id):
        try:
            return [to_t_snapdealOrder(snapdealOrder) for snapdealOrder in get_snapdeal_order(orderId, reference_code, suborder_id)]
            #return to_t_snapdealOrder(get_snapdeal_order(orderId, reference_code, suborder_id))
        finally:
            close_session()
     
    def snapdealOrderExists(self, suborder_id, referenceCode):
        try:
            return snapdeal_order_exists(suborder_id, referenceCode)
        finally:
            close_session()   
            
    def updateLatestFbaPricesForItem(self,fbaitemprices):
        try:        
            update_latest_fba_prices_for_item(fbaitemprices)
        finally:
            close_session()

    def flipkartOrderExists(self,flipkartOrderId,flipkartSubOrderId):
        try:
            return flipkart_order_exists(flipkartOrderId,flipkartSubOrderId)
        finally:
            self.closeSession()
            
    def createFlipkartOrder(self,flipkartOrder):
        try:
            create_flipkart_order(flipkartOrder)
        finally:           
            self.closeSession()
    
    def getFlipkartOrder(self,orderId):
        try:
            return to_t_flipkartOrder(get_flipkart_order(orderId))
        finally:
            self.closeSession()    

    def getFlipkartOrderByOrderItemId(self, flipkartOrderItemId):
        try:
            return to_t_flipkartOrder(get_flipkart_order_by_subOrderId(flipkartOrderItemId))
        finally:
            close_session()    
            self.closeSession()
            
    def updateFlipkartOrderDatesAndAWB(self,flipkartOrderId,flipkartSubOrderId,date,awb):
        try:
            return update_flipkart_order_dates_and_awb(flipkartOrderId,flipkartSubOrderId,date,awb)
        finally:
            self.closeSession()
            
    def getOrdersCreatedAfterTimestampForSource(self,timestamp,source):
        try:
            return get_orders_count_created_after_timestamp_for_source(timestamp,source)
        finally:
            self.closeSession()
                
            
    def getOrderForAirwayBillNo(self, airwaybillNo):
        ret_Orders =[]
        try:
            orderList = get_order_for_awb(airwaybillNo)
            for order in orderList:
                ret_Orders.append(to_t_order(order))
            return ret_Orders
        finally:
            close_session()
            
    def getMinCreatedTimeStampUndeliveredOrdersForSource(self, source): 
        try:
            return get_min_created_timestamp_undelivered_orders_for_source(source)
        finally:
            close_session()
    
    def updateSnapdealOrdersStatus(self, orders):
        try:
            update_snapdeal_orders_status(orders)
        finally:
            close_session()
            
    def updateFlipkartOrdersStatus(self, delivered_orders):
        try:
            update_flipkart_orders_status(delivered_orders)
        finally:
            close_session()
        
    def bulkAddOrUpdateAmazonFbaSalesSnapshot(self, amazonfbasalessnapshotlist):  
        try:
            bulk_add_or_update_amazon_fba_sales_snapshot(amazonfbasalessnapshotlist)
        finally:
            close_session()
    
    def getCreatedOrdersForFlipkart(self,flipkartorderids):
        try:
            return get_created_orders_for_flipkart(flipkartorderids)
        finally:
            close_session()
            
    def isPrivateDealTransaction(self, transactionId):
        try:
            return is_private_deal_transaction(transactionId)
        except:
            return False
        finally:
            close_session()    
            
    def changeEasyshipMfnOrderTxnStatus(self, transactionId, status, description, pickUp, orderType, source, shipTimestamp, deliveryTimeStamp):
        try:
            return change_easyship_mfn_order_txn_status(transactionId, status, description, pickUp, orderType, source, shipTimestamp, deliveryTimeStamp)
        finally:
            close_session() 
            
    def updateAmazonFbaOrdersReturns(self, fbaOrderReturns):
        try:
            update_amazon_fba_order_returns(fbaOrderReturns)
        finally:
            close_session()
            
    def getAllAmazonFbaOrderReturnsByCurrentTime(self, insertionTimestamp):
        try:
            ret_order_returns= []
            returns = get_all_amazon_fba_order_returns(insertionTimestamp)
            for order_return in returns:
                ret_order_returns.append(to_t_amazonFbaOrderReturn(order_return))
            return ret_order_returns
        finally:
            close_session()
    
    def getTotalSaleReturnsFbaSkusCurentTime(self, insertionTimestamp):
        try:
            return get_total_sale_returns_fba_skus_curent_time(insertionTimestamp)
        finally:
            close_session()
    
    def getAmazonFbaSalesLatestSnapshotForItemLocationWise(self,item_id,location):
        try:
            return to_t_amazonFbaSalesSnapshot(get_amazon_fba_sales_latest_snapshot_for_item_location_wise(item_id,location))
        except:
            return None
        finally:
            close_session()
            
    def getVerificationPendingOrdersFK(self):
        ret_Orders = []
        try:
            fk_Orders = get_verification_pending_orders_fk()
            for fk_order in fk_Orders:
                ret_Orders.append(to_t_flipkartOrder(fk_order))
            return ret_Orders
        finally:
            close_session()
            
    def addInvoiceDetailsToOrders(self, transactionId, customerId):
        try:
            add_invoice_details_to_orders(transactionId, customerId)
        finally:
            close_session()
            
    def getFAOrderByFkOrderId(self, fkOrderId, fkOrderItemId):
        try: 
            return to_t_flipkartAdvantageOrder(get_fa_order_by_fk_order_id(fkOrderId, fkOrderItemId))
        finally:
            close_session()
        
    def getAllFAOrdersList(self, status):
        ret_fa_Orders =[]
        try:
            faOrders = get_all_fa_orders_list(status)
            for faOrder in faOrders:
                ret_fa_Orders.append(to_t_flipkartAdvantageOrder(faOrder))
            return ret_fa_Orders
        finally:
            close_session()
        
    def addUpdateFaOrdersBulk(self, faOrdersList):
        try:
            add_update_fa_orders_bulk(faOrdersList)
        finally:
            close_session()
            
    def flipkartFaOrderExists(self, fkOrderId, fkOrderItemId):
        try:
            return flipkart_fa_order_exists(fkOrderId, fkOrderItemId)
        finally:
            close_session()
            
    def getRcgOrderStatus(self,rechargeOrderId,isFinal):
        try:
            return get_recharge_order_status(rechargeOrderId,isFinal).to_thrift_object()
        finally:
            self.closeSession()
    
    def getRcgTransactionStatus(self,rechargeTransactionId,isFinal):
        try:
            return to_t_rechargeTransaction(get_recharge_transaction_status(rechargeTransactionId,isFinal))
        finally:
            self.closeSession()
            
    def acceptPackageOrders(self, orders):
        try:
            return accept_package_orders(orders)
        finally:
            self.closeSession()
            
    def getGroupOrdersByLogisticsTxnId(self, logisticsTxnId):
        ret_Orders =[]
        try:
            ordersList = get_group_orders_by_logistics_txn_id(logisticsTxnId)
            for order in ordersList:
                ret_Orders.append(to_t_order(order))
            return ret_Orders
        finally:
            self.closeSession()
            
    def addBillingDetailsForGrouppedOrders(self, order_ids, invoice_number, itemNumbersMap, serialNumbersMap, freebieWarehouseIdMap, billed_by, jacketNumber, billingType, authorize, invoiceType):
        try:
            return add_billing_details_for_groupped_orders(order_ids, invoice_number, itemNumbersMap, serialNumbersMap, freebieWarehouseIdMap, billed_by, jacketNumber, billingType, authorize, invoiceType)
        finally:
            self.closeSession()
    
    def getInvoiceFormatLogisticsTxnId(self, transactionId, shipementSeq):
        try:
            return get_invoice_format_logistics_txn_id(transactionId, shipementSeq)
        finally:
            self.closeSession()
            
    def createHomeShopOrder(self, hsOrder):
        try:
            create_homeshop_order(hsOrder)
        finally:
            close_session()
    
    def getHomeShopOrder(self, orderId, hsOrderNo, hsSubOrderNo):
        try:
            return [to_t_hsOrder(hsOrder) for hsOrder in get_homeshop_order(orderId, hsOrderNo, hsSubOrderNo)]
            #return to_t_snapdealOrder(get_snapdeal_order(orderId, reference_code, suborder_id))
        finally:
            close_session()
            
    def homeShopOrderExists(self, hsOrderNo, hsSubOrderNo):
        try:
            return homeshop_order_exists(hsOrderNo, hsSubOrderNo)
        finally:
            close_session()   
            
    def closeSession(self, ):
        close_session()

    def isAlive(self, ):
        """
        For checking whether service is alive or not. It also checks connectivity with database
        """
        try:
            return is_alive()
        finally:
            close_session()
    
    def creditBatch(self, batchId, userAmount):
        try:
            now = datetime.datetime.now()
            sum = 0
            for key, amount in json.loads(userAmount).iteritems():
                userId = int(key)
                add_amount_in_wallet(userId, amount, batchId, WalletReferenceType.CASHBACK, True, "Cashback for orders")
                sum += amount
                
            batchCreditTracker = DtrBatchCreditTracker()
            batchCreditTracker.id = batchId
            batchCreditTracker.amount = sum
            batchCreditTracker.creditedOn = now
                 
            session.commit()
        finally:
            close_session()
            
    def splitBulkOrder(self, orderId, splitOrderQty):
        try:
            return to_t_order(split_bulk_order(orderId, splitOrderQty))
        finally:
            close_session()
            
    def moveOrdersToCorrectWarehouse(self):
        try:
            return move_orders_to_correct_warehouse()
        except:
            traceback.print_exc()
            return "Error"
        finally:
            close_session()
            
    def verifyOrderForTransaction(self, transactionId):
        try:
            return verify_orders_for_transaction(transactionId)
        finally:
            close_session()
            
    def getCreditorInfo(self, creditorId, name):
        try:
            return to_t_Creditor(get_creditor_info(creditorId, name))
        except:
            return None
        finally:
            close_session()
            
    def updateCreditorInfo(self, creditor):
        try:
            return update_creditor_info(creditor)
        finally:
            close_session()

    def getUserSanctionDetails(self, userId):
        try:
            returnMap = get_user_sanction_details(userId, None)
            sanctionsList = []
            for creditorMap in returnMap.values():
                for sanction in creditorMap.get('Sanctions'):
                    sanctionsList.append(to_t_UserSanction(sanction, creditorMap.get('TicketSize')))
            return sanctionsList
        finally:
            close_session()
    
    def getUserSanctionDetailsForCreditor(self, userId, creditorId):
        try:
            returnMap = get_user_sanction_details(userId, creditorId)
            sanctionsList = []
            for creditorMap in returnMap.values():
                for sanction in creditorMap.get('Sanctions'):
                    sanctionsList.append(to_t_UserSanction(sanction, creditorMap.get('TicketSize')))
            return sanctionsList[0]
        except:
            return None
        finally:
            close_session()
            
    def updateUserSanction(self, userSanaction):
        try:
            return update_user_sanction(userSanaction)
        finally:
            close_session()
            
    def getCreditHistoryRecordsForTransaction(self, paymentId, creditTxnType):
        try:
            return [to_t_CreditHistory(creditHistory) for creditHistory in get_credit_history_records(paymentId, None, None, creditTxnType)]
        finally:
            close_session()
            
    def getCreditHistoryRecordsForUserAndCreditor(self, userId, creditorId, creditTxnType):
        try:
            return [to_t_CreditHistory(creditHistory) for creditHistory in get_credit_history_records(None, userId, creditorId, creditTxnType)]
        finally:
            close_session()
            
    def processCreditTransaction(self, paymentId, userId, creditorId, creditTxns):
        try:
            return process_credit_transaction(paymentId, userId, creditorId, creditTxns)
        finally:
            close_session()
            
    def getLoanPayableForUserToCreditor(self, userId, creditorId, dueDate):
        try:
            return get_loan_payable_for_user_to_creditor(userId, creditorId, dueDate)
        finally:
            close_session()
            
    def getLoanHistoryRecordsForTransaction(self, paymentId, creditTxnType):
        try:
            return [to_t_LoanHistory(loanHistory) for loanHistory in get_loan_history_records(paymentId, None, None, creditTxnType)]
        finally:
            close_session()
    
    def getLoanHistoryRecordsForUserAndCreditor(self, userId, creditorId, creditTxnType):
        try:
            return [to_t_LoanHistory(loanHistory) for loanHistory in get_loan_history_records(None, userId, creditorId, creditTxnType)]
        finally:
            close_session()
    
    def processLoanTransaction(self, paymentId, userId, creditorId, creditTxns):
        try:
            return process_loan_transaction(paymentId, creditTxns)
        finally:
            close_session()
            
    def getLimitedCreditHistoryRecords(self, paymentId, userId, creditorId, limit, offset):
        try:
            hasMore, totalCount, creditHistoryList = get_credit_history_records_paginated(paymentId, userId, creditorId, None, limit, offset)
            return to_t_PaginatedCreditHistory(hasMore, totalCount, creditHistoryList)
        finally:
            close_session()
    
    def getLimitedLoanHistoryRecords(self, paymentId, userId, creditorId, limit, offset):
        try:
            hasMore, totalCount, loanHistoryList = get_loan_history_records_paginated(paymentId, userId, creditorId, None, limit, offset)
            return to_t_PaginatedLoanHistory(hasMore, totalCount, loanHistoryList)
        finally:
            close_session()
            
    def getUserSanctionsDetailsAsPerLimit(self, userId, creditorId, limit, offset,sort):
        try:
            hasMore, totalCount, returnMap = get_user_sanction_details_paginated(userId, creditorId, limit, offset,sort)
            sanctionsList = []
            for creditorMap in returnMap.values():
                for sanction in creditorMap.get('Sanctions'):
                    sanctionsList.append(to_t_UserSanction(sanction, creditorMap.get('TicketSize')))
            return to_t_PaginatedUserSanction(hasMore, totalCount, sanctionsList)
        finally:
            close_session()
    
    def getOutstandingPayments(self,fetchType,userId,limit):
        try:
            userCounterMap, outstandingResults = get_outstanding_payments(fetchType,userId,limit)
            return [to_t_OutstandingPayments(outstandingResult,userCounterMap.get(outstandingResult.user_id)) for outstandingResult in outstandingResults]
        finally:
            close_session()
            
    def markPaymentSettled(self,userId,paymentId,totalAmount,repaymentDate):
        returnMap = {}
        try:
            flag, message = mark_payment_settled(userId,paymentId,totalAmount,repaymentDate)
            returnMap[flag] = message
            return returnMap
        finally:
            close_session()
            
    def getOrdersInBatchAsPromisedShipping(self, statuses, offset, limit, warehouse_id, source):
        """
        Returns at most 'limit' orders with the given statuses for the given warehouse starting from the given offset.
        These orders should be in order of promised shipping time. 
        Pass the status as null and the limit as 0 to ignore them.
    
        Parameters:
         - statuses
         - offset
         - limit
         - warehouse_id
        """
        try:
            orders = get_orders_in_batch_as_promised_shipping(statuses, offset, limit, warehouse_id, source)
            return [to_t_order(order) for order in orders]
        finally:
            close_session()
            
    def setOrderAttributeForMasterOrderId(self, logisticsTransactionId, attributes):
        try:
            set_order_attribute_for_master_order_id(logisticsTransactionId, attributes)
        finally:
            close_session()
    
    def updateMasterOrderAWB(self, logisticsTransactionId, airwaybill_no):
        try:
            return update_master_order_awb(logisticsTransactionId, airwaybill_no)
        finally:
            close_session()
            
    def addOrUpdateShipmentLogisticsCostDetails(self, shipmentLogisticsCostDetails):
        try:
            return add_or_update_shipment_logistics_cost_details(shipmentLogisticsCostDetails)
        finally:
            close_session()

    def getReturnOrderInfo(self, id):
        try:
            returnOrderInfo = get_return_order_info(id)
            return to_t_returnOrderInfo(returnOrderInfo)
        finally:
            close_session()
    
    def getReturnOrderInfoList(self, order_ids):
        try:
            returnOrdersInfoMap = get_return_orders_info_map(order_ids)
            mapToReturn = {}
            for orderId, returnOrdersList in returnOrdersInfoMap.items():
                returnList = []
                for returnOrder in returnOrdersList:
                    returnList.append(to_t_returnOrderInfo(returnOrder))
                mapToReturn[orderId] = returnList
            return mapToReturn
        finally:
            close_session()
            
    def getReturnOrderInfoListAsByStatus(self, order_ids, statuses):
        try:
            returnOrdersInfoMap = get_return_orders_info_map(order_ids, statuses)
            mapToReturn = {}
            for orderId, returnOrdersList in returnOrdersInfoMap.items():
                returnList = []
                for returnOrder in returnOrdersList:
                    returnList.append(to_t_returnOrderInfo(returnOrder))
                mapToReturn[orderId] = returnList
            return mapToReturn
        finally:
            close_session()
    
    def updateReturnOrderInfo(self, returnInfo):
        try:
            return update_return_order_info(returnInfo)
        finally:
            close_session()
        
    def bulkUpdateReturnOrderInfo(self, orderReturnInfosMap):
        try:
            return bulk_update_return_order_info(orderReturnInfosMap)
        finally:
            close_session()
            
    def getReturnOrdersAsPerWarehouseId(self, warehouseId):
        """
        Returns all return orders list as per warehouse
        
        Parameters:
         - warehouseId
        """
        try:
            all_returns_orders = get_return_orders_as_per_warehouse(warehouseId)
            return [to_t_returnOrderInfo(order) for order in all_returns_orders]
        finally:
            close_session()
            
    def createReturnTransaction(self, returnTransaction, itemCondition, overrideWarranty):
        """
        Create Return Ticket or Transaction for all Returns
        
        Parameters:
         - returnTransaction Thrift Object
         - itemCondition
         - overrideWarranty
        """
        try:
            return to_t_returnTransaction(create_return_transaction(returnTransaction, itemCondition, overrideWarranty))
        finally:
            close_session()
    
    def getReturnTransactionsForCustomer(self, statusList, customerMobile, customerEmail, returnTransactionId, customerId):
        """
        Get all return transactions as per customer and status for sepcific time interval
        
        Parameters:
         - statusList
         - customerMobile
         - customerEmail
         - returnTransactionId
        """
        
        try:
            transactions = get_return_transactions_for_customer(statusList, customerMobile, customerEmail, returnTransactionId, customerId)
            if transactions is None:
                return []
            else:
                return [to_t_returnTransaction(transaction) for transaction in transactions]
        finally:
            close_session()
            
    def getReturnTransaction(self, id):
        """
        Get Return Transaction as per given id 
        
        Parameters:
         - id
        """
        try:
            return to_t_returnTransaction(get_return_transaction(id))
        finally:
            close_session()
            
    def getReturnOrdersForReturnTransaction(self, returnTransactionId):
        """
        Get Return Orders for given return transaction
        
        Parameters:
         - returnTransactionId
        """
        try:
            returnorders = get_return_orders_for_return_transaction(returnTransactionId)
            return [to_t_returnOrderInfo(returnorder) for returnorder in returnorders]    
        finally:
            close_session()
            
    def changeReturnTransactionStatus(self, returnTransactionId, new_status, returnOrdersIds):
        """
        Change Return Transaction Status 
        
        Parameters:
         - returnTransactionId
         - new_status        
        """  
        try:
            return change_return_transaction_status(returnTransactionId, new_status, returnOrdersIds)
        finally:
            close_session()
            
    def createReturnPickupRequest(self, returnOrderIds):
        """
        Create Return Pickup Request
        
        Parameters
         - returnOrderIds
         - providerId
        """    
        try:
            return create_return_pickup_request(returnOrderIds)
        finally:
            close_session()
            
    def updateReturnPickupRequest(self, returnPickupRequest):
        """
        Update Return Pickup Request
        
        Parameters
         - ReturnPickupRequest Object
        """
        try:
            return update_return_pickup_request(returnPickupRequest)
        finally:
            close_session()
            
    def receiveReturnPickup(self, returnOrdersMap, id):
        """
        Receive Return Pickup
        
        Parameters:
         - returnOrdersMap
         - id
         
        """
        try:
            return receive_return_pickup(returnOrdersMap, id)
        finally:
            close_session()
        
    def validateReturnPickup(self, returnPickupId, returnOrdersMap):
        """
        Validate Return Pickup 
        
        Parameters:
         - returnPickupId 
         - returnOrdersMap
        """
        try:
            return validate_return_pickup(returnPickupId, returnOrdersMap)
        finally:
            close_session()
            
    def processReturnPickup(self, returnPickupId, returnOrdersMap):
        """
        Process Return Pickup
        
        Parameters:
         - returnPickupId
         - returnOrdersMap
        """
        try:
            return process_return_pickup(returnPickupId, returnOrdersMap)
        finally:
            close_session()
            
    def markReturnTransactionComplete(self, returnTransactionId):
        """
        Mark Return Transaction Complete based upon the orders processed.
        
        Parameters:
         - returnTransactionId
        """
        try:
            return mark_return_transaction_complete(returnTransactionId)
        finally:
            close_session()
            
    def refundReturnTransactionPayment(self, returnOrdersMap, returnTransactionId):
        """
        Refund Return Transaction Payment
        
        Parameters
         - returnOrdersMap
         - returnTransactionId
        """
        
        try:
            return refund_return_transaction_payment(returnOrdersMap, returnTransactionId)
        finally:
            close_session()
            
    def getEligibleOrdersForReturn(self, customerId, itemCondition, overrideWarranty):
        """
        Return Eligible Orders for Return Process
        
        Parameters 
         - customerId
         - itemCondition - (Damaged for return and Defective for DOA)
         - overrideWarranty for Admin so that he can return any order without any warranty.
         
        """
        try:
            orders = []
            eligibleOrders = get_eligible_orders_for_return(customerId, itemCondition, overrideWarranty)
            for order in eligibleOrders:
                orders.append(to_t_order(order))
            return orders
        finally:
            close_session()
            
    def getEligibleReturnOrdersForPickup(self, customerId):
        """
        Return All Eligible Return Orders awaiting pickup
        
        Parameters 
         - customerId
         
        """
        try:
            returnOrders = []
            eligibleReturnOrders = get_eligible_return_orders_for_pickup(customerId)
            for returnOrder in eligibleReturnOrders:
                returnOrders.append(to_t_returnOrderInfo(returnOrder))
            return returnOrders
        finally:
            close_session()
    
    def validateReturnTransaction(self, customerId, returnOrdersMap, itemCondition, overrideWarranty):
        """
        To Validate return transaction data
        
        Parameters
         - customerId
         - returnOrdersMap
         - itemCondition
         - overrideWarranty
        """
        try:
            return validate_return_transaction(customerId, returnOrdersMap, itemCondition, overrideWarranty)
        finally:
            close_session()
            
    def markReturnNotRequiredOrdersProcessed(self, returnTransactionId):
        """
        Mark Return Not Required Orders as Processed
        
        Parameters
         - returnTransactionId
        """
        try:
            return mark_return_not_required_orders_as_processed(returnTransactionId) 
        finally:
            close_session()
            
    def getReturnPickupRequest(self, returnPickupId):
        """
        Get Particular Return Pickup Id
        Parameters
         - returnPickupId
        """
        try:
            return to_t_rPickupRequest(get_return_pickup_request(returnPickupId))
        finally:
            close_session()
            
    def getAllReturnOrdersForReturnPickupRequest(self, logisticsRequestId):
        try:
            returnOrders = []
            eligibleReturnOrders = get_all_return_orders_for_return_pickup_request(logisticsRequestId)
            for returnOrder in eligibleReturnOrders:
                returnOrders.append(to_t_returnOrderInfo(returnOrder))
            return returnOrders
        finally:
            close_session()
            
    def getSellerInfo(self, sellerId):
        try:
            return get_seller_info(sellerId)
        finally:
            close_session()

    def getWarehouseAddress(self, addressId):
        try:
            return get_warehouse_address(addressId)
        finally:
            close_session()
    
    def addShipmentDelay(self,shipmentDelayDetail):
        try:
            return add_shipment_delay(shipmentDelayDetail)
        finally:
            close_session()
            
    def getBuyerByWarehouse(self, warehouse_id):
        try:
            return get_buyer_by_warehouse(warehouse_id)
        finally:
            close_session()
    
    def refundReturnOrder(self, returnOrderInfo, attributes):
        try:
            return refund_return_order(returnOrderInfo, attributes)
        finally:
            close_session()
    
    def getCostDetailForLogisticsTxnId(self, logisticsTxnId):
        try:
            return to_t_ShipmentLogisticsCostDetail(get_cost_detail_for_logistics_txn_id(logisticsTxnId))
        finally:
            close_session()
    
    def addShipmentLogisticDetail(self, shipmentLogisticsCostDetail):
        try:
            add_shipment_logistic_detail(shipmentLogisticsCostDetail)
        finally:
            close_session()
            
    def createPayment(self,userId, txnId, gatewayId):
        try:
            return create_payment(userId, txnId, gatewayId)
        finally:
            close_session()
    
    def calculatePaymentAmount(self, txnId):
        try:
            return calculate_payment_amount(txnId)
        finally:
            close_session()
            
    def getBilledOrdersForManifestGen(self, warehouse_id, logistics_provider_id, cod):
        try:
            return_orders = []
            orders = get_billed_orders_for_manifest_gen(warehouse_id, logistics_provider_id, cod)
            for order_list in orders:
                for order in order_list:
                    return_orders.append(to_t_order(order))
            return return_orders
        finally:
            close_session()
    
    def registerRsa(self, userId, activation_code):
        try:
            return register_rsa(userId, activation_code)
        finally:
            close_session()
    
    def addSalesAssociate(self, pmsa, referrerEmail, l1_userEmail):
        try:
            return add_sales_associate(pmsa, referrerEmail, l1_userEmail)
        finally:
            close_session()
    
    def searchPmsa(self, pmsaSearchFilter, associateEmail):
        pmsa_list = []
        try:
            for pmsa in search_pmsa(pmsaSearchFilter, associateEmail):
                pmsa_list.append(to_t_pmsa(pmsa, "", ""))
            return pmsa_list
        finally:
            close_session()
    
    def getPmsaUser(self,id, associateEmail):
        try:
            pmsa, l1_user_email, l2_user_email = get_pmsa_user(id, associateEmail)
            return to_t_pmsa(pmsa, l1_user_email, l2_user_email)
        finally:
            close_session()
    
    def updatePmsaUser(self, pmsa, associateEmail):
        try:
            return update_pmsa_user(pmsa, associateEmail)
        finally:
            close_session()
    
    def getPendingAssociates(self, associateEmail):
        pmsa_list = []
        try:
            for pmsa in get_pending_pmsa(associateEmail):
                pmsa_list.append(to_t_pmsa(pmsa, "", ""))
            return pmsa_list
        finally:
            close_session()
    
    def getPmsaUsers(self, associateEmail):
        pmsa_list = []
        try:
            for pmsa in get_pmsa_users(associateEmail):
                pmsa_list.append(to_t_pmsa(pmsa, "", ""))
            return pmsa_list
        finally:
            close_session()
    
    def getStatsForAssociates(self, associateEmail):
        try:
            return get_stats_for_associates(associateEmail)
        finally:
            close_session()
            
    def getmypmsaprofile(self, associateEmail):
        return to_t_pmsa(get_pmsa_user(None, associateEmail), "" ,"")
    
    def creditUserWallet(self, userId, amount, cash_back, shortDesc):
        try:
            return credit_user_wallet(userId, amount, cash_back, shortDesc)
        finally:
            close_session()
            
    def markOrderForRegisteredGstInvoice(self, transaction_ids):
        try:
            return mark_order_for_registered_gst_invoice(transaction_ids)
        finally:
            close_session()
            
    def isShipmentCod(self, logisticsTransactionId):
        try:
            return is_shipment_cod(logisticsTransactionId)
        finally:
            close_session()
            
    def getInTransitOrdersOnDate(self, closingDate):
        try:
            return get_intransit_orders_on_date(closingDate)
        finally:
            close_session()
    def getInTransitOrdersOnDateByItemId(self, closingDate, itemId):
        try:
            return get_intransit_orders_on_date_by_item_id(closingDate, itemId)
        finally:
            close_session()
            
    def addPriceDrop(self, item_id, imeis, amount, affected_on):
        try:
            return add_price_drop(item_id, imeis, amount, affected_on)
        finally:
            close_session()

    #def updateCreditNote(self, item_id, imeis, affected_on, amount, ):
            
    
            
        
def main():
    #OrderServiceHandler().creditBatch(2, '{"483649":100.0, "8021773":23, "123213":10}')
    #OrderServiceHandler('transaction', '192.168.190.112').refundTransaction(, "Deenanath", "Low Inventory Cancellation")
    osh = OrderServiceHandler('transaction', '192.168.190.112')
    for o in osh.getTransaction(1040376).orders:
        try:
            osh.shiftToWarehouse(o.id, 7681)
            if osh.getOrder(o.id).warehouse_id==0:
                print "OrderId ", o.id, "landed to zero" 
                break
        except:
            traceback.print_exc()
            
if __name__ == '__main__':
    main()