Subversion Repositories SmartDukaan

Rev

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

#!/usr/bin/python

import optparse
import time
import datetime
import sys
from elixir import session
from random import randrange
from shop2020.clients.LogisticsClient import LogisticsClient
from shop2020.clients.CatalogClient import CatalogClient
from shop2020.clients.InventoryClient import InventoryClient
from shop2020.model.v1.order.impl.DataService import Attribute
from shop2020.thriftpy.logistics.ttypes import DeliveryType, PickUpType

if __name__ == '__main__' and __package__ is None:
    import os
    sys.path.insert(0, os.getcwd())

from shop2020.thriftpy.model.v1.order.ttypes import OrderStatus, TransactionServiceException, OrderType
from shop2020.model.v1.order.impl import DataService
from shop2020.model.v1.order.impl.DataService import Order, LineItem, Transaction
from shop2020.model.v1.order.impl.DataAccessors import get_order, close_session
from shop2020.model.v1.order.impl.DataAccessors import delhi_pincodes

def cancel(order):
    '''
    Cancel
    '''
    print("Your session has been closed")
    return

def process_order(order):
    '''
    Process Order
    '''
    
    if order.total_amount < 10998:
        print "Order already processed"
        return
    
    bulk_order = Order()

    bulk_order.transaction = order.transaction
    
    bulk_order.customer_id = order.customer_id
    bulk_order.customer_email = order.customer_email
    bulk_order.customer_name = order.customer_name
    bulk_order.customer_pincode = order.customer_pincode
    bulk_order.customer_address1 = order.customer_address1
    bulk_order.customer_address2 = order.customer_address2
    bulk_order.customer_city = order.customer_city
    bulk_order.customer_state = order.customer_state
    bulk_order.customer_mobilenumber = order.customer_mobilenumber
    bulk_order.total_weight = order.total_weight
    bulk_order.status = OrderStatus.ACCEPTED
    bulk_order.statusDescription = "In Process";
    bulk_order.created_timestamp = order.created_timestamp
    bulk_order.accepted_timestamp = datetime.datetime.now()
    bulk_order.cod = order.cod
    bulk_order.orderType = OrderType.B2Cbulk
    bulk_order.pickupStoreId = 0
    bulk_order.otg = 0
    bulk_order.insurer = 0
    bulk_order.insuranceAmount = 0
    
    logistics_client = LogisticsClient().get_client()
    logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, 1, DeliveryType.PREPAID, PickUpType.SELF)
    bulk_order.logistics_provider_id = logistics_info.providerId;
    bulk_order.tracking_id = logistics_info.airway_billno
    bulk_order.airwaybill_no = logistics_info.airway_billno

    bulk_order.expected_delivery_time = order.expected_delivery_time
    bulk_order.promised_delivery_time = order.promised_delivery_time
    bulk_order.expected_shipping_time = order.expected_shipping_time
    bulk_order.promised_shipping_time = order.promised_shipping_time

    catalog_client = CatalogClient().get_client()
    item = catalog_client.getItem(1173)

    litem = LineItem()
    litem.item_id = item.id
    litem.productGroup = item.productGroup
    litem.brand = item.brand
    litem.model_number = item.modelNumber
    litem.model_name = item.modelName
    litem.color = item.color
    litem.extra_info = "Complementary Order for A110,  Order ID " + str(order.id)
    litem.quantity = 1
    litem.unit_price = order.total_amount - order.insuranceAmount - 9999
    litem.unit_weight = item.weight
    litem.total_price = order.total_amount - order.insuranceAmount - 9999
    litem.total_weight = item.weight
    litem.vatRate = 5.0
    
    bulk_order.lineitems.append(litem)

    bulk_order.total_amount = order.total_amount - order.insuranceAmount - 9999
    
    order.total_amount = 9999 + order.insuranceAmount
    order.lineitems[0].unit_price = 9999
    order.lineitems[0].total_price = 9999
    
    inventory_client = InventoryClient().get_client()
    item_availability = inventory_client.getItemAvailabilityAtLocation(bulk_order.lineitems[0].item_id,1)
    bulk_order.warehouse_id = item_availability[2]
    bulk_order.fulfilmentWarehouseId = item_availability[0]
    
    session.commit()
    
    print "New Bulk OrderId : " + str(bulk_order.id)    
    
    return 
    

ACTIONS = {0: cancel,
           1: process_order
           }

def get_py_datetime(time_string):
    time_format = "%Y-%m-%d %H%M"
    mytime = time.strptime(time_string, time_format)
    return datetime.datetime(*mytime[:6])

def main():
    parser = optparse.OptionParser()
    parser.add_option("-H", "--host", dest="hostname",
                      default="localhost",
                      type="string", help="The HOST where the DB server is running",
                      metavar="HOST")
    parser.add_option("-O", "--order", dest="orderId",
                      default =0,
                      type="int", help="A110 OrderId to be processed",
                      metavar="NUM")
    (options, args) = parser.parse_args()
    if len(args) != 0:
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
    
    if options.orderId == 0:
        print "Usage : -O OrderId -H Hostname"
        return
    DataService.initialize(db_hostname=options.hostname, echoOn=False)
    
    orderId = options.orderId
    try:
        order = get_order(orderId)
        print("Please check the details of the order below and ensure that it's the same order which you want to modify:")
        print("Order Id:\t\t" + str(order.id))
        print("Customer Name:\t\t" + order.customer_name)
        print("Pincode:\t\t" + order.customer_pincode)
        print("Amount:\t\t\t" + str(order.total_amount))
        print("Created On:\t\t" + str(order.created_timestamp))
        print("Current Status:\t\t" + str(order.status))
        print("Status Description:\t\t" + order.statusDescription)
        print("Logistics provider id:\t\t" + str(order.logistics_provider_id))
        print("Airway bill number:\t\t" + order.airwaybill_no)
        print("Ordered Items description:")
        for lineitem in order.lineitems:
            print("Item Id:" + str(lineitem.item_id) + "\tBrand: " + str(lineitem.brand) + "\tModel: " + str(lineitem.model_number) + "\tColor: " + str(lineitem.color))
        print
        print
        print("You can perform following operations:")
        for (key, val) in ACTIONS.iteritems():
            print("[" + str(key) + "]" + val.__doc__ )

        raw_action = raw_input("What do you want to do? ")
        if raw_action is None or raw_action == "":
            print("Your session has been closed.")
            return
        try:
            action = int(raw_action)
        except ValueError:
            print("Invalid input.")
            return
        if action > max(ACTIONS.keys()):
            print("Invalid input.")
            return
        ACTIONS[action](order)
    except TransactionServiceException as tsex:
        print tsex.message
    finally:
        close_session()
    
if __name__ == '__main__':
    main()