Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Single table for file attachments #7420

Merged
merged 96 commits into from
Jun 19, 2024

Conversation

SchrodingersGat
Copy link
Member

@SchrodingersGat SchrodingersGat commented Jun 8, 2024

Refactoring how "attachments" are stored, moving to a single table approach.

Tasks

  • Create new table
  • Data migration
  • Remove old tables
  • Expose new model to API
  • Add a mixin class for models which will have attachments associated with them
  • Mixin class must provide method for accessing attachments
  • Expose a list of models we wish to associate attachments with
  • Remove old API endpoints
  • Update attachment tables in PUI
  • Update attachment tables in CUI
  • Update unit tests
  • Extract user information on upload
  • Unit test for data migration
  • Unit tests for InvenTreeAttachmentMixin class mixin
  • Work out how to determine user permissions in backend (i.e on file upload)
  • Work out how to determine user permissions in user interface
  • Update python bindings - Refactor attachment class inventree-python#234
  • Update mobile app - Modern attachments inventree-app#505

Related Issues

@SchrodingersGat SchrodingersGat added enhancement This is an suggested enhancement or new feature api Relates to the API breaking Indicates a major update or change which breaks compatibility refactor migration Data or schema migrations labels Jun 8, 2024
@SchrodingersGat SchrodingersGat added this to the 0.16.0 milestone Jun 8, 2024
Copy link

netlify bot commented Jun 8, 2024

Deploy Preview for inventree-web-pui-preview canceled.

Name Link
🔨 Latest commit c94d901
🔍 Latest deploy log https://app.netlify.com/sites/inventree-web-pui-preview/deploys/6672569f8b59f00008159947

Copy link

codecov bot commented Jun 8, 2024

Codecov Report

Attention: Patch coverage is 86.63283% with 79 lines in your changes missing coverage. Please review.

Project coverage is 84.01%. Comparing base (79ea689) to head (c94d901).
Report is 344 commits behind head on master.

Files with missing lines Patch % Lines
src/backend/InvenTree/common/models.py 76.92% 18 Missing ⚠️
...nTree/common/migrations/0026_auto_20240608_1238.py 62.79% 16 Missing ⚠️
src/frontend/src/states/UserState.tsx 33.33% 11 Missing and 3 partials ⚠️
...rc/frontend/src/tables/general/AttachmentTable.tsx 60.00% 7 Missing and 1 partial ⚠️
src/backend/InvenTree/common/api.py 84.61% 6 Missing ⚠️
src/frontend/src/defaults/formatters.tsx 14.28% 6 Missing ⚠️
src/backend/InvenTree/common/admin.py 82.35% 3 Missing ⚠️
src/backend/InvenTree/common/settings.py 50.00% 2 Missing ⚠️
src/backend/InvenTree/common/validators.py 85.71% 2 Missing ⚠️
src/backend/InvenTree/common/serializers.py 96.42% 1 Missing ⚠️
... and 3 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7420      +/-   ##
==========================================
+ Coverage   83.84%   84.01%   +0.16%     
==========================================
  Files        1058     1066       +8     
  Lines       46442    46618     +176     
  Branches     1386     1389       +3     
==========================================
+ Hits        38941    39166     +225     
+ Misses       7141     7092      -49     
  Partials      360      360              
Flag Coverage Δ
backend 85.18% <79.07%> (+0.03%) ⬆️
migrations 42.50% <55.18%> (-0.06%) ⬇️
pui 65.66% <45.09%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

src/backend/InvenTree/common/models.py Outdated Show resolved Hide resolved
src/backend/InvenTree/common/models.py Outdated Show resolved Hide resolved
src/backend/InvenTree/common/models.py Show resolved Hide resolved
@matmair
Copy link
Member

matmair commented Jun 17, 2024

Looks like the migrations might be tainted? Tough I can not see anything modifying the DB state outside of migrations.

The problem I see is that the error is raised in core Django itself so guarding against it might be difficult/impossible.

@SchrodingersGat
Copy link
Member Author

@matmair all passing now, ready for merge if you're happy :)

Copy link
Member

@matmair matmair left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM; Great effort!

@@ -33,7 +33,7 @@ def __init__(self, **kwargs):

def run_validation(self, data=empty):
"""Override default validation behaviour for this field type."""
strict_urls = get_global_setting('INVENTREE_STRICT_URLS', True, cache=False)
strict_urls = get_global_setting('INVENTREE_STRICT_URLS', cache=False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: Why is this changed?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default value filters through from the definition of the setting itself, and does not need to be passed here.

Comment on lines -641 to -661
forbidden = [
"'",
'"',
'#',
'@',
'!',
'&',
'^',
'<',
'>',
':',
';',
'/',
'\\',
'|',
'?',
'*',
'%',
'~',
'`',
]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We did not add checks when we fixed the original issues as there was some sever time pressure. I will try to add unit tests for unsafe uploads to my todo

Comment on lines +61 to +62
if get_global_setting('INVENTREE_INSTANCE_TITLE'):
return get_global_setting('INVENTREE_INSTANCE')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: Why are these defualts changed?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above, duplicating the default value here is not required.

@@ -502,7 +502,7 @@ def run_print_test(self, qs, model_type, label: bool = True):
},
expected_code=201,
max_query_time=15,
max_query_count=1000, # TODO: Should look into this
max_query_count=500 * len(qs),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C: 500 queries per entry seems a bit much - do we need to optimise this endpoint?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The label printing is pretty inefficient, but there's a lot of work required to profile exactly why

@@ -786,7 +786,7 @@ def calculate_plugin_hash(self):

for k in self.plugin_settings_keys():
try:
val = get_global_setting(k, False, create=False)
val = get_global_setting(k)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: Why were the defaults removed?

@matmair
Copy link
Member

matmair commented Jun 18, 2024

One additonal comment: I do not think #5429 is really covered by this but would be closed - wdyt?

@SchrodingersGat
Copy link
Member Author

SchrodingersGat commented Jun 18, 2024

With regard to #5429 - we can add the "tags" mixin to the new attachment model, and then the tags can be used for custom data storage.

Potentially could add metadata also.

@SchrodingersGat SchrodingersGat merged commit 432e0c6 into inventree:master Jun 19, 2024
27 checks passed
@SchrodingersGat SchrodingersGat deleted the attachments-refactor branch June 19, 2024 04:38
@matmair
Copy link
Member

matmair commented Jun 19, 2024

Thank you for the addition!

martonmiklos pushed a commit to martonmiklos/InvenTree that referenced this pull request Jun 24, 2024
* Add basic model for handling generic attachments

* Refactor migration

* Data migration to convert old files across

* Admin updates

* Increase comment field max_length

* Adjust field name

* Remove legacy serializer classes / endpoints

* Expose new model to API

* Admin site list filters

* Remove legacy attachment models

- Add new mixin class to designate which models can have attachments

* Update data migration

- Ensure other apps are at the correct migration state beforehand

* Add migrations to remove legacy attachment tables

* Fix for "rename_attachment" callback

* Refactor model_type field

- ContentType does not allow easy API serialization

* Set allowed options for admin

* Update model verbose names

* Fix logic for file upload

* Add choices for serializer

* Add API filtering

* Fix for API filter

* Fix for attachment tables in PUI

- Still not solved permission issues

* Bump API version

* Record user when uploading attachment via API

* Refactor <AttachmentTable /> for PUI

* Display 'file_size' in PUI attachment table

* Fix company migrations

* Include permission informtion in roles API endpoint

* Read user permissions in PUI

* Simplify permission checks for <AttachmentTable />

* Automatically clean up old content types

* Cleanup PUI

* Fix typo in data migration

* Add reverse data migration

* Update unit tests

* Use InMemoryStorage for media files in test mode

* Data migration unit test

* Fix "model_type" field

- It is a required field after all

* Add permission check for serializer

* Fix permission check for CUI

* Fix PUI import

* Test python lib against specific branch

- Will be reverted once code is merged

* Revert STORAGES setting

- Might be worth looking into again

* Fix part unit test

* Fix unit test for sales order

* Use 'get_global_setting'

* Use 'get_global_setting'

* Update setting getter

* Unit tests

* Tweaks

* Revert change to settings.py

* More updates for get_global_setting

* Relax API query count requirement

* remove illegal chars and add unit tests

* Fix unit tests

* Fix frontend unit tests

* settings management updates

* Prevent db write under more conditions

* Simplify settings code

* Pop values before creating filters

* Prevent settings write under certain conditions

* Add debug msg

* Clear db on record import

* Refactor permissions checks

- Allows extension / customization of permission checks at a later date

* Unit test updates

* Prevent delete of attachment without correct permissions

* Adjust odcker.yaml

* Cleanup data migrations

* Tweak migration tests for build app

* Update data migration

- Handle case with missing data

* Prevent debug shell in TESTING mode

* Update migration dependencies

- Ensure all apps are "up to date" before removing legacy tables

* add file size test

* Update migration tests

* Revert some settings caching changes

* Fix incorrect logic in migration

* Update unit tests

* Prevent create on CURRENCY_CODES

- Seems to play havoc with bootup sequence

* Fix unit test

* Some refactoring

- Use get_global_setting

* Fix typo

* Revert change

* Add "tags" and "metadata"

* Include "tags" field in API serializer

* add "metadata" endpoint for attachments
@matmair matmair mentioned this pull request Aug 6, 2024
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Relates to the API breaking Indicates a major update or change which breaks compatibility enhancement This is an suggested enhancement or new feature full-run Always do a full QC CI run migration Data or schema migrations refactor
Projects
None yet
2 participants