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