projectal

A python client for the Projectal API.

Getting started

import projectal
import os

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