├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── development
├── poetry.lock
├── pyproject.toml
├── scripts.py
├── tests
├── __init__.py
├── config_template.py
└── test_parser.py
└── xerparser
├── __init__.py
├── schemas
├── __init__.py
├── _node.py
├── account.py
├── actvcode.py
├── actvtype.py
├── calendars.py
├── ermhdr.py
├── findates.py
├── memotype.py
├── pcattype.py
├── pcatval.py
├── project.py
├── projwbs.py
├── rate.py
├── rsrc.py
├── rsrcrate.py
├── schedoptions.py
├── task.py
├── taskfin.py
├── taskmemo.py
├── taskpred.py
├── taskrsrc.py
├── trsrcfin.py
└── udftype.py
├── scripts
├── __init__.py
├── dates.py
└── decorators.py
└── src
├── __init__.py
├── errors.py
├── parser.py
├── utils.py
├── validators.py
└── xer.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Project specific
2 | *.xer
3 | _main.py
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | pip-wheel-metadata/
28 | share/python-wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 | MANIFEST
33 |
34 | # PyInstaller
35 | # Usually these files are written by a python script from a template
36 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
37 | *.manifest
38 | *.spec
39 |
40 | # Installer logs
41 | pip-log.txt
42 | pip-delete-this-directory.txt
43 |
44 | # Unit test / coverage reports
45 | htmlcov/
46 | .tox/
47 | .nox/
48 | .coverage
49 | .coverage.*
50 | .cache
51 | nosetests.xml
52 | coverage.xml
53 | *.cover
54 | *.py,cover
55 | .hypothesis/
56 | .pytest_cache/
57 |
58 | # Translations
59 | *.mo
60 | *.pot
61 |
62 | # Django stuff:
63 | *.log
64 | local_settings.py
65 | db.sqlite3
66 | db.sqlite3-journal
67 |
68 | # Flask stuff:
69 | instance/
70 | .webassets-cache
71 |
72 | # Scrapy stuff:
73 | .scrapy
74 |
75 | # Sphinx documentation
76 | docs/_build/
77 |
78 | # PyBuilder
79 | target/
80 |
81 | # Jupyter Notebook
82 | .ipynb_checkpoints
83 |
84 | # IPython
85 | profile_default/
86 | ipython_config.py
87 |
88 | # pyenv
89 | .python-version
90 |
91 | # pipenv
92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
95 | # install all needed dependencies.
96 | #Pipfile.lock
97 |
98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
99 | __pypackages__/
100 |
101 | # Celery stuff
102 | celerybeat-schedule
103 | celerybeat.pid
104 |
105 | # SageMath parsed files
106 | *.sage.py
107 |
108 | # Environments
109 | .env
110 | .venv
111 | env/
112 | venv/
113 | ENV/
114 | env.bak/
115 | venv.bak/
116 |
117 | # Spyder project settings
118 | .spyderproject
119 | .spyproject
120 |
121 | # Rope project settings
122 | .ropeproject
123 |
124 | # mkdocs documentation
125 | /site
126 |
127 | # mypy
128 | .mypy_cache/
129 | .dmypy.json
130 | dmypy.json
131 |
132 | # Pyre type checker
133 | .pyre/
134 |
135 | .vscode/
136 | tests/fixtures/*.json
137 | tests/config.py
138 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 |
2 | # Changelog - xerparser
3 |
4 | ## 0.13.5 - 2025-05-26
5 |
6 | Adding `day_hr_cnt`, `week_hr_cnt`, `year_hr_cnt` as optional_float to calendar object.
7 |
8 | ---
9 |
10 | ## 0.13.4 - 2024-12-18
11 |
12 | In `TASKRSRC` class, changed data type of `target_lag_drtn_hr_cnt` property from int to float. Reference [Issue #10](https://github.com/jjCode01/xerparser/issues/10)
13 |
14 | ---
15 |
16 | ## 0.13.3
17 |
18 | * Added properties to `PROJWBS` class:
19 | * `project` gives PROJWBS objects access to the project and its properties.
20 | * `original_duration` calendar days between start and finish dates.
21 | * `actual_duration` calendar days between the project data date the wbs start date.
22 | * `remaining_duration` calendar days between the wbd finish date and the project data date.
23 |
24 | ---
25 |
26 | ## 0.13.2 - 2024-10-09
27 |
28 | * Added `all_task` property to `PROJWBS` class, which returns all tasks assigned to a node and all it's children nodes.
29 | * Added `actual_cost`, `budgeted_cost`, `remaining_cost`, and `this_period_cost` properties to `PROJWBS` class. These are sums of the costs for all activities under a WBS node.
30 | * Added `start` and `finish` properties to `PROJWBS` class.
31 | * `PROJWBS` objects are now sorted by seq_num to match the order reflected in P6.
32 |
33 | ---
34 |
35 | ## 0.13.1 - 2024-10-09
36 |
37 | * `Node` object now use `seq_num` attribute for comparison and sorting.
38 | * Fixed potential bug in how children are stored in the `Node` class; switched from a list to a dict to avoid having multiple of the same child.
39 |
40 | ---
41 |
42 | ## 0.13.0 - 2024-10-06
43 |
44 | NOTE: If you have tests setup, this change will require you to delete the existing `xer_data.json` fixture and recreate it in the test process.
45 |
46 | * Added functionality for traversing `Node` objects:
47 | * `traverse_parents` method iterates through parents to root node.
48 | * `traverse_children` method iterates through all children to leaves.
49 | * `height` property is the length of the longest downward path to a leaf from a given node (leaf nodes with have a height of 0).
50 | * `depth` property is the length of the path to the root node from a given node (root node will have a depth of 0).
51 |
52 | ---
53 |
54 | ## 0.12.3 - 2024-09-14
55 |
56 | * Fixed potential KeyErrors in the `SCHEDOPTIONS` class due to missing attributes in files exported from older versions of P6. [Issue #7](https://github.com/jjCode01/xerparser/issues/7)
57 | * Fixed bug where `create_date` and `update_date` attributes of the `TASK` class may be empty. [Issue #8](https://github.com/jjCode01/xerparser/issues/8)
58 |
59 | ---
60 |
61 | ## 0.12.2 - 2024-07-04
62 |
63 | * Added `tasks` (list[`TASK`]) attribute to `PROJWBS` class.
64 | * Added `task_rsrcs` (list[`TASKRSRC`]) attribute to `RSRC` class.
65 |
66 | ---
67 |
68 | ## 0.12.1 - 2024-07-02
69 |
70 | Patched potential errors when transformming from a string to a float. Some languages use a comma rather than a period in floating point numbers.
71 |
72 | ---
73 |
74 | ## 0.12.0 - 2024-06-19
75 |
76 | * Added class `RSRCRATE` which represents a Resource Rate. This can be accessed from the `resource_rate` (dict) attribute of the `Xer` object. [Issue #6](https://github.com/jjCode01/xerparser/issues/6)
77 |
78 | ---
79 |
80 | ## 0.11.2 - 2024-05-25
81 |
82 | * Refactored inheritance for `Node` objects.
83 | * The `description` attribute of the `ACTVCODE` and `PCATVAL` classes has been changed to `name`.
84 |
85 | ---
86 |
87 | ## 0.11.1 - 2024-05-24
88 |
89 | * Fixed bug in the equal override function for the `RSRC` object; missing a return.
90 |
91 | ---
92 |
93 | ## 0.11.0 - 2024-04-28
94 |
95 | * Updated type hints, which now requires a minimum of Python 3.11.
96 | * `RSRC` class now inherits from `Node`.
97 | * Updating / filling in docstrings.
98 |
99 | ---
100 |
101 | ## 0.10.4 - 2024-03-08
102 |
103 | * Updated dependencies to new versions.
104 | * `ACCOUNT` class equal overide now checks if other object is None type.
105 | * The `max_multiple_longest_path` attribute of the `SCHEDOPTIONS` class can be type int or None.
106 |
107 | ---
108 |
109 | ## 0.10.3 - 2023-08-11
110 |
111 | ### Changes
112 |
113 | * Added `Node` class to represent a Tree data structure - can have one parent and multiple children. `ACCOUNT`, `ACTVCODE`, `PCATVAL`, and `PROJWBS` classes now inherit from `Node` class.
114 |
115 | ---
116 |
117 | ## 0.10.2 - 2023-08-05
118 |
119 | ### Changes
120 |
121 | * Updated dependency `html-sanitizer` to the latest version `2.2.0`
122 | * Added `Node` class to represent a Tree data structure - can have one parent and multiple children.
123 | * `ACCOUNT`, `ACTVCODE`, `PCATVAL`, and `PROJWBS` classes now inherit from `Node` class.
124 |
125 | ---
126 |
127 | ## 0.10.1 - 2023-08-05
128 |
129 | ### Added
130 |
131 | * Added `is_wbs` property to `TaskType` enum class. Checks if task is a wbs summary type.
132 |
133 | ---
134 |
135 | ## 0.10.0 - 2023-07-17
136 |
137 | ### Added
138 |
139 | * Added `wbs_root` attribute to the `PROJECT` class. This is the root WBS node.
140 | * Added `children` attribute to the `PROJWBS` class. Along with the `wbs_root` above, this forms a Tree Data Structure.
141 | * Added `children` attribute to the `ACCOUNT` class.
142 | * Added `children` attribute to the `ACTVCODE` class.
143 | * Added `children` attribute to the `PCATVAL` class.
144 |
145 | ### Changes
146 |
147 | * Changed the `PROJECT` `name` from an attribute to a property. The project name is stored in the `wbs_root` added above.
148 |
149 | ---
150 |
151 | ## 0.9.9 - 2023-06-14
152 |
153 | ### Changes
154 |
155 | * The `task_percent` property of the `PROJECT` class now ignores Level of Effort activities when calculating percent complete. There were edge cases where the LOE activity had a remaining duration much greater than its original duration, which significantly reduced the calculated percent complete.
156 |
157 | ---
158 |
159 | ## 0.9.8 - 2023-05-24
160 |
161 | * Bug fixes with validating data types for `TASKPRED` objects.
162 |
163 | ---
164 |
165 | ## 0.9.7 - 2023-05-24
166 |
167 | * Bug fixes with validating data types for `TASK` objects.
168 |
169 | ---
170 |
171 | ## 0.9.6 - 2023-05-14
172 |
173 | ### Added
174 |
175 | * Added `resources` attribute containing a list of `TASKRSRC` objects to the `PROJECT` class. Previously, `TASKRSRC` objects were only accessible through a `TASK` object.
176 |
177 | ---
178 |
179 | ## 0.9.5 - 2023-05-13
180 |
181 | ### General
182 |
183 | Both project specific and global calendars are now included in the `PROJECT` `calendars` attribute. Covers cases where project tasks are assigned to a gobal calendar.
184 |
185 | ---
186 |
187 | ## 0.9.4 - 2023-04-19
188 |
189 | ### Added
190 |
191 | * Added `actual_duartion` property to `PROJECT` class.
192 |
193 | ---
194 |
195 | ## 0.9.3 - 2023-04-08
196 |
197 | ### General
198 |
199 | Some code cleanup and corrections to the python code in the README file.
200 |
201 | ---
202 |
203 | ## 0.9.2 - 2023-03-19
204 |
205 | ### Added
206 |
207 | * Added function `file_reader` which accepts a .xer file and reads it to a string object.
208 | * Accepts str or Path objects for files stored locally or on a server.
209 | * Accepts BinaryIO files from requests, Flask, FastAPI, etc...
210 | * Added classmethods `reader` to the `Xer` class. A .xer file can be passed directly to this method, which will read and decode the file, and return a `Xer` object. Uses the `file_reader` function above.
211 |
212 | ### Changed
213 |
214 | * Changed name of function `xer_to_dict` to `parser`.
215 |
216 | ---
217 |
218 | ## 0.9.1 - 2023-03-18
219 |
220 | Updated `CorruptXerFile` Exception to receive the list of errors and print them out when the exception is raised. The errors can now be accessed from the Exception when using `try` `except`.
221 |
222 | ```python
223 | try:
224 | xer = Xer(file_contents)
225 | except CorruptXerFile as e:
226 | for error in e.errors:
227 | print(error)
228 | ```
229 |
230 | ---
231 |
232 | ## 0.9.0 - 2023-03-17
233 |
234 | ### General Notes
235 |
236 | Remove `error` attribute from `xer` class. If the errors are encoutered during initialization of an `xer` object, then a `CorruptXerFile` Exception is raised.
237 |
238 | ### Added
239 |
240 | * `find_xer_errors` function. Error checking for the file is now its own function that that can find errors in an xer file and povide the results in a list.
241 | * Error checking now looks for invalid `rsrc_id` assigned to a `TASKRSRC` object.
242 |
243 | ### Removed
244 |
245 | The option for None type on the following items was originally done to avoid Exceptions being thrown if the file is corrupted. This created additional code to handle situations when the attributes equal None.
246 | * Removed option for `calendar` attribute of the `TASK` class to be type `None`; All `TASK` objects must have a `calendar` or the `CorruptXerFile` Exception is raised.
247 | * Removed option for the `resource` attribute of the `TASKRSRC` class to be type `None`; all `TASKRSRC` objects must have a `resource` or the `CorruptXerFile` Exception is raised.
248 |
249 | ---
250 |
251 | ## 0.8.2 - 2023-03-05
252 |
253 | ### Added
254 |
255 | * Added `actual_total_cost` property to `TASKFIN` class
256 | * Added `late_start` property to `PROJECT` class
257 |
258 | ### Changes
259 |
260 | * `TASK` method `rem_hours_per_day` can now accept a `late` flag (bool) to calculate late dates rather than early dates.
261 |
262 | ---
263 |
264 | ## 0.8.1 - 2023-02-28
265 |
266 | ### General Notes
267 |
268 | Refactor / cleanup code.
269 | Working on functionality to generate cost loading projections.
270 |
271 | ### Added
272 |
273 | * Added `rem_hours_per_day` method to `TASK` class. This return a dict with date: workhour key value pairs. This function was originally contained within the `calendar.py` module, but was not being used. Makes more sense to have it as a `TASK` method.
274 | * Added `base_calendar` attribute to `CALENDAR` class. The `is_workday` function will now search the `base_calendar` for holidays when determining if a date is a workday.
275 |
276 | ### Changed
277 |
278 | * `remain_drtn_hr_cnt` attribute of `TASK` no longer allows `None` type.
279 | * `finish` property of `TASK` will now check for `reend_date` and return it before it returns `early_end_date`
280 |
281 | ---
282 |
283 | ## 0.8.0 - 2023-02-28
284 |
285 | ### General Notes
286 |
287 | Added parsing of User Defined Fields (UDF). [Issue #4](https://github.com/jjCode01/xerparser/issues/4)
288 | Expanded testing for more coverage.
289 | Refactor / clean up code for initialization of `XER` class.
290 |
291 | ### Added
292 |
293 | * Added class `UDFTYPE` which represents a User Defined Field.
294 | * Added attribute `user_defined_fields` to `PROJECT`, `PROJWBS`, `RSRC`, and `TASK` classes, which hold a dictionary of `UDFTYPE`: `UDF Value` key value pairs.
295 |
296 | ---
297 |
298 | ## 0.7.0 - 2023-02-25
299 |
300 | ### General Notes
301 |
302 | Added parsing of Project Codes. [Issue #3](https://github.com/jjCode01/xerparser/issues/3).
303 |
304 | ### Added
305 |
306 | * Added class `PCATTYPE` which represents a Project Code Type.
307 | * Added class `PCATVAL` which represents a Project Code Value.
308 | * Added attribute `project_code_types` to `Xer` class, which holds a dictionary of `PCATTYPE` objects.
309 | * Added attribute `project_code_values` to `Xer` class, which holds a dictionary of `PCATVAL` objects.
310 | * Added attribute `project_codes` to `PROJECT` class, which holds a dictionary of `PCATTYPE`: `PCATVAL` key value pairs assigned to a project.
311 |
312 | ---
313 |
314 | ## 0.6.0 - 2023-02-24
315 |
316 | ### General Notes
317 |
318 | The `ScheduleWarnings` class will no longer be developed under this project. This is a breaking change if you were using the `ScheduleWarnings` class.
319 |
320 | ### Added
321 |
322 | * Added `__len__` method to `CALENDAR` class. Returns number of workdays in a week.
323 |
324 | ### Removed
325 |
326 | * Removed `warnings.py` from project. This may become a seperate project.
327 |
328 | ---
329 |
330 | ## 0.5.9 - 2023-02-12
331 |
332 | * Added `default_calendar` attribute to `PROJECT` class.
333 |
334 | ---
335 |
336 | ## 0.5.8 - 2023-02-05
337 |
338 | ### Added
339 |
340 | * Added `SCHEDOPTIONS` class.
341 | * Added `options` attribute the `PROJECT` class, which is a `SCHEDOPTIONS` object.`
342 | * Added `lineage` and `full_code` properties to the `ACTVCODE` class. [Issue #2](https://github.com/jjCode01/xerparser/issues/2)
343 |
344 | ### Changes
345 |
346 | * Comparison operators for `ACTVCODE` are now based on `full_code` property rather than `code` property.
347 |
348 | ---
349 |
350 | ## 0.5.7 - 2023-02-03
351 |
352 | ### General Notes
353 |
354 | Added some additional features noted below, and continue working on `Warnings` class.
355 |
356 | ### Added
357 |
358 | * Added `lineage` property to `PROJWBS` class. Returns list of all ancestor `PROJWBS` objects, including self.
359 | * Added `duration` property to `TASK` class. This will return `remaining_duration` if the task is not started; otherwise, it returns `original_duration`. This is usefull when the remaining duration is unlinked from the original duration in the project settings - in these cases, the remaining duration can be different to the original duration in tasks that have not started.
360 |
361 | ---
362 |
363 | ## 0.5.6 - 2023-01-24
364 |
365 | Fixed bug where the `start` property of the `TASK` class will return the early finish date rather than early start date if task is not started. [Issue #1](https://github.com/jjCode01/xerparser/issues/1)
366 |
367 | ---
368 |
369 | ## 0.5.5 - 2023-01-21
370 |
371 | ### General Notes
372 |
373 | * Added docstrings to more classes.
374 | * Improved type validation.
375 |
376 | ### Added
377 |
378 | * Added `full_code` property to `ACCOUNT` class. This property returns the full path to the cost code including any parent codes. This property is now the basis for comparing `ACCOUNT` objects.
379 |
380 | ## 0.5.4 - 2023-01-07
381 |
382 | ### General Notes
383 |
384 | * Small amount of code cleanup and refactoring.
385 |
386 | ### Added
387 |
388 | * Added `parent_acct_id` and `seq_num` attributes to `ACCOUNT` class.
389 | * Added `parent` property to `ACCOUNT` class.
390 |
391 | ---
392 |
393 | ## 0.5.3 - 2023-01-05
394 |
395 | ### General Notes
396 |
397 | * Small amount of refactoring and moving around files.
398 | * Added gt and lt dunder methods to some of the classes.
399 | * Using decorator to round any class method that returns a float. Just playing with decorators, may switch back to rounding directly in the method.
400 |
401 | ---
402 |
403 | ## 0.5.2 - 2023-01-02
404 |
405 | ### General Notes
406 |
407 | * Removed dependency on `Pydantic`. Speeds up code by ~25%.
408 |
409 | ### Added
410 |
411 | * Added testing of `errors` attribute of `Xer` class.
412 |
413 | ### Changed
414 |
415 | * Moved functions `is_workday`, `iter_holidays`, and `iter_workdays` to be methods of the `CALENDAR` class.
416 | * The `budgeted_cost`, `actual_cost`, `this_period_cost`, and `remaining_cost` properties of the `TASK` class now return float values rounded to two decimal places. **Warning**: this may cause the `PROJECT` level values to be off by .01 from what was previously reported; you will need to recreate test data.
417 |
418 | ### Removed
419 |
420 | * Removed `has_predecessor`, `has_successor`, `has_finish_successor`, and `has_start_successor` of `TASK` class. These analyses can be done in the users program.
421 |
422 | ### In Development
423 |
424 | * Continue working on Warnings class.
425 |
426 | ---
427 |
428 | ## 0.5.1 - 2022-12-31
429 |
430 | ### General Notes
431 |
432 | * Updated tests.
433 | * More testing has resulted in minor code cleanup and refactoring.
434 |
435 | ### Changes
436 |
437 | * The `description` attribute of `ACCOUNT` class will now return an empty string if its empty; it used to return None.
438 | * Fixed bug in parser that was stripping out the last values (columns) in a table row if they were empty. This was causing validation errors with missing attributes in Pydantic.
439 | * Changed `CALENDAR` class variable `CALENDAR_TYPES` (dict) to `CalendarTypes` (Enum).
440 | * `wbs` argument is now required during initialization of a `TASK` object.
441 | * `predecessor` and `successor` arguments are now required during initialization of a `TASKPRED` object.
442 |
443 | ---
444 |
445 | ## 0.5.0 - 2022-12-29
446 |
447 | ### General Notes
448 |
449 | * This change focused on parsing Activity Code Data stored in a .xer file. This information is stored in the `ACTVTYPE`, `ACTVCODE`, and `TASKACTV` Tables.
450 | * **WARNING**: Some refactoring includes breaking changes, so this is being considered a `minor` version bump rather than a `patch`.
451 |
452 | ### Added
453 |
454 | * Added `ACTVTYPE` class to represent Activity Code Types.
455 | * Added `ACTVCODE` class to represent Activity Code Values.
456 | * Added `activity_code_types` (dict), `activity_code_values` (dict), `wbs_nodes` (dict), `tasks` (dict) and `relationships` (dict) attributes to `Xer` class.
457 | * Added `activity_codes` attribute to `TASK` class, which holds a dict of `ACTVTYPE`, `ACTVCODE` pairs assigned to a task via the `TASKACTV` Table.
458 | * Added `activity_codes` attribute to `PROJECT` class, which holds Project level activity code types.
459 | * Added `relationships_by_hash` property to `PROJECT` class. Returns a dict with a hash of the relationship as the key and the relationship as the value. This is usefull for evaluating logic changes between two schedules; Unique IDs will change from schedule to schedule, but the hash value will be the same. Note: hash value is calculated based on predecessor task_code, successor task_code, and relationship link.
460 |
461 | ### Changed
462 |
463 | * Moved `conv_excel_date` function from `dates.py` to a Static Method of the `CALENDAR` class. This function is only used to parse dates in the `clndr_data`.
464 | * Moved `CALENDAR_TYPES` from being a Global variable in `calendars.py` to be a `CALENDAR` class variable.
465 | * The Global Regular Expression variables in `calendars.py` now use the `re.compile` method.
466 | * Renamed `fin_dates_id` attribute of `FINDATES` class to `uid`. This is consistent with the naming in other classes.
467 | * Renamed `fin_dates_name` attribute of `FINDATES` class to `name`. This is consistent with the naming in other classes.
468 | * `MEMOTYPE` and `TASKMEMO` classes no longer iherit from Pydantic BaseModel class. All attributes of both `MEMOTYPE` and `TASKMEMO` are strings, so type validation is not needed.
469 | * Added `__eq__` and `__hash__` methods to `MEMOTYPE` class.
470 | * Moved Enumerators `ConstraintType`, `PercentType`, `TaskStatus` and `TaskType` to inside the `TASK` class.
471 | * Refactored how `calendars`, `wbs_nodes`, `tasks` and `relationships` attributes are assigned for the `PROJECT` class. Each of these attributes is now a list rather than a dict or set. These objects are now referenced directly in the `Xer` class as a dict using its Unique ID as the key, so the `PROJECT` reference to these objects can now be a simple list.
472 | * `PROJECT` properties `actual_cost`, `budgeted_cost`, `remaining_cost`, and `this_period_cost` now return float values rounded to two decimal places.
473 |
474 | ### Removed
475 |
476 | * Removed `__str__` method from `WeekDay` class in `calendars.py`. This was originally used for testing and is no longer needed.
477 | * Removed `print_cal` method from `CALENDAR` class. This were originally used for testing and is no longer needed.
478 |
479 | ---
480 |
481 | ## 0.4.1 - 2022-12-21
482 |
483 | ### General Note
484 |
485 | This change focused on parsing Financial Periods and Past Period Data stored in a .xer file. This information is stored in the `FINDATES`, `TASKFIN` and `TRSRCFIN` Tables.
486 |
487 | ### Added
488 |
489 | * Added `FINDATES` class to represent Financial Periods.
490 | * Added `TASKFIN` class to represent Activity Past Period Actuals.
491 | * Added `TRSRCFIN` class to represent Activity Resource Assignment Past Period Actuals.
492 | * `Xer` class now has `financial_periods` (dict) attribute, which stores `FINDATES` objects.
493 | * `TASK` class now has a `periods` (list) attribute, which stores `TASKFIN` objects.
494 | * `TASKRSRC` class now has a `periods` (list) attribute, which stores `TRSRCFIN` objects.
495 |
496 | ### Changed
497 |
498 | * `resources` attribute of `TASK` class changed from type list to type dict. This allows for easier assignment of financial period data (`TRSRCFIN`) to task resources (`TASKRSRC`).
499 |
500 | ---
501 |
502 | ## 0.4.0 - 2022-12-20
503 |
504 | ### General
505 |
506 | * General code clean up and refactoring
507 |
508 | ### Added
509 |
510 | * `Xer` class now has a class variable `CODEC`, which stores the type of encoding for a .xer file.
511 | * Added `LinkToTask` class for use in storing a `TASK` objects predecessor and successor links. Has properties `task`, `link`, and `lag`.
512 | * `TASK` objects now have a `predecessors` attribute, which holds a list of `LinkToTask` objects representing predecessor logic ties.
513 | * `TASK` objects now have a `successors` attribute, which holds a list of `LinkToTask` objects representing successor logic ties.
514 | * `TASK` objects now have a `has_predecessor` property, which return True if task has at least one predecessor stored in its `predecessors` attribute.
515 | * `TASK` objects now have a `has_successors` property, which return True if task has at least one successor stored in its `successors` attribute.
516 | * `TASK` objects now have a `has_finish_successor` property, which return True if task has at least one *Finish-Start* or *Finish-Finish* logic tie (link) stored in its `successors` attribute. Will also return True if the task has no successors.
517 | * `TASK` objects now have a `has_start_predecessor` property, which return True if task has at least one *Finish-Start* or *Start-Start* logic tie (link) stored in its `predecessors` attribute. Will also return True if the task has no predecessors.
518 |
519 | ### Changed
520 |
521 | * `Xer` class no longer accepts raw .xer files as an argument. The xer file must be decoded into a string, which is then passed as an argument. This helps avoid multiple try / except statements to read the xer file.
522 | * `xer_to_dict` function no longer returns a dictionary with a 'tables' key. Each table name is now a top level key in the dictionary.
523 | * `xer_to_dict` function no longer parses the potential **errors** in the xer files. Errors are now parsed when the `Xer` object is initialized.
524 | * `Xer` attribute `notebook` is renamed to `notebook_topic` to better define the objects stored in this attribute.
525 | * `Xer` attribute `export` is renamed to `export_info` to better define the values stored in this attribute.
526 |
527 | ### In Development
528 |
529 | * Working on a `ScheduleWarnings` class to provide schedule health analysis.
530 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # xerparser
2 |
3 | Read the contents of a P6 .xer file and convert it into a Python object.
4 |
5 | *Disclaimers:
6 | It's helpfull if you are already familiar with the mapping and schemas used by P6 during the export process.
7 | Refer to the [Oracle Documentation]( https://docs.oracle.com/cd/F25600_01/English/Mapping_and_Schema/xer_import_export_data_map_project/index.htm) for more information regarding how data is mapped to the XER format.
8 | Tested on .xer files exported as versions 15.2 through 19.12.*
9 |
10 |
11 |
12 | ## Install
13 |
14 | **Windows**:
15 |
16 | ```bash
17 | pip install xerparser
18 | ```
19 |
20 | **Linux/Mac**:
21 |
22 | ```bash
23 | pip3 install xerparser
24 | ```
25 |
26 |
27 |
28 | ## Usage
29 |
30 | Import the `Xer` class from `xerparser` and pass the contents of a .xer file as an argument. Use the `Xer` class variable `CODEC` to set the proper encoding to decode the file.
31 |
32 | ```python
33 | from xerparser import Xer
34 |
35 | file = r"/path/to/file.xer"
36 | with open(file, encoding=Xer.CODEC, errors="ignore") as f:
37 | file_contents = f.read()
38 | xer = Xer(file_contents)
39 | ```
40 |
41 | Do not pass the the .xer file directly as an argument to the `Xer` class. The file must be decoded and read into a string, which can then be passed as an argument. Or, pass the .xer file into the `Xer.reader` classmethod, which accepts:
42 |
43 | * str or pathlib.Path objects for files stored locally or on a server.
44 | * Binary files from requests, Flask, FastAPI, etc...
45 |
46 | ```python
47 | from xerparser import Xer
48 |
49 | file = r"/path/to/file.xer"
50 | xer = Xer.reader(file)
51 | ```
52 |
53 |
54 |
55 | ## Attributes
56 |
57 | The tables stored in the .xer file are accessable as either Global, Project specific, Task specific, or Resource specific:
58 |
59 | ### Global
60 |
61 | ```python
62 | xer.export_info # export data
63 | xer.activity_code_types # dict of ACTVTYPE objects
64 | xer.activity_code_values # dict of ACTVCODE objects
65 | xer.calendars # dict of all CALENDAR objects
66 | xer.financial_periods # dict of FINDATES objects
67 | xer.notebook_topics # dict of MEMOTYPE objects
68 | xer.projects # dict of PROJECT objects
69 | xer.project_code_types # dict of PCATTYPE objects
70 | xer.project_code_values # dict of PCATVAL objects
71 | xer.tasks # dict of all TASK objects
72 | xer.relationships # dict of all TASKPRED objects
73 | xer.resources # dict of RSRC objects
74 | xer.resource_rates # dict of RSRCRATE objects
75 | xer.udf_types # dict of UDFTYPE objects
76 | xer.wbs_nodes # dict of all PROJWBS objects
77 | ```
78 |
79 | ### Project Specific
80 |
81 | ```python
82 | # Get first project
83 | project = list(xer.projects.values())[0]
84 |
85 | project.activity_codes # list of project specific ACTVTYPE objects
86 | project.calendars # list of project specific CALENDAR objects
87 | project.project_codes # dict of PCATTYPE: PCATVAL objects
88 | project.tasks # list of project specific TASK objects
89 | project.relationships # list of project specific TASKPRED objects
90 | project.resources # lest of project specific TASKRSRC objects
91 | project.user_defined_fields # dict of `UDFTYPE`: `UDF Value` pairs
92 | project.wbs_nodes # list of project specific PROJWBS objects
93 | ```
94 |
95 | ### WBS Specific
96 | ```python
97 | # Get projects root wbs node
98 | wbs_node = project.wbs_root
99 |
100 | wbs_node.children # list of child PROJWBS objects
101 | wbs_node.project # PROJECT the WBS node belongs to
102 | wbs_node.tasks # list of TASK objects assigned directly to WBS node
103 | wbs_node.all_tasks # list of TASK objects under the WBS node
104 | wbs_node.user_defined_fields # dict of `UDFTYPE`: `UDF Value` pairs
105 | ```
106 |
107 | ### Task Specific
108 |
109 | ```python
110 | # Get first task
111 | task = project.tasks[0]
112 |
113 | task.activity_codes # dict of ACTVTYPE: ACTVCODE objects
114 | task.memos # list of TASKMEMO objects
115 | task.periods # list of TASKFIN objects
116 | task.resources # dict of TASKRSRC objects
117 | task.user_defined_fields # dict of `UDFTYPE`: `UDF Value` pairs
118 | ```
119 |
120 | ### Resource Specific
121 |
122 | ```python
123 | # Get first task resource
124 | resource = list(task.resources.values())[0]
125 |
126 | resource.periods # list of TRSRCFIN objects
127 | resource.user_defined_fields # dict of `UDFTYPE`: `UDF Value` pairs
128 | ```
129 |
130 |
131 |
132 | ## Error Checking
133 |
134 | Sometimes the xer file is corrupted during the export process. If this is the case, a `CorruptXerFile` Exception will be raised during initialization. A list of the errors can be accessed from the `CorruptXerFile` Exception, or by using the `find_xer_errors` function.
135 |
136 | ### Option 1 - `errors` attribute of `CorruptXerFile` exception (preferred)
137 | ```python
138 | from xerparser import Xer, CorruptXerFile
139 |
140 | file = r"/path/to/file.xer"
141 | try:
142 | xer = Xer.reader(file)
143 | except CorruptXerFile as e:
144 | for error in e.errors:
145 | print(error)
146 | ```
147 |
148 | ### Option 2 - `find_xer_errors` function
149 | ```python
150 | from xerparser import parser, file_reader, find_xer_errors
151 |
152 | file = r"/path/to/file.xer"
153 | xer_data = parser(file_reader(file))
154 | file_errors = find_xer_errors(xer_data)
155 | for error in file_errors:
156 | print(error)
157 | ```
158 |
159 | ### Errors
160 |
161 | - Minimum required tables - an error is recorded if one of the following tables is missing:
162 | - CALENDAR
163 | - PROJECT
164 | - PROJWBS
165 | - TASK
166 | - TASKPRED
167 | - Required table pairs - an error is recorded if Table 1 is included but not Table 2:
168 |
169 | | Table 1 | Table 2 | Notes |
170 | | :----------- |:-------------|----------|
171 | | TASKFIN | FINDATES | *Financial Period Data for Task* |
172 | | TRSRCFIN | FINDATES | *Financial Period Data for Task Resource* |
173 | | TASKRSRC | RSRC | *Resource Data* |
174 | | TASKMEMO | MEMOTYPE | *Notebook Data* |
175 | | ACTVCODE | ACTVTYPE | *Activity Code Data* |
176 | | TASKACTV | ACTVCODE | *Activity Code Data* |
177 | | PCATVAL | PCATTYPE | *Project Code Data* |
178 | | PROJPCAT | PCATVAL | *Project Code Data* |
179 | | UDFVALUE | UDFTYPE | *User Defined Field Data* |
180 |
181 | - Non-existent calendars assigned to tasks.
182 | - Non-existent resources assigned to task resources.
183 |
--------------------------------------------------------------------------------
/development:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jjCode01/xerparser/c425263385807f77c5ffc5d8e930d9f028df668f/development
--------------------------------------------------------------------------------
/poetry.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Poetry 1.8.4 and should not be changed by hand.
2 |
3 | [[package]]
4 | name = "beautifulsoup4"
5 | version = "4.12.3"
6 | description = "Screen-scraping library"
7 | optional = false
8 | python-versions = ">=3.6.0"
9 | files = [
10 | {file = "beautifulsoup4-4.12.3-py3-none-any.whl", hash = "sha256:b80878c9f40111313e55da8ba20bdba06d8fa3969fc68304167741bbf9e082ed"},
11 | {file = "beautifulsoup4-4.12.3.tar.gz", hash = "sha256:74e3d1928edc070d21748185c46e3fb33490f22f52a3addee9aee0f4f7781051"},
12 | ]
13 |
14 | [package.dependencies]
15 | soupsieve = ">1.2"
16 |
17 | [package.extras]
18 | cchardet = ["cchardet"]
19 | chardet = ["chardet"]
20 | charset-normalizer = ["charset-normalizer"]
21 | html5lib = ["html5lib"]
22 | lxml = ["lxml"]
23 |
24 | [[package]]
25 | name = "colorama"
26 | version = "0.4.6"
27 | description = "Cross-platform colored terminal text."
28 | optional = false
29 | python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
30 | files = [
31 | {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
32 | {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
33 | ]
34 |
35 | [[package]]
36 | name = "html-sanitizer"
37 | version = "2.4.4"
38 | description = "HTML sanitizer"
39 | optional = false
40 | python-versions = ">=3.8"
41 | files = [
42 | {file = "html_sanitizer-2.4.4-py3-none-any.whl", hash = "sha256:c4befe85456ce9967403e770b1e335fb1c0cd5334154df2782cb7e015e10b3b6"},
43 | {file = "html_sanitizer-2.4.4.tar.gz", hash = "sha256:f718d3eb150a084d15c80d6546581fb08293ca96234242e9138bf0467cbd5792"},
44 | ]
45 |
46 | [package.dependencies]
47 | beautifulsoup4 = "*"
48 | lxml = ">=5.2"
49 | lxml-html-clean = ">=0.1"
50 |
51 | [[package]]
52 | name = "lxml"
53 | version = "5.3.0"
54 | description = "Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API."
55 | optional = false
56 | python-versions = ">=3.6"
57 | files = [
58 | {file = "lxml-5.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:dd36439be765e2dde7660212b5275641edbc813e7b24668831a5c8ac91180656"},
59 | {file = "lxml-5.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ae5fe5c4b525aa82b8076c1a59d642c17b6e8739ecf852522c6321852178119d"},
60 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:501d0d7e26b4d261fca8132854d845e4988097611ba2531408ec91cf3fd9d20a"},
61 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fb66442c2546446944437df74379e9cf9e9db353e61301d1a0e26482f43f0dd8"},
62 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9e41506fec7a7f9405b14aa2d5c8abbb4dbbd09d88f9496958b6d00cb4d45330"},
63 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f7d4a670107d75dfe5ad080bed6c341d18c4442f9378c9f58e5851e86eb79965"},
64 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:41ce1f1e2c7755abfc7e759dc34d7d05fd221723ff822947132dc934d122fe22"},
65 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:44264ecae91b30e5633013fb66f6ddd05c006d3e0e884f75ce0b4755b3e3847b"},
66 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_28_ppc64le.whl", hash = "sha256:3c174dc350d3ec52deb77f2faf05c439331d6ed5e702fc247ccb4e6b62d884b7"},
67 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_28_s390x.whl", hash = "sha256:2dfab5fa6a28a0b60a20638dc48e6343c02ea9933e3279ccb132f555a62323d8"},
68 | {file = "lxml-5.3.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:b1c8c20847b9f34e98080da785bb2336ea982e7f913eed5809e5a3c872900f32"},
69 | {file = "lxml-5.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2c86bf781b12ba417f64f3422cfc302523ac9cd1d8ae8c0f92a1c66e56ef2e86"},
70 | {file = "lxml-5.3.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:c162b216070f280fa7da844531169be0baf9ccb17263cf5a8bf876fcd3117fa5"},
71 | {file = "lxml-5.3.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:36aef61a1678cb778097b4a6eeae96a69875d51d1e8f4d4b491ab3cfb54b5a03"},
72 | {file = "lxml-5.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:f65e5120863c2b266dbcc927b306c5b78e502c71edf3295dfcb9501ec96e5fc7"},
73 | {file = "lxml-5.3.0-cp310-cp310-win32.whl", hash = "sha256:ef0c1fe22171dd7c7c27147f2e9c3e86f8bdf473fed75f16b0c2e84a5030ce80"},
74 | {file = "lxml-5.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:052d99051e77a4f3e8482c65014cf6372e61b0a6f4fe9edb98503bb5364cfee3"},
75 | {file = "lxml-5.3.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:74bcb423462233bc5d6066e4e98b0264e7c1bed7541fff2f4e34fe6b21563c8b"},
76 | {file = "lxml-5.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a3d819eb6f9b8677f57f9664265d0a10dd6551d227afb4af2b9cd7bdc2ccbf18"},
77 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5b8f5db71b28b8c404956ddf79575ea77aa8b1538e8b2ef9ec877945b3f46442"},
78 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c3406b63232fc7e9b8783ab0b765d7c59e7c59ff96759d8ef9632fca27c7ee4"},
79 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2ecdd78ab768f844c7a1d4a03595038c166b609f6395e25af9b0f3f26ae1230f"},
80 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:168f2dfcfdedf611eb285efac1516c8454c8c99caf271dccda8943576b67552e"},
81 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa617107a410245b8660028a7483b68e7914304a6d4882b5ff3d2d3eb5948d8c"},
82 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:69959bd3167b993e6e710b99051265654133a98f20cec1d9b493b931942e9c16"},
83 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_28_ppc64le.whl", hash = "sha256:bd96517ef76c8654446fc3db9242d019a1bb5fe8b751ba414765d59f99210b79"},
84 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_28_s390x.whl", hash = "sha256:ab6dd83b970dc97c2d10bc71aa925b84788c7c05de30241b9e96f9b6d9ea3080"},
85 | {file = "lxml-5.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:eec1bb8cdbba2925bedc887bc0609a80e599c75b12d87ae42ac23fd199445654"},
86 | {file = "lxml-5.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6a7095eeec6f89111d03dabfe5883a1fd54da319c94e0fb104ee8f23616b572d"},
87 | {file = "lxml-5.3.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:6f651ebd0b21ec65dfca93aa629610a0dbc13dbc13554f19b0113da2e61a4763"},
88 | {file = "lxml-5.3.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:f422a209d2455c56849442ae42f25dbaaba1c6c3f501d58761c619c7836642ec"},
89 | {file = "lxml-5.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:62f7fdb0d1ed2065451f086519865b4c90aa19aed51081979ecd05a21eb4d1be"},
90 | {file = "lxml-5.3.0-cp311-cp311-win32.whl", hash = "sha256:c6379f35350b655fd817cd0d6cbeef7f265f3ae5fedb1caae2eb442bbeae9ab9"},
91 | {file = "lxml-5.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:9c52100e2c2dbb0649b90467935c4b0de5528833c76a35ea1a2691ec9f1ee7a1"},
92 | {file = "lxml-5.3.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:e99f5507401436fdcc85036a2e7dc2e28d962550afe1cbfc07c40e454256a859"},
93 | {file = "lxml-5.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:384aacddf2e5813a36495233b64cb96b1949da72bef933918ba5c84e06af8f0e"},
94 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:874a216bf6afaf97c263b56371434e47e2c652d215788396f60477540298218f"},
95 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65ab5685d56914b9a2a34d67dd5488b83213d680b0c5d10b47f81da5a16b0b0e"},
96 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aac0bbd3e8dd2d9c45ceb82249e8bdd3ac99131a32b4d35c8af3cc9db1657179"},
97 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b369d3db3c22ed14c75ccd5af429086f166a19627e84a8fdade3f8f31426e52a"},
98 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c24037349665434f375645fa9d1f5304800cec574d0310f618490c871fd902b3"},
99 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:62d172f358f33a26d6b41b28c170c63886742f5b6772a42b59b4f0fa10526cb1"},
100 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:c1f794c02903c2824fccce5b20c339a1a14b114e83b306ff11b597c5f71a1c8d"},
101 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:5d6a6972b93c426ace71e0be9a6f4b2cfae9b1baed2eed2006076a746692288c"},
102 | {file = "lxml-5.3.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:3879cc6ce938ff4eb4900d901ed63555c778731a96365e53fadb36437a131a99"},
103 | {file = "lxml-5.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:74068c601baff6ff021c70f0935b0c7bc528baa8ea210c202e03757c68c5a4ff"},
104 | {file = "lxml-5.3.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ecd4ad8453ac17bc7ba3868371bffb46f628161ad0eefbd0a855d2c8c32dd81a"},
105 | {file = "lxml-5.3.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:7e2f58095acc211eb9d8b5771bf04df9ff37d6b87618d1cbf85f92399c98dae8"},
106 | {file = "lxml-5.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e63601ad5cd8f860aa99d109889b5ac34de571c7ee902d6812d5d9ddcc77fa7d"},
107 | {file = "lxml-5.3.0-cp312-cp312-win32.whl", hash = "sha256:17e8d968d04a37c50ad9c456a286b525d78c4a1c15dd53aa46c1d8e06bf6fa30"},
108 | {file = "lxml-5.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:c1a69e58a6bb2de65902051d57fde951febad631a20a64572677a1052690482f"},
109 | {file = "lxml-5.3.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8c72e9563347c7395910de6a3100a4840a75a6f60e05af5e58566868d5eb2d6a"},
110 | {file = "lxml-5.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e92ce66cd919d18d14b3856906a61d3f6b6a8500e0794142338da644260595cd"},
111 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1d04f064bebdfef9240478f7a779e8c5dc32b8b7b0b2fc6a62e39b928d428e51"},
112 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5c2fb570d7823c2bbaf8b419ba6e5662137f8166e364a8b2b91051a1fb40ab8b"},
113 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c120f43553ec759f8de1fee2f4794452b0946773299d44c36bfe18e83caf002"},
114 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:562e7494778a69086f0312ec9689f6b6ac1c6b65670ed7d0267e49f57ffa08c4"},
115 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:423b121f7e6fa514ba0c7918e56955a1d4470ed35faa03e3d9f0e3baa4c7e492"},
116 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:c00f323cc00576df6165cc9d21a4c21285fa6b9989c5c39830c3903dc4303ef3"},
117 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_28_ppc64le.whl", hash = "sha256:1fdc9fae8dd4c763e8a31e7630afef517eab9f5d5d31a278df087f307bf601f4"},
118 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_28_s390x.whl", hash = "sha256:658f2aa69d31e09699705949b5fc4719cbecbd4a97f9656a232e7d6c7be1a367"},
119 | {file = "lxml-5.3.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:1473427aff3d66a3fa2199004c3e601e6c4500ab86696edffdbc84954c72d832"},
120 | {file = "lxml-5.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a87de7dd873bf9a792bf1e58b1c3887b9264036629a5bf2d2e6579fe8e73edff"},
121 | {file = "lxml-5.3.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:0d7b36afa46c97875303a94e8f3ad932bf78bace9e18e603f2085b652422edcd"},
122 | {file = "lxml-5.3.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:cf120cce539453ae086eacc0130a324e7026113510efa83ab42ef3fcfccac7fb"},
123 | {file = "lxml-5.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:df5c7333167b9674aa8ae1d4008fa4bc17a313cc490b2cca27838bbdcc6bb15b"},
124 | {file = "lxml-5.3.0-cp313-cp313-win32.whl", hash = "sha256:c802e1c2ed9f0c06a65bc4ed0189d000ada8049312cfeab6ca635e39c9608957"},
125 | {file = "lxml-5.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:406246b96d552e0503e17a1006fd27edac678b3fcc9f1be71a2f94b4ff61528d"},
126 | {file = "lxml-5.3.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:8f0de2d390af441fe8b2c12626d103540b5d850d585b18fcada58d972b74a74e"},
127 | {file = "lxml-5.3.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1afe0a8c353746e610bd9031a630a95bcfb1a720684c3f2b36c4710a0a96528f"},
128 | {file = "lxml-5.3.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:56b9861a71575f5795bde89256e7467ece3d339c9b43141dbdd54544566b3b94"},
129 | {file = "lxml-5.3.0-cp36-cp36m-manylinux_2_28_x86_64.whl", hash = "sha256:9fb81d2824dff4f2e297a276297e9031f46d2682cafc484f49de182aa5e5df99"},
130 | {file = "lxml-5.3.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:2c226a06ecb8cdef28845ae976da407917542c5e6e75dcac7cc33eb04aaeb237"},
131 | {file = "lxml-5.3.0-cp36-cp36m-musllinux_1_2_x86_64.whl", hash = "sha256:7d3d1ca42870cdb6d0d29939630dbe48fa511c203724820fc0fd507b2fb46577"},
132 | {file = "lxml-5.3.0-cp36-cp36m-win32.whl", hash = "sha256:094cb601ba9f55296774c2d57ad68730daa0b13dc260e1f941b4d13678239e70"},
133 | {file = "lxml-5.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:eafa2c8658f4e560b098fe9fc54539f86528651f61849b22111a9b107d18910c"},
134 | {file = "lxml-5.3.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:cb83f8a875b3d9b458cada4f880fa498646874ba4011dc974e071a0a84a1b033"},
135 | {file = "lxml-5.3.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:25f1b69d41656b05885aa185f5fdf822cb01a586d1b32739633679699f220391"},
136 | {file = "lxml-5.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23e0553b8055600b3bf4a00b255ec5c92e1e4aebf8c2c09334f8368e8bd174d6"},
137 | {file = "lxml-5.3.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ada35dd21dc6c039259596b358caab6b13f4db4d4a7f8665764d616daf9cc1d"},
138 | {file = "lxml-5.3.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:81b4e48da4c69313192d8c8d4311e5d818b8be1afe68ee20f6385d0e96fc9512"},
139 | {file = "lxml-5.3.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:2bc9fd5ca4729af796f9f59cd8ff160fe06a474da40aca03fcc79655ddee1a8b"},
140 | {file = "lxml-5.3.0-cp37-cp37m-musllinux_1_2_aarch64.whl", hash = "sha256:07da23d7ee08577760f0a71d67a861019103e4812c87e2fab26b039054594cc5"},
141 | {file = "lxml-5.3.0-cp37-cp37m-musllinux_1_2_x86_64.whl", hash = "sha256:ea2e2f6f801696ad7de8aec061044d6c8c0dd4037608c7cab38a9a4d316bfb11"},
142 | {file = "lxml-5.3.0-cp37-cp37m-win32.whl", hash = "sha256:5c54afdcbb0182d06836cc3d1be921e540be3ebdf8b8a51ee3ef987537455f84"},
143 | {file = "lxml-5.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:f2901429da1e645ce548bf9171784c0f74f0718c3f6150ce166be39e4dd66c3e"},
144 | {file = "lxml-5.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:c56a1d43b2f9ee4786e4658c7903f05da35b923fb53c11025712562d5cc02753"},
145 | {file = "lxml-5.3.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ee8c39582d2652dcd516d1b879451500f8db3fe3607ce45d7c5957ab2596040"},
146 | {file = "lxml-5.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0fdf3a3059611f7585a78ee10399a15566356116a4288380921a4b598d807a22"},
147 | {file = "lxml-5.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:146173654d79eb1fc97498b4280c1d3e1e5d58c398fa530905c9ea50ea849b22"},
148 | {file = "lxml-5.3.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:0a7056921edbdd7560746f4221dca89bb7a3fe457d3d74267995253f46343f15"},
149 | {file = "lxml-5.3.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:9e4b47ac0f5e749cfc618efdf4726269441014ae1d5583e047b452a32e221920"},
150 | {file = "lxml-5.3.0-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:f914c03e6a31deb632e2daa881fe198461f4d06e57ac3d0e05bbcab8eae01945"},
151 | {file = "lxml-5.3.0-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:213261f168c5e1d9b7535a67e68b1f59f92398dd17a56d934550837143f79c42"},
152 | {file = "lxml-5.3.0-cp38-cp38-win32.whl", hash = "sha256:218c1b2e17a710e363855594230f44060e2025b05c80d1f0661258142b2add2e"},
153 | {file = "lxml-5.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:315f9542011b2c4e1d280e4a20ddcca1761993dda3afc7a73b01235f8641e903"},
154 | {file = "lxml-5.3.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:1ffc23010330c2ab67fac02781df60998ca8fe759e8efde6f8b756a20599c5de"},
155 | {file = "lxml-5.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2b3778cb38212f52fac9fe913017deea2fdf4eb1a4f8e4cfc6b009a13a6d3fcc"},
156 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4b0c7a688944891086ba192e21c5229dea54382f4836a209ff8d0a660fac06be"},
157 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:747a3d3e98e24597981ca0be0fd922aebd471fa99d0043a3842d00cdcad7ad6a"},
158 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:86a6b24b19eaebc448dc56b87c4865527855145d851f9fc3891673ff97950540"},
159 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b11a5d918a6216e521c715b02749240fb07ae5a1fefd4b7bf12f833bc8b4fe70"},
160 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:68b87753c784d6acb8a25b05cb526c3406913c9d988d51f80adecc2b0775d6aa"},
161 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:109fa6fede314cc50eed29e6e56c540075e63d922455346f11e4d7a036d2b8cf"},
162 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_28_ppc64le.whl", hash = "sha256:02ced472497b8362c8e902ade23e3300479f4f43e45f4105c85ef43b8db85229"},
163 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_28_s390x.whl", hash = "sha256:6b038cc86b285e4f9fea2ba5ee76e89f21ed1ea898e287dc277a25884f3a7dfe"},
164 | {file = "lxml-5.3.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:7437237c6a66b7ca341e868cda48be24b8701862757426852c9b3186de1da8a2"},
165 | {file = "lxml-5.3.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:7f41026c1d64043a36fda21d64c5026762d53a77043e73e94b71f0521939cc71"},
166 | {file = "lxml-5.3.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:482c2f67761868f0108b1743098640fbb2a28a8e15bf3f47ada9fa59d9fe08c3"},
167 | {file = "lxml-5.3.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:1483fd3358963cc5c1c9b122c80606a3a79ee0875bcac0204149fa09d6ff2727"},
168 | {file = "lxml-5.3.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:2dec2d1130a9cda5b904696cec33b2cfb451304ba9081eeda7f90f724097300a"},
169 | {file = "lxml-5.3.0-cp39-cp39-win32.whl", hash = "sha256:a0eabd0a81625049c5df745209dc7fcef6e2aea7793e5f003ba363610aa0a3ff"},
170 | {file = "lxml-5.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:89e043f1d9d341c52bf2af6d02e6adde62e0a46e6755d5eb60dc6e4f0b8aeca2"},
171 | {file = "lxml-5.3.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:7b1cd427cb0d5f7393c31b7496419da594fe600e6fdc4b105a54f82405e6626c"},
172 | {file = "lxml-5.3.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:51806cfe0279e06ed8500ce19479d757db42a30fd509940b1701be9c86a5ff9a"},
173 | {file = "lxml-5.3.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ee70d08fd60c9565ba8190f41a46a54096afa0eeb8f76bd66f2c25d3b1b83005"},
174 | {file = "lxml-5.3.0-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:8dc2c0395bea8254d8daebc76dcf8eb3a95ec2a46fa6fae5eaccee366bfe02ce"},
175 | {file = "lxml-5.3.0-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:6ba0d3dcac281aad8a0e5b14c7ed6f9fa89c8612b47939fc94f80b16e2e9bc83"},
176 | {file = "lxml-5.3.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:6e91cf736959057f7aac7adfc83481e03615a8e8dd5758aa1d95ea69e8931dba"},
177 | {file = "lxml-5.3.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:94d6c3782907b5e40e21cadf94b13b0842ac421192f26b84c45f13f3c9d5dc27"},
178 | {file = "lxml-5.3.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c300306673aa0f3ed5ed9372b21867690a17dba38c68c44b287437c362ce486b"},
179 | {file = "lxml-5.3.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:78d9b952e07aed35fe2e1a7ad26e929595412db48535921c5013edc8aa4a35ce"},
180 | {file = "lxml-5.3.0-pp37-pypy37_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:01220dca0d066d1349bd6a1726856a78f7929f3878f7e2ee83c296c69495309e"},
181 | {file = "lxml-5.3.0-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:2d9b8d9177afaef80c53c0a9e30fa252ff3036fb1c6494d427c066a4ce6a282f"},
182 | {file = "lxml-5.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:20094fc3f21ea0a8669dc4c61ed7fa8263bd37d97d93b90f28fc613371e7a875"},
183 | {file = "lxml-5.3.0-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:ace2c2326a319a0bb8a8b0e5b570c764962e95818de9f259ce814ee666603f19"},
184 | {file = "lxml-5.3.0-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:92e67a0be1639c251d21e35fe74df6bcc40cba445c2cda7c4a967656733249e2"},
185 | {file = "lxml-5.3.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd5350b55f9fecddc51385463a4f67a5da829bc741e38cf689f38ec9023f54ab"},
186 | {file = "lxml-5.3.0-pp38-pypy38_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:4c1fefd7e3d00921c44dc9ca80a775af49698bbfd92ea84498e56acffd4c5469"},
187 | {file = "lxml-5.3.0-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:71a8dd38fbd2f2319136d4ae855a7078c69c9a38ae06e0c17c73fd70fc6caad8"},
188 | {file = "lxml-5.3.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:97acf1e1fd66ab53dacd2c35b319d7e548380c2e9e8c54525c6e76d21b1ae3b1"},
189 | {file = "lxml-5.3.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:68934b242c51eb02907c5b81d138cb977b2129a0a75a8f8b60b01cb8586c7b21"},
190 | {file = "lxml-5.3.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b710bc2b8292966b23a6a0121f7a6c51d45d2347edcc75f016ac123b8054d3f2"},
191 | {file = "lxml-5.3.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:18feb4b93302091b1541221196a2155aa296c363fd233814fa11e181adebc52f"},
192 | {file = "lxml-5.3.0-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:3eb44520c4724c2e1a57c0af33a379eee41792595023f367ba3952a2d96c2aab"},
193 | {file = "lxml-5.3.0-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:609251a0ca4770e5a8768ff902aa02bf636339c5a93f9349b48eb1f606f7f3e9"},
194 | {file = "lxml-5.3.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:516f491c834eb320d6c843156440fe7fc0d50b33e44387fcec5b02f0bc118a4c"},
195 | {file = "lxml-5.3.0.tar.gz", hash = "sha256:4e109ca30d1edec1ac60cdbe341905dc3b8f55b16855e03a54aaf59e51ec8c6f"},
196 | ]
197 |
198 | [package.extras]
199 | cssselect = ["cssselect (>=0.7)"]
200 | html-clean = ["lxml-html-clean"]
201 | html5 = ["html5lib"]
202 | htmlsoup = ["BeautifulSoup4"]
203 | source = ["Cython (>=3.0.11)"]
204 |
205 | [[package]]
206 | name = "lxml-html-clean"
207 | version = "0.4.1"
208 | description = "HTML cleaner from lxml project"
209 | optional = false
210 | python-versions = "*"
211 | files = [
212 | {file = "lxml_html_clean-0.4.1-py3-none-any.whl", hash = "sha256:b704f2757e61d793b1c08bf5ad69e4c0b68d6696f4c3c1429982caf90050bcaf"},
213 | {file = "lxml_html_clean-0.4.1.tar.gz", hash = "sha256:40c838bbcf1fc72ba4ce811fbb3135913017b27820d7c16e8bc412ae1d8bc00b"},
214 | ]
215 |
216 | [package.dependencies]
217 | lxml = "*"
218 |
219 | [[package]]
220 | name = "python-dateutil"
221 | version = "2.9.0.post0"
222 | description = "Extensions to the standard Python datetime module"
223 | optional = false
224 | python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
225 | files = [
226 | {file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"},
227 | {file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"},
228 | ]
229 |
230 | [package.dependencies]
231 | six = ">=1.5"
232 |
233 | [[package]]
234 | name = "six"
235 | version = "1.17.0"
236 | description = "Python 2 and 3 compatibility utilities"
237 | optional = false
238 | python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
239 | files = [
240 | {file = "six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"},
241 | {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"},
242 | ]
243 |
244 | [[package]]
245 | name = "soupsieve"
246 | version = "2.6"
247 | description = "A modern CSS selector implementation for Beautiful Soup."
248 | optional = false
249 | python-versions = ">=3.8"
250 | files = [
251 | {file = "soupsieve-2.6-py3-none-any.whl", hash = "sha256:e72c4ff06e4fb6e4b5a9f0f55fe6e81514581fca1515028625d0f299c602ccc9"},
252 | {file = "soupsieve-2.6.tar.gz", hash = "sha256:e2e68417777af359ec65daac1057404a3c8a5455bb8abc36f1a9866ab1a51abb"},
253 | ]
254 |
255 | [[package]]
256 | name = "tqdm"
257 | version = "4.67.1"
258 | description = "Fast, Extensible Progress Meter"
259 | optional = false
260 | python-versions = ">=3.7"
261 | files = [
262 | {file = "tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2"},
263 | {file = "tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2"},
264 | ]
265 |
266 | [package.dependencies]
267 | colorama = {version = "*", markers = "platform_system == \"Windows\""}
268 |
269 | [package.extras]
270 | dev = ["nbval", "pytest (>=6)", "pytest-asyncio (>=0.24)", "pytest-cov", "pytest-timeout"]
271 | discord = ["requests"]
272 | notebook = ["ipywidgets (>=6)"]
273 | slack = ["slack-sdk"]
274 | telegram = ["requests"]
275 |
276 | [metadata]
277 | lock-version = "2.0"
278 | python-versions = "^3.11"
279 | content-hash = "1da29610a53779e9cfdf1dbeb32da803325b597aada5d134f48db71bd4b87613"
280 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "xerparser"
3 | version = "0.13.5"
4 | description = "Parse a P6 .xer file to a Python object."
5 | authors = ["Jesse "]
6 | license = "GPL-3.0-only"
7 | readme = "README.md"
8 | keywords = ["primavera", "p6", "xer", "schedule", "scheduling", "planning", "project management", "project controls"]
9 | repository = "https://github.com/jjCode01/xerparser"
10 |
11 | [tool.poetry.dependencies]
12 | python = "^3.11"
13 | html-sanitizer = "^2.2.0"
14 |
15 | [tool.poetry.group.test.dependencies]
16 | tqdm = "^4.64.1"
17 | python-dateutil = "^2.8.2"
18 |
19 | [tool.poetry.scripts]
20 | test = 'scripts:test'
21 | parse_test = 'scripts:parse_test'
22 | calc_rem_hours_test = 'scripts:rem_hours_per_day_test'
23 | test_task_rsrc_compare = 'scripts:test_task_rsrc_compare'
24 |
25 |
26 | [build-system]
27 | requires = ["poetry-core"]
28 | build-backend = "poetry.core.masonry.api"
29 |
--------------------------------------------------------------------------------
/scripts.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 |
3 |
4 | def test():
5 | """
6 | Run all unittests. Equivalent to:
7 | `poetry run python -u -m unittest discover`
8 | """
9 | subprocess.run(["python", "-u", "-m", "unittest", "discover"])
10 |
11 |
12 | def parse_test():
13 | subprocess.run(
14 | ["python", "-m", "unittest", "tests.test_parser.TestParser.test_create_xer"]
15 | )
16 |
17 |
18 | def test_task_rsrc_compare():
19 | subprocess.run(
20 | [
21 | "python",
22 | "-m",
23 | "unittest",
24 | "tests.test_parser.TestParser.test_task_rsrc_compare",
25 | ]
26 | )
27 |
28 |
29 | def rem_hours_per_day_test():
30 | subprocess.run(
31 | ["python", "-m", "unittest", "tests.test_parser.TestParser.test_rem_hour_calc"]
32 | )
33 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jjCode01/xerparser/c425263385807f77c5ffc5d8e930d9f028df668f/tests/__init__.py
--------------------------------------------------------------------------------
/tests/config_template.py:
--------------------------------------------------------------------------------
1 | """
2 | !!! COPY THIS FILE TO config.py !!!
3 |
4 | Replace value of `directory` with the path to a folder containing .xer files.
5 | The test setup will recursively run through this folder and any subfolders to find
6 | all .xer files.
7 |
8 | Caution: the more .xer files found, the longer the setup and test will take to run.
9 |
10 | """
11 |
12 | # Change directory to path containing .xer files
13 | directory = r"path/to/xer/files"
14 |
--------------------------------------------------------------------------------
/tests/test_parser.py:
--------------------------------------------------------------------------------
1 | """
2 | Unittests for xerparser.
3 |
4 | 1. Setup the config.py file - follow instructions in config_template.py
5 |
6 | 2. Run the tests before making any code changes.
7 | - On the first run, you will be prompted to create a `xer_data.json` file - select y.
8 | - This will run through each .xer file in the specified directory, create a Xer object,
9 | and outputs the values of various attributes, properties, and methods to a json file.
10 |
11 | 3. The subsequent tests will run through each .xer file in the specified directory, create a Xer object,
12 | and compare it's attribute/property/method return values against the values stored in the json file.
13 | - The test will fail if any values differ between the Xer object and the json file.
14 | - The test will also fail if any Exceptions (other than CorruptXerFile) are raised during initialzation of the Xer object.
15 | """
16 |
17 | import json
18 | import os
19 | import sys
20 | import unittest
21 | from collections import Counter
22 | from multiprocessing import Pool
23 | from pathlib import Path
24 | from typing import Any
25 |
26 | from dateutil.relativedelta import relativedelta
27 | from tqdm import tqdm
28 |
29 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
30 |
31 | import tests.config as config
32 | from xerparser.src.errors import CorruptXerFile
33 | from xerparser.src.xer import CALENDAR, PROJECT, TASKRSRC, Xer
34 |
35 | DATE_FORMAT = "%Y-%m-%d %M:%S" # format datetime objects to strings
36 | PLANNED_DAYS = 14 # planned days ahead of data date for planned_progress testing
37 | MAX_TEST_FILES = 250 # maximum number of files to test
38 |
39 |
40 | def process_xer(file: Path) -> dict | None:
41 | try:
42 | xer = Xer.reader(file)
43 | except CorruptXerFile as e:
44 | return {"file": str(file.absolute()), "errors": e.errors}
45 | except KeyError as e:
46 | return {"file": str(file.absolute()), "errors": str(e)}
47 |
48 | xer_data = {
49 | project.short_name: process_project(project)
50 | for project in xer.projects.values()
51 | }
52 |
53 | return {
54 | "file": str(file.absolute()),
55 | "version": xer.export_info.version,
56 | "export_date": xer.export_info.date.strftime(DATE_FORMAT),
57 | "accounts": len(xer.accounts),
58 | "udf_types": [
59 | {"label": udf.label, "table": udf.table, "type": udf.type.value}
60 | for udf in xer.udf_types.values()
61 | ],
62 | **xer_data,
63 | }
64 |
65 |
66 | def process_project(project: PROJECT) -> dict[str, Any]:
67 | return {
68 | "name": project.name,
69 | "activity_codes": [code.name for code in project.activity_codes],
70 | "actual_cost": project.actual_cost,
71 | "actual_start_date": project.actual_start.strftime(DATE_FORMAT),
72 | "budget_cost": project.budgeted_cost,
73 | "calendars": {cal.uid: process_calendar(cal) for cal in project.calendars},
74 | "duration_percent": project.duration_percent,
75 | "original_duration": project.original_duration,
76 | "planned_progress": process_planned_progress(
77 | project.planned_progress(
78 | project.data_date + relativedelta(days=PLANNED_DAYS)
79 | )
80 | ),
81 | "project_codes": {
82 | code.name: val.code for code, val in project.project_codes.items()
83 | },
84 | "relationship_count": len(project.relationships),
85 | "remaining_cost": project.remaining_cost,
86 | "remaining_duration": project.remaining_duration,
87 | "task_activity_code_count": sum(
88 | len(task.activity_codes) for task in project.tasks
89 | ),
90 | "task_count": len(project.tasks),
91 | "task_memo_count": sum(len(task.memos) for task in project.tasks),
92 | "task_period_count": sum(len(task.periods) for task in project.tasks),
93 | "task_resource_count": sum(len(task.resources) for task in project.tasks),
94 | "task_percent": project.task_percent,
95 | "task_udf_count": sum(len(task.user_defined_fields) for task in project.tasks),
96 | "this_period_cost": project.this_period_cost,
97 | "wbs_count": len(project.wbs_nodes),
98 | "wbs_depth": project.wbs_root.height,
99 | }
100 |
101 |
102 | def process_planned_progress(progress: dict) -> dict[str, int]:
103 | prog_counts = {date: len(tasks) for date, tasks in progress.items()}
104 | return prog_counts
105 |
106 |
107 | def process_calendar(calendar: CALENDAR):
108 | return {
109 | "name": calendar.name,
110 | "type": calendar.type.value,
111 | "workdays": [weekday for weekday, day in calendar.work_week.items() if day],
112 | "workweek_hours": sum([day.hours for day in calendar.work_week.values()]),
113 | "holiday_count": len(calendar.holidays),
114 | "work_exception_count": len(calendar.work_exceptions),
115 | }
116 |
117 |
118 | def create_test_data(file_directory: Path) -> None:
119 | files = [file for file in file_directory.glob("**/*.xer")]
120 |
121 | if not files:
122 | raise FileNotFoundError(f"No .xer files found in {file_directory.absolute()}")
123 |
124 | print(f"Found {len(files)} xer files... Max files to test is {MAX_TEST_FILES}")
125 |
126 | if len(files) > MAX_TEST_FILES:
127 | files = files[:MAX_TEST_FILES]
128 |
129 | with Pool() as p:
130 | data_list = list(
131 | tqdm(
132 | p.imap(process_xer, files),
133 | total=len(files),
134 | )
135 | )
136 |
137 | json_data = json.dumps(data_list, indent=4)
138 | file_path = Path("./tests/fixtures")
139 | if not Path.exists(file_path):
140 | Path.mkdir(file_path)
141 |
142 | with open("./tests/fixtures/xer_data.json", "w") as outfile:
143 | outfile.write(json_data)
144 |
145 |
146 | def _taskrsrc_shallow_compare(res_1: TASKRSRC, res_2: TASKRSRC) -> bool:
147 | if (
148 | res_1.resource != res_2.resource
149 | or res_1.account != res_2.account
150 | or res_1.lag != res_2.lag
151 | ):
152 | return False
153 | return True
154 |
155 |
156 | class TestParser(unittest.TestCase):
157 | def setUp(self) -> None:
158 | xer_data_file = Path(r"./tests/fixtures/xer_data.json")
159 | if not Path.is_file(xer_data_file):
160 | if not Path.exists(Path(config.directory)):
161 | raise FileNotFoundError(
162 | f"Could not find the directory in the config.py file {config.directory}"
163 | )
164 |
165 | create_data = input(
166 | "Test data file [xer_data.json] does not exist, would you like to attempt to create it? (y/n) "
167 | )
168 | if create_data.lower() == "y":
169 | print("Creating test data....")
170 | create_test_data(Path(config.directory))
171 | else:
172 | raise FileNotFoundError("Could not find xer_data.json")
173 |
174 | with open(xer_data_file) as f:
175 | self.test_data: dict = json.load(f)
176 |
177 | self.valid_data = [
178 | data for data in self.test_data if data and Path.is_file(Path(data["file"]))
179 | ]
180 |
181 | if not self.valid_data:
182 | re_create_data = input(
183 | "Test data file [xer_data.json] does not reference valid .xer files, would you like to attempt to re-create it? (y/n) "
184 | )
185 |
186 | if re_create_data.lower() == "y":
187 | print("Re-creating test data....")
188 | create_test_data(Path(config.directory))
189 |
190 | def test_task_rsrc_compare(self):
191 | """
192 | Compares resources for two xer files that should have no differences in the task resource assignments.
193 |
194 | TODO:
195 | This test is just thrown together for now and needs to be reworked.
196 |
197 | """
198 | print("Running task rsrc comparison...")
199 |
200 | previous = list(Xer.reader(config.file1).projects.values())[0]
201 | current = list(Xer.reader(config.file2).projects.values())[0]
202 |
203 | for task in sorted(
204 | filter(lambda t: t.task_code in previous.tasks_by_code, current.tasks),
205 | key=lambda t: t.task_code,
206 | ):
207 | prev_task = previous.tasks_by_code[task.task_code]
208 |
209 | res_counter = Counter(task.resources.values())
210 | res_counter.subtract(Counter(prev_task.resources.values()))
211 |
212 | for r, c in res_counter.items():
213 | self.assertEqual(c, 0, "Found variance in Resource Assignments")
214 |
215 | def test_create_xer(self):
216 | """Tests creation of Xer objects"""
217 |
218 | print(
219 | f"Running xer parser tests on {len(self.valid_data)} of {len(self.test_data)} .xer files."
220 | )
221 |
222 | for file in tqdm(self.valid_data):
223 | try:
224 | xer = Xer.reader(file["file"])
225 | except CorruptXerFile as e:
226 | self.assertEqual(e.errors, file["errors"])
227 | except KeyError as e:
228 | self.assertEqual(str(e), file["errors"])
229 | else:
230 | self.assertEqual(len(xer.accounts), file["accounts"])
231 |
232 | self.assertEqual(
233 | [
234 | {"label": udf.label, "table": udf.table, "type": udf.type.value}
235 | for udf in xer.udf_types.values()
236 | ],
237 | file["udf_types"],
238 | )
239 |
240 | for project in xer.projects.values():
241 | self.assertEqual(
242 | project.name,
243 | file[project.short_name]["name"],
244 | f"{project.short_name} Name",
245 | )
246 | self.assertEqual(
247 | project.budgeted_cost,
248 | file[project.short_name]["budget_cost"],
249 | f"{project.short_name} Budgeted Cost",
250 | )
251 | self.assertEqual(
252 | project.actual_cost,
253 | file[project.short_name]["actual_cost"],
254 | f"{project.short_name} Actual Cost",
255 | )
256 | self.assertEqual(
257 | project.this_period_cost,
258 | file[project.short_name]["this_period_cost"],
259 | f"{project.short_name} This Period Cost",
260 | )
261 | self.assertEqual(
262 | project.remaining_cost,
263 | file[project.short_name]["remaining_cost"],
264 | f"{project.short_name} Remaining Cost",
265 | )
266 | self.assertEqual(
267 | [code.name for code in project.activity_codes],
268 | file[project.short_name]["activity_codes"],
269 | f"{project.short_name} Activity Codes",
270 | )
271 | self.assertEqual(
272 | {
273 | code.name: val.code
274 | for code, val in project.project_codes.items()
275 | },
276 | file[project.short_name]["project_codes"],
277 | f"{project.short_name} Project Codes",
278 | )
279 | self.assertEqual(
280 | project.actual_start.strftime(DATE_FORMAT),
281 | file[project.short_name]["actual_start_date"],
282 | f"{project.short_name} Project Acutal Start",
283 | )
284 | self.assertEqual(
285 | project.duration_percent,
286 | file[project.short_name]["duration_percent"],
287 | f"{project.short_name} Project Duration Percent",
288 | )
289 | self.assertEqual(
290 | project.original_duration,
291 | file[project.short_name]["original_duration"],
292 | f"{project.short_name} Project Original Duration",
293 | )
294 | planned_progress = project.planned_progress(
295 | project.data_date + relativedelta(days=PLANNED_DAYS)
296 | )
297 | self.assertEqual(
298 | process_planned_progress(planned_progress),
299 | file[project.short_name]["planned_progress"],
300 | f"{project.short_name} Project Planned Progress Counts",
301 | )
302 | self.assertEqual(
303 | project.remaining_duration,
304 | file[project.short_name]["remaining_duration"],
305 | f"{project.short_name} Project Remaining Duration",
306 | )
307 | self.assertEqual(
308 | project.task_percent,
309 | file[project.short_name]["task_percent"],
310 | f"{project.short_name} Project Task Percent Complete",
311 | )
312 | self.assertEqual(
313 | sum(len(task.memos) for task in project.tasks),
314 | file[project.short_name]["task_memo_count"],
315 | f"{project.short_name} Project Task Memo Count",
316 | )
317 | self.assertEqual(
318 | sum(len(task.periods) for task in project.tasks),
319 | file[project.short_name]["task_period_count"],
320 | f"{project.short_name} Project Task Period Count",
321 | )
322 | self.assertEqual(
323 | sum(len(task.resources) for task in project.tasks),
324 | file[project.short_name]["task_resource_count"],
325 | f"{project.short_name} Project Task Resource Count",
326 | )
327 | self.assertEqual(
328 | sum(len(task.activity_codes) for task in project.tasks),
329 | file[project.short_name]["task_activity_code_count"],
330 | f"{project.short_name} Project Task Activity Code Count",
331 | )
332 | self.assertEqual(
333 | sum(len(task.user_defined_fields) for task in project.tasks),
334 | file[project.short_name]["task_udf_count"],
335 | f"{project.short_name} Project Task UDF Count",
336 | )
337 | self.assertEqual(
338 | sum(len(task.predecessors) for task in project.tasks),
339 | file[project.short_name]["relationship_count"],
340 | f"{project.short_name} Project Task Predecessor Count",
341 | )
342 | self.assertEqual(
343 | sum(len(task.successors) for task in project.tasks),
344 | file[project.short_name]["relationship_count"],
345 | f"{project.short_name} Project Task Successor Count",
346 | )
347 | self.assertEqual(
348 | project.wbs_root.size,
349 | file[project.short_name]["wbs_count"] - 1,
350 | f"{project.short_name} Project WBS count / size",
351 | )
352 | self.assertEqual(
353 | project.wbs_root.height,
354 | file[project.short_name]["wbs_depth"],
355 | f"{project.short_name} Project WBS Depth",
356 | )
357 | self.assertEqual(
358 | len(project.wbs_root.all_tasks),
359 | file[project.short_name]["task_count"],
360 | f"{project.short_name} Project WBS all_tasks",
361 | )
362 | for calendar in project.calendars:
363 | self.assertEqual(
364 | [day for day, work in calendar.work_week.items() if work],
365 | file[project.short_name]["calendars"][calendar.uid][
366 | "workdays"
367 | ],
368 | f"{project.short_name} - Calendar {calendar.uid} work week",
369 | )
370 | self.assertEqual(
371 | sum((day.hours for day in calendar.work_week.values())),
372 | file[project.short_name]["calendars"][calendar.uid][
373 | "workweek_hours"
374 | ],
375 | f"{project.short_name} - Calendar {calendar.uid} work week hours",
376 | )
377 | self.assertEqual(
378 | len(calendar.holidays),
379 | file[project.short_name]["calendars"][calendar.uid][
380 | "holiday_count"
381 | ],
382 | f"{project.short_name} - Calendar {calendar.uid} holiday count",
383 | )
384 | self.assertEqual(
385 | len(calendar.work_exceptions),
386 | file[project.short_name]["calendars"][calendar.uid][
387 | "work_exception_count"
388 | ],
389 | f"{project.short_name} - Calendar {calendar.uid} exception count",
390 | )
391 |
392 | for node in project.wbs_nodes:
393 | self.assertAlmostEqual(
394 | node.budgeted_cost,
395 | round(
396 | node.actual_cost
397 | + node.remaining_cost
398 | - node.cost_variance,
399 | 2,
400 | ),
401 | None,
402 | f"{project.short_name} - WBS {node.name} Cost Variance",
403 | 0.011,
404 | )
405 | self.assertEqual(
406 | node.original_duration,
407 | node.actual_duration + node.remaining_duration,
408 | f"{project.short_name} - WBS {node.name} Duration Variance",
409 | )
410 |
411 | def test_rem_hour_calc(self):
412 | """Tests calculation of task rem work hours"""
413 |
414 | print(
415 | f"Running calc remaining hours tests on {len(self.valid_data)} of {len(self.test_data)} .xer files."
416 | )
417 |
418 | for file in tqdm(self.valid_data):
419 | with open(file["file"], encoding=Xer.CODEC, errors="ignore") as f:
420 | file_contents = f.read()
421 | file_name = f.name
422 | try:
423 | xer = Xer(file_contents)
424 | except CorruptXerFile:
425 | continue
426 | except KeyError:
427 | continue
428 |
429 | for project in xer.projects.values():
430 | for task in project.tasks:
431 | if task.status.is_completed or not task.restart_date:
432 | continue
433 | if task.type.is_milestone:
434 | continue
435 | if not task.calendar:
436 | continue
437 |
438 | rem_hours = task.rem_hours_per_day()
439 | self.assertEqual(
440 | round(sum(day for day in rem_hours.values()), 2),
441 | round(task.remain_drtn_hr_cnt, 2),
442 | f"File: {file_name}\n{project.short_name} - {project.name}\n{task}\nCalendar: {task.calendar} {task.calendar.uid}\nStart: {task.restart_date}\nFinish: {task.reend_date}\nRem Hours: {task.remain_drtn_hr_cnt}\n{rem_hours}",
443 | )
444 |
445 |
446 | if __name__ == "__main__":
447 | print("Running tests....")
448 | unittest.main()
449 |
--------------------------------------------------------------------------------
/xerparser/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = "0.13.5"
2 |
3 | from xerparser.schemas.actvcode import ACTVCODE # noqa: F401
4 | from xerparser.schemas.actvtype import ACTVTYPE # noqa: F401
5 | from xerparser.schemas.calendars import CALENDAR # noqa: F401
6 | from xerparser.schemas.ermhdr import ERMHDR # noqa: F401
7 | from xerparser.schemas.findates import FINDATES # noqa: F401
8 | from xerparser.schemas.pcattype import PCATTYPE # noqa: F401
9 | from xerparser.schemas.pcatval import PCATVAL # noqa: F401
10 | from xerparser.schemas.project import PROJECT # noqa: F401
11 | from xerparser.schemas.projwbs import PROJWBS # noqa: F401
12 | from xerparser.schemas.rsrc import RSRC # noqa: F401
13 | from xerparser.schemas.rsrcrate import RSRCRATE # noqa: F401
14 | from xerparser.schemas.task import TASK # noqa: F401
15 | from xerparser.schemas.taskfin import TASKFIN # noqa: F401
16 | from xerparser.schemas.taskmemo import TASKMEMO # noqa: F401
17 | from xerparser.schemas.taskpred import TASKPRED # noqa: F401
18 | from xerparser.schemas.taskrsrc import TASKRSRC # noqa: F401
19 | from xerparser.schemas.trsrcfin import TRSRCFIN # noqa: F401
20 | from xerparser.schemas.udftype import UDFTYPE # noqa: F401
21 | from xerparser.src.errors import CorruptXerFile, find_xer_errors # noqa: F401
22 | from xerparser.src.parser import file_reader, parser # noqa: F401
23 | from xerparser.src.xer import Xer # noqa: F401
24 |
--------------------------------------------------------------------------------
/xerparser/schemas/__init__.py:
--------------------------------------------------------------------------------
1 | TABLE_UID_MAP = {
2 | "ACCOUNT": "acct_id",
3 | "ACTVCODE": "actv_code_id",
4 | "ACTVTYPE": "actv_code_type_id",
5 | "CALENDAR": "clndr_id",
6 | "FINDATES": "fin_dates_id",
7 | "MEMOTYPE": "memo_type_id",
8 | "PCATTYPE": "proj_catg_type_id",
9 | "PCATVAL": "proj_catg_id",
10 | "PROJECT": "proj_id",
11 | "PROJWBS": "wbs_id",
12 | "RSRC": "rsrc_id",
13 | "RSRCRATE": "rsrc_rate_id",
14 | "SCHEDOPTIONS": "proj_id",
15 | "TASK": "task_id",
16 | "TASKPRED": "task_pred_id",
17 | "UDFTYPE": "udf_type_id",
18 | }
19 |
--------------------------------------------------------------------------------
/xerparser/schemas/_node.py:
--------------------------------------------------------------------------------
1 | from typing import Iterator, Self
2 |
3 |
4 | class Node:
5 | """A class to represent a node in a `Tree Data Structure`."""
6 |
7 | def __init__(
8 | self, uid: str, code: str, name: str, parent_id: str, seq_num: int = 0
9 | ) -> None:
10 | self.uid: str = uid
11 | """Unique Table ID"""
12 | self.code: str = code
13 | """Code or ID for Node"""
14 | self.name: str = name
15 | """Name or description of Node"""
16 | self.parent_id: str = parent_id
17 | """Parent Unique Table ID"""
18 | self.seq_num = seq_num
19 | self._parent: Self | None = None
20 | self._children: dict[str, Self] = {}
21 |
22 | def __eq__(self, __o: Self) -> bool:
23 | self._validate(__o)
24 | return self.full_code == __o.full_code
25 |
26 | def __hash__(self) -> int:
27 | return hash(self.full_code)
28 |
29 | def __gt__(self, __o: Self) -> bool:
30 | self._validate(__o)
31 | if self.parent == __o.parent:
32 | if self.seq_num != __o.seq_num:
33 | return self.seq_num > __o.seq_num
34 | return self.full_code > __o.full_code
35 |
36 | def __lt__(self, __o: Self) -> bool:
37 | self._validate(__o)
38 | if self.parent == __o.parent:
39 | if self.seq_num != __o.seq_num:
40 | return self.seq_num < __o.seq_num
41 | return self.full_code < __o.full_code
42 |
43 | def __str__(self) -> str:
44 | return f"{self.full_code} - {self.name}"
45 |
46 | def addChild(self, child: Self) -> None:
47 | """Add child node"""
48 | self._validate(child)
49 | self._children[child.uid] = child
50 |
51 | @property
52 | def children(self) -> list[Self]:
53 | """List of children nodes"""
54 | return list(self._children.values())
55 |
56 | @property
57 | def depth(self) -> int:
58 | """
59 | Length of the path to the root node (i.e., root path).
60 | Root node will have a depth of 0.
61 | """
62 | return len(list(self.traverse_parents())) - 1
63 |
64 | @property
65 | def height(self) -> int:
66 | """
67 | Length of the longest downward path to a leaf.
68 | Leaves will have a height of 0.
69 | """
70 | return max([child.depth for child in self.traverse_children()]) - self.depth
71 |
72 | @property
73 | def full_code(self) -> str:
74 | """Node code/ID including parent codes/IDs"""
75 | if not self.parent:
76 | return self.code
77 | return f"{self.parent.full_code}.{self.code}"
78 |
79 | @property
80 | def lineage(self) -> list[Self]:
81 | if not self._parent:
82 | return [self]
83 | return self._parent.lineage + [self]
84 |
85 | @property
86 | def parent(self) -> Self | None:
87 | """Parent node"""
88 | return self._parent
89 |
90 | @parent.setter
91 | def parent(self, value: Self | None) -> None:
92 | if value is None:
93 | return
94 | self._parent = self._validate(value)
95 |
96 | @property
97 | def size(self) -> int:
98 | """Number of children and decendent nodes"""
99 | return len([child for child in self.traverse_children()]) - 1
100 |
101 | def traverse_parents(self) -> Iterator[Self]:
102 | """Iterate through parents to root."""
103 | yield self
104 | if self.parent:
105 | yield from self.parent.traverse_parents()
106 |
107 | def traverse_children(self) -> Iterator[Self]:
108 | """Iterate through children to leaves."""
109 | yield self
110 | for child in self.children:
111 | yield from child.traverse_children()
112 |
113 | def _validate(self, _o2) -> Self:
114 | if type(self) is not type(_o2):
115 | raise TypeError(f"Expected {type(self)}; got {type(_o2)}")
116 | return _o2
117 |
118 |
119 | def build_tree(nodes: dict[str, Node]) -> dict:
120 | for node in sorted(list(nodes.values())):
121 | if parent := nodes.get(node.parent_id):
122 | node.parent = parent
123 | parent.addChild(node)
124 | return nodes
125 |
--------------------------------------------------------------------------------
/xerparser/schemas/account.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # account.py
3 |
4 | from typing import Self
5 |
6 | from xerparser.schemas._node import Node
7 | from xerparser.src.validators import int_or_zero
8 |
9 |
10 | class ACCOUNT(Node):
11 | """
12 | A class to represent a cost account.
13 | """
14 |
15 | def __init__(self, **data: str) -> None:
16 | super().__init__(
17 | data["acct_id"],
18 | data["acct_short_name"],
19 | data["acct_name"],
20 | data["parent_acct_id"],
21 | int_or_zero(data["acct_seq_num"]),
22 | )
23 | self.description: str = _check_description(data["acct_descr"])
24 | """Cost Account Description"""
25 |
26 | def __eq__(self, __o: Self) -> bool:
27 | if __o is None:
28 | return False
29 | return self.name == __o.name and self.full_code == __o.full_code
30 |
31 | def __hash__(self) -> int:
32 | return hash((self.name, self.full_code))
33 |
34 |
35 | def _check_description(value: str) -> str:
36 | return (value, "")[value == "" or value == ""]
37 |
--------------------------------------------------------------------------------
/xerparser/schemas/actvcode.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # actvcode.py
3 |
4 |
5 | from xerparser.schemas._node import Node
6 | from xerparser.schemas.actvtype import ACTVTYPE
7 | from xerparser.src.validators import int_or_zero
8 |
9 |
10 | class ACTVCODE(Node):
11 | """
12 | A class to represent an Activity Code Value
13 | """
14 |
15 | def __init__(self, code_type: ACTVTYPE, **data: str) -> None:
16 | super().__init__(
17 | data["actv_code_id"],
18 | data["short_name"],
19 | data["actv_code_name"],
20 | data["parent_actv_code_id"],
21 | int_or_zero(data["seq_num"]),
22 | )
23 | self.actv_code_type_id: str = data["actv_code_type_id"]
24 | """Foreign Key to Activity Code Type"""
25 | self.code_type: ACTVTYPE = self._valid_actvtype(code_type)
26 | """Activity Code Type"""
27 |
28 | def __eq__(self, __o: "ACTVCODE") -> bool:
29 | return self.full_code == __o.full_code and self.code_type == __o.code_type
30 |
31 | def __hash__(self) -> int:
32 | return hash((self.full_code, self.code_type))
33 |
34 | def _valid_actvtype(self, value: ACTVTYPE) -> ACTVTYPE:
35 | """Validate Activity Code Type"""
36 | if not isinstance(value, ACTVTYPE):
37 | raise TypeError(f"Expected ; got {type(value)}")
38 | if value.uid != self.actv_code_type_id:
39 | raise ValueError(
40 | f"{value.uid} does not match act_code_type_id {self.actv_code_type_id}"
41 | )
42 | return value
43 |
--------------------------------------------------------------------------------
/xerparser/schemas/actvtype.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # actvtype.py
3 |
4 |
5 | class ACTVTYPE:
6 | """
7 | A class representing Activity Codes Types
8 | """
9 |
10 | def __init__(self, **data: str) -> None:
11 | self.uid: str = data["actv_code_type_id"]
12 | """Unique Table ID"""
13 | self.max_length: int = int(data["actv_short_len"])
14 | """Max Character Length of Acticity Code"""
15 | self.name: str = data["actv_code_type"]
16 | """Name of Activity Code Type"""
17 | self.proj_id: str = data["proj_id"]
18 | """Foreign Key for Project (Project Level Activity Codes)"""
19 | self.scope: str = _check_scope(data["actv_code_type_scope"])
20 | """Activity Code Scope - Global, Enterpise, or Project"""
21 | self.seq_num: int | None = None if (seq := data["seq_num"]) == "" else int(seq)
22 | """Sort Order"""
23 |
24 | def __eq__(self, __o: "ACTVTYPE") -> bool:
25 | return all(
26 | (
27 | self.max_length == __o.max_length,
28 | self.name == __o.name,
29 | self.scope == __o.scope,
30 | )
31 | )
32 |
33 | def __gt__(self, __o: "ACTVTYPE") -> bool:
34 | return self.name > __o.name
35 |
36 | def __lt__(self, __o: "ACTVTYPE") -> bool:
37 | return self.name < __o.name
38 |
39 | def __hash__(self) -> int:
40 | return hash((self.max_length, self.name, self.scope))
41 |
42 |
43 | def _check_scope(value: str) -> str:
44 | if not value.startswith("AS_"):
45 | raise ValueError(f"Expected 'AS_Project' or 'AS_Global', got {value}")
46 | return value[3:]
47 |
--------------------------------------------------------------------------------
/xerparser/schemas/calendars.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # calendars.py
3 |
4 |
5 | import re
6 | from dataclasses import dataclass, field
7 | from datetime import datetime, time, timedelta
8 | from enum import Enum
9 | from functools import cached_property
10 | from typing import Iterator, Optional
11 |
12 | from xerparser.scripts.dates import (
13 | calc_time_var_hrs,
14 | clean_date,
15 | clean_dates,
16 | conv_time,
17 | )
18 | from xerparser.src.validators import optional_date, optional_str, optional_float
19 |
20 | WEEKDAYS = (
21 | "Sunday",
22 | "Monday",
23 | "Tuesday",
24 | "Wednesday",
25 | "Thursday",
26 | "Friday",
27 | "Saturday",
28 | )
29 |
30 |
31 | class ClndrRegEx(Enum):
32 | """Regular Expressions used to parse the Calendar Data"""
33 |
34 | weekdays = re.compile(
35 | r"(?<=0\|\|)[1-7]\(\).+?(?=\(0\|\|[1-7]\(\)|\(0\|\|VIEW|\(0\|\|Exceptions|\)$)"
36 | )
37 | shifts = re.compile(r"[sf]\|[0-2]?\d:[0-5]\d\|[sf]\|[0-2]?\d:[0-5]\d")
38 | shift_hours = re.compile(r"[0-2]?\d:[0-5]\d")
39 | holidays = re.compile(r"(?<=d\|)\d{5}(?=\)\(\))")
40 | exceptions = re.compile(r"(?<=d\|)\d{5}\)\([^\)]{1}.+?\(\)\)\)")
41 |
42 |
43 | @dataclass(frozen=True)
44 | class WeekDay:
45 | """
46 | A class to represent a weekday.
47 |
48 | ...
49 |
50 | Attributes
51 | ----------
52 | week_day: str
53 | Day of week (Monday, Tuesday, Wednesday, etc...)
54 | shifts: list
55 | List of start and stop work times
56 | hours: int
57 | Total work hours for the day
58 | start: time
59 | Start work time
60 | finish: time
61 | Finish work time
62 | """
63 |
64 | week_day: str
65 | shifts: list[tuple[time, time]] = field(default_factory=list)
66 | hours: float = field(init=False, default=0)
67 | start: time = field(init=False, default=time(0, 0, 0, 0))
68 | finish: time = field(init=False, default=time(0, 0, 0, 0))
69 |
70 | def __post_init__(self):
71 | """
72 | Calculate properties after the object has been initialized
73 | """
74 | if self.shifts:
75 | shift_times = [hr for shift in self.shifts for hr in shift]
76 | object.__setattr__(
77 | self,
78 | "hours",
79 | sum(calc_time_var_hrs(shift[0], shift[1]) for shift in self.shifts),
80 | )
81 |
82 | object.__setattr__(self, "start", min(shift_times))
83 | object.__setattr__(self, "finish", max(shift_times))
84 |
85 | def __len__(self) -> int:
86 | return len(self.shifts)
87 |
88 | def __bool__(self) -> bool:
89 | """[False] if hours == 0; [True] is hours > 0."""
90 | return self.hours != 0
91 |
92 |
93 | class CALENDAR:
94 | """
95 | A class to represent a schedule Calendar.
96 | """
97 |
98 | class CalendarType(Enum):
99 | CA_Base = "Global"
100 | CA_Rsrc = "Resource"
101 | CA_Project = "Project"
102 |
103 | def __init__(self, **data: str) -> None:
104 | self.uid: str = data["clndr_id"]
105 | self.base_clndr_id: str | None = optional_str(data["base_clndr_id"])
106 | self.data: str = data["clndr_data"]
107 | self.is_default: bool = data["default_flag"] == "Y"
108 | self.last_chng_date: datetime | None = optional_date(data["last_chng_date"])
109 | self.name: str = data["clndr_name"]
110 | self.proj_id: str | None = optional_str(data["proj_id"])
111 | self.type: CALENDAR.CalendarType = CALENDAR.CalendarType[data["clndr_type"]]
112 | self.base_calendar: Optional["CALENDAR"] = None
113 | self.day_hr_cnt: float = optional_float(data["day_hr_cnt"])
114 | self.week_hr_cnt: float = optional_float(data["week_hr_cnt"])
115 | self.year_hr_cnt: float = optional_float(data["year_hr_cnt"])
116 |
117 | def __eq__(self, __o: "CALENDAR") -> bool:
118 | return self.name == __o.name and self.type == __o.type
119 |
120 | def __gt__(self, __o: "CALENDAR") -> bool:
121 | if self.name == __o.name:
122 | return self.type.value > __o.type.value
123 | return self.name > __o.name
124 |
125 | def __lt__(self, __o: "CALENDAR") -> bool:
126 | if self.name == __o.name:
127 | return self.type.value < __o.type.value
128 | return self.name < __o.name
129 |
130 | def __len__(self) -> int:
131 | return sum(day.hours > 0 for day in self.work_week.values())
132 |
133 | def __hash__(self) -> int:
134 | return hash((self.name, self.type))
135 |
136 | def __str__(self) -> str:
137 | return f"{self.name} [{self.type}]"
138 |
139 | @staticmethod
140 | def conv_excel_date(ordinal: int, _epoch0=datetime(1899, 12, 31)) -> datetime:
141 | """Convert Excel date format to datetime object"""
142 | if ordinal < 0 or not isinstance(ordinal, int):
143 | raise ValueError("Innappropiate value passed, should be positive integer.")
144 |
145 | # Excel leap year bug, 1900 is not a leap year
146 | if ordinal >= 60:
147 | ordinal -= 1
148 |
149 | return (_epoch0 + timedelta(days=ordinal)).replace(
150 | microsecond=0, second=0, minute=0, hour=0
151 | )
152 |
153 | @cached_property
154 | def holidays(self) -> list[datetime]:
155 | """Parse non-workday exceptions from Calendar data field."""
156 | nonwork_days = []
157 | for e in _parse_clndr_data(self.data, ClndrRegEx.holidays.value):
158 | _date = self.conv_excel_date(int(e))
159 |
160 | # Verify exception is not already a non-work day on the standard calendar
161 | if self.work_week.get(f"{_date:%A}"):
162 | nonwork_days.append(_date)
163 |
164 | return nonwork_days
165 |
166 | def is_workday(self, date_to_check: datetime) -> bool:
167 | """Checks if a date is a workday in a Calendar object"""
168 |
169 | if not isinstance(date_to_check, datetime):
170 | raise ValueError("Argument date_to_check must be a datetime object")
171 |
172 | # _date = date_to_check.date
173 | _date = clean_date(date_to_check)
174 | if _date in self.holidays:
175 | return False
176 | if (
177 | not self.holidays
178 | and self.base_calendar
179 | and _date in self.base_calendar.holidays
180 | ):
181 | return False
182 | if _date in self.work_exceptions.keys():
183 | return True
184 | return bool(self.work_week[f"{date_to_check:%A}"])
185 |
186 | def iter_holidays(self, start: datetime, end: datetime) -> Iterator[datetime]:
187 | """Yields nonwork exceptions (i.e. holidays) between 2 dates."""
188 | if not isinstance(start, datetime) or not isinstance(end, datetime):
189 | raise ValueError("Arguments must be a datetime object")
190 |
191 | # Clean start and end dates to remove time values
192 | cl_dates = clean_dates(start, end)
193 |
194 | check_date = min(cl_dates)
195 | while check_date <= max(cl_dates):
196 | if self.holidays and check_date in self.holidays:
197 | yield check_date
198 | if (
199 | not self.holidays
200 | and self.base_calendar
201 | and check_date in self.base_calendar.holidays
202 | ):
203 | yield check_date
204 | check_date += timedelta(days=1)
205 |
206 | def iter_workdays(self, start: datetime, end: datetime) -> Iterator[datetime]:
207 | """Yields valid workdays between 2 dates"""
208 |
209 | if not isinstance(start, datetime) or not isinstance(end, datetime):
210 | raise ValueError("Arguments must be a datetime object")
211 |
212 | # Clean start and end dates to remove time values
213 | _dates = clean_dates(start, end)
214 |
215 | check_date = min(_dates)
216 | while check_date <= max(_dates):
217 | if self.is_workday(check_date):
218 | yield check_date
219 | check_date += timedelta(days=1)
220 |
221 | @cached_property
222 | def work_exceptions(self) -> dict[datetime, WeekDay]:
223 | """Parse work-day exceptions from Calendar data field."""
224 | exception_dict = {}
225 | for exception in _parse_clndr_data(self.data, ClndrRegEx.exceptions.value):
226 | _date = self.conv_excel_date(int(exception[:5]))
227 | _day = _parse_work_day(exception)
228 |
229 | # Verify exception object is different than standard weekday object
230 | if _day != self.work_week.get(_day.week_day):
231 | exception_dict[_date] = _day
232 |
233 | return exception_dict
234 |
235 | @cached_property
236 | def work_week(self) -> dict[str, WeekDay]:
237 | """Parse work week from Calendar data field."""
238 | return {
239 | WEEKDAYS[int(day[0]) - 1]: _parse_work_day(day)
240 | for day in _parse_clndr_data(self.data, ClndrRegEx.weekdays.value)
241 | }
242 |
243 | def _calc_work_hours(
244 | self, date_to_calc: datetime, start_time: time, end_time: time
245 | ) -> float:
246 | """
247 | Calculate the work hours for a given day based on a start time, end time,
248 | and work shifts apportioned for that day of the week.
249 | """
250 | work_day = self._get_workday(date_to_calc)
251 |
252 | # date is not a workday
253 | if not work_day:
254 | return 0.0
255 |
256 | # reassign times if they were passed in the wrong order
257 | start_time, end_time = min(start_time, end_time), max(start_time, end_time)
258 |
259 | # ensure start and end times do not fall outside the workhours for the Week Day
260 | start_time = max(start_time, work_day.start)
261 | end_time = min(end_time, work_day.finish)
262 |
263 | # date is a full day of work
264 | if start_time == work_day.start and end_time == work_day.finish:
265 | return round(work_day.hours, 3)
266 |
267 | day_work_hrs = work_day.hours
268 |
269 | for shift in work_day.shifts:
270 | # start time falls within this shift
271 | if shift[0] <= start_time < shift[1]:
272 | day_work_hrs -= calc_time_var_hrs(shift[0], start_time)
273 |
274 | # end time also falls within this shift
275 | if end_time < shift[1]:
276 | day_work_hrs -= calc_time_var_hrs(end_time, shift[1])
277 |
278 | continue
279 |
280 | # only end time falls within this shift
281 | if shift[0] <= end_time <= shift[1]:
282 | day_work_hrs -= calc_time_var_hrs(end_time, shift[1])
283 | continue
284 |
285 | # neither start nor end time falls within this shift
286 | # deduct shift work hours from the day work hours
287 | day_work_hrs -= calc_time_var_hrs(shift[0], shift[1])
288 |
289 | return round(day_work_hrs, 3)
290 |
291 | def _get_workday(self, date: datetime) -> WeekDay:
292 | """Get the WeekDay object associated with a date."""
293 | clean_date = date.replace(microsecond=0, second=0, minute=0, hour=0)
294 | if clean_date in self.work_exceptions.keys():
295 | return self.work_exceptions[clean_date]
296 |
297 | return self.work_week[f"{clean_date:%A}"]
298 |
299 |
300 | def _parse_clndr_data(clndr_data: str, reg_ex) -> list:
301 | """
302 | Searches Calendar data property and returns strings
303 | matching reg_ex argument.
304 | """
305 | return re.findall(reg_ex, clndr_data)
306 |
307 |
308 | def _parse_work_day(day: str) -> WeekDay:
309 | """
310 | Parse WeekDay objects from string representing a work day.
311 | """
312 | weekday = WEEKDAYS[int(day[0]) - 1]
313 | shift_hours = sorted(
314 | [conv_time(hr) for hr in re.findall(ClndrRegEx.shift_hours.value, day)]
315 | )
316 |
317 | shift_hours_tuple: list[tuple[time, time]] = []
318 | for hr in range(0, len(shift_hours), 2):
319 | shift_hours_tuple.append((shift_hours[hr], shift_hours[hr + 1]))
320 |
321 | return WeekDay(weekday, shift_hours_tuple)
322 |
--------------------------------------------------------------------------------
/xerparser/schemas/ermhdr.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # ermhdr.py
3 |
4 | from datetime import datetime
5 |
6 |
7 | class ERMHDR:
8 | """
9 | Export information for .xer file.
10 |
11 | Attributes
12 | ----------
13 | version: str
14 | Version of P6 set during export
15 | date: datetime
16 | Date .xer file was created
17 | user: str
18 | User name that created the .xer file
19 | currency:
20 | Currency type
21 |
22 | """
23 |
24 | def __init__(self, *args: str) -> None:
25 | self.version: str = args[0]
26 | self.date: datetime = datetime.strptime(args[1], "%Y-%m-%d")
27 | self.user: str = args[4]
28 | self.currency: str = args[7]
29 |
30 | def __eq__(self, __o: "ERMHDR") -> bool:
31 | return all(
32 | (
33 | self.version == __o.version,
34 | self.date == __o.date,
35 | self.user == __o.user,
36 | self.currency == __o.currency,
37 | )
38 | )
39 |
40 | def __hash__(self) -> int:
41 | return hash((self.version, self.date, self.user, self.currency))
42 |
--------------------------------------------------------------------------------
/xerparser/schemas/findates.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # findates.py
3 |
4 | from datetime import datetime
5 |
6 | from xerparser.src.validators import date_format
7 |
8 |
9 | class FINDATES:
10 | """
11 | A class representing a Financial Period
12 | """
13 |
14 | def __init__(self, **data: str) -> None:
15 | self.uid: str = data["fin_dates_id"]
16 | """Unique Table ID"""
17 | self.name: str = data["fin_dates_name"]
18 | """Financial Period Name"""
19 | self.start_date: datetime = datetime.strptime(data["start_date"], date_format)
20 | """Financial Period Start Date"""
21 | self.end_date: datetime = datetime.strptime(data["end_date"], date_format)
22 | """Financial Period End Date"""
23 |
24 | def __eq__(self, __o: "FINDATES") -> bool:
25 | return self.start_date == __o.start_date and self.end_date == __o.end_date
26 |
27 | def __gt__(self, __o: "FINDATES") -> bool:
28 | if self.start_date == __o.start_date:
29 | return self.end_date > __o.end_date
30 | return self.start_date > __o.start_date
31 |
32 | def __lt__(self, __o: "FINDATES") -> bool:
33 | if self.start_date == __o.start_date:
34 | return self.end_date < __o.end_date
35 | return self.start_date < __o.start_date
36 |
37 | def __hash__(self) -> int:
38 | return hash((self.name, self.start_date, self.end_date))
39 |
--------------------------------------------------------------------------------
/xerparser/schemas/memotype.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # memotype.py
3 |
4 |
5 | class MEMOTYPE:
6 | """
7 | A class to represent a notebook topic.
8 | """
9 |
10 | def __init__(self, **data: str) -> None:
11 | self.uid: str = data["memo_type_id"]
12 | """Unique Table ID"""
13 | self.topic: str = data["memo_type"]
14 | """Notebook Topic"""
15 |
16 | def __eq__(self, __o: "MEMOTYPE") -> bool:
17 | return self.topic == __o.topic
18 |
19 | def __gt__(self, __o: "MEMOTYPE") -> bool:
20 | return self.topic > __o.topic
21 |
22 | def __lt__(self, __o: "MEMOTYPE") -> bool:
23 | return self.topic < __o.topic
24 |
25 | def __hash__(self) -> int:
26 | return hash(self.topic)
27 |
28 | def __str__(self) -> str:
29 | return self.topic
30 |
--------------------------------------------------------------------------------
/xerparser/schemas/pcattype.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # pcattype.py
3 |
4 |
5 | class PCATTYPE:
6 | """
7 | A class representing Project Code Types
8 | """
9 |
10 | def __init__(self, **data: str) -> None:
11 | self.uid: str = data["proj_catg_type_id"]
12 | """Unique Table ID"""
13 | self.max_length: int = int(data["proj_catg_short_len"])
14 | """Max Character Length"""
15 | self.name: str = data["proj_catg_type"]
16 | """Project Code Name"""
17 | self.seq_num: int | None = None if (seq := data["seq_num"]) == "" else int(seq)
18 | """Sort Order"""
19 |
20 | def __eq__(self, __o: "PCATTYPE") -> bool:
21 | return all(
22 | (
23 | self.max_length == __o.max_length,
24 | self.name == __o.name,
25 | )
26 | )
27 |
28 | def __gt__(self, __o: "PCATTYPE") -> bool:
29 | return self.name > __o.name
30 |
31 | def __lt__(self, __o: "PCATTYPE") -> bool:
32 | return self.name < __o.name
33 |
34 | def __hash__(self) -> int:
35 | return hash((self.max_length, self.name))
36 |
--------------------------------------------------------------------------------
/xerparser/schemas/pcatval.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # pcatval.py
3 |
4 |
5 | from xerparser.schemas._node import Node
6 | from xerparser.schemas.pcattype import PCATTYPE
7 | from xerparser.src.validators import int_or_zero
8 |
9 |
10 | class PCATVAL(Node):
11 | """
12 | A class to represent an Project Code Value
13 | """
14 |
15 | def __init__(self, code_type: PCATTYPE, **data: str) -> None:
16 | super().__init__(
17 | data["proj_catg_id"],
18 | data["proj_catg_short_name"],
19 | data["proj_catg_name"],
20 | data["parent_proj_catg_id"],
21 | int_or_zero(data["seq_num"]),
22 | )
23 | self.proj_catg_type_id: str = data["proj_catg_type_id"]
24 | """Foreign Key for Project Code Type `PCATTYPE`"""
25 | self.code_type: PCATTYPE = self._valid_pcattype(code_type)
26 | """Project Code Type"""
27 |
28 | def __eq__(self, __o: "PCATVAL") -> bool:
29 | return self.full_code == __o.full_code and self.code_type == __o.code_type
30 |
31 | def __hash__(self) -> int:
32 | return hash((self.full_code, self.code_type))
33 |
34 | def _valid_pcattype(self, value: PCATTYPE) -> PCATTYPE:
35 | """Validate Activity Code Type"""
36 | if not isinstance(value, PCATTYPE):
37 | raise ValueError(
38 | f"ValueError: expected ; got {type(value)}"
39 | )
40 | if value.uid != self.proj_catg_type_id:
41 | raise ValueError(
42 | f"ValueError: Unique ID {value.uid} does not match proj_catg_type_id {self.proj_catg_type_id}" # noqa: E501
43 | )
44 | return value
45 |
--------------------------------------------------------------------------------
/xerparser/schemas/project.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # project.py
3 |
4 | from collections import Counter
5 | from datetime import datetime
6 | from functools import cached_property
7 | from statistics import mean
8 | from typing import Any
9 |
10 | from xerparser.schemas.actvtype import ACTVTYPE
11 | from xerparser.schemas.calendars import CALENDAR
12 | from xerparser.schemas.pcattype import PCATTYPE
13 | from xerparser.schemas.pcatval import PCATVAL
14 | from xerparser.schemas.projwbs import PROJWBS
15 | from xerparser.schemas.schedoptions import SCHEDOPTIONS
16 | from xerparser.schemas.task import TASK
17 | from xerparser.schemas.taskpred import TASKPRED
18 | from xerparser.schemas.taskrsrc import TASKRSRC
19 | from xerparser.schemas.udftype import UDFTYPE
20 | from xerparser.scripts.decorators import rounded
21 | from xerparser.src.validators import date_format, optional_date, optional_str
22 |
23 |
24 | class PROJECT:
25 | """
26 | A class representing a schedule.
27 | """
28 |
29 | _wbs_root: PROJWBS
30 |
31 | def __init__(
32 | self,
33 | sched_options: SCHEDOPTIONS,
34 | default_calendar: CALENDAR | None = None,
35 | **data: str,
36 | ) -> None:
37 | self.options: SCHEDOPTIONS = sched_options
38 |
39 | # table fields from .xer file
40 | self.uid: str = data["proj_id"]
41 | """Unique Table ID"""
42 | self.add_date: datetime = datetime.strptime(data["add_date"], date_format)
43 | """Date Project was Created"""
44 | self.default_calendar: CALENDAR | None = default_calendar
45 | """Default Calendar Assigned to Project"""
46 | self.data_date: datetime = datetime.strptime(
47 | data["last_recalc_date"], date_format
48 | )
49 | """Date Project is Updated To"""
50 | self.export_flag: bool = data["export_flag"] == "Y"
51 | """Project Export Flag"""
52 | self.finish_date: datetime = datetime.strptime(
53 | data["scd_end_date"], date_format
54 | )
55 | """Projected Completion Date"""
56 | self.last_fin_dates_id: str | None = optional_str(data["last_fin_dates_id"])
57 | """Last Stored Financial Period"""
58 | self.last_schedule_date: datetime | None = optional_date(
59 | data.get("last_schedule_date", "")
60 | )
61 | """Last Date Schedule was Calculated"""
62 | self.must_finish_date: datetime | None = optional_date(data["plan_end_date"])
63 | """Must Finish by Date Assigned to Project"""
64 | self.plan_start_date: datetime = datetime.strptime(
65 | data["plan_start_date"], date_format
66 | )
67 | """Planned Start Date Assigned to Project"""
68 | self.short_name: str = data["proj_short_name"]
69 | """Project Code"""
70 |
71 | # manually set from other tables
72 | self.activity_codes: list[ACTVTYPE] = []
73 | """Project Level Activity Codes"""
74 | self.calendars: list[CALENDAR] = []
75 | """Project Calendars"""
76 | self.project_codes: dict[PCATTYPE, PCATVAL] = {}
77 | """Project Codes Assigned to Project"""
78 | self.tasks: list[TASK] = []
79 | """Project Activities"""
80 | self.relationships: list[TASKPRED] = []
81 | """Project Relationships"""
82 | self.resources: list[TASKRSRC] = []
83 | """Activity Resources"""
84 | self.wbs_nodes: list[PROJWBS] = []
85 | """Project Work Breakdown Structure"""
86 | # self.wbs_root: PROJWBS | None = None
87 | self.user_defined_fields: dict[UDFTYPE, Any] = {}
88 |
89 | def __str__(self) -> str:
90 | return f"{self.short_name} - {self.name}"
91 |
92 | def __getitem__(self, obj: Any):
93 | if isinstance(obj, TASK):
94 | return self.tasks_by_code.get(obj.task_code)
95 |
96 | if isinstance(obj, TASKPRED):
97 | return self.relationships_by_hash.get(hash(obj))
98 |
99 | if isinstance(obj, PROJWBS):
100 | return self.wbs_by_path.get(obj.full_code)
101 |
102 | @cached_property
103 | @rounded()
104 | def actual_cost(self) -> float:
105 | """Sum of task resource actual costs"""
106 | return sum(res.act_total_cost for res in self.resources)
107 |
108 | @property
109 | def actual_duration(self) -> int:
110 | """Project actual duration in calendar days from start date to data date"""
111 | return max((0, (self.data_date - self.actual_start).days))
112 |
113 | @cached_property
114 | def actual_start(self) -> datetime:
115 | """Earliest task start date"""
116 | if not self.tasks:
117 | return self.plan_start_date
118 | return min((task.start for task in self.tasks))
119 |
120 | @cached_property
121 | @rounded()
122 | def budgeted_cost(self) -> float:
123 | """Sum of task resource budgeted costs"""
124 | return sum(res.target_cost for res in self.resources)
125 |
126 | @property
127 | @rounded(ndigits=4)
128 | def duration_percent(self) -> float:
129 | """Project duration percent complete"""
130 | if self.original_duration == 0:
131 | return 0.0
132 |
133 | if self.data_date >= self.finish_date:
134 | return 1.0
135 |
136 | return 1 - self.remaining_duration / self.original_duration
137 |
138 | @cached_property
139 | def finish_constraints(self) -> list[tuple[TASK, str]]:
140 | """List of all Tasks with Finish on or Before constraints"""
141 | return sorted(
142 | [
143 | (task, cnst)
144 | for task in self.tasks
145 | for cnst in ("prime", "second")
146 | if task.constraints[cnst]["type"] is TASK.ConstraintType.CS_MEOB
147 | ],
148 | key=lambda t: t[0].finish,
149 | )
150 |
151 | @cached_property
152 | def late_start(self) -> datetime:
153 | """Earliest task late start date"""
154 | if not self.tasks:
155 | return self.plan_start_date
156 | return min(
157 | (task.late_start_date for task in self.tasks if task.late_start_date)
158 | )
159 |
160 | @property
161 | def name(self) -> str:
162 | """Project Name"""
163 | if not self.wbs_root:
164 | return ""
165 | return self.wbs_root.name
166 |
167 | @property
168 | def original_duration(self) -> int:
169 | """
170 | Project overall duration in calendar days
171 | from actual start date to finish date
172 | """
173 | return (self.finish_date - self.actual_start).days
174 |
175 | @cached_property
176 | def relationships_by_hash(self) -> dict[int, TASKPRED]:
177 | return {hash(rel): rel for rel in self.relationships}
178 |
179 | @cached_property
180 | @rounded()
181 | def remaining_cost(self) -> float:
182 | """Sum of task resource remaining costs"""
183 | return sum(res.remain_cost for res in self.resources)
184 |
185 | @property
186 | def remaining_duration(self) -> int:
187 | """Project remaining duration in calendar days from data date to finish date"""
188 | return max((0, (self.finish_date - self.data_date).days))
189 |
190 | @cached_property
191 | @rounded(ndigits=4)
192 | def task_percent(self) -> float:
193 | """
194 | Project percent complete based on task updates.
195 | Calculated using the median of the following 2 ratios:
196 |
197 | * Ratio between Actual Dates and Activity Count.
198 | `(Actual Start Count + Actual Finish Count) ÷ (Activity Count * 2)`
199 | * Ratio between Sum of Task Remaining Durations and Task Original Durations.
200 | `1 - (sum of task remaining duration ÷ sum of task original duration)`
201 | """
202 | if not self.tasks:
203 | return 0.0
204 |
205 | orig_dur_sum = sum(
206 | task.original_duration
207 | for task in self.tasks
208 | if not any([task.type.is_loe, task.type.is_wbs])
209 | )
210 | rem_dur_sum = sum(
211 | task.remaining_duration
212 | for task in self.tasks
213 | if not any([task.type.is_loe, task.type.is_wbs])
214 | )
215 | task_dur_percent = 1 - rem_dur_sum / orig_dur_sum if orig_dur_sum else 0.0
216 |
217 | status_cnt = Counter([t.status for t in self.tasks])
218 | status_percent = (
219 | status_cnt[TASK.TaskStatus.TK_Active] / 2
220 | + status_cnt[TASK.TaskStatus.TK_Complete]
221 | ) / len(self.tasks)
222 |
223 | return mean([task_dur_percent, status_percent])
224 |
225 | @cached_property
226 | def tasks_by_code(self) -> dict[str, TASK]:
227 | """
228 | Returns a dictionary of the Activities using the
229 | Activity ID as the key and the TASK object as the value.
230 | """
231 | return {task.task_code: task for task in self.tasks}
232 |
233 | @cached_property
234 | @rounded()
235 | def this_period_cost(self) -> float:
236 | """Sum of task resource this period costs"""
237 | return sum(res.act_this_per_cost for res in self.resources)
238 |
239 | @cached_property
240 | def wbs_by_path(self) -> dict[str, PROJWBS]:
241 | return {node.full_code: node for node in self.wbs_nodes}
242 |
243 | @property
244 | def wbs_root(self) -> PROJWBS:
245 | if not self._wbs_root:
246 | raise UnboundLocalError("WBS Root is not assigned")
247 |
248 | return self._wbs_root
249 |
250 | @wbs_root.setter
251 | def wbs_root(self, value: PROJWBS) -> None:
252 | if not isinstance(value, PROJWBS):
253 | raise TypeError(f"wbs_root must be type `PROJWBS`; got {type(value)}")
254 |
255 | if value.code != self.short_name:
256 | raise ValueError(
257 | f"WBS Code ({value.code}) does not match project ({self.short_name})"
258 | )
259 |
260 | self._wbs_root = value
261 |
262 | def planned_progress(self, before_date: datetime) -> dict[str, list[TASK]]:
263 | """All planned progress through a given date.
264 |
265 | Args:
266 | before_date (datetime): End date for planned progress
267 |
268 | Returns:
269 | dict[str, list[TASK]]: Early and late planned progress during time frame
270 | """
271 | progress = {"start": [], "finish": [], "late_start": [], "late_finish": []}
272 |
273 | if before_date < self.data_date:
274 | return progress
275 |
276 | for task in self.tasks:
277 | if task.status.is_completed:
278 | continue
279 |
280 | if task.status.is_not_started:
281 | if task.start < before_date:
282 | progress["start"].append(task)
283 |
284 | if task.late_start_date and task.late_start_date < before_date:
285 | progress["late_start"].append(task)
286 |
287 | if task.finish < before_date:
288 | progress["finish"].append(task)
289 |
290 | if task.late_end_date and task.late_end_date < before_date:
291 | progress["late_finish"].append(task)
292 |
293 | return progress
294 |
--------------------------------------------------------------------------------
/xerparser/schemas/projwbs.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # projwbs.py
3 |
4 | import itertools
5 | from datetime import datetime
6 | from typing import Any
7 |
8 | from xerparser.schemas._node import Node
9 | from xerparser.schemas.task import TASK
10 | from xerparser.schemas.udftype import UDFTYPE
11 | from xerparser.scripts.decorators import rounded
12 | from xerparser.src.validators import int_or_zero, optional_int
13 |
14 |
15 | class PROJWBS(Node):
16 | """
17 | A class to represent a schedule WBS node.
18 | """
19 |
20 | def __init__(self, project, **data: str) -> None:
21 | from xerparser.schemas.project import PROJECT
22 |
23 | super().__init__(
24 | data["wbs_id"],
25 | data["wbs_short_name"],
26 | data["wbs_name"],
27 | data["parent_wbs_id"],
28 | int_or_zero(data["seq_num"]),
29 | )
30 | self.is_proj_node: bool = data["proj_node_flag"] == "Y"
31 | """Project Level Code Flag"""
32 | self.proj_id: str = data["proj_id"]
33 | """Foreign Key for `PROJECT` WBS node belongs to"""
34 | self.project: PROJECT = project
35 | self.seq_num: int | None = optional_int(data["seq_num"])
36 | """Sort Order"""
37 | self.status_code: str = data["status_code"]
38 |
39 | self.user_defined_fields: dict[UDFTYPE, Any] = {}
40 | self._tasks: dict[str, TASK] = {}
41 |
42 | self.project.wbs_nodes.append(self)
43 | if self.is_proj_node:
44 | self.project.wbs_root = self
45 |
46 | @property
47 | @rounded()
48 | def actual_cost(self) -> float:
49 | """Sum of task resource actual costs"""
50 | return sum(task.actual_cost for task in self.all_tasks)
51 |
52 | @property
53 | def actual_duration(self) -> int:
54 | if not (_start := self.start) or not (_finish := self.finish):
55 | return 0
56 | if _finish < self.project.data_date:
57 | return self.original_duration
58 | return max((0, (self.project.data_date.date() - _start.date()).days))
59 |
60 | @property
61 | def all_tasks(self) -> list[TASK]:
62 | return list(
63 | itertools.chain.from_iterable(
64 | [node.tasks for node in self.traverse_children()]
65 | )
66 | )
67 |
68 | @property
69 | def assignments(self) -> int:
70 | """Activity Assignment Count"""
71 | return len(self.tasks)
72 |
73 | @property
74 | @rounded()
75 | def budgeted_cost(self) -> float:
76 | """Sum of task budgeted costs"""
77 | return sum(task.budgeted_cost for task in self.all_tasks)
78 |
79 | @property
80 | @rounded()
81 | def cost_variance(self) -> float:
82 | return sum(task.cost_variance for task in self.all_tasks)
83 |
84 | @property
85 | def lineage(self) -> list["PROJWBS"]:
86 | if self.is_proj_node:
87 | return []
88 |
89 | if not self._parent:
90 | return [self]
91 |
92 | return self._parent.lineage + [self]
93 |
94 | @property
95 | def finish(self) -> datetime | None:
96 | return max((task.finish for task in self.all_tasks), default=None)
97 |
98 | @property
99 | def full_code(self) -> str:
100 | return ".".join([node.code for node in self.lineage])
101 |
102 | @property
103 | def late_finish(self) -> datetime | None:
104 | return max(
105 | (task.late_end_date for task in self.all_tasks if task.late_end_date),
106 | default=self.finish,
107 | )
108 |
109 | @property
110 | def late_start(self) -> datetime | None:
111 | return min(
112 | (task.late_start_date for task in self.all_tasks if task.late_start_date),
113 | default=self.start,
114 | )
115 |
116 | @property
117 | def original_duration(self) -> int:
118 | if not (_start := self.start) or not (_finish := self.finish):
119 | return 0
120 | return (_finish.date() - _start.date()).days
121 |
122 | @property
123 | @rounded()
124 | def remaining_cost(self) -> float:
125 | """Sum of task resource remaining costs"""
126 | return sum(task.remaining_cost for task in self.all_tasks)
127 |
128 | @property
129 | def remaining_duration(self) -> int:
130 | if not (_start := self.start) or not (_finish := self.finish):
131 | return 0
132 | if _start >= self.project.data_date:
133 | return self.original_duration
134 | return max((0, (_finish.date() - self.project.data_date.date()).days))
135 |
136 | @property
137 | def start(self) -> datetime | None:
138 | return min((task.start for task in self.all_tasks), default=None)
139 |
140 | @property
141 | def tasks(self) -> list[TASK]:
142 | return list(self._tasks.values())
143 |
144 | @property
145 | @rounded()
146 | def this_period_cost(self) -> float:
147 | """Sum of task this period costs"""
148 | return sum((task.this_period_cost for task in self.all_tasks), 0.0)
149 |
150 | def add_task(self, task: TASK):
151 | self._tasks[task.uid] = task
152 |
--------------------------------------------------------------------------------
/xerparser/schemas/rate.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 |
3 | from xerparser.src.validators import date_format, float_or_zero
4 |
5 |
6 | class Rate:
7 | """Units per Time Limits"""
8 |
9 | def __init__(self, **data: str) -> None:
10 | self.cost_per_qty: float = float_or_zero(data["cost_per_qty"])
11 | """Standard Rate"""
12 | self.cost_per_qty2: float = float_or_zero(data["cost_per_qty2"])
13 | """Internal Rate"""
14 | self.cost_per_qty3: float = float_or_zero(data["cost_per_qty3"])
15 | """External Rate"""
16 | self.cost_per_qty4: float = float_or_zero(data["cost_per_qty4"])
17 | """Price per Unit 4"""
18 | self.cost_per_qty5: float = float_or_zero(data["cost_per_qty5"])
19 | """Price per Unit 5"""
20 | self.max_qty_per_hr: float = float(data["max_qty_per_hr"].replace(",", "."))
21 | """Max Units per Time"""
22 | self.start_date: datetime = datetime.strptime(data["start_date"], date_format)
23 | """Effective Date"""
24 |
25 | def __eq__(self, __other: "Rate") -> bool:
26 | return self.start_date == __other.start_date
27 |
28 | def __gt__(self, __other: "Rate") -> bool:
29 | return self.start_date > __other.start_date
30 |
31 | def __hash__(self) -> int:
32 | return hash(self.start_date)
33 |
34 | def __lt__(self, __other: "Rate") -> bool:
35 | return self.start_date < __other.start_date
36 |
--------------------------------------------------------------------------------
/xerparser/schemas/rsrc.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # rsrc.py
3 |
4 | from typing import Any
5 |
6 | from xerparser.schemas._node import Node
7 | from xerparser.schemas.udftype import UDFTYPE
8 | from xerparser.src.validators import int_or_zero
9 |
10 |
11 | class RSRC(Node):
12 | """
13 | A class to represent a Resource.
14 | """
15 |
16 | def __init__(self, **data: str) -> None:
17 | from xerparser.schemas.taskrsrc import TASKRSRC
18 |
19 | super().__init__(
20 | data["rsrc_id"],
21 | data["rsrc_short_name"],
22 | data["rsrc_name"],
23 | data["parent_rsrc_id"],
24 | int_or_zero(data["rsrc_seq_num"]),
25 | )
26 | self.clndr_id: str = data["clndr_id"]
27 | self.type: str = data["rsrc_type"]
28 | self.user_defined_fields: dict[UDFTYPE, Any] = {}
29 | self.task_rsrcs: list[TASKRSRC] = []
30 |
--------------------------------------------------------------------------------
/xerparser/schemas/rsrcrate.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # rsrc.py
3 |
4 | from xerparser.schemas.rate import Rate
5 | from xerparser.schemas.rsrc import RSRC
6 |
7 |
8 | class RSRCRATE(Rate):
9 | def __init__(self, resource: RSRC, **data: str):
10 | super().__init__(**data)
11 | self.uid: str = data["rsrc_rate_id"]
12 | """(str) Unique Table ID"""
13 | self.rsrc_id: str = data["rsrc_id"]
14 | """(str) Resource Unique Table ID"""
15 | self.resource: RSRC = resource
16 | """(RSRC) Resource"""
17 | self.shift_period_id: str = data["shift_period_id"]
18 | """(str) Shift Unique Table ID"""
19 |
--------------------------------------------------------------------------------
/xerparser/schemas/schedoptions.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # schedoptions.py
3 |
4 | from xerparser.src.validators import optional_int
5 |
6 |
7 | class SCHEDOPTIONS:
8 | def __init__(self, **data: str) -> None:
9 | """
10 | A class to represent the Schedule Options.
11 | """
12 | self.max_multiple_longest_path: int | None = optional_int(
13 | data.get("max_multiple_longest_path")
14 | )
15 | self.proj_id: str = data["proj_id"]
16 | self.calendar_on_relationship_lag: str = data.get(
17 | "sched_calendar_on_relationship_lag", ""
18 | )
19 | self.float_type: str = data["sched_float_type"]
20 | self.lag_early_start_flag: bool = data["sched_lag_early_start_flag"] == "Y"
21 | self.open_critical_flag: bool = data["sched_open_critical_flag"] == "Y"
22 | self.outer_depend_type: str = data["sched_outer_depend_type"]
23 | self.progress_override: bool = data["sched_progress_override"] == "Y"
24 | self.retained_logic: bool = data["sched_retained_logic"] == "Y"
25 | self.setplantoforecast: bool = data["sched_setplantoforecast"] == "Y"
26 | self.use_expect_end_flag: bool = data["sched_use_expect_end_flag"] == "Y"
27 | self.use_project_end_date_for_float = (
28 | data.get("sched_use_project_end_date_for_float", "N") == "Y"
29 | )
30 | self.schedoptions_id: str = data["schedoptions_id"]
31 | self.use_total_float_multiple_longest_paths: bool = (
32 | data.get("use_total_float_multiple_longest_paths", "N") == "Y"
33 | )
34 |
35 | def __eq__(self, __o: "SCHEDOPTIONS") -> bool:
36 | return all(
37 | (
38 | self.max_multiple_longest_path == __o.max_multiple_longest_path,
39 | self.calendar_on_relationship_lag == __o.calendar_on_relationship_lag,
40 | self.float_type == __o.float_type,
41 | self.lag_early_start_flag == __o.lag_early_start_flag,
42 | self.open_critical_flag == __o.open_critical_flag,
43 | self.outer_depend_type == __o.outer_depend_type,
44 | self.progress_override == __o.progress_override,
45 | self.retained_logic == __o.retained_logic,
46 | self.setplantoforecast == __o.setplantoforecast,
47 | self.use_expect_end_flag == __o.use_expect_end_flag,
48 | self.use_project_end_date_for_float
49 | == __o.use_project_end_date_for_float,
50 | self.use_total_float_multiple_longest_paths
51 | == __o.use_total_float_multiple_longest_paths,
52 | )
53 | )
54 |
55 | def __hash__(self) -> int:
56 | return hash(
57 | (
58 | self.max_multiple_longest_path,
59 | self.calendar_on_relationship_lag,
60 | self.float_type,
61 | self.lag_early_start_flag,
62 | self.open_critical_flag,
63 | self.outer_depend_type,
64 | self.progress_override,
65 | self.retained_logic,
66 | self.setplantoforecast,
67 | self.use_expect_end_flag,
68 | self.use_project_end_date_for_float,
69 | self.use_total_float_multiple_longest_paths,
70 | )
71 | )
72 |
--------------------------------------------------------------------------------
/xerparser/schemas/task.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # task.py
3 |
4 | from datetime import datetime
5 | from enum import Enum
6 | from functools import cached_property
7 | from typing import Any, Self
8 |
9 | from xerparser.schemas.actvcode import ACTVCODE
10 | from xerparser.schemas.actvtype import ACTVTYPE
11 | from xerparser.schemas.calendars import CALENDAR
12 | from xerparser.schemas.taskfin import TASKFIN
13 | from xerparser.schemas.taskmemo import TASKMEMO
14 | from xerparser.schemas.taskrsrc import TASKRSRC
15 | from xerparser.schemas.udftype import UDFTYPE
16 | from xerparser.scripts.dates import clean_date
17 | from xerparser.scripts.decorators import rounded
18 | from xerparser.src.validators import (
19 | date_format,
20 | float_or_zero,
21 | optional_date,
22 | optional_float,
23 | optional_int,
24 | optional_str,
25 | )
26 |
27 |
28 | class TASK:
29 | """
30 | A class to represent a scehdule activity.
31 | """
32 |
33 | class ConstraintType(Enum):
34 | """Map codes used for constraint types to readable descriptions"""
35 |
36 | CS_ALAP = "As Late as Possible"
37 | CS_MEO = "Finish On"
38 | CS_MEOA = "Finish on or After"
39 | CS_MEOB = "Finish on or Before"
40 | CS_MANDFIN = "Mandatory Finish"
41 | CS_MANDSTART = "Mandatory Start"
42 | CS_MSO = "Start On"
43 | CS_MSOA = "Start On or After"
44 | CS_MSOB = "Start On or Before"
45 |
46 | class PercentType(Enum):
47 | """Map codes used for percent types to readable descriptions"""
48 |
49 | CP_Phys = "Physical"
50 | CP_Drtn = "Duration"
51 | CP_Units = "Unit"
52 |
53 | class TaskStatus(Enum):
54 | """Map codes used for Task status to readable descriptions"""
55 |
56 | TK_NotStart = "Not Started"
57 | TK_Active = "In Progress"
58 | TK_Complete = "Complete"
59 |
60 | @property
61 | def is_not_started(self) -> bool:
62 | return self is self.TK_NotStart
63 |
64 | @property
65 | def is_in_progress(self) -> bool:
66 | return self is self.TK_Active
67 |
68 | @property
69 | def is_completed(self) -> bool:
70 | return self is self.TK_Complete
71 |
72 | @property
73 | def is_open(self) -> bool:
74 | return self is not self.TK_Complete
75 |
76 | class TaskType(Enum):
77 | """Map codes used for Task types to readable descriptions"""
78 |
79 | TT_Mile = "Start Milestone"
80 | TT_FinMile = "Finish Milestone"
81 | TT_LOE = "Level of Effort"
82 | TT_Task = "Task Dependent"
83 | TT_Rsrc = "Resource Dependent"
84 | TT_WBS = "WBS Summary"
85 |
86 | @property
87 | def is_milestone(self) -> bool:
88 | return self is self.TT_FinMile or self is self.TT_Mile
89 |
90 | @property
91 | def is_loe(self) -> bool:
92 | return self is self.TT_LOE
93 |
94 | @property
95 | def is_task(self) -> bool:
96 | return self is self.TT_Task
97 |
98 | @property
99 | def is_wbs(self) -> bool:
100 | return self is self.TT_WBS
101 |
102 | def __init__(self, calendar: CALENDAR, wbs, **data: str) -> None:
103 | from xerparser.schemas.projwbs import PROJWBS
104 |
105 | self.uid: str = data["task_id"]
106 | """Unique Table ID"""
107 | # Foreign keys
108 | self.proj_id: str = data["proj_id"]
109 | """Foreign Key for Project"""
110 | self.wbs_id: str = data["wbs_id"]
111 | """Foreign Key for WBS Node"""
112 | self.clndr_id: str = data["clndr_id"]
113 | """Foreign Key for Calendar"""
114 |
115 | # General Task info
116 | self.phys_complete_pct: float = float(
117 | data["phys_complete_pct"].replace(",", ".")
118 | )
119 | """Activity physical percent complete"""
120 | self.complete_pct_type: str = data["complete_pct_type"]
121 | """Activity percent complete type: duration, physical, or units"""
122 | self.type: TASK.TaskType = TASK.TaskType[data["task_type"]]
123 | """
124 | Activity type:
125 | Task, Start Milestone, Finish Milestone, Level of Effort,
126 | WBS Summary, or Resource Dependent"""
127 | self.status: TASK.TaskStatus = TASK.TaskStatus[data["status_code"]]
128 | self.task_code: str = data["task_code"]
129 | """Activity ID"""
130 | self.name: str = data["task_name"]
131 | """Activity Name"""
132 |
133 | # Durations and float
134 | self.duration_type: str = data["duration_type"]
135 | self.total_float_hr_cnt: float | None = optional_float(
136 | data["total_float_hr_cnt"]
137 | )
138 | self.free_float_hr_cnt: float | None = optional_float(data["free_float_hr_cnt"])
139 | self.remain_drtn_hr_cnt: float = float(
140 | data["remain_drtn_hr_cnt"].replace(",", ".")
141 | )
142 | self.target_drtn_hr_cnt: float = float(
143 | data["target_drtn_hr_cnt"].replace(",", ".")
144 | )
145 | self.float_path: int | None = optional_int(data["float_path"])
146 | self.float_path_order: int | None = optional_int(data["float_path_order"])
147 | self.is_longest_path: bool = data["driving_path_flag"] == "Y"
148 |
149 | # Dates
150 | self.act_start_date: datetime | None = optional_date(data["act_start_date"])
151 | self.act_end_date: datetime | None = optional_date(data["act_end_date"])
152 | self.late_start_date: datetime | None = optional_date(data["late_start_date"])
153 | self.late_end_date: datetime | None = optional_date(data["late_end_date"])
154 | self.expect_end_date: datetime | None = optional_date(data["expect_end_date"])
155 | self.early_start_date: datetime | None = optional_date(data["early_start_date"])
156 | self.early_end_date: datetime | None = optional_date(data["early_end_date"])
157 | self.rem_late_start_date: datetime | None = optional_date(
158 | data["rem_late_start_date"]
159 | )
160 | self.rem_late_end_date: datetime | None = optional_date(
161 | data["rem_late_end_date"]
162 | )
163 | self.restart_date: datetime | None = optional_date(data["restart_date"])
164 | self.reend_date: datetime | None = optional_date(data["reend_date"])
165 | self.target_start_date: datetime = datetime.strptime(
166 | data["target_start_date"], date_format
167 | )
168 | self.target_end_date: datetime = datetime.strptime(
169 | data["target_end_date"], date_format
170 | )
171 | self.suspend_date: datetime | None = optional_date(data["suspend_date"])
172 | self.resume_date: datetime | None = optional_date(data["resume_date"])
173 | self.create_date: datetime | None = optional_date(data["create_date"])
174 | self.update_date: datetime | None = optional_date(data["update_date"])
175 |
176 | # Constraints
177 | self.cstr_date: datetime | None = optional_date(data["cstr_date"])
178 | self.cstr_type: str | None = optional_str(data["cstr_type"])
179 | self.cstr_date2: datetime | None = optional_date(data["cstr_date2"])
180 | self.cstr_type2: str | None = optional_str(data["cstr_type2"])
181 |
182 | # Unit quantities
183 | # Have encoutered XER files where these qty's are stored as empty strings.
184 | self.target_work_qty: float = float_or_zero(data["target_work_qty"])
185 | self.act_work_qty: float = float_or_zero(data["act_work_qty"])
186 | self.target_equip_qty: float = float_or_zero(data["target_equip_qty"])
187 | self.act_equip_qty: float = float_or_zero(data["act_equip_qty"])
188 |
189 | self.activity_codes: dict[ACTVTYPE, ACTVCODE] = {}
190 | self.user_defined_fields: dict[UDFTYPE, Any] = {}
191 | self.calendar: CALENDAR = calendar
192 | self.wbs: PROJWBS = wbs
193 | self.memos: list[TASKMEMO] = []
194 | self.resources: dict[str, TASKRSRC] = {}
195 | self.predecessors: list["LinkToTask"] = []
196 | self.successors: list["LinkToTask"] = []
197 | self.periods: list[TASKFIN] = []
198 |
199 | def __eq__(self, __o: "TASK") -> bool:
200 | return self.task_code == __o.task_code
201 |
202 | def __lt__(self, __o: "TASK") -> bool:
203 | if self == __o:
204 | if self.start == __o.start:
205 | return self.finish < __o.finish
206 | return self.start < __o.start
207 | return self.task_code < __o.task_code
208 |
209 | def __gt__(self, __o: "TASK") -> bool:
210 | if self == __o:
211 | if self.start == __o.start:
212 | return self.finish > __o.finish
213 | return self.start > __o.start
214 | return self.task_code > __o.task_code
215 |
216 | def __hash__(self) -> int:
217 | return hash(self.task_code)
218 |
219 | def __str__(self) -> str:
220 | return f"{self.task_code} - {self.name}"
221 |
222 | @property
223 | @rounded()
224 | def actual_cost(self) -> float:
225 | return sum(res.act_total_cost for res in self.resources.values())
226 |
227 | @property
228 | @rounded()
229 | def at_completion_cost(self) -> float:
230 | return sum(res.at_completion_cost for res in self.resources.values())
231 |
232 | @property
233 | @rounded()
234 | def budgeted_cost(self) -> float:
235 | return sum(res.target_cost for res in self.resources.values())
236 |
237 | @property
238 | def constraints(self) -> dict:
239 | return {
240 | "prime": {
241 | "type": TASK.ConstraintType[self.cstr_type] if self.cstr_type else None,
242 | "date": self.cstr_date,
243 | },
244 | "second": {
245 | "type": TASK.ConstraintType[self.cstr_type2]
246 | if self.cstr_type2
247 | else None,
248 | "date": self.cstr_date2,
249 | },
250 | }
251 |
252 | @property
253 | @rounded()
254 | def cost_variance(self) -> float:
255 | return sum(res.cost_variance for res in self.resources.values())
256 |
257 | @property
258 | def duration(self) -> int:
259 | """
260 | Returns remaining duration if task is not started;
261 | otherwise, returns original duration.
262 | """
263 | # This is usefull when the remaining duration is unlinked from the
264 | # original duration in the project settings
265 | # In these cases, the remaining duration can be different from the
266 | # original duration in tasks that have not started.
267 |
268 | if self.status.is_not_started:
269 | return self.remaining_duration
270 | return self.original_duration
271 |
272 | @property
273 | def finish(self) -> datetime:
274 | """Calculated activity finish date (Actual Finish or Early Finish)"""
275 | if self.act_end_date:
276 | return self.act_end_date
277 | if self.reend_date:
278 | return self.reend_date
279 | if self.early_end_date:
280 | return self.early_end_date
281 | raise ValueError(f"Could not find finish date for task {self.task_code}")
282 |
283 | @property
284 | def free_float(self) -> int | None:
285 | if not self.free_float_hr_cnt:
286 | return None
287 |
288 | return int(self.free_float_hr_cnt / 8)
289 |
290 | @property
291 | def is_critical(self) -> bool:
292 | return self.total_float_hr_cnt is not None and self.total_float_hr_cnt <= 0
293 |
294 | @property
295 | def original_duration(self) -> int:
296 | """Original Duration in Days"""
297 | return int(self.target_drtn_hr_cnt / 8)
298 |
299 | @cached_property
300 | @rounded(ndigits=4)
301 | def percent_complete(self) -> float:
302 | if self.percent_type is TASK.PercentType.CP_Phys:
303 | return self.phys_complete_pct / 100
304 |
305 | if self.percent_type is TASK.PercentType.CP_Drtn:
306 | if self.remain_drtn_hr_cnt is None or self.status.is_completed:
307 | return 1.0
308 | if self.status.is_not_started or self.original_duration == 0:
309 | return 0.0
310 | if self.remain_drtn_hr_cnt >= self.target_drtn_hr_cnt:
311 | return 0.0
312 |
313 | return 1 - self.remain_drtn_hr_cnt / self.target_drtn_hr_cnt
314 |
315 | if self.percent_type is TASK.PercentType.CP_Units:
316 | target_units = self.target_work_qty + self.target_equip_qty
317 | if target_units == 0:
318 | return 0.0
319 | actual_units = self.act_work_qty + self.act_equip_qty
320 | return 1 - actual_units / target_units
321 |
322 | raise ValueError(
323 | f"Could not calculate percent compelete for task {self.task_code}"
324 | )
325 |
326 | @property
327 | def percent_type(self) -> PercentType:
328 | return TASK.PercentType[self.complete_pct_type]
329 |
330 | @property
331 | @rounded()
332 | def remaining_cost(self) -> float:
333 | return sum(res.remain_cost for res in self.resources.values())
334 |
335 | @property
336 | def remaining_duration(self) -> int:
337 | if self.remain_drtn_hr_cnt is None:
338 | return 0
339 | return int(self.remain_drtn_hr_cnt / 8)
340 |
341 | def rem_hours_per_day(self, late_dates=False) -> dict[datetime, float]:
342 | """
343 | Calculate the remaining workhours per day for a task.
344 | Will only return valid workdays in a list of tuples containing
345 | the date and workhour values.
346 | This is usefull for calculating projections like cash flow.
347 |
348 | P6 calculates remaining duration based on hours rather than days,
349 | So the start and/or finish date for an activity may be a partial day.
350 |
351 | Returns:
352 | dict[datetime, float]: date and workhour pairs
353 | """
354 | if self.remain_drtn_hr_cnt == 0:
355 | return {}
356 |
357 | if self.status.is_completed or not self.restart_date:
358 | return {}
359 |
360 | if late_dates and (not self.rem_late_end_date or not self.rem_late_start_date):
361 | return {}
362 |
363 | if late_dates and self.rem_late_end_date and self.rem_late_start_date:
364 | start_date = self.rem_late_start_date
365 | end_date = self.rem_late_end_date
366 | else:
367 | start_date = self.restart_date
368 | end_date = self.finish
369 |
370 | # edge case that start and end dates are equal
371 | if start_date.date() == end_date.date():
372 | work_hrs = self.calendar._calc_work_hours(
373 | start_date, start_date.time(), end_date.time()
374 | )
375 | return {clean_date(start_date): round(work_hrs, 3)}
376 |
377 | # Get a list of all workdays between the start and end dates
378 | date_range = list(self.calendar.iter_workdays(start_date, end_date))
379 |
380 | # edge cases that only 1 valid workday between start date and end date these
381 | # may never actually occur since the dates are pulled directly from the schedule
382 | # did not find any case where these occur in testing, but leaving anyway
383 | if len(date_range) == 1 and end_date.date() > start_date.date():
384 | if start_date.date() == date_range[0].date():
385 | work_day = self.calendar._get_workday(start_date)
386 | work_hrs = self.calendar._calc_work_hours(
387 | start_date, start_date.time(), work_day.finish
388 | )
389 | return {clean_date(start_date): round(work_hrs, 3)}
390 |
391 | if end_date.date() == date_range[0].date():
392 | work_day = self.calendar._get_workday(end_date)
393 | work_hrs = self.calendar._calc_work_hours(
394 | end_date, work_day.start, end_date.time()
395 | )
396 | return {clean_date(end_date): round(work_hrs, 3)}
397 |
398 | work_day = self.calendar._get_workday(date_range[0])
399 | return {clean_date(date_range[0]): round(work_day.hours, 3)}
400 |
401 | # cases were multiple valid workdays between start and end date
402 | # initialize hours with start date
403 | rem_hrs = {
404 | clean_date(start_date): round(
405 | self.calendar._calc_work_hours(
406 | date_to_calc=start_date,
407 | start_time=start_date.time(),
408 | end_time=self.calendar._get_workday(start_date).finish,
409 | ),
410 | 3,
411 | ),
412 | }
413 |
414 | # loop through 2nd to 2nd to last day in date range
415 | # these would be a full workday
416 | for dt in date_range[1 : len(date_range) - 1]:
417 | if not self.calendar.is_workday(dt):
418 | continue
419 | if wd := self.calendar._get_workday(dt):
420 | rem_hrs[dt] = round(wd.hours, 3)
421 |
422 | # calculate work hours for the last day
423 | rem_hrs[clean_date(end_date)] = round(
424 | self.calendar._calc_work_hours(
425 | date_to_calc=end_date,
426 | start_time=self.calendar._get_workday(end_date).start,
427 | end_time=end_date.time(),
428 | ),
429 | 3,
430 | )
431 |
432 | return rem_hrs
433 |
434 | @property
435 | def start(self) -> datetime:
436 | """Calculated activity start date (Actual Start or Early Start)"""
437 | if self.act_start_date:
438 | return self.act_start_date
439 | if self.early_start_date:
440 | return self.early_start_date
441 | raise ValueError(f"Could not find start date for task {self.task_code}")
442 |
443 | @property
444 | @rounded()
445 | def this_period_cost(self) -> float:
446 | return sum(res.act_this_per_cost for res in self.resources.values())
447 |
448 | @property
449 | def total_float(self) -> int | None:
450 | if self.total_float_hr_cnt is None:
451 | return
452 | return int(self.total_float_hr_cnt / 8)
453 |
454 |
455 | class LinkToTask:
456 | """
457 | A class to represent a logic tie to another activity
458 | """
459 |
460 | def __init__(self, task: TASK, link: str, lag_days: int) -> None:
461 | if link.upper() not in ("FF", "FS", "SF", "SS"):
462 | raise AttributeError(
463 | f"link attribute must have a value FF, FS, SF, or SS; got {link}"
464 | )
465 | self.task: TASK = task
466 | self.link: str = link
467 | self.lag: int = lag_days
468 |
469 | def __eq__(self, __o: Self) -> bool:
470 | return all((self.task == __o.task, self.link == __o.link))
471 |
472 | def __hash__(self) -> int:
473 | return hash((self.task, self.link))
474 |
475 | def __repr__(self) -> str:
476 | return f"<{self.task.task_code}[{self.link}:{self.lag}]>"
477 |
478 | def __str__(self) -> str:
479 | return f"{self.task.task_code}[{self.link}:{self.lag}]"
480 |
--------------------------------------------------------------------------------
/xerparser/schemas/taskfin.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # taskfin.py
3 |
4 | from xerparser.schemas.findates import FINDATES
5 | from xerparser.src.validators import float_or_zero
6 |
7 |
8 | class TASKFIN:
9 | """
10 | A class to represent a past Finacial Period for an activity
11 | """
12 |
13 | def __init__(self, period: FINDATES, **data) -> None:
14 | self.act_equip_cost: float = float_or_zero(data["act_equip_cost"])
15 | self.act_equip_qty: float = float_or_zero(data["act_equip_qty"])
16 | self.act_expense_cost: float = float_or_zero(data["act_expense_cost"])
17 | self.act_mat_cost: float = float_or_zero(data["act_mat_cost"])
18 | self.act_work_cost: float = float_or_zero(data["act_work_cost"])
19 | self.act_work_qty: float = float_or_zero(data["act_work_qty"])
20 | self.bcwp: float = float_or_zero(data["bcwp"])
21 | self.bcws: float = float_or_zero(data["bcws"])
22 | self.fin_dates_id: str = data["fin_dates_id"]
23 | self.perfm_work_qty: float = float_or_zero(data["perfm_work_qty"])
24 | self.proj_id: str = data["proj_id"]
25 | self.sched_work_qty: float = float_or_zero(data.get("sched_work_qty", ""))
26 | self.task_id: str = data["task_id"]
27 | self.period: FINDATES = period
28 |
29 | def __eq__(self, __o: "TASKFIN") -> bool:
30 | return self.period == __o.period
31 |
32 | def __hash__(self) -> int:
33 | return hash(self.period)
34 |
35 | @property
36 | def actual_total_cost(self) -> float:
37 | return (
38 | self.act_equip_cost
39 | + self.act_expense_cost
40 | + self.act_mat_cost
41 | + self.act_work_cost
42 | )
43 |
--------------------------------------------------------------------------------
/xerparser/schemas/taskmemo.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # taskmemo.py
3 |
4 | import re
5 | from html_sanitizer import Sanitizer
6 | from typing import Any
7 |
8 |
9 | class TASKMEMO:
10 | """A class to represent a note assigned to an activity"""
11 |
12 | def __init__(self, **data: Any) -> None:
13 | self.uid: str = data["memo_id"]
14 | self.memo: str = _sanitize_html(data["task_memo"])
15 | self.memo_type_id: str = data["memo_type_id"]
16 | self.proj_id: str = data["proj_id"]
17 | self.task_id: str = data["task_id"]
18 | self.topic: str = data["topic"]
19 |
20 | def __eq__(self, __o: "TASKMEMO") -> bool:
21 | return self.topic == __o.topic
22 |
23 | def __hash__(self) -> int:
24 | return hash(self.topic)
25 |
26 |
27 | def _sanitize_html(value) -> str:
28 | re_remove = re.compile(r"(\u007F+)|()")
29 | sanitzer = Sanitizer()
30 | memo = re.sub(re_remove, "", value)
31 | return sanitzer.sanitize(memo)
32 |
--------------------------------------------------------------------------------
/xerparser/schemas/taskpred.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # taskpred.py
3 |
4 | from datetime import datetime
5 | from xerparser.schemas.task import TASK
6 | from xerparser.src.validators import optional_int, optional_date, int_or_zero
7 |
8 |
9 | class TASKPRED:
10 | """
11 | A class to represent a relationship between two activities.
12 |
13 | """
14 |
15 | def __init__(self, predecessor: TASK, successor: TASK, **data) -> None:
16 | self.uid: str = data["task_pred_id"]
17 | self.task_id: str = data["task_id"]
18 | self.pred_task_id: str = data["pred_task_id"]
19 | self.proj_id: str = data["proj_id"]
20 | self.pred_proj_id: str = data["pred_proj_id"]
21 | self.pred_type: str = data["pred_type"]
22 | self.lag_hr_cnt: int = int_or_zero(data["lag_hr_cnt"])
23 | self.float_path: int | None = optional_int(data["float_path"])
24 | self.aref: datetime | None = optional_date(data["aref"])
25 | self.arls: datetime | None = optional_date(data["arls"])
26 | self.predecessor: TASK = predecessor
27 | self.successor: TASK = successor
28 |
29 | def __eq__(self, __o: "TASKPRED") -> bool:
30 | return (
31 | self.predecessor == __o.predecessor
32 | and self.successor == __o.successor
33 | and self.link == __o.link
34 | )
35 |
36 | def __gt__(self, __o: "TASKPRED") -> bool:
37 | if self.predecessor == __o.predecessor:
38 | if self.successor == __o.successor:
39 | return self.link > __o.link
40 | return self.successor > __o.successor
41 | return self.predecessor > __o.predecessor
42 |
43 | def __lt__(self, __o: "TASKPRED") -> bool:
44 | if self.predecessor == __o.predecessor:
45 | if self.successor == __o.successor:
46 | return self.link < __o.link
47 | return self.successor < __o.successor
48 | return self.predecessor < __o.predecessor
49 |
50 | def __hash__(self) -> int:
51 | return hash((self.predecessor, self.successor, self.link))
52 |
53 | @property
54 | def lag(self) -> int:
55 | return int(self.lag_hr_cnt / 8)
56 |
57 | @property
58 | def link(self) -> str:
59 | return self.pred_type[-2:]
60 |
--------------------------------------------------------------------------------
/xerparser/schemas/taskrsrc.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # taskrsrc.py
3 |
4 | # from dataclasses import dataclass, field
5 | from datetime import datetime
6 |
7 | from xerparser.schemas.account import ACCOUNT
8 | from xerparser.schemas.rsrc import RSRC
9 | from xerparser.schemas.trsrcfin import TRSRCFIN
10 | from xerparser.scripts.decorators import rounded
11 | from xerparser.src.validators import (
12 | date_format,
13 | optional_date,
14 | optional_str,
15 | )
16 |
17 |
18 | class TASKRSRC:
19 | """A class to represent a resource assigned to an activity."""
20 |
21 | def __init__(self, account: ACCOUNT | None, resource: RSRC, **data: str) -> None:
22 | self.uid: str = data["taskrsrc_id"]
23 | self.task_id: str = data["task_id"]
24 | self.proj_id: str = data["proj_id"]
25 | self.acct_id: str | None = optional_str(data["acct_id"])
26 | self.rsrc_id: str = data["rsrc_id"]
27 | self.remain_qty: float = float(data["remain_qty"].replace(",", "."))
28 | self.target_qty: float = float(data["target_qty"].replace(",", "."))
29 | self.act_ot_qty: float = float(data["act_ot_qty"].replace(",", "."))
30 | self.act_reg_qty: float = float(data["act_reg_qty"].replace(",", "."))
31 | self.target_cost: float = float(data["target_cost"].replace(",", "."))
32 | self.act_reg_cost: float = float(data["act_reg_cost"].replace(",", "."))
33 | self.act_ot_cost: float = float(data["act_ot_cost"].replace(",", "."))
34 | self.remain_cost: float = float(data["remain_cost"].replace(",", "."))
35 | self.act_start_date: datetime | None = optional_date(data["act_start_date"])
36 | self.act_end_date: datetime | None = optional_date(data["act_end_date"])
37 | self.restart_date: datetime | None = optional_date(data["restart_date"])
38 | self.reend_date: datetime | None = optional_date(data["reend_date"])
39 | self.target_start_date: datetime = datetime.strptime(
40 | data["target_start_date"], date_format
41 | )
42 | self.target_end_date: datetime = datetime.strptime(
43 | data["target_end_date"], date_format
44 | )
45 | self.target_lag_drtn_hr_cnt: float = float(data["target_lag_drtn_hr_cnt"].replace(",", "."))
46 | self.rem_late_start_date: datetime | None = optional_date(
47 | data["rem_late_start_date"]
48 | )
49 | self.rem_late_end_date: datetime | None = optional_date(
50 | data["rem_late_end_date"]
51 | )
52 | self.act_this_per_cost: float = float(
53 | data["act_this_per_cost"].replace(",", ".")
54 | )
55 | self.act_this_per_qty: float = float(data["act_this_per_qty"].replace(",", "."))
56 | self.rsrc_type: str = data["rsrc_type"]
57 | self.account: ACCOUNT | None = account_or_none(account)
58 | self.resource: RSRC = resource
59 | self.periods: list[TRSRCFIN] = []
60 |
61 | def __eq__(self, __o: "TASKRSRC") -> bool:
62 | return all(
63 | (
64 | self.resource == __o.resource,
65 | self.account == __o.account,
66 | self.target_qty == __o.target_qty,
67 | self.target_cost == __o.target_cost,
68 | )
69 | )
70 |
71 | def __hash__(self) -> int:
72 | return hash(
73 | (
74 | self.resource,
75 | self.account,
76 | self.target_qty,
77 | self.target_cost,
78 | )
79 | )
80 |
81 | @property
82 | @rounded()
83 | def act_total_cost(self) -> float:
84 | return self.act_reg_cost + self.act_ot_cost
85 |
86 | @property
87 | @rounded()
88 | def act_total_qty(self) -> float:
89 | return self.act_reg_qty + self.act_ot_qty
90 |
91 | @property
92 | def at_completion_cost(self) -> float:
93 | return self.act_total_cost + self.remain_cost
94 |
95 | @property
96 | def at_completion_qty(self) -> float:
97 | return self.act_total_qty + self.remain_qty
98 |
99 | @property
100 | @rounded(ndigits=4)
101 | def cost_percent(self) -> float:
102 | return self.act_total_cost / self.target_cost if self.target_cost else 0.0
103 |
104 | @property
105 | @rounded()
106 | def cost_variance(self) -> float:
107 | return self.at_completion_cost - self.target_cost
108 |
109 | @property
110 | def finish(self) -> datetime:
111 | """Calculated Finish Date for task resource (Actual Finish or Early Finish)"""
112 | if self.act_end_date:
113 | return self.act_end_date
114 | if self.reend_date:
115 | return self.reend_date
116 | raise ValueError(f"Could not find finish date for taskrsrc {self.uid}")
117 |
118 | @property
119 | def lag(self) -> int:
120 | return int(self.target_lag_drtn_hr_cnt / 8)
121 |
122 | @property
123 | def resource_type(self) -> str | None:
124 | """Resource type (Labor, Material, Non-Labor)"""
125 | return self.resource.type[3:] if self.resource else None
126 |
127 | @property
128 | def start(self) -> datetime:
129 | """Calculated Start Date for task resource (Actual Start or Early Start)"""
130 | if self.act_start_date:
131 | return self.act_start_date
132 | if self.restart_date:
133 | return self.restart_date
134 | raise ValueError(f"Could not find start date for taskrsrc {self.uid}")
135 |
136 |
137 | def account_or_none(value: ACCOUNT | None) -> ACCOUNT | None:
138 | if value is None:
139 | return None
140 | if not isinstance(value, ACCOUNT):
141 | raise ValueError(f"ValueError: expected ; got {type(value)}")
142 | return value
143 |
--------------------------------------------------------------------------------
/xerparser/schemas/trsrcfin.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # trsrcfin.py
3 |
4 | from xerparser.schemas.findates import FINDATES
5 | from xerparser.src.validators import float_or_zero
6 |
7 |
8 | class TRSRCFIN:
9 | """
10 | A class to represent a Activity Resource Assignment Past Period Actuals
11 | """
12 |
13 | def __init__(self, period: FINDATES, **data) -> None:
14 | self.act_cost: float = float_or_zero(data["act_cost"])
15 | self.act_qty: float = float_or_zero(data["act_qty"])
16 | self.fin_dates_id: str = data["fin_dates_id"]
17 | self.proj_id: str = data["proj_id"]
18 | self.task_id: str = data["task_id"]
19 | self.taskrsrc_id: str = data["taskrsrc_id"]
20 | self.period: FINDATES = self._valid_findates(period)
21 |
22 | def __eq__(self, __o: "TRSRCFIN") -> bool:
23 | return self.period == __o.period
24 |
25 | def __hash__(self) -> int:
26 | return hash(self.period)
27 |
28 | def __gt__(self, __o: "TRSRCFIN") -> bool:
29 | return self.period > __o.period
30 |
31 | def __lt__(self, __o: "TRSRCFIN") -> bool:
32 | return self.period < __o.period
33 |
34 | def _valid_findates(self, value: FINDATES) -> FINDATES:
35 | """Validate assignment of Financial Period"""
36 | if not isinstance(value, FINDATES):
37 | raise ValueError(f"Expected ; got {type(value)}")
38 | if value.uid != self.fin_dates_id:
39 | raise ValueError(
40 | f"FINDATES {value.uid} does not equal fin_dates_id {self.fin_dates_id}"
41 | )
42 | return value
43 |
--------------------------------------------------------------------------------
/xerparser/schemas/udftype.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # udftype.py
3 |
4 | from datetime import datetime
5 | from enum import Enum
6 | from typing import Any
7 |
8 |
9 | class UDFTYPE:
10 | """
11 | A class to represent a User Defined Field.
12 | """
13 |
14 | class FieldType(Enum):
15 | """
16 | An enum class to represent the data type stored
17 | in a User Defined Field.
18 | """
19 |
20 | FT_END_DATE = "End Date"
21 | FT_FLOAT_2_DECIMALS = "Float"
22 | FT_INT = "Integer"
23 | FT_MONEY = "Cost"
24 | FT_START_DATE = "Start Date"
25 | FT_STATICTYPE = "Indicator"
26 | FT_TEXT = "Text"
27 |
28 | class Indicators(Enum):
29 | """
30 | An enum class to store the indicator icons that may be
31 | assigned to a UDF of type `FT_STATICTYPE` ("Indicator").
32 | """
33 |
34 | # Emoji's don't match perfectly with icons used by P6 but are close.
35 | UDF_G1 = "🛑"
36 | UDF_G2 = "⚠️"
37 | UDF_G3 = "✅"
38 | UDF_G4 = "⭐"
39 |
40 | def __init__(self, **data) -> None:
41 | self.uid: str = data["udf_type_id"]
42 | self.table: str = data["table_name"]
43 | self.label: str = data["udf_type_label"]
44 | self.udf_type_name: str = data["udf_type_name"]
45 | self.type: UDFTYPE.FieldType = UDFTYPE.FieldType[data["logical_data_type"]]
46 |
47 | @staticmethod
48 | def get_udf_value(udf_type: "UDFTYPE", **data: str) -> Any:
49 | if udf_type.type in (
50 | UDFTYPE.FieldType.FT_END_DATE,
51 | UDFTYPE.FieldType.FT_START_DATE,
52 | ):
53 | return datetime.strptime(data["udf_date"], "%Y-%m-%d %H:%M")
54 |
55 | if udf_type.type in (
56 | UDFTYPE.FieldType.FT_FLOAT_2_DECIMALS,
57 | UDFTYPE.FieldType.FT_MONEY,
58 | ):
59 | return float(data["udf_number"].replace(",", "."))
60 |
61 | if udf_type.type is UDFTYPE.FieldType.FT_INT:
62 | return int(data["udf_number"])
63 |
64 | if udf_type.type is UDFTYPE.FieldType.FT_STATICTYPE:
65 | return UDFTYPE.Indicators[data["udf_text"]].value
66 |
67 | return data["udf_text"]
68 |
--------------------------------------------------------------------------------
/xerparser/scripts/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jjCode01/xerparser/c425263385807f77c5ffc5d8e930d9f028df668f/xerparser/scripts/__init__.py
--------------------------------------------------------------------------------
/xerparser/scripts/dates.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime, time
2 |
3 |
4 | def calc_time_var_hrs(start: time, end: time, ordered: bool = False) -> float:
5 | """Calculate the variance in hours between two time objects
6 |
7 | Args:
8 | start (time): start time
9 | end (time): end time
10 | ordered (bool, optional): If False, reorder start and end times if start is greater than end. Defaults to False.
11 |
12 | Returns:
13 | float: Variance between two times in hours
14 | """
15 |
16 | if not all(isinstance(t, time) for t in [start, end]):
17 | raise ValueError("Value Error: Arguments must be a time object")
18 |
19 | if not ordered:
20 | # put dates in proper order so that the smaller date
21 | # is subtracted from the larger date.
22 | start, end = min(start, end), max(start, end)
23 |
24 | start_date = datetime.combine(datetime.today(), start)
25 | end_date = datetime.combine(datetime.today(), end)
26 |
27 | return round((end_date - start_date).total_seconds() / 3600, 2)
28 |
29 |
30 | def clean_date(date: datetime) -> datetime:
31 | """Sets time value to 00:00:00 (12AM)"""
32 | if not isinstance(date, datetime):
33 | raise ValueError("Value Error: Argument must be a datetime object")
34 |
35 | return date.replace(microsecond=0, second=0, minute=0, hour=0)
36 |
37 |
38 | def clean_dates(*dates: datetime) -> list[datetime]:
39 | """Remove time values from a list of datetime objects"""
40 | return [clean_date(d) for d in dates]
41 |
42 |
43 | def conv_time(time_str: str) -> time:
44 | """Convert a string representing time into a datetime.time object."""
45 | return datetime.strptime(time_str, "%H:%M").time()
46 |
--------------------------------------------------------------------------------
/xerparser/scripts/decorators.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # decorators.py
3 |
4 |
5 | def rounded(ndigits: int = 2):
6 | def inner(function):
7 | def wrapper(*args, **kwargs):
8 | value = function(*args, **kwargs)
9 | if isinstance(value, float):
10 | value = round(value, ndigits)
11 | elif isinstance(value, int):
12 | value = float(value)
13 | return value
14 |
15 | return wrapper
16 |
17 | return inner
18 |
--------------------------------------------------------------------------------
/xerparser/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jjCode01/xerparser/c425263385807f77c5ffc5d8e930d9f028df668f/xerparser/src/__init__.py
--------------------------------------------------------------------------------
/xerparser/src/errors.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # errors.py
3 |
4 |
5 | class CorruptXerFile(Exception):
6 | """Raised when xer contains missing data."""
7 |
8 | def __init__(self, errors: list[str], message="XER file is corrupt") -> None:
9 | self.errors = errors
10 | self.message = message
11 |
12 | def __str__(self) -> str:
13 | error_list = "\n".join(self.errors)
14 | return f"{self.message}\n{error_list}"
15 |
16 |
17 | class InvalidParent(Exception):
18 | """Raised when Parent does not match parent id."""
19 |
20 | def __init__(self, parent_id: str, expected_id: str | None) -> None:
21 | self.message = f"Expcted parent with id {parent_id}, got {expected_id}"
22 |
23 | def __str__(self) -> str:
24 | return self.message
25 |
26 |
27 | def find_xer_errors(tables: dict) -> list[str]:
28 | """
29 | Find issues with the xer file, including
30 | - Missing tables
31 | - Non-existent calendars assigned to activities
32 | """
33 | # This list of required tables may be subjective
34 | # TODO: Add ability to pass in your own list of required tables.
35 |
36 | REQUIRED_TABLES = {"CALENDAR", "PROJECT", "PROJWBS", "TASK", "TASKPRED"}
37 | REQUIRED_TABLE_PAIRS = {
38 | ("TASKFIN", "FINDATES"),
39 | ("TRSRCFIN", "FINDATES"),
40 | ("TASKRSRC", "RSRC"),
41 | ("TASKMEMO", "MEMOTYPE"),
42 | ("ACTVCODE", "ACTVTYPE"),
43 | ("TASKACTV", "ACTVCODE"),
44 | ("PCATVAL", "PCATTYPE"),
45 | ("PROJPCAT", "PCATVAL"),
46 | ("UDFVALUE", "UDFTYPE"),
47 | }
48 |
49 | errors = []
50 |
51 | # Check for minimum tables required to be in the XER
52 | for name in REQUIRED_TABLES:
53 | if name not in tables:
54 | errors.append(f"Missing Required Table {name}")
55 |
56 | # Check for required table pairs
57 | for t1, t2 in REQUIRED_TABLE_PAIRS:
58 | if t1 in tables and t2 not in tables:
59 | errors.append(f"Missing Table {t2} Required for Table {t1}")
60 |
61 | # check for tasks assigned to an invalid calendar (not included in CALENDAR TABLE)
62 | clndr_ids = {c["clndr_id"] for c in tables.get("CALENDAR", [])}
63 | export_projects = {
64 | p["proj_id"] for p in tables.get("PROJECT", []) if p["export_flag"] == "Y"
65 | }
66 | tasks_with_invalid_calendar = [
67 | task
68 | for task in tables.get("TASK", [])
69 | if task["clndr_id"] not in clndr_ids and task["proj_id"] in export_projects
70 | ]
71 | if tasks_with_invalid_calendar:
72 | invalid_cal_count = len({t["clndr_id"] for t in tasks_with_invalid_calendar})
73 | errors.append(
74 | f"XER is Missing {invalid_cal_count} Calendars Assigned to {len(tasks_with_invalid_calendar)} Tasks"
75 | )
76 |
77 | # check for missing resources (not included in RSRC TABLE)
78 | rsrc_ids = {r["rsrc_id"] for r in tables.get("RSRC", [])}
79 | task_rsrc_with_invalid_rsrc = [
80 | res
81 | for res in tables.get("TASKRSRC", [])
82 | if res["rsrc_id"] not in rsrc_ids and res["proj_id"] in export_projects
83 | ]
84 | if task_rsrc_with_invalid_rsrc:
85 | invalid_rsrc_count = len({r["rsrc_id"] for r in task_rsrc_with_invalid_rsrc})
86 | errors.append(
87 | f"XER is Missing {invalid_rsrc_count} Resources Assigned to {len(task_rsrc_with_invalid_rsrc)} Task Resources."
88 | )
89 | return errors
90 |
--------------------------------------------------------------------------------
/xerparser/src/parser.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # parser.py
3 |
4 | import re
5 | from pathlib import Path
6 | from typing import BinaryIO
7 |
8 | CODEC = "cp1252"
9 |
10 |
11 | def file_reader(file: str | Path | BinaryIO) -> str:
12 | """Reads a P6 .xer file and returns it's contents as a string.
13 |
14 | Args:
15 | file (str | Path | BinaryIO): .xer file
16 |
17 | Returns:
18 | str: Contents of .xer file
19 | """
20 | file_contents = ""
21 |
22 | # Path directory to file
23 | if isinstance(file, (str, Path)):
24 | with open(file, encoding=CODEC, errors="ignore") as f:
25 | file_contents = f.read()
26 | return file_contents
27 |
28 | # Binary file from requests, Flask, FastAPI, etc...
29 | file_contents = file.read().decode(CODEC, errors="ignore")
30 |
31 | return file_contents
32 |
33 |
34 | def parser(xer_contents: str) -> dict[str, list]:
35 | """
36 | Parses the contents of a P6 .xer file and converts it into a
37 | Python dictionary object.
38 |
39 | Args:
40 | xer_contents (str): .xer file contents
41 |
42 | Returns:
43 | dict: xer information and data tables
44 | """
45 | if not isinstance(xer_contents, str):
46 | raise TypeError(
47 | f"TypeError: xer_contents must be ; got {type(xer_contents)}"
48 | )
49 |
50 | if not xer_contents.startswith("ERMHDR"):
51 | raise ValueError("ValueError: invalid XER file")
52 |
53 | table_delimiter = "%T\t"
54 | tables = xer_contents.split(table_delimiter)
55 | xer_data: dict[str, list] = {}
56 |
57 | # The first row in the xer file includes file export information
58 | xer_data["ERMHDR"] = tables.pop(0).strip().split("\t")[1:]
59 | xer_data.update(
60 | **{name: rows for table in tables for name, rows in _parse_table(table).items()}
61 | )
62 |
63 | return xer_data
64 |
65 |
66 | def _parse_table(table: str) -> dict[str, list[dict]]:
67 | """Parse table name, columns, and rows"""
68 |
69 | lines: list[str] = re.split(r"\r?\n", table)
70 |
71 | name = lines.pop(0).strip() # First line is the table name
72 | cols = lines.pop(0).strip().split("\t")[1:] # Second line is the column labels
73 | data = [
74 | dict(zip(cols, row.split("\t")[1:])) for row in lines if row.startswith("%R")
75 | ]
76 | return {name: data}
77 |
--------------------------------------------------------------------------------
/xerparser/src/utils.py:
--------------------------------------------------------------------------------
1 | from xerparser.schemas.task import TASK, LinkToTask
2 |
3 |
4 | def find_redundant_logic(task: TASK) -> list[list[LinkToTask]]:
5 | redundant_paths = []
6 |
7 | for pred in task.predecessors:
8 | path = [pred]
9 | mem = set()
10 | if paths := _search_redundant_paths(pred, task, path, mem):
11 | redundant_paths.extend(paths)
12 |
13 | return redundant_paths
14 |
15 |
16 | def _search_redundant_paths(
17 | task_pred: LinkToTask,
18 | epoch_task: TASK,
19 | path: list[LinkToTask],
20 | mem: set[TASK],
21 | ):
22 | paths = []
23 |
24 | for pred in task_pred.task.predecessors:
25 | if pred.task.type.is_loe:
26 | continue
27 |
28 | if _is_valid_path(epoch_task.predecessors, pred, path):
29 | paths.append([pred] + path)
30 |
31 | if pred.task in mem:
32 | continue
33 |
34 | if new_paths := _search_redundant_paths(pred, epoch_task, [pred] + path, mem):
35 | paths.extend(new_paths)
36 |
37 | mem.add(pred.task)
38 | return paths
39 |
40 |
41 | def _is_valid_path(
42 | epoch_preds: list[LinkToTask], pred: LinkToTask, path: list[LinkToTask]
43 | ) -> bool:
44 | if pred not in epoch_preds:
45 | return False
46 | if not all(
47 | (p.link[0] == pred.link[0]) or (p.link[1] == pred.link[1])
48 | for p in [pred] + path
49 | ):
50 | return False
51 |
52 | return pred.link[1] == path[-1].link[1]
53 |
--------------------------------------------------------------------------------
/xerparser/src/validators.py:
--------------------------------------------------------------------------------
1 | """
2 | This module contains functions to validate and transorm data during object initialization.
3 | """
4 |
5 | from datetime import datetime
6 |
7 | date_format = "%Y-%m-%d %H:%M" # date format used by P6 when exporting to an xer file
8 |
9 |
10 | def optional_date(value: str) -> datetime | None:
11 | """
12 | Transform a string to a datetime object or return `None` if
13 | the string is empty.
14 | """
15 | if value == "" or value is None:
16 | return None
17 | return datetime.strptime(value, date_format)
18 |
19 |
20 | def optional_float(value: str) -> float | None:
21 | """
22 | Transform a string to a float or return `None` if
23 | the string is empty.
24 | """
25 | if value == "" or value is None:
26 | return None
27 | return float(value.replace(",", "."))
28 |
29 |
30 | def float_or_zero(value: str) -> float:
31 | """
32 | Transform a string to a float or return 0.0 if
33 | the string is empty.
34 | """
35 | if value == "" or value is None:
36 | return 0.0
37 | return float(value.replace(",", "."))
38 |
39 |
40 | def optional_int(value: str) -> int | None:
41 | """
42 | Transform a string to an integer or return `None` if
43 | the string is empty.
44 | """
45 | if value == "" or value is None:
46 | return None
47 | return int(value)
48 |
49 |
50 | def int_or_zero(value: str) -> int:
51 | """
52 | Transform a string to an integer or return 0 if
53 | the string is empty.
54 | """
55 | if value == "" or value is None:
56 | return 0
57 | return int(value)
58 |
59 |
60 | def optional_str(value: str) -> str | None:
61 | """Transform a string to None if its empty."""
62 | return (value, None)[value == ""]
63 |
--------------------------------------------------------------------------------
/xerparser/src/xer.py:
--------------------------------------------------------------------------------
1 | # xerparser
2 | # xer.py
3 |
4 | from itertools import groupby
5 | from pathlib import Path
6 | from typing import Any, BinaryIO
7 |
8 | from xerparser.schemas import TABLE_UID_MAP
9 | from xerparser.schemas._node import build_tree
10 | from xerparser.schemas.account import ACCOUNT
11 | from xerparser.schemas.actvcode import ACTVCODE
12 | from xerparser.schemas.actvtype import ACTVTYPE
13 | from xerparser.schemas.calendars import CALENDAR
14 | from xerparser.schemas.ermhdr import ERMHDR
15 | from xerparser.schemas.findates import FINDATES
16 | from xerparser.schemas.memotype import MEMOTYPE
17 | from xerparser.schemas.pcattype import PCATTYPE
18 | from xerparser.schemas.pcatval import PCATVAL
19 | from xerparser.schemas.project import PROJECT
20 | from xerparser.schemas.projwbs import PROJWBS
21 | from xerparser.schemas.rsrc import RSRC
22 | from xerparser.schemas.rsrcrate import RSRCRATE
23 | from xerparser.schemas.schedoptions import SCHEDOPTIONS
24 | from xerparser.schemas.task import TASK, LinkToTask
25 | from xerparser.schemas.taskfin import TASKFIN
26 | from xerparser.schemas.taskmemo import TASKMEMO
27 | from xerparser.schemas.taskpred import TASKPRED
28 | from xerparser.schemas.taskrsrc import TASKRSRC
29 | from xerparser.schemas.trsrcfin import TRSRCFIN
30 | from xerparser.schemas.udftype import UDFTYPE
31 | from xerparser.src.errors import CorruptXerFile, find_xer_errors
32 | from xerparser.src.parser import CODEC, file_reader, parser
33 |
34 |
35 | class Xer:
36 | """
37 | A class to represent the schedule data included in a .xer file.
38 | """
39 |
40 | # class variables
41 | CODEC = CODEC
42 |
43 | def __init__(self, xer_file_contents: str) -> None:
44 | self.tables: dict[str, list] = parser(xer_file_contents)
45 | if errors := find_xer_errors(self.tables):
46 | raise CorruptXerFile(errors)
47 | self.export_info = ERMHDR(*self.tables["ERMHDR"])
48 | self.accounts: dict[str, ACCOUNT] = build_tree(self._get_attr("ACCOUNT"))
49 | self.activity_code_types: dict[str, ACTVTYPE] = self._get_attr("ACTVTYPE")
50 | self.activity_code_values: dict[str, ACTVCODE] = build_tree(
51 | self._get_activity_codes()
52 | )
53 | self.calendars: dict[str, CALENDAR] = self._get_attr("CALENDAR")
54 |
55 | for cal in self.calendars.values():
56 | if cal.base_clndr_id:
57 | cal.base_calendar = self.calendars.get(cal.base_clndr_id)
58 |
59 | self.financial_periods: dict[str, FINDATES] = self._get_attr("FINDATES")
60 | self.notebook_topics: dict[str, MEMOTYPE] = self._get_attr("MEMOTYPE")
61 | self.project_code_types: dict[str, PCATTYPE] = self._get_attr("PCATTYPE")
62 | self.project_code_values: dict[str, PCATVAL] = build_tree(
63 | self._get_proj_codes()
64 | )
65 | self.resources: dict[str, RSRC] = build_tree(self._get_attr("RSRC"))
66 | self.resource_rates: dict[str, RSRCRATE] = self._get_rsrc_rates()
67 | self.sched_options: dict[str, SCHEDOPTIONS] = self._get_attr("SCHEDOPTIONS")
68 | self.udf_types: dict[str, UDFTYPE] = self._get_attr("UDFTYPE")
69 | self.projects = self._get_projects()
70 | self.wbs_nodes: dict[str, PROJWBS] = build_tree(self._get_wbs_nodes())
71 | self.tasks: dict[str, TASK] = self._get_tasks()
72 | self.relationships: dict[str, TASKPRED] = self._get_relationships()
73 |
74 | self._set_proj_activity_codes()
75 | self._set_proj_codes()
76 | self._set_proj_calendars()
77 | self._set_task_actv_codes()
78 | self._set_task_memos()
79 | self._set_task_resources()
80 | self._set_financial_periods()
81 | self._set_udf_values()
82 |
83 | @classmethod
84 | def reader(cls, file: Path | str | BinaryIO) -> "Xer":
85 | """
86 | Create an Xer object directly from a .XER file.
87 |
88 | Files can be passed as a:
89 | * Path directory (str or pathlib.Path)
90 | * Binary file (from requests, Flask, FastAPI, etc...)
91 |
92 | """
93 | file_contents = file_reader(file)
94 | return cls(file_contents)
95 |
96 | def _get_activity_codes(self) -> dict:
97 | activity_code_values = {
98 | code_val["actv_code_id"]: ACTVCODE(
99 | code_type=self.activity_code_types[code_val["actv_code_type_id"]],
100 | **code_val,
101 | )
102 | for code_val in self.tables.get("ACTVCODE", [])
103 | }
104 | return activity_code_values
105 |
106 | def _get_attr(self, table_name: str) -> dict:
107 | if table := self.tables.get(table_name):
108 | row_id = TABLE_UID_MAP[table_name]
109 | return {row[row_id]: eval(table_name)(**row) for row in table}
110 | return {}
111 |
112 | def _get_projects(self) -> dict[str, PROJECT]:
113 | projects = {
114 | proj["proj_id"]: PROJECT(
115 | self.sched_options[proj["proj_id"]],
116 | self.calendars.get(proj["clndr_id"]),
117 | **proj,
118 | )
119 | for proj in self.tables.get("PROJECT", [])
120 | if proj["export_flag"] == "Y"
121 | }
122 | return projects
123 |
124 | def _get_proj_codes(self) -> dict:
125 | project_code_values = {
126 | code_val["proj_catg_id"]: PCATVAL(
127 | code_type=self.project_code_types[code_val["proj_catg_type_id"]],
128 | **code_val,
129 | )
130 | for code_val in self.tables.get("PCATVAL", [])
131 | }
132 |
133 | return project_code_values
134 |
135 | def _get_relationships(self) -> dict[str, TASKPRED]:
136 | return {
137 | rel["task_pred_id"]: self._set_taskpred(**rel)
138 | for rel in self.tables.get("TASKPRED", [])
139 | }
140 |
141 | def _get_rsrc_rates(self) -> dict[str, RSRCRATE]:
142 | return {
143 | rr["rsrc_rate_id"]: self._set_rsrc_rates(**rr)
144 | for rr in self.tables.get("RSRCRATE", [])
145 | }
146 |
147 | def _get_tasks(self) -> dict[str, TASK]:
148 | return {
149 | task["task_id"]: self._set_task(**task)
150 | for task in self.tables.get("TASK", [])
151 | }
152 |
153 | def _get_wbs_nodes(self) -> dict:
154 | nodes: dict[str, PROJWBS] = {
155 | node["wbs_id"]: self._set_proj_wbs(**node)
156 | for node in self.tables.get("PROJWBS", [])
157 | }
158 | return nodes
159 |
160 | def _set_proj_activity_codes(self) -> None:
161 | code_group = groupby(
162 | sorted(self.activity_code_types.values(), key=proj_key), proj_key
163 | )
164 | for proj_id, codes in code_group:
165 | if proj := self.projects.get(proj_id):
166 | proj.activity_codes = list(codes)
167 |
168 | def _set_proj_calendars(self) -> None:
169 | for project in self.projects.values():
170 | cal_list = []
171 | for cal in self.calendars.values():
172 | if not cal.proj_id or cal.proj_id == project.uid:
173 | cal_list.append(cal)
174 | project.calendars = cal_list
175 |
176 | def _set_proj_codes(self) -> None:
177 | for proj_code in self.tables.get("PROJPCAT", []):
178 | proj = self.projects.get(proj_code["proj_id"])
179 | code = self.project_code_values.get(proj_code["proj_catg_id"])
180 | if proj and code:
181 | proj.project_codes.update({code.code_type: code})
182 |
183 | def _set_task_actv_codes(self) -> None:
184 | for act_code in self.tables.get("TASKACTV", []):
185 | task = self.tasks.get(act_code["task_id"])
186 | code_value = self.activity_code_values.get(act_code["actv_code_id"])
187 | if task and code_value:
188 | task.activity_codes.update({code_value.code_type: code_value})
189 |
190 | def _set_task_memos(self) -> None:
191 | for memo in self.tables.get("TASKMEMO", []):
192 | self._set_memo(**memo)
193 |
194 | def _set_task_resources(self) -> None:
195 | for res in self.tables.get("TASKRSRC", []):
196 | self._set_taskrsrc(**res)
197 |
198 | def _set_udf_values(self) -> None:
199 | for udf in self.tables.get("UDFVALUE", []):
200 | udf_type = self.udf_types[udf["udf_type_id"]]
201 | udf_value = UDFTYPE.get_udf_value(udf_type, **udf)
202 | if udf_type.table == "TASK":
203 | self.tasks[udf["fk_id"]].user_defined_fields[udf_type] = udf_value
204 | elif udf_type.table == "PROJECT":
205 | self.projects[udf["fk_id"]].user_defined_fields[udf_type] = udf_value
206 | elif udf_type.table == "PROJWBS":
207 | self.wbs_nodes[udf["fk_id"]].user_defined_fields[udf_type] = udf_value
208 | elif udf_type.table == "RSRC":
209 | self.resources[udf["fk_id"]].user_defined_fields[udf_type] = udf_value
210 |
211 | def _set_financial_periods(self) -> None:
212 | for task_fin in self.tables.get("TASKFIN", []):
213 | self._set_taskfin(**task_fin)
214 |
215 | for rsrc_fin in self.tables.get("TRSRCFIN", []):
216 | self._set_taskrsrc_fin(**rsrc_fin)
217 |
218 | def _set_memo(self, **kwargs) -> None:
219 | topic = self.notebook_topics[kwargs["memo_type_id"]].topic
220 | task = self.tasks[kwargs["task_id"]]
221 | task.memos.append(TASKMEMO(topic=topic, **kwargs))
222 |
223 | def _set_proj_wbs(self, **kwargs) -> PROJWBS:
224 | proj = self.projects[kwargs["proj_id"]]
225 | wbs = PROJWBS(proj, **kwargs)
226 | return wbs
227 |
228 | def _set_rsrc_rates(self, **kwargs) -> RSRCRATE:
229 | rsrc = self.resources[kwargs["rsrc_id"]]
230 | rsrc_rate = RSRCRATE(rsrc, **kwargs)
231 | return rsrc_rate
232 |
233 | def _set_task(self, **kwargs) -> TASK:
234 | calendar = self.calendars[kwargs["clndr_id"]]
235 | wbs = self.wbs_nodes[kwargs["wbs_id"]]
236 | task = TASK(calendar=calendar, wbs=wbs, **kwargs)
237 | wbs.add_task(task)
238 | self.projects[task.proj_id].tasks.append(task)
239 | return task
240 |
241 | def _set_taskpred(self, **kwargs) -> TASKPRED:
242 | pred = self.tasks[kwargs["pred_task_id"]]
243 | succ = self.tasks[kwargs["task_id"]]
244 | task_pred = TASKPRED(predecessor=pred, successor=succ, **kwargs)
245 | pred.successors.append(LinkToTask(succ, task_pred.link, task_pred.lag))
246 | succ.predecessors.append(LinkToTask(pred, task_pred.link, task_pred.lag))
247 | self.projects[task_pred.proj_id].relationships.append(task_pred)
248 | return task_pred
249 |
250 | def _set_taskrsrc(self, **kwargs) -> None:
251 | rsrc = self.resources[kwargs["rsrc_id"]]
252 | account = self.accounts.get(kwargs["acct_id"])
253 | task = self.tasks[kwargs["task_id"]]
254 | proj = self.projects[kwargs["proj_id"]]
255 | taskrsrc = TASKRSRC(resource=rsrc, account=account, **kwargs)
256 | rsrc.task_rsrcs.append(taskrsrc)
257 | task.resources.update({taskrsrc.uid: taskrsrc})
258 | proj.resources.append(taskrsrc)
259 |
260 | def _set_taskfin(self, **kwargs) -> None:
261 | period = self.financial_periods[kwargs["fin_dates_id"]]
262 | task_fin = TASKFIN(period=period, **kwargs)
263 | self.tasks[task_fin.task_id].periods.append(task_fin)
264 |
265 | def _set_taskrsrc_fin(self, **kwargs) -> None:
266 | period = self.financial_periods[kwargs["fin_dates_id"]]
267 | rsrc_fin = TRSRCFIN(period=period, **kwargs)
268 | self.tasks[rsrc_fin.task_id].resources[rsrc_fin.taskrsrc_id].periods.append(
269 | rsrc_fin
270 | )
271 |
272 |
273 | def proj_key(obj: Any) -> str:
274 | return (obj.proj_id, "")[obj.proj_id is None]
275 |
--------------------------------------------------------------------------------