Beispiel #1
0
 def get(self, cart_number=None):
     result = {}
     if cart_number is not None:
         cart_number = int(cart_number)
         result = {'purchases': Purchase.todaysPurchases(cart_number)}
     else:
         result = {'purchases': Purchase.todaysPurchases()}
     self.renderJson(result)
Beispiel #2
0
def main(options, cookies):
    # build a object for purchasing.
    pc = Purchase(options, cookies)
    # print (pc.good_stock())
    # print (pc.good_price())
    # pc.good_detail()
    pc.cart_detail()
    pass
Beispiel #3
0
def main():
    annual_rent = input("Property Annual Rent: ")
    property_tax_rate = input("Property Tax Rate: ")

    property_tax_rate /= 100.0
    myProperty = Property(annual_rent=annual_rent, tax_rate=property_tax_rate)

    equity = input("Equity: ")
    closing_costs = input("Closing Costs: ")
    debt_amount = input("Debt Amount: ")
    interest_rate = input("Interest Rate: ")
    interest_rate /= 100.0

    term = input("Term: ")
    myPurchase = Purchase(equity=equity,
                          closing_cost=closing_costs,
                          debt_amount=debt_amount,
                          interest_rate=interest_rate,
                          term=term)

    duration = input("Duration: ")
    rental_rate_increase_percent = input("Rental rate increase %: ")
    rental_rate_increase_percent /= 100.0

    rental_rate_occupancy = input("Rental rate occupancy: ")
    rental_rate_occupancy /= 100.0

    tax_rate_increase_percent = input("Tax Rate increase %: ")
    tax_rate_increase_percent /= 100.0

    home_appreciation_annual_percent = input("Home Appreciation Annual %: ")
    home_appreciation_annual_percent /= 100.0

    maintainance_cost_annual_percent = input("Maintainance Cost Annual %: ")
    maintainance_cost_annual_percent /= 100.0

    insurance_cost_percent = input("Insurance Cost %: ")
    insurance_cost_percent /= 100.0

    exit_closing_costs = input("Exit Closing Cost: ")
    myPropertyPerformace = PropertyPerformance(
        duration, rental_rate_increase_percent, rental_rate_occupancy,
        tax_rate_increase_percent, home_appreciation_annual_percent,
        maintainance_cost_annual_percent, insurance_cost_percent,
        exit_closing_costs)

    print "Upfront Costs: ", myPurchase.upfront_costs()
    print "Total Rental Revenue: ", total_rental_revenue(
        myProperty, myPropertyPerformace)
    print "Home Exit value: ", home_exit_value(myPurchase,
                                               myPropertyPerformace)
    print "Total Taxes Paid: ", total_taxes_paid(myProperty, myPurchase,
                                                 myPropertyPerformace)
    print "Total Mainatainance: ", total_maintainance_spend(
        myPurchase, myPropertyPerformace)
    print "Total Insurance: ", total_insurance_costs(myPurchase,
                                                     myPropertyPerformace)
 def menu():
     os.system('clear')
     while True:
         choice = Menu.display_menu(sentence="votre choix: ", menu="first")
         if choice == "voir les achats en cours":
             Purchase.false_purchase()
         elif choice == "commencer un achat":
             Purchase.record_purchase_product()
         elif choice == "explorer des données":
             print(" vous voulez explorer les donnée enregistrée en base")
         else:
             break
Beispiel #5
0
    def get_purchase(self, order_id, date_mail):
        ''' returns Order object '''
        try:
            query = "SELECT * FROM Purchase WHERE id = ? AND mail_date = ?"
            values = (str(order_id), date_mail)
            self.cursor.execute(query, values)
            info_purchase = self.cursor.fetchall()[0]
        except Exception as e:
            print("Error on get_purchase(" + str(order_id) + ") : ", str(e))
            return

        try:
            order = Purchase(info_purchase[0])
            order.set_purchase_date_order(
                info_purchase[1]).set_purchase_date_mail(info_purchase[2])
            order.set_purchase_client(info_purchase[3]).set_purchase_reference(
                info_purchase[4])

            self.cursor.execute(
                "SELECT * FROM PurchaseList WHERE order_id = " + str(order_id))
            info_articles = self.cursor.fetchall()

            for article_data in info_articles:
                article_object = self.get_article(article_data[1])
                order.add_articles([(article_object, article_data[2],
                                     article_data[3])])

            return order
        except Exception as e:
            print("Error on get_purchase(" + str(order_id) + ") : ", str(e))
            return
Beispiel #6
0
    def from_xml(cls, xml_doc):
        from add_payment_method import AddPaymentMethod
        from purchase import Purchase
        from retain_payment_method import RetainPaymentMethod
        from redact_payment_method import RedactPaymentMethod
        from redact_gateway import RedactGateway

        transaction_type = xml_doc.xpath('.//transaction_type')[0].text

        if transaction_type == 'AddPaymentMethod':
            return AddPaymentMethod(xml_doc)
        elif transaction_type == 'Purchase':
            return Purchase(xml_doc)
        elif transaction_type == 'Authorization':
            #return Authorization.from_xml(xml_doc)
            pass
        elif transaction_type == 'Capture':
            #return Capture.from_xml(xml_doc)
            pass
        elif transaction_type == 'Credit':
            #return Refund.from_xml(xml_doc)
            pass
        elif transaction_type == 'Void':
            #return Void.from_xml(xml_doc)
            pass
        elif transaction_type == 'RetainPaymentMethod':
            return RetainPaymentMethod(xml_doc)
        elif transaction_type == 'RedactPaymentMethod':
            return RedactPaymentMethod(xml_doc)
        elif transaction_type == 'RedactGateway':
            return RedactGateway(xml_doc)
        else:
            #TODO Need to understand what is happening here.
            pass
def load_file(filename):
    purchases = []
    with open(filename, 'r', encoding='utf-8') as infile:
        reader = csv.DictReader(infile)
        for row in reader:
            p = Purchase.create_from_dict(row)
            purchases.append(p)
    return purchases
Beispiel #8
0
def friends_purchase_tag_similarity():
    # get result set
    result = Purchase().friends_purchase_tag_similarity(
        graph_db, request.get_cookie(graphstoryUserAuthKey))
    return template(
        'public/templates/graphs/intent/index.html',
        layout=applayout,
        title="Products Purchased by Friends and Matches User's Tags",
        mappedProductUserPurchaseList=result)
 def insert_purchase(self, product_id, date_time):
     try:
         purchase = Purchase(product_id, date_time)
         self.session.add(purchase)
         self.session.commit()
         if id is not None or id != 0:
             return [True, purchase]
     except SQLAlchemyError as e:
         return [False, e]
Beispiel #10
0
 def asDict(self):
     d = {
         'name': self.name,
         'dob': self.dob,
         'phone': self.phone,
         'card_number': self.card_number,
         'points': self.points,
         'vip_status': Purchase.findDiscountStatus(self)[0]
     }
     return d
Beispiel #11
0
def load_file(filename):
    with open(filename, 'r', encoding='utf-8') as fin:
        # Refactored using DictReader
        reader = csv.DictReader(fin)
        purchases = []
        for row in reader:
            p = Purchase.create_from_dict(row)
            purchases.append(p)

        return purchases
Beispiel #12
0
def friends_purchase_by_product():
    # get or use default product title
    producttitle = request.query.producttitle or 'Star Wars Mimobot Thumb Drives'
    # get result set
    result = Purchase().friends_purchase_by_product(
        graph_db, request.get_cookie(graphstoryUserAuthKey), producttitle)
    return template('public/templates/graphs/intent/index.html',
                    layout=applayout,
                    title="Specific Products Purchased by Friends",
                    mappedProductUserPurchaseList=result,
                    producttitle=producttitle)
Beispiel #13
0
 def prompt_init():
     """
     This method calls the parent methods prompt_init(), which
     asks user to initialize appropriate instances of classes House
     and Purchase.
     :return: an instance which represents house for rent - inherits
     from House and Purchase.
     """
     init = House.prompt_init()
     init.update(Purchase.prompt_init())
     return init
Beispiel #14
0
 def prompt_init():
     """
     This method calls the parent methods prompt_init(), which
     asks user to initialize appropriate instances of classes Apartment
     and Purchase.
     :return: an instance which represents an apartment for purchasing -
     inherits from Apartment and Purchase.
     """
     init = Apartment.prompt_init()
     init.update(Purchase.prompt_init())
     return init
Beispiel #15
0
    def prompt_init():
        init = House.prompt_init()
        init.update(Purchase.prompt_init())

        return init


#Sets the prompt to set de values
#init = HousePurchase.prompt_init()
#print(init)

#with the data setted, instance a object and sets
# the data(**) by the constructor
#house = HousePurchase(**init)
#print(house.__dict__, '--->')

#show data for a purchase house
#house.display()
Beispiel #16
0
    def prompt_init():
        init = Apartment.prompt_init()
        init.update(Purchase.prompt_init())

        return init


#Sets the prompt to set de values
#init = ApartmentPurchase.prompt_init()
#print(init)

#with the data setted, instance a object and sets
# the data(**) by the constructor
#apartment = ApartmentPurchase(**init)
#print(Apartment.__dict__, '--->')

#show data for a Purchase Apartment
#apartment.display()
Beispiel #17
0
def friends_purchase_tag_similarity_and_proximity_to_location():
    # get user location
    userlocations = UserLocation().get_user_location(
        graph_db, request.get_cookie(graphstoryUserAuthKey))
    # use first location
    ul = userlocations[0]

    # get result set
    result = Purchase(
    ).friends_purchase_tag_similarity_and_proximity_to_location(
        graph_db, request.get_cookie(graphstoryUserAuthKey),
        UserLocation().get_lq_distance_set(ul))

    return template(
        'public/templates/graphs/intent/index.html',
        layout=applayout,
        title="Products Purchased by Friends Nearby and Matches User's Tags",
        mappedProductUserPurchaseList=result,
        mappedUserLocation=userlocations)
Beispiel #18
0
import sys
sys.path.append('./common')  #required so that i can import my modules
sys.path.append('./model')
from item import Item
from purchase import Purchase
from client import Client
from credit import Credit
import json

cred = json.load(open('../cred.json'))
creditCard = Credit(cred)
# Client(credit)
eduardo = Client(creditCard, '*****@*****.**', '1234567890')
# Item (name, color, size, item_type)
item = Item('Duffle Bag', 'Dark Orange', 'XLarge', 'bags')
# page reload frequency
frequency = 5
bot = Purchase(item, eduardo, frequency)
bot.start()


def test(bot):
    print('keep alive')
Beispiel #19
0
def historyExtended(purchaseid):
    return Purchase(helper).historyExtended(purchaseid)
Beispiel #20
0
    def prompt_init():
        init = Apartment.prompt_init()
        init.update(Purchase.prompt_init())

        return init
Beispiel #21
0
def buy():
    return Purchase(helper).buy()
Beispiel #22
0
def history():
    return Purchase(helper).getHistory()
Beispiel #23
0
    def post(self):
        #log.debug("PurchaseHandler")
        have_error = False
        params = {}
        try:
            params = json_util.decodeDict(json.loads(self.request.body))
        except ValueError:
            self.error(400)
            self.renderJson(
                {'error': "The information provided was incomplete."})

        if not 'card_number' in params.keys():
            params['error_card_number'] = "No vip card number provided."
            have_error = True
        else:
            self.customer = Customer.byID(params["card_number"])
            if not self.customer:
                params[
                    'error_card_number'] = "The vip card number provided does not exist."
                have_error = True

        self.order_list = []
        if not 'item_list' in params.keys() or len(params['item_list']) == 0:
            params['error_items'] = "No list of items was provided."
            have_error = True
        else:
            error_items = "Invalid item ID provided:"
            have_item_error = False
            for itemID in params['item_list']:
                item = Item.byID(itemID)
                if not item:
                    error_items = error_items + " " + str(itemID) + ","
                    have_item_error = True
                else:
                    self.order_list.append(item)
            if have_item_error:
                params['error_items'] = rstrip(error_items, ',')
                have_error = True

        if not 'cart_number' in params.keys():
            params[
                'error_cart_num'] = "The cart number where this order was placed was not provided."
            have_error = True

        if have_error:
            params['error'] = "The information provided was incomplete."
            self.error(400)
            self.renderJson(params)

        else:
            purcahse = Purchase.newPurchase(self.customer, self.order_list,
                                            params["cart_number"])
            if purcahse:
                result = {
                    "complete": "Order successfully added.",
                    "purchase": purcahse.asDict()
                }
                self.renderJson(result)
            else:
                params[
                    'error'] = "There was an error while completing the order."
                self.error(400)
                self.renderJson(params)
Beispiel #24
0
def checkout():
    return Purchase(helper).checkout()
 def prompt_init():
     init = House.prompt_init()
     init.update(Purchase.prompt_init())
     return init 
Beispiel #26
0
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")
Beispiel #27
0
 def create():
     Purchase.create()
     Product.create()
     Purchase_product.create()
     Store.create()
from users import User, Admin
from stock import StockItem, Inventory
from purchase import Purchase
from money import Money

from datetime import datetime

# (("fanta", 2), ("sprite", 3))

# ________________________program logic_________________________#

fanta = StockItem("fanta", 0, 120, 248, "Orange juice")
fanta = StockItem("fanta2", 0, 1220, 224, "2Orange juice")

sprite = StockItem("sprite", 0, 120, 24, "sweet water😅")
print(Purchase.preview(Purchase, "fanta", "sprite", "Bobo"))

r = Purchase((("fanta", 18), ("sprite", 1)))
print(r.total)
# r2 = Purchase.preview(Purchase,"dud","fanta", "sprite")
# r3 = Purchase.preview(Purchase,"dud","fanta","fanta", "sprite")

# Money = Money(2300)

# Money.update(1200, "Used to restock")

# print(Money.money_history)
# Money.update(-1200, "given to manager")
# print(Money.money_history)

ADMIN = User("ADMIN", "ADMIN")
Beispiel #29
0
def parse_receipt(raw_text):
    purchases = []
    raw_text_lines = raw_text.split("\n")
    items = [
        " ".join(a.split()[1:]) for a in re.findall("(?=\d+\. ).*", raw_text)
    ]

    for i, it in enumerate(items):
        weight_search_result = re.search("\d+(\.d+)?\ ?(к?гр?|м?л|шт)", it)
        if weight_search_result:
            weight_start, weight_end = weight_search_result.span()
            name = it[:weight_start].strip()
            *_, weight, measurement = re.split("(\d+)",
                                               it[weight_start:weight_end])
            weight = float(weight.strip())
            try:
                measurement, to_divide = normalize_measurement(
                    measurement.strip())
                weight /= to_divide
            except UnrecognizedMeasurement as e:
                print(e)
                measurement = ITEMS_CODE
        else:
            # weighted item, but ask user
            name = it
            measurement = KILOGRAMM_CODE
            weight = None

        if i < len(items) - 1:
            i1, i2 = find_line(raw_text_lines,
                               items[i]), find_line(raw_text_lines,
                                                    items[i + 1])
        else:
            i1, i2 = find_line(raw_text_lines, items[i]), len(raw_text_lines)
        if i1 is not None and i2 is not None:
            metadata = list(filter(lambda x: x, raw_text_lines[i1 + 1:i2]))
            quantity_line = metadata[0].split('x')[1].strip()
            full_price = float(
                quantity_line.split('=')[1].strip().replace(",", "."))
            quantity = float(
                quantity_line.split('=')[0].strip().replace(",", "."))
            if len(metadata) > 1:
                full_price -= float(metadata[1].split(":")[1].strip().replace(
                    ",", "."))

            if weight is None:
                if quantity == 1:
                    # TODO: suspicious, possibly it's pieces and it might not be one, ask user
                    measurement = ITEMS_CODE
                weight = quantity
                full_weight = weight
            else:
                if measurement == ITEMS_CODE:
                    # TODO: multiply by weight of one piece
                    pass
                full_weight = quantity * weight
#             print(f"Name: {name}, Weight: {weight} {code2name[measurement]}, "
#                   f"Quantity: {quantity}, Full weight: {full_weight} {code2name[measurement]} Full price: {full_price}")
            purchases.append(
                Purchase(name, weight, measurement, quantity, full_weight,
                         full_price))
    return purchases