projectal

A python client for the Projectal API.

Getting started

import projectal
import os

# Supply your Projectal server URL and account credentials
api_base = https://yourcompany.projectal.com
api_username = os.environ.get('PROJECTAL_USERNAME')
api_password = os.environ.get('PROJECTAL_PASSWORD')

# Test communication with server
status = projectal.status()

# Test account credentials
projectal.login()
details = projectal.auth_details()

Changelog

4.3.0

Breaking changes:

  • Added "PREDECESSOR_TASK" option when fetching projectal.Task with links
  • Predecessor tasks will be returned as a list of tasks under the taskList attribute
  • This attribute name is different to what you would see when using the REST API directly (planLink). This change was necessary to allow for directly manipulating the list of links and then saving the task entity to commit any changes, since the REST API is expecting a different key for linking calls (taskList).
  • Existing Predecessor Task linking methods were also updated to match the new linking functionality. They now work as a reverse linker, automatically inverting the link relationship between the task entities. This more closely matches what you would expect to see based on the Web UI. I.e. When previously calling some_task.link_predecessor_task(another_task), some_task would be set as a predecessor for another_task instead of the other way around. Now another_task would be set as the predecessor for some_task.

4.2.2

  • projectal.User.current_user_permissions() fixed incorrect query.
  • projectal.Webhook.list() default limit increased to 1000.

4.2.1

  • Added classes allowing for the management of dynamic enums. The user must have the "List Management" permission to update enums.

    New classes:

    • projectal.CompanyTypes
    • projectal.SkillLevels
    • projectal.StaffTypes
    • projectal.PriorityLevels
    • projectal.ComplexityLevels
    • projectal.CurrencyList

    The current enum can be retrieved with get(), and updated with set(). For example, to return the current SkillLevels enum:

    projectal.SkillLevels.get()
    

    For each enum the entire list of key value pairs must be provided when calling set(), any existing values that are omitted from the dictionary will be removed, and any additional values will be added.

    To update the SkillLevels enum with a new value:

    new_value_added = {
        "Senior": 10,
        "Mid": 20,
        "Junior": 30,
        # new SkillLevel value "Beginner"
        "Beginner": 40,
    }
    projectal.SkillLevels.set(new_value_added)
    

    To change the name of a value, set a new key name for the original value:

    updated_value_name = {
        # changing "Senior" SkillLevel to "Expert"
        "Expert": 10,
        "Mid": 20,
        "Junior": 30,
    }
    projectal.SkillLevels.set(updated_value_name)
    

    To remove an existing value, call set on a dictionary with that value removed:

    value_removed = {
        "Senior": 10,
        "Mid": 20,
        # "Junior" SkillLevel removed
    }
    projectal.SkillLevels.set(new_value_added)
    

    Updating the CurrencyList works differently to the other enums, since the names of values must match the alphabetic currency code and the value must match the numeric currency code. This will cause an exception if you try to change the name for any values.

    Adding a new currency:

    new_currency_added = {
      "AED": 784
      ...
      # rest of the existing currencies
      ...
      # new currency to add with the alphabetic and numeric code
      "ZWL": 932,
    }
    projectal.CurrencyList.set(new_currency_added)
    

    Removing an existing currency requires you to provide the numeric code for the currency as a negative value.

    currency_removed = {
      # this currency will be removed
      "AED": -784
      ...
      # rest of the existing currencies
      ...
    }
    projectal.CurrencyList.set(currency_removed)
    

4.2.0

Version 4.2.0 accompanies the release of Projectal 4.1.0

  • Minimum Projectal version is now 4.1.0.

  • Changed order of applying link types when an entity is initialized, prevents a type error with reverse linking in certain situations.

  • projectal.Task.reset_duration() now supports adjustments with multi day calendar exceptions.

  • projectal.Task.reset_duration() location working days override base exceptions.

  • projectal.TaskTemplate.list() fixed incorrect query when using inherited method.

4.1.0

  • DateLimit.Max enum value changed from "9999-12-31" to "3000-01-01". This reflects changes to the Projectal backend that defines this as the maximum allowable date value. The front end typically considers this value as equivalent with having no end date.

  • Updated requirements.txt version for requests package

  • Minimum Projectal version is now 4.0.40

4.0.3

  • When a dict object is passed to the update class method, it will be converted to the corresponding Entity type. Allows for proper handling of keys that require being treated as links.

4.0.2

  • Booking entity is now fetched with project field and either staff or resource field.

  • Added missing link methods for 'Booking' entity (Note, File)

  • Added missing link methods for 'Activity' entity (Booking, Note, File, Rebate)

  • Reduced maximum number of link methods to 100 for a single batch request to prevent timeouts under heavy load.

4.0.1

  • Minimum Projectal version is now 4.0.0.

4.0.0

Version 4.0.0 accompanies the release of Projectal 4.0.

  • Added the Activity entity, new in Projectal 4.0.

  • Added the Booking entity, new in Projectal 4.0.

3.1.1

  • Link requests generated by 'projectal.Entity.create()' and 'projectal.Entity.update()' are now executed in batches. This is enabled by default with the 'batch_linking=True' parameter and can be disabled to execute each link request individually. It is recommended to leave this parameter enabled as this can greatly reduce the number of network requests.

3.1.0

  • Minimum Projectal version is now 3.1.5.

  • Added projectal.Webhook.list_events(). See API doc for details on how to use.

  • Added deleted_at parameter to projectal.Entity.get(). This value should be a UTC timestamp from a webhook delete event.

  • Added projectal.ldap_sync() to initiate a user sync with the LDAP/AD service configured in the Projectal server settings.

  • Enhanced output of projectal.Entity.changes() function when reporting link changes. It no longer dumps the entire before-and-after list with the full content of each linked entity. Now reports three lists: added, updated, removed. Entities within the updated list follow the same old vs new dictionary model for the data attributes within them. E.g:

    resourceList: [
        'added': [],
        'updated': [
            {'uuId': '14eb4c31-0f92-49d1-8b4d-507ab939003e', 'resourceLink': {'utilization': {'old': 0.1, 'new': 0.9}}},
        ],
        'removed': []
    ]
    

    This should result in slimmer logs that are much easier to understand as the changes are clearly indicated.

3.0.2

  • Added projectal.Entity.get_link_definitions(). Exposes entity link definition dictionary. Consumers can inspect which links an Entity knows about and their internal settings. Link definitions that appear here are the links valid for links=[] parameters.

3.0.1

  • Fixed fetching project with links=['task'] not being available.

  • Improved Permission.list(). Now returns a dict with the permission name as key with Permission objects as the value (instead of list of uuIds).

  • Added a way to use the aliasing feature of the API (new in Projectal 3.0). Set api_alias = 'uuid' to the UUID of a User object and all requests made will be done as that user. Restore this value to None to resume normal operation. (Some rules and limitations apply. See API for more details.)

  • Added complete support for the Tags entity (including linkers).

3.0

Version 3.0 accompanies the release of Projectal 3.0.

Breaking changes:

  • The links parameter on Entity functions now consumes a list of entity names instead of a comma-separated string. For example:

    # Before:
    projectal.Staff.get('<uuid>', links='skill,location')  # No longer valid
    # Now:
    projectal.Staff.get('<uuid>', links=['skill', 'location'])
    
  • The projectal.enums.SkillLevel enum has had all values renamed to match the new values used in Projectal (Junior, Mid, Senior). This includes the properties on Skill entities indicating work time for auto-scheduling (now juniorLevel, midLevel, seniorLevel).

Other changes:

  • Working with entity links has changed in this release. The previous methods are still available and continue to work as before, but there is no need to interact with the projectal.linkers methods yourself anymore.

    You can now modify the list of links within an entity and save the entity directly. The library will automatically determine how the links have been modified and issue the correct linker methods on your behalf. E.g., you can now do:

    staff = projectal.Staff.get('<uuid>', links=['skill'])
    staff['firstName'] = "New name"  # Field update
    staff['skillList'] = [skill1, skill2, skill3]  # Link update
    staff.save()  # Both changes are saved
    
    task = projectal.Task.get('<uuid>', links=['stage'])
    task['stage'] = stage1  # Uses a single object instead of list
    task.save()
    

    See examples/linking.py for a more complete demonstration of linking capabilities and limitations.

  • Linkers (projectal.linkers) can now be given a list of Entities (of one type) to link/unlink/relink in bulk. E.g:

    staff.unlink_skill(skill1)  # Before
    staff.unlink_skill([skill1, skill2, skill3])  # This works now too
    
  • Linkers now strip the payload to only the required fields instead of passing on the entire Entity object. This cuts down on network traffic significantly.

  • Linkers now also work in reverse. The Projectal server currently only supports linking entities in one direction (e.g., Company to Staff), which often means writing something like:

    staff.link_location(location)
    company.link_staff(staff)
    

    The change in direction is not very intuitive and would require you to constantly verify which direction is the one available to you in the documentation.

    Reverse linkers hide this from you and figure out the direction of the relationship for you behind the scenes. So now this is possible, even though the API doesn't strictly support it:

    staff.link_location(location)
    staff.link_company(company)
    

    Caveat: the documentation for Staff will not list Company links. You will still have to look up the Company documentation for the link description.

  • Requesting entity links with the links= parameter will now always ensure the link field (e.g., taskList) exists in the result, even if there are no links. The server may not always return a value, but we can use a default value ([] for lists, None for dicts).

  • Added a Permission entity to correctly type Permissions in responses.

  • Added a Tag entity, new in Projectal 3.0.

  • Added links parameter to Company.get_primary_company()

  • Department.tree(): now consumes a holder Entity object instead of a uuId.

  • Department.tree(): added generic_staff parameter, new in Projectal 3.0.

  • Don't break on trailing slash in Projectal URL

  • When creating tasks, populate the projectRef and parent fields in the returned Task object.

  • Added convenience functions for matching on fields where you only want one result (e.g match_one()) which return the first match found.

  • Update the entity history() method for Projectal 3.0. Some new parameters allow you to restrict the history to a particular range or to get only the changes for a webhook timestamp.

  • Entity objects can call .history() on themselves.

  • The library now keeps a reference to the User account that is currently logged in and using the API: api_auth_details.

Known issues:

  • You cannot save changes to Notes or Calendars via their holding entity. You must save the changes on the Note or Calendar directly. To illustrate:
    staff = projectal.Staff.get(<uuid>, links=['calendar'])
    calendar = staff['calendarList'][0]
    calendar['name'] = 'Calendar 2'
    
    # Cannot do this - will not pick up the changes
    staff.save()
    
    # You must do this for now
    calendar.save()
This will be resolved in a future release.

  • When creating Notes, the created and modified values may differ by 1ms in the object you have a reference to compared to what is actually stored in the database.

  • Duration calculation is not precise yet (mentioned in 2.1.0)

2.1.0

**Breaking changes**: - Getting location calendar is now done on an instance instead of class. So `projectal.Location.calendar(uuid)` is now simply `location.calendar()` - The `CompanyType.Master` enum has been replaced with `CompanyType.Primary`. This was a leftover reference to the Master Company which was renamed in Projectal several versions ago. **Other changes**: - Date conversion functions return None when given None or empty string - Added `Task.reset_duration()` as a basic duration calculator for tasks. This is a work-in-progress and will be gradually improved. The duration calculator takes into consideration the location to remove non-work days from the estimate of working duration. It currently does not work for the time component or `isWorking=True` exceptions. - Change detection in `Entity.changes()` now excludes cases where the server has no value and the new value is None. Saving this change has no effect and would always detect a change until a non-None value is set, which is noisy and generates more network activity.

2.0.3

  • Better support for calendars.

    • Distinguish between calendar containers ("Calendar") and the calendar items within them ("CalendarItem").
    • Allow CalendarItems to be saved directly. E.G item.save()
  • Fix 'holder' parameter in contact/staff/location/task_template not permitting object type. Now consumes uuId or object to match rest of the library.
  • Entity.changes() has been extended with an old=True flag. When this flag is true, the set of changes will now return both the original and the new values. E.g.
md5-f7279c698f1b0d3b306e87f9e151e7a8

  • Fixed entity link cache causing errors when deleting a link from an entity which has not been fetched with links (deleting from empty list).

2.0.2

  • Fixed updating Webhook entities

2.0.1

  • Fixed application ID not being used correctly.

2.0.0

  • Version 2.0 accompanies the release of Projectal 2.0. There are no major changes since the previous release.
  • Expose Entity.changes() function. It returns a list of fields on an entity that have changed since fetching it. These are the changes that will be sent over to the server when an update request is made.
  • Added missing 'packaging' dependency to requirements.

1.2.0

**Breaking changes**:

  • Renamed request_timestamp to response_timestamp to better reflect its purpose.
  • Automatic timestamp conversion into dates (introduced in 1.1.0) has been reverted. All date fields returned from the server remain as UTC timestamps.

    The reason is that date fields on tasks contain a time component and converting them into date strings was erasing the time, resulting in a value that does not match the database.

    Note: the server supports setting date fields using a date string like 2022-04-05. You may use this if you prefer but the server will always return a timestamp.

    Note: we provide utility functions for easily converting dates from/to timestamps expected by the Projectal server. See: projectal.date_from_timestamp(),projectal.timestamp_from_date(), and projectal.timestamp_from_datetime().

**Other changes**: - Implement request chunking - for methods that consume a list of entities, we now automatically batch them up into multiple requests to prevent timeouts on really large request. Values are configurable through `chunk_size_read` and `chunk_size_write`. Default values: Read: 1000 items. Write: 200 items. - Added profile get/set functions on entities for easier use. Now you only need to supply the key and the data. E.g: md5-659103e2d1bcee22b7bd70e7c18d4bc5
  • Entity link methods now automatically update the entity's cached list of links. E.g: a task fetched with staff links will have task['staffList'] = [Staff1,Staff2]. Before, doing a task.link_staff(staff) did not modify the list to reflect the addition. Now, it will turn into [Staff1,Staff2,Staff3]. The same applies for update and delete.

    This allows you to modify links and continue working with that object without having to fetch it again to obtain the most recent link data. Be aware that if you acquire the object without requesting the link data as well (e.g: projectal.Task.get(id, links='STAFF')), these lists will not accurately reflect what's in the database, only the changes made while the object is held.

  • Support new applicationId property on login. Set with: api_application_id. The application ID is sent back to you in webhooks so you know which application was the source of the event (and you can choose to filter them accordingly).

  • Added Entity.set_readonly() to allow setting values on entities that will not be sent over to the server when updating/saving the entity.

    The main use case for this is to populate cached entities which you have just created with values you already know about. This is mainly a workaround for the limitation of the server not sending the full object back after creating it, resulting in the client needing to fetch the object in full again if it needs some of the fields set by the server after creation.

    Additionally, some read-only fields will generate an error on the server if included in the update request. This method lets you set these values on newly created objects without triggering this error.

    A common example is setting the projectRef of a task you just created.

1.1.1

  • Add support for 'profiles' API. Profiles are a type of key-value storage that target any entity. Not currently documented.
  • Fix handling error message parsing in ProjectalException for batch create operation
  • Add Task.update_order() to set task order
  • Return empty list when GETing empty list instead of failing (no request to server)
  • Expose the timestamp returned by requests that modify the database. Use projectal.request_timestamp to get the value of the most recent request (None if no timestamp in response)

1.1.0

  • Minimum Projectal version is now 1.9.4.

Breaking changes:

  • Entity list() now returns a list of UUIDs instead of full objects. You may provide an expand parameter to restore the previous behavior: Entity.list(expand=True). This change is made for performance reasons where you may have thousands of tasks and getting them all may time out. For those cases, we suggest writing a query to filter down to only the tasks and fields you need.
  • Company.get_master_company() has been renamed to Company.get_primary_company() to match the server.
  • The following date fields are converted into date strings upon fetch: startTime, closeTime, scheduleStart, scheduleFinish. These fields are added or updated using date strings (like 2022-03-02), but the server returns timestamps (e.g: 1646006400000) upon fetch, which is confusing. This change ensures they are always date strings for consistency.

Other changes:

  • When updating an entity, only the fields that have changed are sent to the server. When updating a list of entities, unmodified entities are not sent to the server at all. This dramatically reduces the payload size and should speed things up.
  • When fetching entities, entity links are now typed as well. E.g. project['rebateList'] contains a list of Rebate instead of dict.
  • Added date_from_timestamp() and timestamp_from_date() functions to help with converting to/from dates and Projectal timestamps.
  • Entity history now uses desc by default (index 0 is newest)
  • Added Project.tasks() to list all task UUIDs within a project.

1.0.3

  • Fix another case of automatic JWT refresh not working

1.0.2

  • Entity instances can save() or delete() on themselves
  • Fix broken dict methods (get() and update()) when called from Entity instances
  • Fix automatic JWT refresh only working in some cases

1.0.1

  • Added list() function for all entities
  • Added search functions for all entities (match-, search, query)
  • Added Company.get_master_company()
  • Fixed adding template tasks
  1"""
  2A python client for the [Projectal API](https://projectal.com/docs/latest).
  3
  4## Getting started
  5
  6```
  7import projectal
  8import os
  9
 10# Supply your Projectal server URL and account credentials
 11projectal.api_base = https://yourcompany.projectal.com
 12projectal.api_username = os.environ.get('PROJECTAL_USERNAME')
 13projectal.api_password = os.environ.get('PROJECTAL_PASSWORD')
 14
 15# Test communication with server
 16status = projectal.status()
 17
 18# Test account credentials
 19projectal.login()
 20details = projectal.auth_details()
 21```
 22
 23----
 24
 25## Changelog
 26
 27### 4.3.0
 28
 29**Breaking changes:**
 30
 31- Added "PREDECESSOR_TASK" option when fetching projectal.Task with links
 32- Predecessor tasks will be returned as a list of tasks under the taskList attribute
 33- This attribute name is different to what you would see when using the REST API directly
 34  (planLink). This change was necessary to allow for directly manipulating
 35  the list of links and then saving the task entity to commit any changes,
 36  since the REST API is expecting a different key for linking calls (taskList).
 37- Existing Predecessor Task linking methods were also updated to match the new linking functionality.
 38  They now work as a reverse linker, automatically inverting the link relationship between
 39  the task entities. This more closely matches what you would expect to see based on the Web UI.
 40  I.e. When previously calling `some_task.link_predecessor_task(another_task)`,
 41  some_task would be set as a predecessor for another_task instead of the other way around.
 42  Now another_task would be set as the predecessor for some_task.
 43
 44### 4.2.2
 45- `projectal.User.current_user_permissions()` fixed incorrect query.
 46- `projectal.Webhook.list()` default limit increased to 1000.
 47
 48### 4.2.1
 49- Added classes allowing for the management of dynamic enums. The user must have the "List Management"
 50  permission to update enums.
 51
 52  New classes:
 53  - `projectal.CompanyTypes`
 54  - `projectal.SkillLevels`
 55  - `projectal.StaffTypes`
 56  - `projectal.PriorityLevels`
 57  - `projectal.ComplexityLevels`
 58  - `projectal.CurrencyList`
 59
 60  The current enum can be retrieved with get(), and updated with set().
 61  For example, to return the current SkillLevels enum:
 62
 63  ```
 64  projectal.SkillLevels.get()
 65  ```
 66
 67  For each enum the entire list of key value pairs must be provided when calling set(),
 68  any existing values that are omitted from the dictionary will be removed,
 69  and any additional values will be added.
 70
 71  To update the SkillLevels enum with a new value:
 72
 73  ```
 74  new_value_added = {
 75      "Senior": 10,
 76      "Mid": 20,
 77      "Junior": 30,
 78      # new SkillLevel value "Beginner"
 79      "Beginner": 40,
 80  }
 81  projectal.SkillLevels.set(new_value_added)
 82  ```
 83
 84  To change the name of a value, set a new key name for the original value:
 85
 86  ```
 87  updated_value_name = {
 88      # changing "Senior" SkillLevel to "Expert"
 89      "Expert": 10,
 90      "Mid": 20,
 91      "Junior": 30,
 92  }
 93  projectal.SkillLevels.set(updated_value_name)
 94  ```
 95
 96  To remove an existing value, call set on a dictionary with that value removed:
 97
 98  ```
 99  value_removed = {
100      "Senior": 10,
101      "Mid": 20,
102      # "Junior" SkillLevel removed
103  }
104  projectal.SkillLevels.set(new_value_added)
105  ```
106
107  Updating the CurrencyList works differently to the other enums, since the
108  names of values must match the alphabetic currency code and the value must
109  match the numeric currency code.
110  This will cause an exception if you try to change the name for any values.
111
112  Adding a new currency:
113
114  ```
115  new_currency_added = {
116    "AED": 784
117    ...
118    # rest of the existing currencies
119    ...
120    # new currency to add with the alphabetic and numeric code
121    "ZWL": 932,
122  }
123  projectal.CurrencyList.set(new_currency_added)
124  ```
125
126  Removing an existing currency requires you to provide the numeric code for
127  the currency as a negative value.
128
129  ```
130  currency_removed = {
131    # this currency will be removed
132    "AED": -784
133    ...
134    # rest of the existing currencies
135    ...
136  }
137  projectal.CurrencyList.set(currency_removed)
138  ```
139
140### 4.2.0
141Version 4.2.0 accompanies the release of Projectal 4.1.0
142
143- Minimum Projectal version is now 4.1.0.
144
145- Changed order of applying link types when an entity is initialized,
146prevents a type error with reverse linking in certain situations.
147
148- `projectal.Task.reset_duration()` now supports adjustments with multi day calendar exceptions.
149
150- `projectal.Task.reset_duration()` location working days override base exceptions.
151
152- `projectal.TaskTemplate.list()` fixed incorrect query when using inherited method.
153
154### 4.1.0
155- DateLimit.Max enum value changed from "9999-12-31" to "3000-01-01". This reflects changes to the Projectal
156backend that defines this as the maximum allowable date value. The front end typically considers this value as
157equivalent with having no end date.
158
159- Updated requirements.txt version for requests package
160
161- Minimum Projectal version is now 4.0.40
162
163### 4.0.3
164- When a dict object is passed to the update class method, it will be converted to the corresponding Entity type.
165  Allows for proper handling of keys that require being treated as links.
166
167### 4.0.2
168- Booking entity is now fetched with project field and either staff or resource field.
169
170- Added missing link methods for 'Booking' entity (Note, File)
171
172- Added missing link methods for 'Activity' entity (Booking, Note, File, Rebate)
173
174- Reduced maximum number of link methods to 100 for a single batch request to prevent timeouts
175under heavy load.
176
177### 4.0.1
178- Minimum Projectal version is now 4.0.0.
179
180### 4.0.0
181
182Version 4.0.0 accompanies the release of Projectal 4.0.
183
184- Added the `Activity` entity, new in Projectal 4.0.
185
186- Added the `Booking` entity, new in Projectal 4.0.
187
188### 3.1.1
189- Link requests generated by 'projectal.Entity.create()' and 'projectal.Entity.update()' are now
190  executed in batches. This is enabled by default with the 'batch_linking=True' parameter and can
191  be disabled to execute each link request individually. It is recommended to leave this parameter
192  enabled as this can greatly reduce the number of network requests.
193
194### 3.1.0
195- Minimum Projectal version is now 3.1.5.
196
197- Added `projectal.Webhook.list_events()`. See API doc for details on how to use.
198
199- Added `deleted_at` parameter to `projectal.Entity.get()`. This value should be a UTC timestamp
200  from a webhook delete event.
201
202- Added `projectal.ldap_sync()` to initiate a user sync with the LDAP/AD service configured in
203  the Projectal server settings.
204
205- Enhanced output of `projectal.Entity.changes()` function when reporting link changes.
206  It no longer dumps the entire before-and-after list with the full content of each linked entity.
207  Now reports three lists: `added`, `updated`, `removed`. Entities within the `updated` list
208  follow the same `old` vs `new` dictionary model for the data attributes within them. E.g:
209
210    ```
211    resourceList: [
212        'added': [],
213        'updated': [
214            {'uuId': '14eb4c31-0f92-49d1-8b4d-507ab939003e', 'resourceLink': {'utilization': {'old': 0.1, 'new': 0.9}}},
215        ],
216        'removed': []
217    ]
218    ```
219  This should result in slimmer logs that are much easier to understand as the changes are
220  clearly indicated.
221
222### 3.0.2
223- Added `projectal.Entity.get_link_definitions()`. Exposes entity link definition dictionary.
224  Consumers can inspect which links an Entity knows about and their internal settings.
225  Link definitions that appear here are the links valid for `links=[]` parameters.
226
227### 3.0.1
228- Fixed fetching project with links=['task'] not being available.
229
230- Improved Permission.list(). Now returns a dict with the permission name as
231  key with Permission objects as the value (instead of list of uuIds).
232
233- Added a way to use the aliasing feature of the API (new in Projectal 3.0).
234Set `projectal.api_alias = 'uuid'` to the UUID of a User object and all
235requests made will be done as that user. Restore this value to None to resume
236normal operation. (Some rules and limitations apply. See API for more details.)
237
238- Added complete support for the Tags entity (including linkers).
239
240### 3.0
241
242Version 3.0 accompanies the release of Projectal 3.0.
243
244**Breaking changes**:
245
246- The `links` parameter on `Entity` functions now consumes a list of entity
247  names instead of a comma-separated string. For example:
248
249    ```
250    # Before:
251    projectal.Staff.get('<uuid>', links='skill,location')  # No longer valid
252    # Now:
253    projectal.Staff.get('<uuid>', links=['skill', 'location'])
254    ```
255
256- The `projectal.enums.SkillLevel` enum has had all values renamed to match the new values
257  used in Projectal (Junior, Mid, Senior). This includes the properties on
258  Skill entities indicating work time for auto-scheduling (now `juniorLevel`,
259  `midLevel`, `seniorLevel`).
260
261**Other changes**:
262
263- Working with entity links has changed in this release. The previous methods
264  are still available and continue to work as before, but there is no need
265  to interact with the `projectal.linkers` methods yourself anymore.
266
267  You can now modify the list of links within an entity and save the entity
268  directly. The library will automatically determine how the links have been
269  modified and issue the correct linker methods on your behalf. E.g.,
270  you can now do:
271
272    ```
273    staff = projectal.Staff.get('<uuid>', links=['skill'])
274    staff['firstName'] = "New name"  # Field update
275    staff['skillList'] = [skill1, skill2, skill3]  # Link update
276    staff.save()  # Both changes are saved
277
278    task = projectal.Task.get('<uuid>', links=['stage'])
279    task['stage'] = stage1  # Uses a single object instead of list
280    task.save()
281    ```
282
283  See `examples/linking.py` for a more complete demonstration of linking
284  capabilities and limitations.
285
286- Linkers (`projectal.linkers`) can now be given a list of Entities (of one
287 type) to link/unlink/relink in bulk. E.g:
288    ```
289    staff.unlink_skill(skill1)  # Before
290    staff.unlink_skill([skill1, skill2, skill3])  # This works now too
291    ```
292
293- Linkers now strip the payload to only the required fields instead of passing
294  on the entire Entity object. This cuts down on network traffic significantly.
295
296- Linkers now also work in reverse. The Projectal server currently only supports
297  linking entities in one direction (e.g., Company to Staff), which often means
298  writing something like:
299    ```
300    staff.link_location(location)
301    company.link_staff(staff)
302    ```
303  The change in direction is not very intuitive and would require you to constantly
304  verify which direction is the one available to you in the documentation.
305
306  Reverse linkers hide this from you and figure out the direction of the relationship
307  for you behind the scenes. So now this is possible, even though the API doesn't
308  strictly support it:
309    ```
310    staff.link_location(location)
311    staff.link_company(company)
312    ```
313    Caveat: the documentation for Staff will not list Company links. You will still
314    have to look up the Company documentation for the link description.
315
316- Requesting entity links with the `links=` parameter will now always ensure the
317  link field (e.g., `taskList`) exists in the result, even if there are no links.
318  The server may not always return a value, but we can use a default value ([] for
319  lists, None for dicts).
320
321- Added a `Permission` entity to correctly type Permissions in responses.
322
323- Added a `Tag` entity, new in Projectal 3.0.
324
325- Added `links` parameter to `Company.get_primary_company()`
326
327- `Department.tree()`: now consumes a `holder` Entity object instead
328  of a uuId.
329
330- `Department.tree()`: added `generic_staff` parameter, new in
331  Projectal 3.0.
332
333- Don't break on trailing slash in Projectal URL
334
335- When creating tasks, populate the `projectRef` and `parent` fields in the
336  returned Task object.
337
338- Added convenience functions for matching on fields where you only want
339  one result (e.g match_one()) which return the first match found.
340
341- Update the entity `history()` method for Projectal 3.0. Some new parameters
342  allow you to restrict the history to a particular range or to get only the
343  changes for a webhook timestamp.
344
345- Entity objects can call `.history()` on themselves.
346
347- The library now keeps a reference to the User account that is currently logged
348  in and using the API: `projectal.api_auth_details`.
349
350**Known issues**:
351- You cannot save changes to Notes or Calendars via their holding entity. You
352  must save the changes on the Note or Calendar directly. To illustrate:
353  ```
354  staff = projectal.Staff.get(<uuid>, links=['calendar'])
355  calendar = staff['calendarList'][0]
356  calendar['name'] = 'Calendar 2'
357
358  # Cannot do this - will not pick up the changes
359  staff.save()
360
361  # You must do this for now
362  calendar.save()
363  ```
364  This will be resolved in a future release.
365
366- When creating Notes, the `created` and `modified` values may differ by
367  1ms in the object you have a reference to compared to what is actually
368  stored in the database.
369
370- Duration calculation is not precise yet (mentioned in 2.1.0)
371
372### 2.1.0
373**Breaking changes**:
374- Getting location calendar is now done on an instance instead of class. So
375  `projectal.Location.calendar(uuid)` is now simply `location.calendar()`
376- The `CompanyType.Master` enum has been replaced with `CompanyType.Primary`.
377  This was a leftover reference to the Master Company which was renamed in
378  Projectal several versions ago.
379
380**Other changes**:
381- Date conversion functions return None when given None or empty string
382- Added `Task.reset_duration()` as a basic duration calculator for tasks.
383  This is a work-in-progress and will be gradually improved. The duration
384  calculator takes into consideration the location to remove non-work
385  days from the estimate of working duration. It currently does not work
386  for the time component or `isWorking=True` exceptions.
387- Change detection in `Entity.changes()` now excludes cases where the
388  server has no value and the new value is None. Saving this change has
389  no effect and would always detect a change until a non-None value is
390  set, which is noisy and generates more network activity.
391
392### 2.0.3
393- Better support for calendars.
394  - Distinguish between calendar containers ("Calendar") and the
395    calendar items within them ("CalendarItem").
396  - Allow CalendarItems to be saved directly. E.G item.save()
397- Fix 'holder' parameter in contact/staff/location/task_template not
398  permitting object type. Now consumes uuId or object to match rest of
399  the library.
400- `Entity.changes()` has been extended with an `old=True` flag. When
401  this flag is true, the set of changes will now return both the original
402  and the new values. E.g.
403```
404task.changes()
405# {'name': 'current'}
406task.changes(old=True)
407# {'name': {'old': 'original', 'new': 'current'}}
408```
409- Fixed entity link cache causing errors when deleting a link from an entity
410  which has not been fetched with links (deleting from empty list).
411
412### 2.0.2
413- Fixed updating Webhook entities
414
415### 2.0.1
416- Fixed application ID not being used correctly.
417
418### 2.0.0
419- Version 2.0 accompanies the release of Projectal 2.0. There are no major changes
420  since the previous release.
421- Expose `Entity.changes()` function. It returns a list of fields on an entity that
422  have changed since fetching it. These are the changes that will be sent over to the
423  server when an update request is made.
424- Added missing 'packaging' dependency to requirements.
425
426### 1.2.0
427
428**Breaking changes**:
429
430- Renamed `request_timestamp` to `response_timestamp` to better reflect its purpose.
431- Automatic timestamp conversion into dates (introduced in `1.1.0`) has been reverted.
432  All date fields returned from the server remain as UTC timestamps.
433
434  The reason is that date fields on tasks contain a time component and converting them
435  into date strings was erasing the time, resulting in a value that does not match
436  the database.
437
438  Note: the server supports setting date fields using a date string like `2022-04-05`.
439  You may use this if you prefer but the server will always return a timestamp.
440
441  Note: we provide utility functions for easily converting dates from/to
442  timestamps expected by the Projectal server. See:
443  `projectal.date_from_timestamp()`,`projectal.timestamp_from_date()`, and
444  `projectal.timestamp_from_datetime()`.
445
446**Other changes**:
447- Implement request chunking - for methods that consume a list of entities, we now
448  automatically batch them up into multiple requests to prevent timeouts on really
449  large request. Values are configurable through
450  `projectal.chunk_size_read` and `projectal.chunk_size_write`.
451  Default values: Read: 1000 items. Write: 200 items.
452- Added profile get/set functions on entities for easier use. Now you only need to supply
453  the key and the data. E.g:
454
455```
456key = 'hr_connector'
457data = {'staff_source': 'company_z'}
458task.profile_set(key, data)
459```
460
461- Entity link methods now automatically update the entity's cached list of links. E.g:
462  a task fetched with staff links will have `task['staffList'] = [Staff1,Staff2]`.
463  Before, doing a `task.link_staff(staff)` did not modify the list to reflect the
464  addition. Now, it will turn into `[Staff1,Staff2,Staff3]`. The same applies for update
465  and delete.
466
467  This allows you to modify links and continue working with that object without having
468  to fetch it again to obtain the most recent link data. Be aware that if you acquire
469  the object without requesting the link data as well
470  (e.g: `projectal.Task.get(id, links='STAFF')`),
471  these lists will not accurately reflect what's in the database, only the changes made
472  while the object is held.
473
474- Support new `applicationId` property on login. Set with: `projectal.api_application_id`.
475  The application ID is sent back to you in webhooks so you know which application was
476  the source of the event (and you can choose to filter them accordingly).
477- Added `Entity.set_readonly()` to allow setting values on entities that will not
478  be sent over to the server when updating/saving the entity.
479
480  The main use case for this is to populate cached entities which you have just created
481  with values you already know about. This is mainly a workaround for the limitation of
482  the server not sending the full object back after creating it, resulting in the client
483  needing to fetch the object in full again if it needs some of the fields set by the
484  server after creation.
485
486  Additionally, some read-only fields will generate an error on the server if
487  included in the update request. This method lets you set these values on newly
488  created objects without triggering this error.
489
490  A common example is setting the `projectRef` of a task you just created.
491
492
493### 1.1.1
494- Add support for 'profiles' API. Profiles are a type of key-value storage that target
495  any entity. Not currently documented.
496- Fix handling error message parsing in ProjectalException for batch create operation
497- Add `Task.update_order()` to set task order
498- Return empty list when GETing empty list instead of failing (no request to server)
499- Expose the timestamp returned by requests that modify the database. Use
500  `projectal.request_timestamp` to get the value of the most recent request (None
501  if no timestamp in response)
502
503### 1.1.0
504- Minimum Projectal version is now 1.9.4.
505
506**Breaking changes**:
507- Entity `list()` now returns a list of UUIDs instead of full objects. You may provide
508  an `expand` parameter to restore the previous behavior: `Entity.list(expand=True)`.
509  This change is made for performance reasons where you may have thousands of tasks
510  and getting them all may time out. For those cases, we suggest writing a query to filter
511  down to only the tasks and fields you need.
512- `Company.get_master_company()` has been renamed to `Company.get_primary_company()`
513  to match the server.
514- The following date fields are converted into date strings upon fetch:
515  `startTime`, `closeTime`, `scheduleStart`, `scheduleFinish`.
516  These fields are added or updated using date strings (like `2022-03-02`), but the
517  server returns timestamps (e.g: 1646006400000) upon fetch, which is confusing. This
518  change ensures they are always date strings for consistency.
519
520**Other changes**:
521- When updating an entity, only the fields that have changed are sent to the server. When
522  updating a list of entities, unmodified entities are not sent to the server at all. This
523  dramatically reduces the payload size and should speed things up.
524- When fetching entities, entity links are now typed as well. E.g. `project['rebateList']`
525  contains a list of `Rebate` instead of `dict`.
526- Added `date_from_timestamp()` and `timestamp_from_date()` functions to help with
527  converting to/from dates and Projectal timestamps.
528- Entity history now uses `desc` by default (index 0 is newest)
529- Added `Project.tasks()` to list all task UUIDs within a project.
530
531### 1.0.3
532- Fix another case of automatic JWT refresh not working
533
534### 1.0.2
535- Entity instances can `save()` or `delete()` on themselves
536- Fix broken `dict` methods (`get()` and `update()`) when called from Entity instances
537- Fix automatic JWT refresh only working in some cases
538
539### 1.0.1
540- Added `list()` function for all entities
541- Added search functions for all entities (match-, search, query)
542- Added `Company.get_master_company()`
543- Fixed adding template tasks
544
545"""
546import logging
547import os
548
549from projectal.entities import *
550from projectal.dynamic_enums import *
551from .api import *
552from . import profile
553
554api_base = os.getenv("PROJECTAL_URL")
555api_username = os.getenv("PROJECTAL_USERNAME")
556api_password = os.getenv("PROJECTAL_PASSWORD")
557api_application_id = None
558api_auth_details = None
559api_alias = None
560cookies = None
561chunk_size_read = 1000
562chunk_size_write = 200
563
564# Records the timestamp generated by the last request (database
565# event time). These are reported on add or updates; if there is
566# no timestamp in the response, this is set to None.
567response_timestamp = None
568
569
570# The minimum version number of the Projectal instance that this
571# API client targets. Lower versions are not supported and will
572# raise an exception.
573MIN_PROJECTAL_VERSION = "4.0.40"
574
575__verify = True
576
577logging.getLogger("projectal-api-client").addHandler(logging.NullHandler())
api_base = None
api_username = None
api_password = None
api_application_id = None
api_auth_details = None
api_alias = None
cookies = None
chunk_size_read = 1000
chunk_size_write = 200
response_timestamp = None
MIN_PROJECTAL_VERSION = '4.0.40'