Fill ``headers`` and ``cost_items`` based on data from csv file.
(self)
| 144 | self.create_cost_items(self.cost_items) |
| 145 | |
| 146 | def parse_csv(self) -> None: |
| 147 | """Fill ``headers`` and ``cost_items`` based on data from csv file.""" |
| 148 | self.cost_items = [] |
| 149 | self.headers = {} |
| 150 | |
| 151 | parents: dict[int, CostItem] = {} |
| 152 | locale.setlocale(locale.LC_ALL, "") # set the system locale |
| 153 | |
| 154 | # TODO: 25-04-17 Deprecated 0 indices, should fully remove later. |
| 155 | min_index = None |
| 156 | |
| 157 | with open(self.csv, "r", encoding="utf-8") as csv_file: |
| 158 | reader = csv.reader(csv_file) |
| 159 | for row in reader: |
| 160 | if not row[0]: |
| 161 | continue |
| 162 | # parse header |
| 163 | if not self.headers: |
| 164 | self.has_categories = True |
| 165 | self.has_rates = False |
| 166 | self.headers = {col: i for i, col in enumerate(row) if col} |
| 167 | if "RateSchedule" in self.headers and "RateID" in self.headers: |
| 168 | self.has_rates = True |
| 169 | if "Value" in self.headers: |
| 170 | self.has_categories = False |
| 171 | else: |
| 172 | # Very fragile part of the code. |
| 173 | self.categories = { # pyright: ignore [reportAttributeAccessIssue] |
| 174 | # ' Cost' is a sufix added on export. |
| 175 | name.removesuffix(" Cost"): index |
| 176 | for name, index in self.headers.items() |
| 177 | if name not in MAIN_CSV_HEADER_COLUMNS |
| 178 | } |
| 179 | if self.categories: |
| 180 | print( |
| 181 | f"The following columns will be used as cost values categories: {', '.join(self.categories)}" |
| 182 | ) |
| 183 | |
| 184 | # validate header |
| 185 | mandatory_fields = {"Name", "Unit"} |
| 186 | available_fields = set(self.headers.keys()) |
| 187 | missing_fields = mandatory_fields - available_fields |
| 188 | |
| 189 | if missing_fields: |
| 190 | raise Exception(f"Missing mandatory fields in CSV header: {', '.join(missing_fields)}") |
| 191 | |
| 192 | continue |
| 193 | cost_data = self.get_row_cost_data(row) |
| 194 | index = int(row[self.headers["Index"]]) |
| 195 | if min_index is None and index in (0, 1): |
| 196 | if index == 0: |
| 197 | print( |
| 198 | "WARNING. Indices in csv table start from 0, they should start from 1. It will be deprecated soon completely." |
| 199 | ) |
| 200 | min_index = index |
| 201 | if index == min_index: |
| 202 | self.cost_items.append(cost_data) |
| 203 | else: |