Subversion Repositories SmartDukaan

Rev

Rev 21141 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
20718 kshitij.so 1
from suds.client import Client
2
from shop2020.clients.TransactionClient import TransactionClient
3
from datetime import datetime, time, timedelta
4
import traceback
20724 kshitij.so 5
import re
20718 kshitij.so 6
 
7
raclient = None
8
user_profile = None
20820 kshitij.so 9
shipperMap = {}
20718 kshitij.so 10
 
11
DEBUG=True
12
 
21099 kshitij.so 13
acc_url="http://netconnect.bluedart.com/Ver1.7/ShippingAPI/WayBill/WayBillGeneration.svc?wsdl"
20718 kshitij.so 14
LOGIN_ID ="FA316326"
21099 kshitij.so 15
LICENCE_KEY="131f6cfe91591bcc9de7032bb1ed6d13"
16
API_VERSION="1.3"
20718 kshitij.so 17
API_TYPE="S"
18
AREA="ALL"
19
 
20768 kshitij.so 20
xstr = lambda s: s or ""
21
 
20745 kshitij.so 22
class __BluedartAWBResponse:
23
    def __init__(self, awbNo, destArea, destLocation):
24
        self.awbNo = awbNo
25
        self.destArea = destArea
26
        self.destLocation = destLocation
27
 
20718 kshitij.so 28
def get_client():
29
    global raclient
30
    if raclient is None:
31
        raclient = Client(acc_url, timeout=70)
32
        return raclient
33
    else:
34
        return raclient
35
 
36
def get_profile():
37
    global user_profile
38
    if user_profile is None:
39
        profile = get_client().factory.create('ns0:UserProfile')
40
        profile.Api_type = API_TYPE
41
        profile.Area = AREA 
42
        profile.LicenceKey = LICENCE_KEY
43
        profile.LoginID = LOGIN_ID
44
        profile.Version = API_VERSION
45
        user_profile = profile
46
    return user_profile
47
 
20820 kshitij.so 48
def get_shipper_object(warehouse_id):
49
    global shipperMap
50
    if shipperMap.has_key(warehouse_id):
51
        return shipperMap.get(warehouse_id)
52
    else:
53
        tc = TransactionClient().get_client()
54
        info = tc.getBuyerByWarehouse(warehouse_id)
55
        if info is None:
56
            raise RuntimeError("Buyer address mapping is None")
20718 kshitij.so 57
        ship = get_client().factory.create('ns2:Shipper')
20820 kshitij.so 58
        ship.CustomerAddress1 = info.buyerAddress.address[:30]
59
        ship.CustomerAddress2 = info.buyerAddress.address[30:60]
60
        ship.CustomerAddress3 = info.buyerAddress.address[60:90]
20718 kshitij.so 61
        ship.CustomerCode = "316326"
20820 kshitij.so 62
        ship.CustomerMobile = info.buyerAddress.contact_number
20718 kshitij.so 63
        ship.VendorCode="AMPFAR"
64
        ship.OriginArea = "FAR"
20820 kshitij.so 65
        ship.CustomerPincode = info.buyerAddress.pin
20823 kshitij.so 66
        info.organisationName = info.organisationName+" "
67
        temp_org = info.organisationName.split(" ")
20822 kshitij.so 68
        ship.Sender = (xstr(temp_org[0])+" "+xstr(temp_org[1])).strip()
20824 kshitij.so 69
        ship.CustomerName = ship.Sender
20820 kshitij.so 70
        ship.CustomerTelephone= info.buyerAddress.contact_number 
71
        shipperMap[warehouse_id] = ship
72
    return shipperMap.get(warehouse_id)
20718 kshitij.so 73
 
20809 kshitij.so 74
def create_commodity_obj(orders_list, cd, ser):
75
    SpecialInstruction = ""
20817 kshitij.so 76
    it=0
20809 kshitij.so 77
    for order in orders_list:
20817 kshitij.so 78
        it+=1
20809 kshitij.so 79
        temp = xstr(order.lineitems[0].brand)+" "+xstr(order.lineitems[0].model_name)+" "+xstr(order.lineitems[0].model_number)+" "+xstr(order.lineitems[0].color)+"-"+str(order.lineitems[0].quantity)
20817 kshitij.so 80
        SpecialInstruction+=temp
81
        if len(orders_list) == it:
82
            pass
83
        else:
84
            SpecialInstruction+=","
85
 
20809 kshitij.so 86
    SpecialInstruction = re.sub(' +',' ',SpecialInstruction)
20817 kshitij.so 87
    ser.SpecialInstruction = SpecialInstruction[:50]
20809 kshitij.so 88
    cd.CommodityDetail1 = SpecialInstruction[:30]
89
    cd.CommodityDetail2 = SpecialInstruction[30:60]
20817 kshitij.so 90
    cd.CommodityDetail3 = SpecialInstruction[60:90]
20816 kshitij.so 91
    ser.Commodity = cd
20809 kshitij.so 92
    return ser
93
 
20768 kshitij.so 94
def clean_address(order, consignee):
95
    address_string = xstr(order.customer_address1)+" "+xstr(order.customer_address2)
96
    address_string = re.sub(",",' ',address_string)
97
    add_string = re.sub(' +',' ',address_string)
98
    c_1, idx = sub_address(address_string, 0, 30)
99
    c_2, idx = sub_address(address_string, idx, idx+30)
100
    c_3, idx = sub_address(address_string, idx, len(add_string))
20772 kshitij.so 101
    consignee.ConsigneeAddress1 = c_1.strip()
102
    consignee.ConsigneeAddress2 = c_2.strip()
103
    consignee.ConsigneeAddress3 = (c_3 +" "+order.customer_city).strip()
20768 kshitij.so 104
    return consignee
21102 kshitij.so 105
 
20768 kshitij.so 106
 
107
def sub_address(add_str, previous_loc, final_loc):
108
    sub = add_str[previous_loc:final_loc]
109
    max_idx = sub.rfind(" ")
110
    if max_idx==-1:
111
        return sub, len(sub)
112
    if max_idx == (final_loc-1):
21102 kshitij.so 113
        return sub, final_loc-1
20768 kshitij.so 114
    return sub[: max_idx], max_idx+previous_loc
20808 kshitij.so 115
 
116
def get_shipment_details(logisticsTxnId):
117
    tc = TransactionClient().get_client()
118
    shipment_cost_detail = tc.getCostDetailForLogisticsTxnId(logisticsTxnId)
119
    return shipment_cost_detail
20768 kshitij.so 120
 
121
 
20718 kshitij.so 122
def generate_awb(orders_list):
123
    try:
124
        if not isinstance(orders_list, list) or not orders_list:
20724 kshitij.so 125
            raise ValueError("Expecting list of orders")
20718 kshitij.so 126
        consignee = get_client().factory.create('ns2:Consignee')
20768 kshitij.so 127
        consignee = clean_address(orders_list[0], consignee)
20718 kshitij.so 128
        consignee.ConsigneeAttention = orders_list[0].customer_name
129
        consignee.ConsigneeMobile = orders_list[0].customer_mobilenumber
130
        consignee.ConsigneeName = orders_list[0].customer_name
131
        consignee.ConsigneePincode = orders_list[0].customer_pincode
132
        consignee.ConsigneeTelephone = orders_list[0].customer_mobilenumber
133
        ser = get_client().factory.create('ns2:Services')
134
        productType = get_client().factory.create('ns1:ProductType')
135
        actual_weight = 0.0
136
        collectable_amount = 0.0
137
        declared_value = 0.0
138
        isCod = orders_list[0].cod
139
        for order in orders_list:
140
            line_item = order.lineitems[0]
141
            actual_weight += line_item.total_weight
21099 kshitij.so 142
            collectable_amount += order.net_payable_amount
20718 kshitij.so 143
            declared_value += order.total_amount
144
        ser.ActualWeight = actual_weight
145
        ser.CreditReferenceNo = orders_list[0].logisticsTransactionId
146
        ser.DeclaredValue = declared_value 
147
        ser.ProductCode = "A"
148
        ser.ProductType = productType.Dutiables
20726 kshitij.so 149
        ser.PieceCount = 1
20718 kshitij.so 150
        now_time = datetime.now().time()
151
        if now_time <= time(19,00):
152
            ser.PickupDate = datetime.today().strftime('%Y-%m-%d')
153
        else:
154
            ser.PickupDate = (datetime.now()+timedelta(days=1)).strftime('%Y-%m-%d')
155
        ser.PickupTime="1900"
156
        ser.IsReversePickup = False
157
        ser.PDFOutputNotRequired = True
158
        ser.RegisterPickup = False
21099 kshitij.so 159
        if isCod and collectable_amount > 0:
20718 kshitij.so 160
            ser.CollectableAmount = collectable_amount 
161
            ser.SubProductCode = "C"
21141 kshitij.so 162
        else:
163
            ser.SubProductCode = "P"
20718 kshitij.so 164
        wbg = get_client().factory.create('ns2:WayBillGenerationRequest')
165
 
166
        d= get_client().factory.create('ns2:Dimension')
20808 kshitij.so 167
        shipment_cost = get_shipment_details(orders_list[0].logisticsTransactionId)
168
        if shipment_cost is None or shipment_cost.packageDimensions is None:
169
            raise RuntimeError("Package dim. is none")
170
        t_dimensions = shipment_cost.packageDimensions.split("X")
20815 kshitij.so 171
        if len(t_dimensions)!=3:
20808 kshitij.so 172
            raise RuntimeError("Package dim. is not valid")
173
        d.Count=1
20809 kshitij.so 174
        d.Length = float(t_dimensions[0].strip())
175
        d.Breadth = float(t_dimensions[1].strip())
176
        d.Height = float(t_dimensions[2].strip())
20820 kshitij.so 177
        ser.Dimensions.Dimension=[d]
20809 kshitij.so 178
 
20816 kshitij.so 179
        cd = get_client().factory.create('ns2:Commodity')
20809 kshitij.so 180
 
181
        ser = create_commodity_obj(orders_list, cd, ser)
182
 
183
        wbg.Consignee = consignee
184
        wbg.Services = ser
20820 kshitij.so 185
        wbg.Shipper = get_shipper_object(orders_list[0].warehouse_id)
20809 kshitij.so 186
 
20724 kshitij.so 187
        response = get_client().service.GenerateWayBill(wbg, get_profile())
188
        if response.AWBNo is None:
20745 kshitij.so 189
            raise RuntimeError("AWB generated is empty")
20724 kshitij.so 190
        else:
20745 kshitij.so 191
            bluedartResponse = __BluedartAWBResponse(str(response.AWBNo),str(response.DestinationArea),str(response.DestinationLocation))
192
            return bluedartResponse
20718 kshitij.so 193
    finally:
194
        if DEBUG:
195
            print get_client().last_sent()
196
            print get_client().last_received()
197
 
198
def main():
20724 kshitij.so 199
    print generate_awb([])
20718 kshitij.so 200
 
201
 
202
 
203
if __name__ == '__main__':
204
    main()