def build_dict_from_table_details(self, table): announcement = {} announcement_detail = {} isFirstRow = True for row in table: if isFirstRow: #if creating a announcement for the first time announcement = {} announcement['ann_id'] = row[0] announcement['date'] = row[1] announcement['supplier'] = Supplier().build_dict_from_row( row[2:11]) announcement['details'] = [] announcement_detail['qty'] = row[11] announcement_detail['price_at_time'] = row[12] announcement_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) isFirstRow = False else: announcement_detail['qty'] = row[11] announcement_detail['price_at_time'] = row[12] announcement_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) announcement['details'].append(announcement_detail) announcement_detail = {} return announcement
def build_dict_from_row(self, row): result = {} result['resource'] = Resource().build_dict_from_row_category(row[0:4]) result['supplier'] = Supplier().build_dict_from_row_region(row[4:10]) result['currentPricePerItem'] = row[10] result['qty'] = row[11] return result
def build_dict_from_table(self, table): transaction = {} transaction_detail = {} isFirstRow = True for row in table: if isFirstRow: #if creating a transaction for the first time transaction = {} transaction['transactionId'] = row[0] transaction['total'] = row[1] transaction['purchaseId'] = row[2] transaction['supplier'] = Supplier().build_dict_from_row( row[3:11]) transaction['details'] = [] transaction_detail['qty'] = row[11] transaction_detail['purchase_price'] = row[12] transaction_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) isFirstRow = False else: transaction_detail['qty'] = row[11] transaction_detail['purchasePrice'] = row[12] transaction_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) transaction['details'].append(transaction_detail) transaction_detail = {} return transaction
def getSupplierById(self, sid): dao = SuppliersDAO() row = dao.getSupplierById(sid) if not row: return jsonify(Error="Supplier Not Found"), 404 else: supplier = Supplier().build_dict_from_row(row) return jsonify(supplier)
def getAllSuppliers(self): dao = SuppliersDAO() suppliers_list = dao.getAllSuppliers() result_list = [] for row in suppliers_list: supplier = Supplier().build_dict_from_row(row) result_list.append(supplier) return jsonify(result_list)
def update_supplier(id): name = request.form["name"] address = request.form["address"] phone_number = request.form["phone_number"] product = request.form["product"] supplier = Supplier(name, address, phone_number, product, id) supplier_repository.update(supplier) return redirect("/suppliers")
def create_supplier(): name = request.form['name'] address = request.form['address'] phone_number = request.form['phone_number'] product = request.form['product'] supplier = Supplier(name, address, phone_number, product) supplier_repository.save(supplier) print("SYHHKJTLKTLTLY", supplier) return redirect('/suppliers')
def select(id): supplier = None sql = "SELECT * FROM suppliers WHERE id = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: supplier = Supplier(result["name"], result["address"], result["phone_number"], result["product"], result["id"]) return supplier
def select_all(): suppliers = [] sql = "SELECT * FROM suppliers" results = run_sql(sql) for row in results: supplier = Supplier(row["name"], row["address"], row["phone_number"], row["product"], row["id"]) suppliers.append(supplier) return suppliers
def insert(self, form): if len(form) != 1: return jsonify(Error="Malformed post request"), 400 else: uid = form['uid'] if uid: dao = UsersDAO() if not dao.getUserById(uid): return jsonify(Error="User not found"), 404 dao = SuppliersDAO() sid = dao.insert(uid) result = Supplier().build_dict_from_row( dao.getSupplierById(sid)) return jsonify(result) else: return jsonify( Error="Unexpected attributes in post request"), 400
def build_dict_from_table_detailed(self, table): purchase = {} transaction = {} currentTransaction = None isCurrentTransaction = False isFirstRow = True for row in table: if isFirstRow: #Purchase Object purchase['purchaseId'] = row[0] purchase['date'] = row[1] purchase['total'] = row[2] purchase['paymentInfo'] = PaymentInfo().build_dict_from_row( row[3:7]) purchase['transactions'] = [] isFirstRow = False if not currentTransaction or row[7] != currentTransaction: if currentTransaction: purchase['transactions'].append(transaction) transaction = {} transaction['tid'] = row[7] transaction['transactionammount'] = row[8] transaction['supplier'] = Supplier().build_dict_from_row( row[9:17]) transaction['details'] = [] currentTransaction = transaction['tid'] if row[7] == currentTransaction: ############## detail = {} detail['resource'] = Resource().build_dict_from_row_category( row[17:21]) detail['qty'] = row[21] detail['purchasePrice'] = row[22] transaction['details'].append(detail) purchase['transactions'].append(transaction) return purchase
def searchSuppliers(self, args): # Query parameters allowed when searching # These parameters are from Resource, Category and Stock allowed_keys = {"rid", "rname", "catid", "catname", "region", "city"} allowed_range_keys = {"qtysum", "currentpriceperitem", "zipcode"} # Allow every query parameter stated in allowed_keys to have a min or max value max_and_min_keys = set() for key in allowed_range_keys: max_and_min_keys.add("max-" + key) max_and_min_keys.add("min-" + key) allowed_keys = allowed_keys.union(max_and_min_keys) allowed_keys = allowed_keys.union(allowed_range_keys) # Divide the args given by user into min, max and equal parameters for use in DAO max_args = {} min_args = {} equal_args = {} for key in args.keys(): if key in allowed_keys and key[0:4] == "max-": max_args[key[4:]] = args[key] elif key in allowed_keys and key[0:4] == "min-": min_args[key[4:]] = args[key] elif key not in allowed_keys: return jsonify(Error="Malfromed query string"), 400 else: equal_args[key] = args[key] # Get all the results for the search dao = SuppliersDAO() suppliers_list = dao.getSuppliersByResourceParams( equal_args, max_args, min_args) result_list = [] for row in suppliers_list: supplier = Supplier().build_dict_from_row_stock(row) result_list.append(supplier) return jsonify(result_list)
import pdb from models.product import Product from models.supplier import Supplier import repositories.product_repository as product_repository import repositories.supplier_repository as supplier_repository product_repository.delete_all() supplier_repository.delete_all() supplier1 = Supplier("Timothy Taylors", "Knowle Spring Brewery, Keighley", "01535-555-555", "Landlord") supplier_repository.save(supplier1) supplier2 = Supplier("ABV Wholesale", "Dalton Lane, Keighley", "01535-699-699", "Budvar") supplier_repository.save(supplier2) supplier3 = Supplier("Premier Cru", "Ballpark Road, Shipley", "01274-545-667", "Chenin Blanc") supplier_repository.save(supplier3) supplier_repository.select_all() product1 = Product("Landlord", "Draught", 12, 1.23, 70, 2.09, "A Strong Pale Ale", 36, supplier1) product_repository.save(product1) product2 = Product("Budvar", "Bottles", 24, 2.20, 70, 3.74, "A Czech Pilsner", 24, supplier2) product_repository.save(product2)
def main(agrv = list()): projectLocation = '/home/pavel/code/python/gos_zak_analitics/goszak/' addpath(projectLocation) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "goszak.settings") setConsoleEncoding() checkMissingValues() from searchForm import searchForm as SearchFormParser from purchase import Purchase as PurchasepageParser from protocol import Protocol as ProtocolPageParser from models.customer import Organization, Person, Staff, PurchaseStaff from models.purchase import Purchase, Lot, PurchaseMethod from models.supplier import Supplier, Bet, PurchaseResult from okvedData.models.okdpCodes import OKDPCodes from okvedData.models.okvedCodes import OkvedCodes from django.core.exceptions import ObjectDoesNotExist pageLimit = 2 purchasseStage = "PLACEMENT_COMPLETE" ######################################## ## GET PURCHASE LIST FROM SEARCH FORM ## ######################################## searchPageparcer = SearchFormParser() #pageLimit = searchPageparcer.totalPagesCount() + 1 print(searchPageparcer.totalPagesCount()) for url, _purchaseMethod, published, _startPrice, lastModified \ in searchPageparcer.allPurchaseFor(purchaseStage=purchasseStage, startPage=1, pagelimit=pageLimit): ########################################### ## PARSE PURCHASE PAGE AND GET INFO DICT ## ## [Общие сведения о закупке] ## ## [Заказчик] ## ## [Контактное лицо] ## ## ## ## VALUES ## ## [Предоставление документации] ## ## [Порядок размещения закупки] ## ## RETURNS BUT ARE IGNORED ## ########################################### purchasePageParser = PurchasepageParser(url) resDict = purchasePageParser.purchaseInfo() ######################################## ## PARSE PURCHASE INFO DICT WITH KEY ## ## [Общие сведения о закупке] ## ######################################## values = resDict.get(u"Общие сведения о закупке") name = values.get(u"Наименование закупки") noticeNumber = values.get(u"Номер извещения") purchaseMethod = values.get(u"Способ размещения закупки").lower() edition = values.get(u"Редакция") try: purchaseMethodObj = PurchaseMethod.objects.get(name=purchaseMethod) except ObjectDoesNotExist: purchaseMethodObj = PurchaseMethod(name=purchaseMethod) purchaseMethodObj.save() try: print("Purchase %s" % noticeNumber) purchaseObj = Purchase.objects.get(noticeNumber=noticeNumber, url=url) if purchaseObj.stage != purchasseStage: purchaseObj.stage = purchasseStage purchaseObj.lastModified = lastModified print("\tExists") except ObjectDoesNotExist: print("\tNOT Exists") purchaseObj = Purchase(noticeNumber=noticeNumber , name=name , url=url , edition=edition , stage=purchasseStage , method_fk=purchaseMethodObj , publishDate=published , lastModified=lastModified) purchaseObj.save() ######################################## ## PARSE PURCHASE INFO DICT WITH KEY ## ## [Заказчик] ## ######################################## values = resDict.get(u"Заказчик") INN, KPP = (x.strip() for x in values.get(u"ИНН \ КПП").split("\\")[0:2]) try: print("Organization %s %s" % (INN, KPP)) organization = Organization.objects.get(INN=INN, KPP=KPP) print("\tExists") except ObjectDoesNotExist: print("\tNOT Exists") print("FIRST RUN \"OrganizationSearchForm.py\" to upload new companies") raise SystemExit() ######################################## ## PARSE PURCHASE INFO DICT WITH KEY ## ## [Контактное лицо] ## ######################################## values = resDict.get(u"Контактное лицо", "") FIO = values.get(u"Контактное лицо") FIO = FIO if len(FIO) > 0 else None email = values.get(u"Электронная почта", "") email = email if len(email) > 0 else None telephone = values.get(u"Телефон", "") telephone = telephone if len(telephone) > 0 else None fax = values.get(u"Факс") fax = fax if len(fax) > 0 else None try: print("Customer Person %s" % FIO) person = Person.objects.get(FIO=FIO, email=email, telephone=telephone, fax=fax) print("\tExists") except ObjectDoesNotExist: print("\tNOT Exists") person = Person(FIO=FIO, email=email, telephone=telephone, fax=fax) person.save() ############################################ ## MATCH ORGANIZATION AND CONTACT PERSON ## ############################################ try: print("Staff") staff = Staff.objects.get(organization_fk=organization, person_fk=person) print("\tExists") except ObjectDoesNotExist: print("\tNOT Exists") staff = Staff(organization_fk=organization, person_fk=person) staff.save() pass ############################### ## MATCH PURCHASE AND STAFF ## ############################### try: purchaseStaffObj = PurchaseStaff.objects.get(purchase_fk=purchaseObj, staff_fk=staff) except ObjectDoesNotExist: purchaseStaffObj = PurchaseStaff(purchase_fk=purchaseObj, staff_fk=staff) purchaseStaffObj.save() pass ################### ### GET LOT LIST ## ################### for lot in purchasePageParser.getLotList(): priceParams = lot.get(u"Начальная (макс.) цена договора") joint = lot.get(u"Совместная закупка") name = lot.get(u"Наименование лота") OKVEDstr = lot.get(u"Классификация по ОКВЭД") OKDPstr = lot.get(u"Классификация по ОКДП") valstr = ''.join([x for x in priceParams if x in '0123456789.,']) priceValue = float(valstr.replace(',', '.')) # TODO Add MONEY FIELD to BET priceCurrency = priceParams[len(valstr):].strip() joint = False if joint == u"Нет" else True OKVED = OKVEDstr.split()[0] OKDP = OKDPstr.split()[0] print("OKVED %s OKDP %s" % (OKVED, OKDP)) try: OKVEDObj = OkvedCodes.objects.get(code=OKVED) except ObjectDoesNotExist: OKVEDObj = OkvedCodes(code=OKVED, description=OKVEDstr[len(OKVED)].strip(), parent=None) OKVEDObj.save() try: OKDPObj = OKDPCodes.objects.get(code=OKDP) except ObjectDoesNotExist: print("\tOKDP Code %s not found.Saved" % OKDP) OKDPObj = OKDPCodes(code=OKDP, description=OKDPstr[len(OKDP):].strip()) OKDPObj.save() try: print("LOT %s" % name) lotObj = Lot.objects.get(name=name, purchase_fk=purchaseObj) print("\tFound") except ObjectDoesNotExist: print("\tNot Found") lotObj = Lot(name=name , joint=joint \ , startPrice=priceValue \ , OKVED_fk=OKVEDObj \ , OKDP_fk=OKDPObj , purchase_fk=purchaseObj) lotObj.save() ############################## ## CHECK IF PROTOCOL EXISTS ## ############################## protocolparam = purchasePageParser.getLastProtocolUrl() print("Protocol") if protocolparam is not None: print("\tFound") protocolPageParser = ProtocolPageParser(protocolparam) for applicant in protocolPageParser.getFullResult(): applicantParams = applicant.get(u"Участник") if applicantParams is None: ## NO APPLICANTS ## print("\tNo applicants -> Next") break priceParams = applicant.get(u"Предложенная цена договора") publicTime = applicant.get(u"Дата и время получения заявки") admission = applicant.get(u"Допуск") place = applicant.get(U"Результат") isLegalEntity = applicant.get(u"Юридическое лицо") isIndividual = applicant.get(u"Физическое лицо") notRussianResident = applicant.get(u"Не резидент") try: innIndex = applicantParams.index(u"ИНН") INN = ''.join(x for x in applicantParams[innIndex:] if x.isdigit()) innValueEnd = applicantParams.index(INN) + len(INN) applicantParams = applicantParams[0: innIndex] + applicantParams[innValueEnd:] except ValueError: INN = u"" try: KPPIndex = applicantParams.index(u"КПП") KPP = ''.join(x for x in applicantParams[KPPIndex:] if x.isdigit()) KPPValueEnd = applicantParams.index(KPP) + len(KPP) applicantParams = applicantParams[0: KPPIndex] + applicantParams[KPPValueEnd:] except ValueError: KPP = u"" name = applicantParams.strip() ########################### ## GET APPLICANT COMPANY ## ########################### try: print("Applicant %s" % name) if notRussianResident: supplierObj = Supplier.objects.get(name=name, notRussianResident=notRussianResident) else: if isLegalEntity: supplierObj = Supplier.objects.get(INN=INN, KPP=KPP) else: supplierObj = Supplier.objects.get(name=name) print("\tFound") except ObjectDoesNotExist: print("\tNOT Found") supplierObj = Supplier(INN=INN\ , KPP=KPP\ , name=name\ , isLegalEntity=isLegalEntity\ , isIndividual=isIndividual\ , notRussianResident=notRussianResident) supplierObj.save() ####################### ## GET APPLICANT BET ## ####################### try: print("BET") betObj = Bet.objects.get(supplier_fk=supplierObj, purchase_fk=purchaseObj) print("\tFound") except ObjectDoesNotExist: valstr = ''.join([x for x in priceParams if x in '0123456789.,']) priceValue = float(valstr.replace(',', '.')) # TODO Add MONEY FIELD to BET priceCurrency = priceParams[len(valstr):].strip() print("\tNot Found with value %s" % priceValue) betObj = Bet(value=priceValue, supplier_fk=supplierObj, purchase_fk=purchaseObj) betObj.save() ################### ## GET BET PLACE ## ################### try: print("BET PLACE") placeObj = PurchaseResult.objects.get(bet_fk=betObj) print("\tfound") except ObjectDoesNotExist: print("\tNOT found with place %s" % place) placeObj = PurchaseResult(bet_fk=betObj, admission=admission, place=place) placeObj.save() ############# ## SKIPPED ## ############# #values = resDict.get(u"Предоставление документации") #values = resDict.get(u"Порядок размещения закупки") print("\n")
def setUp(self): self.supplier = Supplier("Timothy Taylors", "Knowle Spring Brewery, Queens Road, Keighley", "01535605506", "Landlord" )