Subversion Repositories SmartDukaan

Rev

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

from datetime import *
from shop2020 import utils
from shop2020.clients.InventoryClient import InventoryClient
from shop2020.clients.TransactionClient import TransactionClient
from shop2020.clients.CatalogClient import CatalogClient
from shop2020.config.client.ConfigClient import ConfigClient
from shop2020.thriftpy.logistics.ttypes import DeliveryType
from shop2020.thriftpy.model.v1.order.TransactionService import Client
from shop2020.thriftpy.model.v1.order.ttypes import Order, LineItem, SellerInfo
from shop2020.utils.Utils import to_py_date
from shop2020.utils.caching.SimpleCaching import memoized
import json
import logging
import urllib
import urllib2
import traceback
logging.basicConfig(level=logging.DEBUG)
try:
    cc = ConfigClient()
    live = cc.get_property("live")
except:
    live = "false"
#live = "false"
warehouseMap = {}
shipperMap = {}

if live=="true":
    username = 'newspice671445'
    password = 'npcs67unsd44debm'
    wayBillApi = 'http://api.ecomexpress.in/apiv2/fetch_awb/'
    forwardApi = 'http://api.ecomexpress.in/apiv3/manifest_awb/'
    serviceablePincodeApi = 'http://api.ecomexpress.in/apiv2/pincodes/'
else:
    username = 'ecomexpress'
    password = 'Ke$3c@4oT5m6h#$'
    wayBillApi = 'http://staging.ecomexpress.in/apiv2/fetch_awb/'
    forwardApi = 'http://staging.ecomexpress.in/apiv2/manifest_awb/'
    serviceablePincodeApi = 'http://staging.ecomexpress.in/apiv2/pincodes/'
    
F_AWB_NUMBER = "AWB_NUMBER" 
F_ORDER_NUMBER = "ORDER_NUMBER" 
F_PRODUCT = "PRODUCT" 
F_CONSIGNEE = "CONSIGNEE" 
F_CONSIGNEE_ADDRESS1 = "CONSIGNEE_ADDRESS1" 
F_CONSIGNEE_ADDRESS2 = "CONSIGNEE_ADDRESS2" 
F_CONSIGNEE_ADDRESS3 = "CONSIGNEE_ADDRESS3" 
F_DESTINATION_CITY = "DESTINATION_CITY" 
F_PINCODE = "PINCODE" 
F_STATE = "STATE" 
F_MOBILE = "MOBILE" 
F_ITEM_DESCRIPTION = "ITEM_DESCRIPTION" 
F_PIECES = "PIECES" 
F_COLLECTABLE_VALUE = "COLLECTABLE_VALUE" 
F_DECLARED_VALUE = "DECLARED_VALUE" 
F_ACTUAL_WEIGHT = "ACTUAL_WEIGHT" 
F_VOLUMETRIC_WEIGHT = "VOLUMETRIC_WEIGHT" 
F_LENGTH = "LENGTH" 
F_BREADTH = "BREADTH" 
F_HEIGHT = "HEIGHT" 
F_PICKUP_NAME = "PICKUP_NAME" 
F_PICKUP_ADDRESS_LINE1 = "PICKUP_ADDRESS_LINE1" 
F_PICKUP_ADDRESS_LINE2 = "PICKUP_ADDRESS_LINE2" 
F_PICKUP_PINCODE = "PICKUP_PINCODE" 
F_PICKUP_PHONE = "PICKUP_PHONE" 
F_PICKUP_MOBILE = "PICKUP_MOBILE" 
F_RETURN_NAME = "RETURN_NAME" 
F_RETURN_ADDRESS_LINE1 = "RETURN_ADDRESS_LINE1" 
F_RETURN_ADDRESS_LINE2 = "RETURN_ADDRESS_LINE2" 
F_RETURN_PINCODE = "RETURN_PINCODE" 
F_RETURN_PHONE = "RETURN_PHONE" 
F_RETURN_MOBILE = "RETURN_MOBILE" 
F_DG_SHIPMENT = "DG_SHIPMENT" 
F_ADDITIONAL_INFORMATION = "ADDITIONAL_INFORMATION" 
F_INVOICE_NUMBER = "INVOICE_NUMBER" 
F_INVOICE_DATE = "INVOICE_DATE" 
F_ITEM_CATEGORY = "ITEM_CATEGORY" 
F_PACKING_TYPE = "PACKING_TYPE" 
F_PICKUP_TYPE = "PICKUP_TYPE" 
F_RETURN_TYPE = "RETURN_TYPE" 
F_PICKUP_LOCATION_CODE = "PICKUP_LOCATION_CODE" 
F_SELLER_GSTIN = "SELLER_GSTIN" 
F_GST_HSN = "GST_HSN" 
F_GST_ERN = "GST_ERN" 
F_GST_TAX_NAME = "GST_TAX_NAME"
F_GST_TAX_BASE = "GST_TAX_BASE"
F_GST_TAX_RATE_CGSTN = "GST_TAX_RATE_CGSTN"
F_GST_TAX_RATE_SGSTN = "GST_TAX_RATE_SGSTN"
F_GST_TAX_RATE_IGSTN = "GST_TAX_RATE_IGSTN"
F_GST_TAX_TOTAL = "GST_TAX_TOTAL"
F_TELEPHONE = "TELEPHONE"

#returns list of awb of specified type
#will generate 500 awbs at once

@memoized(3600)
def fetchStateMaster():
    inventory_client = InventoryClient().get_client()
    return inventory_client.getStateMaster()


def generate_awb(deliveryType):
    if deliveryType == DeliveryType.COD:
        ecomDeliveryType = "COD"
    if deliveryType == DeliveryType.PREPAID:
        ecomDeliveryType = "PPD"
    values = {'username' : username,
              'password' : password,
              'count' : '500',
              'type' : ecomDeliveryType }
    data = urllib.urlencode(values)
    print data
    req = urllib2.Request(wayBillApi, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
    awbs  = [str(awb) for awb in json.loads(the_page)['awb']]
    return awbs

#All orders awbwise
#{'awb':[o1, o2, o3]}
def forward_request(logisticsTxnId):
    try:
        client = TransactionClient().get_client()
        orders = client.getGroupOrdersByLogisticsTxnId(logisticsTxnId)
        values = {'username' : username,
                  'password' : password,
                  'json_input' : _forwardMap(orders[0].airwaybill_no, orders),
                  }
        print "values - ", values 
        data = urllib.urlencode(values)
        print "------ data start ------"
        print  data
        print "------- date end ------ " 
        req = urllib2.Request(forwardApi, data)
        response = urllib2.urlopen(req)
        the_page = response.read()
        jsonResponse = json.loads(the_page)
        print 
        return jsonResponse['shipments'][0]['success']
    except:
        traceback.print_exc()
        return False
    
def _forwardMap(airwaybill_no, orders):
    shipments = []
    shipments.append(_createShipment(airwaybill_no, orders))
    return json.dumps(shipments)
    
        
def _createShipment(airwaybill_no, orders):
    shipment = {}
    total_payable = 0
    total_pieces = 0
    declared_value = 0
    total_weight = 0
    order = orders[0]
    sellerInfo = getBuyerWarehouse(order.warehouse_id)
    itemDescription = []
    for order1 in orders:
        total_payable += order1.net_payable_amount
        total_pieces += order1.lineitems[0].quantity
        declared_value += order1.total_amount
        total_weight += order1.total_weight
        itemDescription.append(" ".join(filter(None, [order.lineitems[0].brand, order.lineitems[0].model_name,  order.lineitems[0].model_number])))
    warehouseAddressObj = sellerInfo.buyerAddress
    shipment[F_AWB_NUMBER] = airwaybill_no
    shipment[F_ORDER_NUMBER] = order.logisticsTransactionId 
    shipment[F_PRODUCT] = 'COD' if order.cod and total_payable > 0 else 'PPD' 
    shipment[F_CONSIGNEE] = order.customer_name 
    shipment[F_CONSIGNEE_ADDRESS1] = order.customer_address1 
    shipment[F_CONSIGNEE_ADDRESS2] = order.customer_address2
    shipment[F_CONSIGNEE_ADDRESS3] = ''
    shipment[F_DESTINATION_CITY] = order.customer_city 
    shipment[F_STATE] = order.customer_state
    shipment[F_TELEPHONE] = order.customer_mobilenumber
    shipment[F_MOBILE] = order.customer_mobilenumber 
    shipment[F_ITEM_DESCRIPTION] = "/".join(itemDescription)
    shipment[F_PINCODE] = order.customer_pincode
    shipment[F_PIECES] = int(total_pieces)
    shipment[F_COLLECTABLE_VALUE] = total_payable if order.cod else 0
    shipment[F_DECLARED_VALUE] = declared_value 
    shipment[F_ACTUAL_WEIGHT] = total_weight 
    shipment[F_VOLUMETRIC_WEIGHT] = '0'
    shipment[F_LENGTH] = 10
    shipment[F_BREADTH] = 10
    shipment[F_HEIGHT] = 10
    shipment[F_PICKUP_NAME] = sellerInfo.organisationName
    shipment[F_PICKUP_ADDRESS_LINE1] = warehouseAddressObj.address
    shipment[F_PICKUP_ADDRESS_LINE2] = ''
    shipment[F_PICKUP_PINCODE] = warehouseAddressObj.pin
    shipment[F_PICKUP_MOBILE] = warehouseAddressObj.contact_number
    shipment[F_PICKUP_PHONE] = warehouseAddressObj.contact_number
    
    shipment[F_RETURN_NAME] = sellerInfo.organisationName
    shipment[F_RETURN_ADDRESS_LINE1] = warehouseAddressObj.address
    shipment[F_RETURN_ADDRESS_LINE2] = ''
    shipment[F_RETURN_PINCODE] = warehouseAddressObj.pin
    shipment[F_RETURN_MOBILE] = warehouseAddressObj.contact_number
    shipment[F_RETURN_PHONE] = warehouseAddressObj.contact_number
    shipment[F_DG_SHIPMENT] = 'false'
    shipment[F_ADDITIONAL_INFORMATION] = {"MULTI_SELLER_INFORMATION": _getMultiSellerInfo(orders, sellerInfo, warehouseAddressObj)}
    return shipment 
    
def _getMultiSellerInfo(orders, sellerInfo, warehouseAddressObj):
    for order in orders:
        lineitem = order.lineitems[0]
        totalTaxRate = lineitem.sgstRate + lineitem.cgstRate + lineitem.igstRate
        stateMaster = fetchStateMaster()
        return {
            "ITEM_DESCRIPTION": " ".join(filter(None, [lineitem.brand, lineitem.model_name,  lineitem.model_number])),
            "ITEM_VALUE": lineitem.unit_price,
            "ITEM_CATEGORY": "Mobile/Mobile Accessory",
            "SELLER_NAME": sellerInfo.organisationName,
            "SELLER_ADDRESS": sellerInfo.registeredAddress,
            "SELLER_STATE": stateMaster[sellerInfo.stateId].shortName,
            "SELLER_PINCODE": warehouseAddressObj.pin,
            "SELLER_TIN": "",
            "INVOICE_NUMBER": order.invoice_number,
            "INVOICE_DATE": datetime.strftime(to_py_date(order.billing_timestamp), '%d-%b-%Y'),
            "ESUGAM_NUMBER": "",
            "SELLER_GSTIN": sellerInfo.gstin,
            "GST_HSN": lineitem.hsnCode,
            "GST_TAX_BASE": lineitem.unit_price,
            "DISCOUNT": 0.0,
            "GST_TAX_RATE_CGSTN": lineitem.cgstRate,
            "GST_TAX_RATE_SGSTN": lineitem.sgstRate,
            "GST_TAX_RATE_IGSTN": lineitem.igstRate,
            "GST_TAX_TOTAL": lineitem.unit_price - lineitem.unit_price / (1 + (totalTaxRate/100)),
            "GST_TAX_CGSTN": lineitem.unit_price - lineitem.unit_price / (1 + (lineitem.cgstRate/100)),
            "GST_TAX_SGSTN": lineitem.unit_price - lineitem.unit_price / (1 + (lineitem.sgstRate/100)),
            "GST_TAX_IGSTN": lineitem.unit_price - lineitem.unit_price / (1 + (lineitem.igstRate/100)),
        }
        
#we will always fetch for previous date
def getServiceablePinCodes(date=None):
    if date:
        dateString = datetime.strftime(date, '%Y-%m-%d')
    else:
        dateString = ''
    print dateString
    values = {'username' : username,
              'password' : password,
              'date' :  dateString,
              'state' : ''
              }
    data = urllib.urlencode(values)
    print data
    req = urllib2.Request(serviceablePincodeApi, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
    return json.loads(the_page)

def main():
    pass
    #print generate_awb(DeliveryType.COD)

def getBuyerWarehouse(warehouse_id):
    global shipperMap
    if shipperMap.has_key(warehouse_id):
        return shipperMap.get(warehouse_id)
    else:
        tc = TransactionClient().get_client()
        info = tc.getBuyerByWarehouse(warehouse_id)
        if info is None:
            raise RuntimeError("Buyer address mapping is None")
        shipperMap[warehouse_id] = info
    return shipperMap.get(warehouse_id)    
    

if __name__ == '__main__':
    pass
    #oc = TransactionClient().get_client()
    #awbs = generate_awb(DeliveryType.COD)
    #print awbs
    #'706831493', '706831494'
    #logisticsTxnId = '1036348-1'
    #orders = oc.getGroupOrdersByLogisticsTxnId(logisticsTxnId)
    #ordersMap = {}
    #forward_request('706831494', logisticsTxnId)
    #print getServiceablePinCodes(datetime.now()-timedelta(days=30))
    #getServiceablePinCodes()