-
Notifications
You must be signed in to change notification settings - Fork 0
/
BOMpricer.py~
executable file
·343 lines (282 loc) · 11.8 KB
/
BOMpricer.py~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/python
#This file was written by Chris Canal for iRobot
#If you have any questions or need help with
#a similair script, please contact me at
#Got some help with parsing Json from:
#http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python
#Import dependencies
import requests
import json
import pprint
import sys
import urllib2
import csv
import time
from random import randint
from pprint import pprint
from xml.dom import minidom
import yaml
import pprint
from Tkinter import *
import tkFileDialog
import glob
CSVMatrix = []
class Window(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.initialize()
self.dir_opt = options = {}
options['initialdir'] = 'C:\\'
options['mustexist'] = False
options['parent'] = self.parent
def initialize(self):
self.geometry("600x400+30+30")
self.wButton = Button(self, text='Import', command = self.OnButtonClick)
self.wButton.pack()
self.check = Checkbutton(text="Digikey Only")
self.check.pack()
def OnButtonClick(self):
self.top = Toplevel()
self.top.title("Browse For File")
self.top.geometry("300x150+30+30")
self.top.transient(self)
self.wButton.config(state='disabled')
button_opt = {'padx': 5, 'pady': 5}
self.topButton = Button(self.top, text='Open Directory', command=self.file_save)
self.topButton.pack()
def file_save(self):
f = tkFileDialog.askopenfilename()
out = open(f, 'r')
CSVMatrix = csv.reader(out, skipinitialspace=False)
CSVMatrix = [row for row in CSVMatrix]
out.close()
print CSVMatrix
if __name__ == "__main__":
window = Window(None)
window.title("Import CSV File")
window.mainloop()
<<<<<<< HEAD
=======
fileLocation = '/Users/christophercanal4/GithubProjects/iRobot/BOMpricer/shortTest.csv'
>>>>>>> 3315acea35d1f877c182763c023a5ea926b8b990
outputFileLocation = "/Users/christophercanal4/Desktop/PriceAndQuantity.csv"
#--------Methods Section------------#
#This method gets the data from the CSV file and returns it
def getPartData(fileLocation):
out = open(fileLocation,"rb")
CSVdata = csv.reader(out, skipinitialspace=False)
CSVdata = [row for row in CSVdata]
out.close()
return CSVdata
def writeObjectToFile(bestPrices):
with open(outputFileLocation, "wb") as f:
writer = csv.writer(f)
writer.writerows(bestPrices)
def formatSearchResults(searchData):
formattedData = []
formattedData.append(['Part Number','Lowest Price Found','Vendor','Buy Link','DataSheet Link','Amount in Stock','Manufacturer'])
for x in range(0, len(searchData)):
partNumber = searchData[x]['partNumber']
lowestPrice = str(searchData[x]['lowestPrice'])
vendor = searchData[x]['Vendor']
buyLink = findBuyLink(searchData[x])
datasheet = findDatasheetLink(searchData[x])
stock = str(findStockAmount(searchData[x]['Stock']))
manufacturer = searchData[x]['Manufacturer']
formattedData.append([partNumber, lowestPrice, vendor, buyLink, datasheet, stock, manufacturer])
print "-----------------Formatted Data-----------------"
pprint.pprint(formattedData)
return formattedData
def findBuyLink(partData):
buyLink = "Not Found"
if 'links' in partData:
for x in range(0, len(partData['links'])):
if (partData['links'][x])['Type'] == 'Buy':
buyLink = partData['links'][x]['Url']
return buyLink
def findStockAmount(stockData):
quantityOnHand = "unknown"
if 'QuantityOnHand' in stockData:
quantityOnHand = stockData['QuantityOnHand']
return quantityOnHand
def findDatasheetLink(partData):
datasheetLink = "Not Found"
if 'links' in partData:
for x in range(0, len(partData['links'])):
if partData['links'][x]['Type'] == 'Datasheet':
datasheetLink = partData['links'][x]['Url']
return datasheetLink
##This Block finds strings in the CSV file that have the new line character and seperates them
def seperatePartNumbers(partNumberField):
partNumbers = []
index = 0
newLine = partNumberField.find('\n', index)
while newLine != -1:
partNumbers.extend({partNumberField[index:newLine]})
index = newLine+1
newLine = partNumberField.find('\n', index)
partNumbers.extend({partNumberField[index:]})
return partNumbers
#Looks for where the partNumbers are in the CSV file
def findPartNumbersIndex(CSVdata):
for x in range(0,len(CSVdata)):
for y in range(0, len(CSVdata[x])):
if CSVdata[x][y] == "Part Number":
return x+1, y
return 0,0
#Looks for where the quantityNeeded numbers are in the CSV file
def findQuantityIndex(CSVdata):
for x in range(0,len(CSVdata)):
for y in range(0, len(CSVdata[x])):
if CSVdata[x][y] == "Quantity":
return y
return 0,0
#--------Compare Excel-BOM Requirements to Search Results------------#
#Returns the length of the Parts
def lengthOfPartResults(decodedData):
return len(decodedData['PartResults'])
#Returns the length of the Parts
def lengthOfDistributors(PartResults):
return len(PartResults['Distributors'])
#Returns the length of the Parts
def lengthOfDistributorResults(Distributors):
return len(Distributors['DistributorResults'])
#This method creates an empty part and returns it
def createNewPart():
newPart = {
'partNumber':"Not Found",
'lowestPrice': 1000000,
'cutOffQuantity': 1000000,
'links':"Not Found",
'Stock':"Not Found",
'Manufacturer':"Not Found",
'Vendor':"Not Found"
}
return newPart
#Creates a new Part from searched data and
#prepares relevant data for writing to file
def newBestPart(currentPart, pricesIndex, vendor):
newPart = {
'partNumber': currentPart['PartNumber'],
'lowestPrice': (((currentPart['Pricing']['Prices'])[pricesIndex])['Amount']),
'cutOffQuantity': (((currentPart['Pricing']['Prices'])[pricesIndex])['Quantity']),
'links': currentPart['Links'],
'Stock': currentPart['Stock'],
'Manufacturer': testForManufacturer(currentPart),
'Vendor': vendor
}
return newPart
def testForManufacturer(part):
if 'Manufacturer' in part:
if part['Manufacturer'] != None:
return part['Manufacturer']
return "Not Found"
#Check if BOM Part Number Matches Distributor Part number
#Only matches half of the part number for less strict search
def BOMPartNumberMatches(DistributorResults, BOMpartNumber):
if 'PartNumber' in DistributorResults:
if len(DistributorResults['PartNumber']) > 2:
halfLength = (len(DistributorResults['PartNumber']))/2
for x in range(0, len(BOMpartNumber)):
if halfLength > len(BOMpartNumber[x]):
print "halfLength is equal to: "+halfLength
halfLength = len(BOMpartNumber[x])
if DistributorResults['PartNumber'][0:halfLength] == BOMpartNumber[x][0:halfLength]:
return True
return False
def testForBuyLinkAvailability(currentPart):
if 'Links' in currentPart:
for x in range(0, len(currentPart['Links'])):
if 'Type' in currentPart['Links'][x]:
if currentPart['Links'][x]['Type'] == 'Buy':
return True
return False
#Checks part prices from a given distributor
#and finds the best cutoff quantity price
#for the based on the quantity needed
def checkPricesAndQuantities(currentPart, bestPart, quantityNeeded, vendor):
if testForBuyLinkAvailability(currentPart):
if (currentPart['Stock'])['QuantityOnHand'] > quantityNeeded:
if 'Pricing' in currentPart:
if 'Prices' in currentPart['Pricing']:
for y in range(0, len(currentPart['Pricing']['Prices'])):
if ((currentPart['Pricing']['Prices'])[y])['Quantity'] <= quantityNeeded and ((currentPart['Pricing']['Prices'])[y])['Quantity'] != 0:
print "-----------Test 1----------"
if bestPart['lowestPrice'] > ((currentPart['Pricing']['Prices'])[y])['Amount']:
print "-----------Test 2----------"
if ((currentPart['Pricing']['Prices'])[y])['Amount'] != 0.0:
print "-----------Test 3----------"
if (type(((currentPart['Pricing']['Prices'])[y])['Amount']) == type(0.0)):
print "-----------Test 4----------"
if (((currentPart['Pricing']['Prices'])[y])['Amount']) != None:
print "-----------Test 5----------"
bestPart = newBestPart(currentPart, y, vendor)
return bestPart
#Iterates through all the data gathered from the
#API query and finds the cheapest part.
def findCheapestPart(decodedData, BOMpartNumber, quantityNeeded):
bestPart = createNewPart()
pprint.pprint(bestPart)
for i in range(0, lengthOfPartResults(decodedData)):
PartResults = (decodedData['PartResults'])[i]
for j in range(0, lengthOfDistributors(PartResults)):
Distributors = (PartResults['Distributors'])[j]
for k in range(0, lengthOfDistributorResults(Distributors)):
DistributorResults = (Distributors['DistributorResults'])[k]
if BOMPartNumberMatches(DistributorResults, BOMpartNumber):
bestPart = checkPricesAndQuantities(DistributorResults, bestPart, quantityNeeded, Distributors['Name'] )
return bestPart
#--------API Server Request Section------------#
def formatPartNumberArray(excelField):
partNumbersArray = []
for x in range(0,len(excelField)):
searchToken = {"SearchToken":excelField[x]}
partNumbersArray.append(searchToken)
return partNumbersArray
def executeSearch(partNumber):
#Establish Global variables needed for making
#POST requests to the ECIA Authorized server
#via the ECIA's API.
Company_ID = 'iRobot'
API_Key = '8e2b4c56-05aa-4ce9-82dc-be9a660bb1ea'
endpoint = 'http://inventory.api.eciaauthorized.com/api/Search/Query'
#Part Queries from any iRobot BOM
query_params = {
"CompanyID": "iRobot",
"APIKey": "8e2b4c56-05aa-4ce9-82dc-be9a660bb1ea",
"CountryCode": "",
"CurrencyCode": "",
"InStockOnly": "false",
"ExactMatch": "false",
"Queries": partNumber
}
header = { 'Content-Type': 'application/json'}
#The request to the ECIA server
response = requests.post(endpoint, data = json.dumps(query_params), headers= header)
#Parsing the response. The data is contained
#in a attribute of the response called 'content'
#response.content is a string
data = response.content
#Changes data from string to python dictionary
decodedData = yaml.safe_load(data)
return decodedData
#--------API Server Request Section------------#
def main():
searchResults = []
CSVdata = CSVMatrix
currentPart, partIndex = findPartNumbersIndex(CSVdata)
quantityIndex = findQuantityIndex(CSVdata)
while (currentPart < len(CSVdata)):
partNumberArray = seperatePartNumbers(CSVdata[currentPart][partIndex])
formattedPartNumberArray = formatPartNumberArray(partNumberArray)
ECIAdata = executeSearch(formattedPartNumberArray)
bestPart = findCheapestPart(ECIAdata, partNumberArray, int(CSVdata[currentPart][quantityIndex]))
searchResults.append(bestPart)
print "-------------Search Results Thus Far--------------"
pprint.pprint(searchResults)
currentPart = currentPart+1
finalPartData = formatSearchResults(searchResults)
writeObjectToFile(finalPartData)
main()