Rev 23237 | Blame | Compare with Previous | Last modification | View Log | RSS feed
from datetime import *from shop2020 import utilsfrom shop2020.clients.InventoryClient import InventoryClientfrom shop2020.clients.TransactionClient import TransactionClientfrom shop2020.clients.CatalogClient import CatalogClientfrom shop2020.config.client.ConfigClient import ConfigClientfrom shop2020.thriftpy.logistics.ttypes import DeliveryTypefrom shop2020.thriftpy.model.v1.order.TransactionService import Clientfrom shop2020.thriftpy.model.v1.order.ttypes import Order, LineItem, SellerInfofrom shop2020.utils.Utils import to_py_datefrom shop2020.utils.caching.SimpleCaching import memoizedimport jsonimport loggingimport urllibimport urllib2import tracebacklogging.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 datareq = 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 - ", valuesdata = urllib.urlencode(values)print "------ data start ------"print dataprint "------- date end ------ "req = urllib2.Request(forwardApi, data)response = urllib2.urlopen(req)the_page = response.read()jsonResponse = json.loads(the_page)return jsonResponse['shipments'][0]['success']except:traceback.print_exc()return Falsedef _forwardMap(airwaybill_no, orders):shipments = []shipments.append(_createShipment(airwaybill_no, orders))return json.dumps(shipments)def _createShipment(airwaybill_no, orders):shipment = {}total_payable = 0total_pieces = 0declared_value = 0total_weight = 0order = orders[0]sellerInfo = getBuyerWarehouse(order.warehouse_id)itemDescription = []for order1 in orders:total_payable += order1.net_payable_amounttotal_pieces += order1.lineitems[0].quantitydeclared_value += order1.total_amounttotal_weight += order1.total_weightitemDescription.append(" ".join(filter(None, [order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number])))warehouseAddressObj = sellerInfo.buyerAddressshipment[F_AWB_NUMBER] = airwaybill_noshipment[F_ORDER_NUMBER] = order.logisticsTransactionIdshipment[F_PRODUCT] = 'COD' if order.cod and total_payable > 0 else 'PPD'shipment[F_CONSIGNEE] = order.customer_nameshipment[F_CONSIGNEE_ADDRESS1] = order.customer_address1shipment[F_CONSIGNEE_ADDRESS2] = order.customer_address2shipment[F_CONSIGNEE_ADDRESS3] = ''shipment[F_DESTINATION_CITY] = order.customer_cityshipment[F_STATE] = order.customer_stateshipment[F_TELEPHONE] = order.customer_mobilenumbershipment[F_MOBILE] = order.customer_mobilenumbershipment[F_ITEM_DESCRIPTION] = "/".join(itemDescription)shipment[F_PINCODE] = order.customer_pincodeshipment[F_PIECES] = int(total_pieces)shipment[F_COLLECTABLE_VALUE] = total_payable if order.cod else 0shipment[F_DECLARED_VALUE] = declared_valueshipment[F_ACTUAL_WEIGHT] = total_weightshipment[F_VOLUMETRIC_WEIGHT] = '0'shipment[F_LENGTH] = 10shipment[F_BREADTH] = 10shipment[F_HEIGHT] = 10shipment[F_PICKUP_NAME] = sellerInfo.organisationNameshipment[F_PICKUP_ADDRESS_LINE1] = warehouseAddressObj.addressshipment[F_PICKUP_ADDRESS_LINE2] = ''shipment[F_PICKUP_PINCODE] = warehouseAddressObj.pinshipment[F_PICKUP_MOBILE] = warehouseAddressObj.contact_numbershipment[F_PICKUP_PHONE] = warehouseAddressObj.contact_numbershipment[F_RETURN_NAME] = sellerInfo.organisationNameshipment[F_RETURN_ADDRESS_LINE1] = warehouseAddressObj.addressshipment[F_RETURN_ADDRESS_LINE2] = ''shipment[F_RETURN_PINCODE] = warehouseAddressObj.pinshipment[F_RETURN_MOBILE] = warehouseAddressObj.contact_numbershipment[F_RETURN_PHONE] = warehouseAddressObj.contact_numbershipment[F_DG_SHIPMENT] = 'false'shipment[F_ADDITIONAL_INFORMATION] = {"MULTI_SELLER_INFORMATION": _getMultiSellerInfo(orders, sellerInfo, warehouseAddressObj)}return shipmentdef _getMultiSellerInfo(orders, sellerInfo, warehouseAddressObj):for order in orders:lineitem = order.lineitems[0]totalTaxRate = lineitem.sgstRate + lineitem.cgstRate + lineitem.igstRatestateMaster = 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 datedef getServiceablePinCodes(date=None):if date:dateString = datetime.strftime(date, '%Y-%m-%d')else:dateString = ''print dateStringvalues = {'username' : username,'password' : password,'date' : dateString,'state' : ''}data = urllib.urlencode(values)print datareq = 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 shipperMapif 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] = inforeturn 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()