Guest User

Untitled

a guest
Apr 23rd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.94 KB | None | 0 0
  1. """This module reads a spreadsheet of products from shop and defines their properties.
  2. Everything is based on our custom spreasheed with a given format.
  3. Every line of sheet corresponds to one product which will be saved as instance ouf our defined class Item.
  4. With these atributes and methods we can create various features in the final app. Such as selling/adding products, or
  5. exporting all missing products from stock to a list etc...
  6. """
  7. import gspread
  8. from oauth2client.service_account import ServiceAccountCredentials
  9.  
  10. from datetime import date
  11.  
  12. import unidecode
  13.  
  14.  
  15. class Item(object):
  16. """Every instance of this class will correspond to one product from our spreadsheet.
  17.  
  18. This spreadsheet is made from multiple sheets, with diffrent kind of products. Every sheet is in the same format.
  19. Name of the product is in the first column, second - prices of one piece, third - bonus for salesman, forth is the amount
  20. of items in stock.
  21.  
  22. Reading and writing to these sheets is done by Google Spreadsheet API(gspread)
  23. """
  24. @staticmethod
  25. def open_spreadsheet():
  26. """This method returns opened spreadsheet as instance of class defined by gspread"""
  27. scope = ['https://spreadsheets.google.com/feeds']
  28. credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
  29. gspread_creds = gspread.authorize(credentials)
  30. spreadsheet = gspread_creds.open_by_key('1m0Vhn2eDaGDAh5XcUzUvw2LCbHlHkju_bVnWsu60kW4')
  31. return spreadsheet
  32.  
  33. @classmethod
  34. def get_all_items(cls):
  35. """Reads all sheets and returns dictionary of all products.
  36.  
  37. Key is name of product in lowercase and with no special charcaters for easier accesing.
  38. The value of every key is a instance of this class.
  39. """
  40. spreadsheet = cls.open_spreadsheet()
  41. all_items = {}
  42. for index, worksheet in enumerate(spreadsheet.worksheets()): # Works for any number of sheets in spreadsheet.
  43. whole_list_of_cells = worksheet.range(2, 1, worksheet.row_count, 4) # First row has only titles of colmuns so its not included.
  44. for x in range(0, len(whole_list_of_cells), 4):
  45. if whole_list_of_cells[x + 3].value: # This avoids empty rows
  46. all_items[unidecode.unidecode(whole_list_of_cells[x].value).lower()] =
  47. cls.get_item_from_list(whole_list_of_cells[x:x + 4], index)
  48. return all_items
  49.  
  50. @classmethod
  51. def get_item_from_list(cls, list_of_cells, index_of_worksheet):
  52. """A custom constructor which returns instance of this class from row of 4 cells used by get_all_items clsmethod"""
  53. name = list_of_cells[0].value
  54. price = list_of_cells[1].value
  55. bonus = list_of_cells[2].value
  56. quantity = list_of_cells[3].value
  57. row = list_of_cells[0].row
  58. return cls(name, price, bonus, quantity, row, index_of_worksheet)
  59.  
  60. def __init__(self, name, price, bonus, quantity, row, index_of_worksheet):
  61. self.name = name
  62. self.price = get_digit_from_str(price)
  63. self.bonus = get_digit_from_str(bonus)
  64. self.quantity = int(quantity)
  65. self.row = row
  66. self.index_of_worksheet = index_of_worksheet
  67.  
  68. def __repr__(self):
  69. return "Item(name = {}, price = {}, bonus = {}, "
  70. "quantity = {}, row = {}, index = {})".format(self.name, self.price, self.bonus, self.quantity,
  71. self.row, self.index_of_worksheet)
  72.  
  73. def __str__(self):
  74. return "{} - price: {},- Czk, bonus {},- Czk, quantity: {}.".format(self.name, self.price, self.bonus,
  75. self.quantity)
  76.  
  77. def sell(self, number_of_sold_items=1):
  78. """Method used when we sell a product.
  79.  
  80. Updates the amount of items in stock(quantity) of the particular product and writes updated amount to the sheet.
  81. Also records when and how much we sold to the sheet to the rightmost column.
  82. """
  83. spreadsheet = self.open_spreadsheet()
  84. worksheet = spreadsheet.get_worksheet(self.index_of_worksheet)
  85. if self.quantity - number_of_sold_items < 0:
  86. raise ValueError("There aren't enough items in stock.")
  87. else:
  88. self.quantity -= number_of_sold_items
  89. worksheet.update_cell(self.row, 4, self.quantity)
  90. self.update_history_of_changes(-number_of_sold_items, worksheet)
  91.  
  92. def add(self, number_of_added_items=1):
  93. """Method used when we add a items of product to stock. See docstring of method sell for additional info"""
  94. self.quantity += number_of_added_items
  95. spreadsheet = self.open_spreadsheet()
  96. worksheet = spreadsheet.get_worksheet(self.index_of_worksheet)
  97. worksheet.update_cell(self.row, 4, self.quantity)
  98. self.update_history_of_changes(number_of_added_items, worksheet)
  99.  
  100. def update_history_of_changes(self, change, worksheet):
  101. """Records the changes made to the amount of items at stock in one day.
  102.  
  103. Creats a new column with current date at first cell. And below the changes to corresponding products.
  104. This change can be modified throughout the day, but only the final change will be stored at the end of the day.
  105. """
  106. index_of_last_nonempty_col = len(worksheet.row_values(1))
  107. current_date = "{}.{}.".format(date.today().day, date.today().month)
  108. if worksheet.cell(1, index_of_last_nonempty_col).value != current_date:
  109. if index_of_last_nonempty_col == worksheet.col_count:
  110. worksheet.add_cols(1)
  111. index_of_last_nonempty_col += 1
  112. worksheet.update_cell(1, index_of_last_nonempty_col, current_date)
  113. curr_value = (int(worksheet.cell(self.row, index_of_last_nonempty_col).value)
  114. if worksheet.cell(self.row, index_of_last_nonempty_col).value.strip() else 0)
  115. worksheet.update_cell(self.row, index_of_last_nonempty_col, str(curr_value + change))
Add Comment
Please, Sign In to add comment