From 45d3fe0583389cc3f3706303860890f06e414303 Mon Sep 17 00:00:00 2001 From: Jason Melton <64045831+melton-jason@users.noreply.github.com> Date: Mon, 13 Jan 2025 15:16:21 +0000 Subject: [PATCH 01/80] Lint code with ESLint and Prettier Triggered by f1aa17c41cc918f2e5365aa79922f9f101616922 on branch refs/heads/issue-5418 --- .../Preferences/UserDefinitions.tsx | 41 ++++++++----------- .../js_src/lib/components/TreeView/Row.tsx | 14 ++++--- 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx index d925e9f3c7b..f3856c2fee4 100644 --- a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx +++ b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx @@ -1103,8 +1103,7 @@ export const userPreferenceDefinitions = { }, }, recordSet: { - title: () => - tableLabel('RecordSet'), + title: () => tableLabel('RecordSet'), items: { recordToOpen: definePref<'first' | 'last'>({ title: preferencesText.recordSetRecordToOpen(), @@ -1348,7 +1347,9 @@ export const userPreferenceDefinitions = { defaultValue: false, type: 'java.lang.Boolean', }), - orderByField: definePref<'fullName' | 'name' | 'nodeNumber' | 'rankId'>({ + orderByField: definePref< + 'fullName' | 'name' | 'nodeNumber' | 'rankId' + >({ title: preferencesText.sortByField(), requiresReload: false, visible: true, @@ -1413,8 +1414,7 @@ export const userPreferenceDefinitions = { * This would be replaced with labels from schema once * schema is loaded */ - title: () => - tableLabel('Geography'), + title: () => tableLabel('Geography'), items: { treeAccentColor: definePref({ title: preferencesText.treeAccentColor(), @@ -1435,8 +1435,7 @@ export const userPreferenceDefinitions = { }, }, taxon: { - title: () => - tableLabel('Taxon'), + title: () => tableLabel('Taxon'), items: { treeAccentColor: definePref({ title: preferencesText.treeAccentColor(), @@ -1457,8 +1456,7 @@ export const userPreferenceDefinitions = { }, }, storage: { - title: () => - tableLabel('Storage'), + title: () => tableLabel('Storage'), items: { treeAccentColor: definePref({ title: preferencesText.treeAccentColor(), @@ -1479,8 +1477,7 @@ export const userPreferenceDefinitions = { }, }, geologicTimePeriod: { - title: () => - tableLabel('GeologicTimePeriod'), + title: () => tableLabel('GeologicTimePeriod'), items: { treeAccentColor: definePref({ title: preferencesText.treeAccentColor(), @@ -1501,8 +1498,7 @@ export const userPreferenceDefinitions = { }, }, lithoStrat: { - title: () => - tableLabel('LithoStrat'), + title: () => tableLabel('LithoStrat'), items: { treeAccentColor: definePref({ title: preferencesText.treeAccentColor(), @@ -1523,8 +1519,7 @@ export const userPreferenceDefinitions = { }, }, tectonicUnit: { - title: () => - tableLabel('TectonicUnit'), + title: () => tableLabel('TectonicUnit'), items: { treeAccentColor: definePref({ title: preferencesText.treeAccentColor(), @@ -2052,10 +2047,7 @@ import('../DataModel/tables') ), 'Unable to find tree full name value' ); - overwriteReadOnly( - name, - 'title', - getField(tables.Taxon, 'name').label); + overwriteReadOnly(name, 'title', getField(tables.Taxon, 'name').label); overwriteReadOnly( fullName, 'title', @@ -2067,7 +2059,8 @@ import('../DataModel/tables') // Update titles for orderByField const treeOrderByBehavior = - userPreferenceDefinitions.treeEditor.subCategories.behavior.items.orderByField; + userPreferenceDefinitions.treeEditor.subCategories.behavior.items + .orderByField; if ('values' in treeOrderByBehavior) { const orderByValues = treeOrderByBehavior.values as RA<{ readonly value: string; @@ -2112,7 +2105,7 @@ import('../DataModel/tables') overwriteReadOnly( rankId, 'title', - getField(tables.Taxon,'rankId').label + getField(tables.Taxon, 'rankId').label ); overwriteReadOnly( nodeNumber, @@ -2120,11 +2113,13 @@ import('../DataModel/tables') getField(tables.Taxon, 'nodeNumber').label ); } else { - softError('Unable to replace the tree preferences item title for orderByField'); + softError( + 'Unable to replace the tree preferences item title for orderByField' + ); } }) ) - + // Not using softFail here to avoid circular dependency .catch(console.error); diff --git a/specifyweb/frontend/js_src/lib/components/TreeView/Row.tsx b/specifyweb/frontend/js_src/lib/components/TreeView/Row.tsx index 5e33a25ea64..0d6c06b08c8 100644 --- a/specifyweb/frontend/js_src/lib/components/TreeView/Row.tsx +++ b/specifyweb/frontend/js_src/lib/components/TreeView/Row.tsx @@ -87,11 +87,15 @@ export function TreeRow({ void getRows(row.nodeId).then((fetchedRows: RA) => { const sortedRows = Array.from(fetchedRows).sort( sortFunction( - orderByField === 'rankId' ? (row) => row.rankId : - orderByField === 'nodeNumber' ? (row) => row.nodeNumber : - orderByField === 'name' ? (row) => row.name : - orderByField === 'fullName' ? (row) => row.fullName : - () => 0 + orderByField === 'rankId' + ? (row) => row.rankId + : orderByField === 'nodeNumber' + ? (row) => row.nodeNumber + : orderByField === 'name' + ? (row) => row.name + : orderByField === 'fullName' + ? (row) => row.fullName + : () => 0 ) ); destructorCalled ? undefined : setRows(sortedRows); From 9b719672a4832ed6c370aebe3fb200ca7be6b0b0 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Tue, 14 Jan 2025 02:37:51 -0600 Subject: [PATCH 02/80] Alter required status for Geo fields in WB --- .../js_src/lib/components/DataModel/schemaOverrides.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/specifyweb/frontend/js_src/lib/components/DataModel/schemaOverrides.ts b/specifyweb/frontend/js_src/lib/components/DataModel/schemaOverrides.ts index 971f4f33524..06d45420603 100644 --- a/specifyweb/frontend/js_src/lib/components/DataModel/schemaOverrides.ts +++ b/specifyweb/frontend/js_src/lib/components/DataModel/schemaOverrides.ts @@ -237,6 +237,13 @@ const fieldOverwrites: typeof globalFieldOverrides = { CollectionObject: { collectionObjectType: { visibility: 'optional' }, }, + CollectionObjectGroupType: { + type: { visibility: 'optional' }, + }, + CollectionObjectGroupJoin: { + precedence: { visibility: 'optional' }, + isSubstrate: { visibility: 'optional' }, + }, LoanPreparation: { isResolved: { visibility: 'optional' }, }, From 634b9986ae27048b1fdd2f3b7c1755793eb1f72e Mon Sep 17 00:00:00 2001 From: melton-jason Date: Tue, 14 Jan 2025 02:40:17 -0600 Subject: [PATCH 03/80] Add cojo businessrule to automatically set precedence --- specifyweb/businessrules/rules/cojo_rules.py | 28 +++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/specifyweb/businessrules/rules/cojo_rules.py b/specifyweb/businessrules/rules/cojo_rules.py index 3156c6d3ce7..556e6cca2b0 100644 --- a/specifyweb/businessrules/rules/cojo_rules.py +++ b/specifyweb/businessrules/rules/cojo_rules.py @@ -1,18 +1,17 @@ -import os -import sys from enum import Enum +from django.db.models import Max + from specifyweb.businessrules.exceptions import BusinessRuleException from specifyweb.businessrules.orm_signal_handler import orm_signal_handler from specifyweb.specify.models import Collectionobjectgroupjoin + class COGType(Enum): DISCRETE = "Discrete" CONSOLIDATED = "Consolidated" DRILL_CORE = "Drill Core" -def is_running_tests(): - return any(module in sys.modules for module in ('pytest', 'unittest')) @orm_signal_handler('pre_save', 'Collectionobjectgroupjoin') def cojo_pre_save(cojo): @@ -41,24 +40,33 @@ def cojo_pre_save(cojo): cojo.childcog is not None and cojo.childcog.cojo is not None and cojo.childcog.cojo.id is not cojo.id - and not is_running_tests() ): - raise BusinessRuleException('ChildCog is already in use as a child in another COG.') + raise BusinessRuleException( + 'ChildCog is already in use as a child in another COG.') if ( cojo.childco is not None and cojo.childco.cojo is not None and cojo.childco.cojo.id is not cojo.id - and not is_running_tests() ): - raise BusinessRuleException('ChildCo is already in use as a child in another COG.') - + raise BusinessRuleException( + 'ChildCo is already in use as a child in another COG.') + + if cojo.precedence is None: + others = Collectionobjectgroupjoin.objects.filter( + parentcog=cojo.parentcog + ) + top = others.aggregate(Max('precedence'))['precedence__max'] + cojo.precedence = 0 if top is None else top + 1 + + @orm_signal_handler('post_save', 'Collectionobjectgroupjoin') def cojo_post_save(cojo): """ For Consolidated COGs, mark the first CO child as primary if none have been set by the user """ - co_children = Collectionobjectgroupjoin.objects.filter(parentcog=cojo.parentcog, childco__isnull=False) + co_children = Collectionobjectgroupjoin.objects.filter( + parentcog=cojo.parentcog, childco__isnull=False) if len(co_children) > 0 and not co_children.filter(isprimary=True).exists() and cojo.parentcog.cogtype.type == COGType.CONSOLIDATED.value: first_child = co_children.first() first_child.isprimary = True From 7139a76489056978c3d093a3d93ace7500ac3d06 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Tue, 14 Jan 2025 02:42:48 -0600 Subject: [PATCH 04/80] Support one-to-one relationships in the WB --- .../workbench/upload/upload_plan_schema.py | 7 ++- specifyweb/workbench/upload/upload_table.py | 44 +++++++++++++++---- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/specifyweb/workbench/upload/upload_plan_schema.py b/specifyweb/workbench/upload/upload_plan_schema.py index e148307fa46..dc7b1c6873b 100644 --- a/specifyweb/workbench/upload/upload_plan_schema.py +++ b/specifyweb/workbench/upload/upload_plan_schema.py @@ -1,13 +1,12 @@ from functools import reduce -from os import name -from typing import Dict, Any, Optional, Union, Tuple +from typing import Dict, Union, Tuple import logging -from specifyweb.specify.datamodel import datamodel, Table, Relationship +from specifyweb.specify.datamodel import datamodel, Table from .upload_table import DeferredScopeUploadTable, UploadTable, OneToOneTable, MustMatchTable from .tomany import ToManyRecord -from .treerecord import TreeRank, TreeRankRecord, TreeRecord, MustMatchTreeRecord +from .treerecord import TreeRank, TreeRecord, MustMatchTreeRecord from .uploadable import Uploadable from .column_options import ColumnOptions from .scoping import DEFERRED_SCOPING diff --git a/specifyweb/workbench/upload/upload_table.py b/specifyweb/workbench/upload/upload_table.py index e361ebb478f..dd036708d24 100644 --- a/specifyweb/workbench/upload/upload_table.py +++ b/specifyweb/workbench/upload/upload_table.py @@ -367,7 +367,9 @@ def _handle_row(self, force_upload: bool) -> UploadResult: info = ReportInfo(tableName=self.name, columns=[pr.column for pr in self.parsedFields], treeInfo=None) - toOneResults_ = self._process_to_ones() + local_to_ones, remote_to_ones = separate_to_ones(model, self.toOne) + + toOneResults_ = self._process_to_ones(local_to_ones) multi_one_to_one = lambda field, result: self.toOne[field].is_one_to_one() and isinstance(result.record_result, MatchedMultiple) @@ -412,13 +414,13 @@ def _handle_row(self, force_upload: bool) -> UploadResult: if match: return UploadResult(match, toOneResults, {}) - return self._do_upload(model, toOneResults, info) + return self._do_upload(model, toOneResults, remote_to_ones, info) - def _process_to_ones(self) -> Dict[str, UploadResult]: + def _process_to_ones(self, toOnes: Dict[str, BoundUploadable]) -> Dict[str, UploadResult]: return { fieldname: to_one_def.process_row() for fieldname, to_one_def in - sorted(self.toOne.items(), key=lambda kv: kv[0]) # make the upload order deterministic + sorted(toOnes.items(), key=lambda kv: kv[0]) # make the upload order deterministic } def _match(self, model, toOneResults: Dict[str, UploadResult], toManyFilters: FilterPack, info: ReportInfo) -> Union[Matched, MatchedMultiple, None]: @@ -463,7 +465,7 @@ def _match(self, model, toOneResults: Dict[str, UploadResult], toManyFilters: Fi else: return None - def _do_upload(self, model, toOneResults: Dict[str, UploadResult], info: ReportInfo) -> UploadResult: + def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: Dict[str, BoundUploadable], info: ReportInfo) -> UploadResult: missing_requireds = [ # TODO: there should probably be a different structure for # missing required fields than ParseFailure @@ -516,12 +518,14 @@ def _do_upload(self, model, toOneResults: Dict[str, UploadResult], info: ReportI self.auditor.insert(uploaded, self.uploadingAgentId, None) + remoteToOneResults = _upload_remote_to_ones(model, uploaded.id, remoteToOnes) + toManyResults = { fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, records) for fieldname, records in sorted(self.toMany.items(), key=lambda kv: kv[0]) # make the upload order deterministic } - return UploadResult(Uploaded(uploaded.id, info, picklist_additions), toOneResults, toManyResults) + return UploadResult(Uploaded(uploaded.id, info, picklist_additions), {**toOneResults, **remoteToOneResults}, toManyResults) def _do_insert(self, model, **attrs) -> Any: return model.objects.create(**attrs) @@ -547,13 +551,13 @@ def must_match(self) -> bool: def force_upload_row(self) -> UploadResult: raise Exception('trying to force upload of must-match table') - def _process_to_ones(self) -> Dict[str, UploadResult]: + def _process_to_ones(self, toOnes: Dict[str, BoundUploadable]) -> Dict[str, UploadResult]: return { fieldname: to_one_def.match_row() - for fieldname, to_one_def in self.toOne.items() + for fieldname, to_one_def in toOnes.items() } - def _do_upload(self, model, toOneResults: Dict[str, UploadResult], info: ReportInfo) -> UploadResult: + def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: Dict[str, BoundUploadable], info: ReportInfo) -> UploadResult: return UploadResult(NoMatch(info), toOneResults, {}) @@ -588,3 +592,25 @@ def _upload_to_manys(parent_model, parent_id, parent_field, uploadingAgentId: Op ).force_upload_row() for record in records ] + +def _upload_remote_to_ones(parent_model, parent_id, remoteToOnes: Dict[str, BoundUploadTable]) -> Dict[str, UploadResult]: + toOnes: Dict[str, UploadResult] = dict() + for field_name, upload_table in sorted(remoteToOnes.items(), key=lambda kv: kv[0]): + related_field = parent_model._meta.get_field(field_name).field + related_column = related_field.attname + static = {**upload_table.static, related_column: parent_id} + toOnes[field_name] = upload_table._replace(static=static).process_row() + return toOnes + + +def separate_to_ones(parent_model, toOnes: Dict[str, BoundUploadable]): + remote_to_ones = dict() + local_to_ones = dict() + + for field_name, uploadable in toOnes.items(): + field = parent_model._meta.get_field(field_name) + if field.concrete: + local_to_ones[field_name] = uploadable + else: + remote_to_ones[field_name] = uploadable + return local_to_ones, remote_to_ones From 04b576e206d14a416d8edca9fbe4f74bebedd669 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 16 Jan 2025 00:15:10 -0600 Subject: [PATCH 05/80] Use BoundUploadTable for remoteToOne relationships --- specifyweb/workbench/upload/upload_table.py | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/specifyweb/workbench/upload/upload_table.py b/specifyweb/workbench/upload/upload_table.py index dd036708d24..cc7290f4ee8 100644 --- a/specifyweb/workbench/upload/upload_table.py +++ b/specifyweb/workbench/upload/upload_table.py @@ -1,7 +1,7 @@ import logging from functools import reduce -from typing import List, Dict, Any, NamedTuple, Union, Optional, Set, Callable, Literal, cast +from typing import List, Dict, Any, NamedTuple, Union, Optional, Set, Callable, Literal, Tuple, cast from django.db import transaction, IntegrityError @@ -518,7 +518,11 @@ def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: self.auditor.insert(uploaded, self.uploadingAgentId, None) - remoteToOneResults = _upload_remote_to_ones(model, uploaded.id, remoteToOnes) + remoteToOneResults = { + fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, [upload_table])[0] + for fieldname, upload_table in + sorted(remoteToOnes.items(), key=lambda kv: kv[0]) + } toManyResults = { fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, records) @@ -593,17 +597,7 @@ def _upload_to_manys(parent_model, parent_id, parent_field, uploadingAgentId: Op for record in records ] -def _upload_remote_to_ones(parent_model, parent_id, remoteToOnes: Dict[str, BoundUploadTable]) -> Dict[str, UploadResult]: - toOnes: Dict[str, UploadResult] = dict() - for field_name, upload_table in sorted(remoteToOnes.items(), key=lambda kv: kv[0]): - related_field = parent_model._meta.get_field(field_name).field - related_column = related_field.attname - static = {**upload_table.static, related_column: parent_id} - toOnes[field_name] = upload_table._replace(static=static).process_row() - return toOnes - - -def separate_to_ones(parent_model, toOnes: Dict[str, BoundUploadable]): +def separate_to_ones(parent_model, toOnes: Dict[str, BoundUploadable]) -> Tuple[Dict[str, BoundUploadable], Dict[str, BoundUploadable]]: remote_to_ones = dict() local_to_ones = dict() From 54c95f3deb9d3199fd3a01413c3af1ea6c4c4184 Mon Sep 17 00:00:00 2001 From: Jason Melton <64045831+melton-jason@users.noreply.github.com> Date: Thu, 16 Jan 2025 06:19:49 +0000 Subject: [PATCH 06/80] Lint code with ESLint and Prettier Triggered by 79a2adcc724392dc39bee7452d887fa3f7110964 on branch refs/heads/issue-5418 --- .../js_src/lib/components/InitialContext/systemInfo.ts | 4 ++-- .../js_src/lib/components/WbPlanView/navigator.ts | 9 ++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/InitialContext/systemInfo.ts b/specifyweb/frontend/js_src/lib/components/InitialContext/systemInfo.ts index dbc7015261d..8ff7a789077 100644 --- a/specifyweb/frontend/js_src/lib/components/InitialContext/systemInfo.ts +++ b/specifyweb/frontend/js_src/lib/components/InitialContext/systemInfo.ts @@ -22,7 +22,7 @@ type SystemInfo = { readonly institution_guid: LocalizedString; readonly isa_number: LocalizedString; readonly stats_url: string | null; - readonly discipline_type: string + readonly discipline_type: string; }; let systemInfo: SystemInfo; @@ -45,7 +45,7 @@ export const fetchContext = load( collection: systemInfo.collection, collectionGUID: systemInfo.collection_guid, isaNumber: systemInfo.isa_number, - disciplineType: systemInfo.discipline_type + disciplineType: systemInfo.discipline_type, }, /* * I don't know if the receiving server handles GET parameters in a diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts index 769c5990df5..b7a1b46606c 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts @@ -542,13 +542,12 @@ export function getMappingLineData({ .filter((field) => { let isIncluded = true; - const disciplineType = getSystemInfo().discipline_type?.toLowerCase() - const geoPaleoDisciplines= ['geology', 'invertpaleo', 'vertpaleo'] + const disciplineType = + getSystemInfo().discipline_type?.toLowerCase(); + const geoPaleoDisciplines = ['geology', 'invertpaleo', 'vertpaleo']; if ( field.name === 'age' && - !geoPaleoDisciplines.includes( - disciplineType - ) + !geoPaleoDisciplines.includes(disciplineType) ) { return false; } From 4bf969183ab4614336ce83bbce7c2fe32f36a2a0 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 16 Jan 2025 00:26:04 -0600 Subject: [PATCH 07/80] Add comment --- specifyweb/workbench/upload/upload_table.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/specifyweb/workbench/upload/upload_table.py b/specifyweb/workbench/upload/upload_table.py index cc7290f4ee8..b46cc8f058c 100644 --- a/specifyweb/workbench/upload/upload_table.py +++ b/specifyweb/workbench/upload/upload_table.py @@ -518,6 +518,9 @@ def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: self.auditor.insert(uploaded, self.uploadingAgentId, None) + # Like to-many relationships, remote to-one relationships can not be + # directly inserted with the main base record, and instead are + # uploaded with a reference to the base record remoteToOneResults = { fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, [upload_table])[0] for fieldname, upload_table in From e00513f3f116c58bca6c582a8fd8af8b7fed31dc Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 16 Jan 2025 09:35:36 -0600 Subject: [PATCH 08/80] Upload remoteToOne relationships as toMany --- specifyweb/workbench/upload/upload_table.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specifyweb/workbench/upload/upload_table.py b/specifyweb/workbench/upload/upload_table.py index b46cc8f058c..a8fcd18ae84 100644 --- a/specifyweb/workbench/upload/upload_table.py +++ b/specifyweb/workbench/upload/upload_table.py @@ -522,7 +522,7 @@ def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: # directly inserted with the main base record, and instead are # uploaded with a reference to the base record remoteToOneResults = { - fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, [upload_table])[0] + fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, [upload_table]) for fieldname, upload_table in sorted(remoteToOnes.items(), key=lambda kv: kv[0]) } @@ -532,7 +532,7 @@ def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: for fieldname, records in sorted(self.toMany.items(), key=lambda kv: kv[0]) # make the upload order deterministic } - return UploadResult(Uploaded(uploaded.id, info, picklist_additions), {**toOneResults, **remoteToOneResults}, toManyResults) + return UploadResult(Uploaded(uploaded.id, info, picklist_additions), toOneResults, {**remoteToOneResults, **toManyResults}) def _do_insert(self, model, **attrs) -> Any: return model.objects.create(**attrs) From 1c77d3150c908fc30f9581ee6761c5521fa8f378 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 16 Jan 2025 10:52:16 -0600 Subject: [PATCH 09/80] add one-to-one rel type to objformat logic --- specifyweb/stored_queries/queryfieldspec.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/stored_queries/queryfieldspec.py b/specifyweb/stored_queries/queryfieldspec.py index 2d80d8aeb61..feab5828fc4 100644 --- a/specifyweb/stored_queries/queryfieldspec.py +++ b/specifyweb/stored_queries/queryfieldspec.py @@ -255,7 +255,7 @@ def add_spec_to_query(self, query, formatter=None, aggregator=None, cycle_detect if self.is_relationship(): # will be formatting or aggregating related objects - if self.get_field().type == 'many-to-one': + if self.get_field().type in {'many-to-one', 'one-to-one'}: query, orm_model, table, field = self.build_join(query, self.join_path) query, orm_field = query.objectformatter.objformat(query, orm_model, formatter, cycle_detector) else: From 4837bfb21efac9b40b2d774310770280c77ab34c Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 16 Jan 2025 14:41:37 -0600 Subject: [PATCH 10/80] add temp blank_nulls catalognumber conditional --- specifyweb/stored_queries/blank_nulls.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/specifyweb/stored_queries/blank_nulls.py b/specifyweb/stored_queries/blank_nulls.py index 48aa2195936..4443e211a25 100644 --- a/specifyweb/stored_queries/blank_nulls.py +++ b/specifyweb/stored_queries/blank_nulls.py @@ -1,3 +1,4 @@ +import re from sqlalchemy.sql import expression from sqlalchemy.ext.compiler import compiles from sqlalchemy.types import String @@ -38,5 +39,8 @@ def _blank_nulls(element: blank_nulls, compiler: MySQLCompiler_mysqldb, **kwargs expr = compiler.process(element.clauses.clauses[0]) if isinstance(element.clauses.clauses[0], blank_nulls): return expr + elif re.search(r'CAST.+\`CatalogNumber\`\sAS\sDECIMAL.+', expr) is not None: + # NOTE: Temporary expiriment, this fixes CatalogNumber casting to DECIMAL instead of string + return "IFNULL(%s, NULL)" % expr else: return "IFNULL(%s, '')" % expr From 9b8ccc866362736427560ef6f726304992a81198 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 16 Jan 2025 14:43:43 -0600 Subject: [PATCH 11/80] simplify blank_nulls conditional --- specifyweb/stored_queries/blank_nulls.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/specifyweb/stored_queries/blank_nulls.py b/specifyweb/stored_queries/blank_nulls.py index 4443e211a25..98cf1e6a1be 100644 --- a/specifyweb/stored_queries/blank_nulls.py +++ b/specifyweb/stored_queries/blank_nulls.py @@ -41,6 +41,7 @@ def _blank_nulls(element: blank_nulls, compiler: MySQLCompiler_mysqldb, **kwargs return expr elif re.search(r'CAST.+\`CatalogNumber\`\sAS\sDECIMAL.+', expr) is not None: # NOTE: Temporary expiriment, this fixes CatalogNumber casting to DECIMAL instead of string - return "IFNULL(%s, NULL)" % expr + # return "IFNULL(%s, NULL)" % expr + return expr else: return "IFNULL(%s, '')" % expr From 147301bbebb693d79606418517afff445d9e3270 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 16 Jan 2025 17:00:57 -0600 Subject: [PATCH 12/80] null dataobjformatter logger --- specifyweb/stored_queries/blank_nulls.py | 4 ++-- specifyweb/stored_queries/format.py | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/specifyweb/stored_queries/blank_nulls.py b/specifyweb/stored_queries/blank_nulls.py index 98cf1e6a1be..01e6f4ab743 100644 --- a/specifyweb/stored_queries/blank_nulls.py +++ b/specifyweb/stored_queries/blank_nulls.py @@ -41,7 +41,7 @@ def _blank_nulls(element: blank_nulls, compiler: MySQLCompiler_mysqldb, **kwargs return expr elif re.search(r'CAST.+\`CatalogNumber\`\sAS\sDECIMAL.+', expr) is not None: # NOTE: Temporary expiriment, this fixes CatalogNumber casting to DECIMAL instead of string - # return "IFNULL(%s, NULL)" % expr - return expr + # return expr + return "IFNULL(%s, NULL)" % expr else: return "IFNULL(%s, '')" % expr diff --git a/specifyweb/stored_queries/format.py b/specifyweb/stored_queries/format.py index 034da95faa2..436385f286f 100644 --- a/specifyweb/stored_queries/format.py +++ b/specifyweb/stored_queries/format.py @@ -98,7 +98,12 @@ def getFormatterFromSchema() -> Element: if result is not None: return result - return lookup('class', specify_model.classname) + result = lookup('class', specify_model.classname) + if result is not None: + return result + + logger.warning("no dataobjformatter for %s", specify_model.classname) + return None def hasFormatterDef(self, specify_model: Table, formatter_name) -> bool: if formatter_name is None: From a8797d38538060277c6ea952f9313b64730016f9 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Fri, 17 Jan 2025 14:44:36 +0000 Subject: [PATCH 13/80] Lint code with ESLint and Prettier Triggered by 1d14140b792bde093cfff63ca65931d7ce5f0316 on branch refs/heads/issue-5418 --- .../lib/components/QueryComboBox/index.tsx | 60 ++++++++++--------- .../lib/components/SearchDialog/index.tsx | 12 +++- 2 files changed, 42 insertions(+), 30 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx index b34927c8c7c..1e776d86977 100644 --- a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx @@ -524,41 +524,45 @@ export function QueryComboBox({ .map(serializeResource) .map(({ fieldName, startValue }) => fieldName === 'rankId' - ? { - field: 'rankId', - isRelationship: false, - isNot: false, - operation: 'less', - value: startValue, - } - : fieldName === 'nodeNumber' - ? { - field: 'nodeNumber', - isRelationship: false, - operation: 'between', - isNot: true, - value: startValue, - } - : fieldName === 'collectionRelTypeId' ? { - field: 'id', + field: 'rankId', isRelationship: false, - operation: 'in', isNot: false, + operation: 'less', value: startValue, } - : fieldName === 'taxonTreeDefId' + : fieldName === 'nodeNumber' ? { - field: 'definition', - isRelationship: true, - operation: 'in', - isNot: false, - value: startValue + field: 'nodeNumber', + isRelationship: false, + operation: 'between', + isNot: true, + value: startValue, } - : f.error(`extended filter not created`, { - fieldName, - startValue, - })) + : fieldName === 'collectionRelTypeId' + ? { + field: 'id', + isRelationship: false, + operation: 'in', + isNot: false, + value: startValue, + } + : fieldName === 'taxonTreeDefId' + ? { + field: 'definition', + isRelationship: true, + operation: 'in', + isNot: false, + value: startValue, + } + : f.error( + `extended filter not created`, + { + fieldName, + startValue, + } + ) + ) ), }) : undefined diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index 9b5bd1d3213..ea01ebff46b 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -139,7 +139,13 @@ const filterResults = ( function testFilter( resource: SpecifyResource, - { operation, field, value, isNot, isRelationship }: QueryComboBoxFilter + { + operation, + field, + value, + isNot, + isRelationship, + }: QueryComboBoxFilter ): boolean { const values = value.split(',').map(f.trim); const result = @@ -151,7 +157,9 @@ function testFilter( values.some((value) => { const fieldValue = resource.get(field); // eslint-disable-next-line eqeqeq - return isRelationship ? value == strictIdFromUrl(fieldValue!).toString() : value == fieldValue + return isRelationship + ? value == strictIdFromUrl(fieldValue!).toString() + : value == fieldValue; }) : operation === 'less' ? values.every((value) => (resource.get(field) ?? 0) < value) From 05f42f7278881f7a7e356509637421c7f8a36e39 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Fri, 17 Jan 2025 13:03:07 -0500 Subject: [PATCH 14/80] Add exceptions for recursive rendering --- .../frontend/js_src/lib/components/Forms/SubView.tsx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx b/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx index 163ed7cb474..d569d6b1624 100644 --- a/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx +++ b/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx @@ -16,6 +16,8 @@ import type { AnySchema } from '../DataModel/helperTypes'; import type { SpecifyResource } from '../DataModel/legacyTypes'; import { resourceOn } from '../DataModel/resource'; import type { Relationship } from '../DataModel/specifyField'; +import { SpecifyTable } from '../DataModel/specifyTable'; +import { tables } from '../DataModel/tables'; import type { FormType } from '../FormParse'; import type { SubViewSortField } from '../FormParse/cells'; import { IntegratedRecordSelector } from '../FormSliders/IntegratedRecordSelector'; @@ -137,7 +139,8 @@ export function SubView({ return ( - {parentContext + {!RECURSIVE_RENDERING_EXCEPTIONS.has(parentResource.specifyTable) && + parentContext .map(({ relationship }) => relationship) .includes(relationship) || collection === false ? undefined : ( <> @@ -243,3 +246,7 @@ export function SubView({ ); } + +const RECURSIVE_RENDERING_EXCEPTIONS = new Set>([ + tables.CollectionObjectGroup, +]); From 4c6327eb871a48ef97259b515f97df7ae0daffc6 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Fri, 17 Jan 2025 18:07:17 +0000 Subject: [PATCH 15/80] Lint code with ESLint and Prettier Triggered by 05f42f7278881f7a7e356509637421c7f8a36e39 on branch refs/heads/issue-6067 --- specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx b/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx index d569d6b1624..a31b661de35 100644 --- a/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx +++ b/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx @@ -16,7 +16,7 @@ import type { AnySchema } from '../DataModel/helperTypes'; import type { SpecifyResource } from '../DataModel/legacyTypes'; import { resourceOn } from '../DataModel/resource'; import type { Relationship } from '../DataModel/specifyField'; -import { SpecifyTable } from '../DataModel/specifyTable'; +import type { SpecifyTable } from '../DataModel/specifyTable'; import { tables } from '../DataModel/tables'; import type { FormType } from '../FormParse'; import type { SubViewSortField } from '../FormParse/cells'; @@ -247,6 +247,6 @@ export function SubView({ ); } -const RECURSIVE_RENDERING_EXCEPTIONS = new Set>([ +const RECURSIVE_RENDERING_EXCEPTIONS = new Set([ tables.CollectionObjectGroup, ]); From 87df266c05138d5a69603c1edf5ccc3f89a4e6af Mon Sep 17 00:00:00 2001 From: alec_dev Date: Fri, 17 Jan 2025 14:40:31 -0600 Subject: [PATCH 16/80] rescope PR --- specifyweb/stored_queries/blank_nulls.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/specifyweb/stored_queries/blank_nulls.py b/specifyweb/stored_queries/blank_nulls.py index 01e6f4ab743..48aa2195936 100644 --- a/specifyweb/stored_queries/blank_nulls.py +++ b/specifyweb/stored_queries/blank_nulls.py @@ -1,4 +1,3 @@ -import re from sqlalchemy.sql import expression from sqlalchemy.ext.compiler import compiles from sqlalchemy.types import String @@ -39,9 +38,5 @@ def _blank_nulls(element: blank_nulls, compiler: MySQLCompiler_mysqldb, **kwargs expr = compiler.process(element.clauses.clauses[0]) if isinstance(element.clauses.clauses[0], blank_nulls): return expr - elif re.search(r'CAST.+\`CatalogNumber\`\sAS\sDECIMAL.+', expr) is not None: - # NOTE: Temporary expiriment, this fixes CatalogNumber casting to DECIMAL instead of string - # return expr - return "IFNULL(%s, NULL)" % expr else: return "IFNULL(%s, '')" % expr From f3fc2f71ded8564e7c6f85b2fcc76993d0e5169d Mon Sep 17 00:00:00 2001 From: alec_dev Date: Fri, 17 Jan 2025 14:41:24 -0600 Subject: [PATCH 17/80] sql log reformatting --- specifyweb/specify/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/specify/utils.py b/specifyweb/specify/utils.py index b0b2f93a070..ccc4b7508f8 100644 --- a/specifyweb/specify/utils.py +++ b/specifyweb/specify/utils.py @@ -38,7 +38,7 @@ def log_sqlalchemy_query(query): # Call this function to debug the raw SQL query generated by SQLAlchemy from sqlalchemy.dialects import mysql compiled_query = query.statement.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}) - raw_sql = str(compiled_query) + raw_sql = str(compiled_query).replace('\n', ' ') + ';' logger.debug(raw_sql) # Run in the storred_queries.execute file, in the execute function, right before the return statement, line 546 # from specifyweb.specify.utils import log_sqlalchemy_query; log_sqlalchemy_query(query) From 0873af2a1b31fbc15e0bd409a94c3793d5abb525 Mon Sep 17 00:00:00 2001 From: Grant Fitzsimmons <37256050+grantfitzsimmons@users.noreply.github.com> Date: Fri, 17 Jan 2025 14:54:08 -0600 Subject: [PATCH 18/80] Update LICENSE --- LICENSE | 899 ++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 617 insertions(+), 282 deletions(-) diff --git a/LICENSE b/LICENSE index d159169d105..f288702d2fa 100644 --- a/LICENSE +++ b/LICENSE @@ -1,281 +1,622 @@ GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS @@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From cd027bb75a85d66de7062953a5fcdab81b8d6c91 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Fri, 17 Jan 2025 13:58:53 -0800 Subject: [PATCH 19/80] Allow displaying children on Chrono node subview Fixes #6086 --- specifyweb/specify/api.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/specifyweb/specify/api.py b/specifyweb/specify/api.py index e1dfbfd9319..ad2ddd4e16d 100644 --- a/specifyweb/specify/api.py +++ b/specifyweb/specify/api.py @@ -1010,13 +1010,14 @@ def apply_filters(logged_in_collection, params, model, control_params=GetCollect filters.update({param: val}) - if model.__name__ == 'Geologictimeperiod': - # Filter out invalid chronostrats - filters.update({ - 'startperiod__isnull': False, - 'endperiod__isnull': False, - 'startperiod__gte': F('endperiod') - }) +#code repsonsible for issue 6086, this snipet is called to display the children of GeologicTimePeriod node. Need to refine to be applied only in the context of extended age query + # if model.__name__ == 'Geologictimeperiod': + # # Filter out invalid chronostrats + # filters.update({ + # 'startperiod__isnull': False, + # 'endperiod__isnull': False, + # 'startperiod__gte': F('endperiod') + # }) try: objs = model.objects.filter(**filters) From b1f73526dc13bedbc2329d646661d21247743340 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Mon, 20 Jan 2025 21:48:25 -0600 Subject: [PATCH 20/80] Revert remoteToOne changes in backend --- .../workbench/upload/upload_plan_schema.py | 7 +-- specifyweb/workbench/upload/upload_table.py | 43 +++++-------------- 2 files changed, 14 insertions(+), 36 deletions(-) diff --git a/specifyweb/workbench/upload/upload_plan_schema.py b/specifyweb/workbench/upload/upload_plan_schema.py index dc7b1c6873b..e148307fa46 100644 --- a/specifyweb/workbench/upload/upload_plan_schema.py +++ b/specifyweb/workbench/upload/upload_plan_schema.py @@ -1,12 +1,13 @@ from functools import reduce -from typing import Dict, Union, Tuple +from os import name +from typing import Dict, Any, Optional, Union, Tuple import logging -from specifyweb.specify.datamodel import datamodel, Table +from specifyweb.specify.datamodel import datamodel, Table, Relationship from .upload_table import DeferredScopeUploadTable, UploadTable, OneToOneTable, MustMatchTable from .tomany import ToManyRecord -from .treerecord import TreeRank, TreeRecord, MustMatchTreeRecord +from .treerecord import TreeRank, TreeRankRecord, TreeRecord, MustMatchTreeRecord from .uploadable import Uploadable from .column_options import ColumnOptions from .scoping import DEFERRED_SCOPING diff --git a/specifyweb/workbench/upload/upload_table.py b/specifyweb/workbench/upload/upload_table.py index a8fcd18ae84..e361ebb478f 100644 --- a/specifyweb/workbench/upload/upload_table.py +++ b/specifyweb/workbench/upload/upload_table.py @@ -1,7 +1,7 @@ import logging from functools import reduce -from typing import List, Dict, Any, NamedTuple, Union, Optional, Set, Callable, Literal, Tuple, cast +from typing import List, Dict, Any, NamedTuple, Union, Optional, Set, Callable, Literal, cast from django.db import transaction, IntegrityError @@ -367,9 +367,7 @@ def _handle_row(self, force_upload: bool) -> UploadResult: info = ReportInfo(tableName=self.name, columns=[pr.column for pr in self.parsedFields], treeInfo=None) - local_to_ones, remote_to_ones = separate_to_ones(model, self.toOne) - - toOneResults_ = self._process_to_ones(local_to_ones) + toOneResults_ = self._process_to_ones() multi_one_to_one = lambda field, result: self.toOne[field].is_one_to_one() and isinstance(result.record_result, MatchedMultiple) @@ -414,13 +412,13 @@ def _handle_row(self, force_upload: bool) -> UploadResult: if match: return UploadResult(match, toOneResults, {}) - return self._do_upload(model, toOneResults, remote_to_ones, info) + return self._do_upload(model, toOneResults, info) - def _process_to_ones(self, toOnes: Dict[str, BoundUploadable]) -> Dict[str, UploadResult]: + def _process_to_ones(self) -> Dict[str, UploadResult]: return { fieldname: to_one_def.process_row() for fieldname, to_one_def in - sorted(toOnes.items(), key=lambda kv: kv[0]) # make the upload order deterministic + sorted(self.toOne.items(), key=lambda kv: kv[0]) # make the upload order deterministic } def _match(self, model, toOneResults: Dict[str, UploadResult], toManyFilters: FilterPack, info: ReportInfo) -> Union[Matched, MatchedMultiple, None]: @@ -465,7 +463,7 @@ def _match(self, model, toOneResults: Dict[str, UploadResult], toManyFilters: Fi else: return None - def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: Dict[str, BoundUploadable], info: ReportInfo) -> UploadResult: + def _do_upload(self, model, toOneResults: Dict[str, UploadResult], info: ReportInfo) -> UploadResult: missing_requireds = [ # TODO: there should probably be a different structure for # missing required fields than ParseFailure @@ -518,21 +516,12 @@ def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: self.auditor.insert(uploaded, self.uploadingAgentId, None) - # Like to-many relationships, remote to-one relationships can not be - # directly inserted with the main base record, and instead are - # uploaded with a reference to the base record - remoteToOneResults = { - fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, [upload_table]) - for fieldname, upload_table in - sorted(remoteToOnes.items(), key=lambda kv: kv[0]) - } - toManyResults = { fieldname: _upload_to_manys(model, uploaded.id, fieldname, self.uploadingAgentId, self.auditor, self.cache, records) for fieldname, records in sorted(self.toMany.items(), key=lambda kv: kv[0]) # make the upload order deterministic } - return UploadResult(Uploaded(uploaded.id, info, picklist_additions), toOneResults, {**remoteToOneResults, **toManyResults}) + return UploadResult(Uploaded(uploaded.id, info, picklist_additions), toOneResults, toManyResults) def _do_insert(self, model, **attrs) -> Any: return model.objects.create(**attrs) @@ -558,13 +547,13 @@ def must_match(self) -> bool: def force_upload_row(self) -> UploadResult: raise Exception('trying to force upload of must-match table') - def _process_to_ones(self, toOnes: Dict[str, BoundUploadable]) -> Dict[str, UploadResult]: + def _process_to_ones(self) -> Dict[str, UploadResult]: return { fieldname: to_one_def.match_row() - for fieldname, to_one_def in toOnes.items() + for fieldname, to_one_def in self.toOne.items() } - def _do_upload(self, model, toOneResults: Dict[str, UploadResult], remoteToOnes: Dict[str, BoundUploadable], info: ReportInfo) -> UploadResult: + def _do_upload(self, model, toOneResults: Dict[str, UploadResult], info: ReportInfo) -> UploadResult: return UploadResult(NoMatch(info), toOneResults, {}) @@ -599,15 +588,3 @@ def _upload_to_manys(parent_model, parent_id, parent_field, uploadingAgentId: Op ).force_upload_row() for record in records ] - -def separate_to_ones(parent_model, toOnes: Dict[str, BoundUploadable]) -> Tuple[Dict[str, BoundUploadable], Dict[str, BoundUploadable]]: - remote_to_ones = dict() - local_to_ones = dict() - - for field_name, uploadable in toOnes.items(): - field = parent_model._meta.get_field(field_name) - if field.concrete: - local_to_ones[field_name] = uploadable - else: - remote_to_ones[field_name] = uploadable - return local_to_ones, remote_to_ones From 07dfcf2a227b45dc70d465e6d218929292d59812 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Mon, 20 Jan 2025 22:55:03 -0600 Subject: [PATCH 21/80] Parse the remote side of one-to-ones as toMany on frontend --- .../components/FormCells/PickListEditor.tsx | 3 +-- .../components/FormSliders/RecordSelector.tsx | 4 +--- .../RecordSelectorFromCollection.tsx | 3 +-- .../lib/components/WbPlanView/autoMapper.ts | 6 ++++- .../lib/components/WbPlanView/helpers.ts | 8 +++++-- .../components/WbPlanView/mappingHelpers.ts | 15 +++++++++++++ .../lib/components/WbPlanView/modelHelpers.ts | 7 ++++-- .../lib/components/WbPlanView/navigator.ts | 19 +++++++++++----- .../js_src/lib/hooks/useCollection.tsx | 22 ++++++++----------- 9 files changed, 57 insertions(+), 30 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx b/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx index 52b0400bc9f..34e569c7e8c 100644 --- a/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx +++ b/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx @@ -56,8 +56,7 @@ export function PickListEditor({ relationship={relationship} sortField={undefined} onAdd={ - relationshipIsToMany(relationship) && - relationship.type !== 'zero-to-one' + relationship.type.includes('-to-many') ? undefined : ([resource]): void => void resource.set(relationship.name, resource as never) diff --git a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx index 5d18eb99be4..371da11c494 100644 --- a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx +++ b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx @@ -84,9 +84,7 @@ export function useRecordSelector({ ); const isToOne = - field === undefined - ? false - : !relationshipIsToMany(field) || field.type === 'zero-to-one'; + field === undefined ? false : !field.type.includes('-to-many'); const handleResourcesSelected = React.useMemo( () => diff --git a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx index aa2c572b570..ab40df892e8 100644 --- a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx +++ b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx @@ -58,8 +58,7 @@ export function RecordSelectorFromCollection({ const isDependent = collection instanceof DependentCollection; const isLazy = collection instanceof LazyCollection; - const isToOne = - !relationshipIsToMany(relationship) || relationship.type === 'zero-to-one'; + const isToOne = !relationship.type.includes('-to-many'); // Listen for changes to collection React.useEffect( diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/autoMapper.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/autoMapper.ts index 1192e618a8f..f78001c9edc 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/autoMapper.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/autoMapper.ts @@ -30,6 +30,7 @@ import { getNameFromTreeRankName, getNumberFromToManyIndex, mappingPathToString, + relationshipIsRemoteToOne, relationshipIsToMany, valueIsToManyIndex, valueIsTreeRank, @@ -809,7 +810,10 @@ export class AutoMapper { .forEach((relationship) => { const localPath = [...mappingPath, relationship.name]; - if (relationshipIsToMany(relationship)) + if ( + relationshipIsToMany(relationship) || + relationshipIsRemoteToOne(relationship) + ) localPath.push(formatToManyIndex(1)); const newDepthLevel = localPath.length; diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/helpers.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/helpers.ts index 7b7dd213d92..a540ff24c2b 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/helpers.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/helpers.ts @@ -28,6 +28,7 @@ import { formatToManyIndex, formatTreeRank, mappingPathToString, + relationshipIsRemoteToOne, relationshipIsToMany, valueIsToManyIndex, valueIsTreeRank, @@ -266,10 +267,13 @@ export function mutateMappingPath({ const table = getTable(parentTableName ?? ''); const currentField = table?.getField(mappingPath[index] ?? ''); const isCurrentToMany = - currentField?.isRelationship === true && relationshipIsToMany(currentField); + currentField?.isRelationship === true && + (relationshipIsToMany(currentField) || + relationshipIsRemoteToOne(currentField)); const newField = table?.getField(newValue); const isNewToMany = - newField?.isRelationship === true && relationshipIsToMany(newField); + newField?.isRelationship === true && + (relationshipIsToMany(newField) || relationshipIsRemoteToOne(newField)); const isNewTree = newField?.isRelationship === true && isTreeTable(newField.relatedTable.name); diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingHelpers.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingHelpers.ts index dc65961182d..6265f184cdc 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingHelpers.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingHelpers.ts @@ -22,6 +22,21 @@ export const relationshipIsToMany = ( relationship?.type.includes('-to-many') === true || relationship?.type === 'zero-to-one'; +/** + * Returns whether the relatation is one-to-one from the remote side + * (the foreign key exists on the other table of the relationship) + * + * In the WorkBench, remote one-to-one relationships are parsed as to-many + * in the upload plan + * + * See https://github.com/specify/specify7/pull/6073#discussion_r1915397675 + */ +export const relationshipIsRemoteToOne = ( + relationship: Relationship | undefined +): boolean => + relationship?.type === 'one-to-one' && + relationship.databaseColumn === undefined; + export type FieldType = Exclude; /** Returns whether a value is a -to-many index (e.x #1, #2, etc...) */ diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/modelHelpers.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/modelHelpers.ts index 9acc365b8c9..36a4ca97c62 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/modelHelpers.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/modelHelpers.ts @@ -18,6 +18,7 @@ import type { MappingPath } from './Mapper'; import { formatTreeRank, getNumberFromToManyIndex, + relationshipIsRemoteToOne, relationshipIsToMany, valueIsToManyIndex, valueIsTreeRank, @@ -103,8 +104,10 @@ export function findRequiredMissingFields( // Disable circular relationships (isCircularRelationship(parentRelationship, relationship) || // Skip -to-many inside -to-many - (relationshipIsToMany(parentRelationship) && - relationshipIsToMany(relationship))) + ((relationshipIsToMany(parentRelationship) || + relationshipIsRemoteToOne(parentRelationship)) && + (relationshipIsToMany(relationship) || + relationshipIsRemoteToOne(relationship)))) ) return []; diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts index b7a1b46606c..1dd5a3291a1 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/navigator.ts @@ -36,6 +36,7 @@ import { getNameFromTreeDefinitionName, getNameFromTreeRankName, parsePartialField, + relationshipIsRemoteToOne, relationshipIsToMany, valueIsPartialField, valueIsToManyIndex, @@ -121,7 +122,8 @@ function navigator({ if (next === undefined) return; const childrenAreToManyElements = - relationshipIsToMany(parentRelationship) && + (relationshipIsToMany(parentRelationship) || + relationshipIsRemoteToOne(parentRelationship)) && !valueIsToManyIndex(parentPartName) && !valueIsTreeMeta(parentPartName); @@ -328,7 +330,9 @@ export function getMappingLineData({ internalState.defaultValue, ]); - const isToOne = parentRelationship?.type === 'zero-to-one'; + const isToOne = + parentRelationship?.type === 'one-to-one' || + parentRelationship?.type === 'zero-to-one'; const toManyLimit = isToOne ? 1 : Number.POSITIVE_INFINITY; const additional = maxMappedElementNumber < toManyLimit @@ -588,8 +592,10 @@ export function getMappingLineData({ parentRelationship === undefined || (!isCircularRelationship(parentRelationship, field) && !( - relationshipIsToMany(field) && - relationshipIsToMany(parentRelationship) + (relationshipIsToMany(field) || + relationshipIsRemoteToOne(field)) && + (relationshipIsToMany(parentRelationship) || + relationshipIsRemoteToOne(parentRelationship)) )); isIncluded &&= @@ -611,7 +617,10 @@ export function getMappingLineData({ * Hide -to-many relationships to a tree table as they are * not supported by the WorkBench */ - !relationshipIsToMany(field) || + !( + relationshipIsToMany(field) || + relationshipIsRemoteToOne(field) + ) || !isTreeTable(field.relatedTable.name); } diff --git a/specifyweb/frontend/js_src/lib/hooks/useCollection.tsx b/specifyweb/frontend/js_src/lib/hooks/useCollection.tsx index 2ac9bff2452..be9d7b3c7a0 100644 --- a/specifyweb/frontend/js_src/lib/hooks/useCollection.tsx +++ b/specifyweb/frontend/js_src/lib/hooks/useCollection.tsx @@ -6,7 +6,6 @@ import type { SpecifyResource } from '../components/DataModel/legacyTypes'; import type { Relationship } from '../components/DataModel/specifyField'; import type { Collection } from '../components/DataModel/specifyTable'; import type { SubViewSortField } from '../components/FormParse/cells'; -import { relationshipIsToMany } from '../components/WbPlanView/mappingHelpers'; import type { GetOrSet } from '../utils/types'; import { overwriteReadOnly } from '../utils/types'; import { sortFunction } from '../utils/utils'; @@ -34,8 +33,7 @@ export function useCollection({ >( React.useCallback( async () => - relationshipIsToMany(relationship) && - relationship.type !== 'zero-to-one' + relationship.type.includes('-to-many') ? fetchToManyCollection({ parentResource, relationship, @@ -61,16 +59,14 @@ export function useCollection({ versionRef.current += 1; const localVersionRef = versionRef.current; - const fetchCollection = - relationshipIsToMany(relationship) && - relationship.type !== 'zero-to-one' - ? fetchToManyCollection({ - parentResource, - relationship, - sortBy, - filters, - }) - : fetchToOneCollection({ parentResource, relationship, filters }); + const fetchCollection = relationship.type.includes('-to-many') + ? fetchToManyCollection({ + parentResource, + relationship, + sortBy, + filters, + }) + : fetchToOneCollection({ parentResource, relationship, filters }); return fetchCollection.then((collection) => { if ( From 3a0adb6deab7c279fd3f0ba68594fd378fed7568 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Mon, 20 Jan 2025 23:00:49 -0600 Subject: [PATCH 22/80] Remove unused imports --- .../frontend/js_src/lib/components/FormCells/PickListEditor.tsx | 1 - .../js_src/lib/components/FormSliders/RecordSelector.tsx | 1 - .../lib/components/FormSliders/RecordSelectorFromCollection.tsx | 1 - 3 files changed, 3 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx b/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx index 34e569c7e8c..05e26277ce6 100644 --- a/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx +++ b/specifyweb/frontend/js_src/lib/components/FormCells/PickListEditor.tsx @@ -10,7 +10,6 @@ import type { Collection } from '../DataModel/specifyTable'; import { getTable } from '../DataModel/tables'; import type { PickList } from '../DataModel/types'; import { IntegratedRecordSelector } from '../FormSliders/IntegratedRecordSelector'; -import { relationshipIsToMany } from '../WbPlanView/mappingHelpers'; export function PickListEditor({ resource, diff --git a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx index 371da11c494..e013ec223a0 100644 --- a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx +++ b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelector.tsx @@ -8,7 +8,6 @@ import type { SpecifyResource } from '../DataModel/legacyTypes'; import type { Relationship } from '../DataModel/specifyField'; import type { SpecifyTable } from '../DataModel/specifyTable'; import { useSearchDialog } from '../SearchDialog'; -import { relationshipIsToMany } from '../WbPlanView/mappingHelpers'; import { Slider } from './Slider'; export type RecordSelectorProps = { diff --git a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx index ab40df892e8..949228d9d95 100644 --- a/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx +++ b/specifyweb/frontend/js_src/lib/components/FormSliders/RecordSelectorFromCollection.tsx @@ -14,7 +14,6 @@ import type { SpecifyResource } from '../DataModel/legacyTypes'; import { resourceOn } from '../DataModel/resource'; import type { Relationship } from '../DataModel/specifyField'; import type { Collection } from '../DataModel/specifyTable'; -import { relationshipIsToMany } from '../WbPlanView/mappingHelpers'; import type { RecordSelectorProps, RecordSelectorState, From eeadce6dfb16bdaaba063409e62f6d6fe96c2d33 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Mon, 20 Jan 2025 23:35:11 -0600 Subject: [PATCH 23/80] Map built-in celery states to WB statuses Fixes #1835 --- specifyweb/workbench/views.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/specifyweb/workbench/views.py b/specifyweb/workbench/views.py index a1f94d3e2d0..03201d6459a 100644 --- a/specifyweb/workbench/views.py +++ b/specifyweb/workbench/views.py @@ -1,6 +1,6 @@ import json import logging -from typing import List, Optional +from typing import List, Optional, Dict, Literal, get_args as get_typing_args from uuid import uuid4 from django import http @@ -12,8 +12,8 @@ from jsonschema.exceptions import ValidationError # type: ignore from specifyweb.middleware.general import require_GET, require_http_methods -from specifyweb.specify.api import create_obj, get_object_or_404, obj_to_data, \ - toJson, uri_for_model +from specifyweb.celery_tasks import CELERY_TASK_STATE +from specifyweb.specify.api import get_object_or_404 from specifyweb.specify.views import login_maybe_required, openapi from specifyweb.specify.models import Recordset, Specifyuser from specifyweb.notifications.models import Message @@ -35,6 +35,9 @@ class DataSetPT(PermissionTarget): transfer = PermissionTargetAction() create_recordset = PermissionTargetAction() +WorkbenchUpdateStatus = Literal["PROGRESS", "PENDING", "FAILURE"] + + def regularize_rows(ncols: int, rows: List[List]) -> List[List[str]]: n = ncols + 1 # extra row info such as disambiguation in hidden col at end @@ -93,11 +96,7 @@ def regularize(row: List) -> Optional[List]: }, "taskstatus": { "type": "string", - "enum": [ - "PROGRESS", - "PENDING", - "FAILURE", - ] + "enum": list(get_typing_args(WorkbenchUpdateStatus)) }, "uploaderstatus": { "type": "object", @@ -729,16 +728,26 @@ def status(request, ds_id: int) -> http.HttpResponse: if ds.uploaderstatus is None: return http.JsonResponse(None, safe=False) + + task_status_map: Dict[str, WorkbenchUpdateStatus] = { + CELERY_TASK_STATE.RECEIVED: "PENDING", + CELERY_TASK_STATE.STARTED: "PENDING", + CELERY_TASK_STATE.SUCCESS: "PENDING", + CELERY_TASK_STATE.RETRY: "FAILURE", + CELERY_TASK_STATE.REVOKED: "FAILURE", + } task = { 'uploading': tasks.upload, 'validating': tasks.upload, 'unuploading': tasks.unupload, }[ds.uploaderstatus['operation']] + result = task.AsyncResult(ds.uploaderstatus['taskid']) + status = { 'uploaderstatus': ds.uploaderstatus, - 'taskstatus': result.state, + 'taskstatus': task_status_map.get(result.state, result.state), 'taskinfo': result.info if isinstance(result.info, dict) else repr(result.info) } return http.JsonResponse(status) From 7be63160e3cd2f2e4256756324c8facd31488c52 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Tue, 21 Jan 2025 00:29:20 -0600 Subject: [PATCH 24/80] Renable cojo.childco and cojo.childcog parity businessrules --- specifyweb/businessrules/rules/cojo_rules.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/specifyweb/businessrules/rules/cojo_rules.py b/specifyweb/businessrules/rules/cojo_rules.py index 556e6cca2b0..cd66eb53ffb 100644 --- a/specifyweb/businessrules/rules/cojo_rules.py +++ b/specifyweb/businessrules/rules/cojo_rules.py @@ -16,12 +16,12 @@ class COGType(Enum): @orm_signal_handler('pre_save', 'Collectionobjectgroupjoin') def cojo_pre_save(cojo): # Ensure the both the childcog and childco fields are not null. - # if cojo.childcog == None and cojo.childco == None: - # raise BusinessRuleException('Both childcog and childco cannot be null.') + if cojo.childcog == None and cojo.childco == None: + raise BusinessRuleException('Both childcog and childco cannot be null.') # Ensure the childcog and childco fields are not both set. - # if cojo.childcog != None and cojo.childco != None: - # raise BusinessRuleException('Both childcog and childco cannot be set.') + if cojo.childcog != None and cojo.childco != None: + raise BusinessRuleException('Both childcog and childco cannot be set.') # For records with the same parentcog field, there can be only one isPrimare field set to True. # So when a record is saved with isPrimary set to True, we need to set all other records with the same parentcog From d30f414d30d51591c147484f5a6c7322d3e30393 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Tue, 21 Jan 2025 00:31:11 -0600 Subject: [PATCH 25/80] Use identity comparator over equality comparator --- specifyweb/businessrules/rules/cojo_rules.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specifyweb/businessrules/rules/cojo_rules.py b/specifyweb/businessrules/rules/cojo_rules.py index cd66eb53ffb..8c01bfdacf6 100644 --- a/specifyweb/businessrules/rules/cojo_rules.py +++ b/specifyweb/businessrules/rules/cojo_rules.py @@ -16,11 +16,11 @@ class COGType(Enum): @orm_signal_handler('pre_save', 'Collectionobjectgroupjoin') def cojo_pre_save(cojo): # Ensure the both the childcog and childco fields are not null. - if cojo.childcog == None and cojo.childco == None: + if cojo.childcog is None and cojo.childco is None: raise BusinessRuleException('Both childcog and childco cannot be null.') # Ensure the childcog and childco fields are not both set. - if cojo.childcog != None and cojo.childco != None: + if cojo.childcog is not None and cojo.childco is not None: raise BusinessRuleException('Both childcog and childco cannot be set.') # For records with the same parentcog field, there can be only one isPrimare field set to True. From ecde7db7b04f672c980313529c5d68d4ff9b329a Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 21 Jan 2025 12:45:59 -0600 Subject: [PATCH 26/80] add CustomBIT to sqlalchemy model --- specifyweb/stored_queries/build_models.py | 45 +++++++++++++++-------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/specifyweb/stored_queries/build_models.py b/specifyweb/stored_queries/build_models.py index 6ae6a564782..2c0d7c36b1c 100644 --- a/specifyweb/stored_queries/build_models.py +++ b/specifyweb/stored_queries/build_models.py @@ -4,6 +4,18 @@ from sqlalchemy.dialects.mysql import BIT as mysql_bit_type metadata = MetaData() +# Custom BIT type to handle both BIT(1) and TINYINT +class CustomBIT(mysql_bit_type): + def result_processor(self, dialect, coltype): + def process(value): + # Handle TINYINT (integer values) and BIT(1) (byte values) + if isinstance(value, int): + return value != 0 # Convert integer to boolean + if isinstance(value, (bytes, bytearray)): + return value != b'\x00' # Convert BIT(1) to boolean + return value + return process + def make_table(datamodel: Datamodel, tabledef: Table): columns = [ Column(tabledef.idColumn, types.Integer, primary_key=True) ] @@ -40,21 +52,23 @@ def make_column(flddef: Field): nullable = not flddef.required) -field_type_map = {'text' : types.Text, - 'json' : types.JSON, - 'blob' : types.LargeBinary, # mediumblob - 'java.lang.String' : types.String, - 'java.lang.Integer' : types.Integer, - 'java.lang.Long' : types.Integer, - 'java.lang.Byte' : types.Integer, - 'java.lang.Short' : types.Integer, - 'java.util.Calendar' : types.Date, - 'java.util.Date' : types.Date, - 'java.lang.Float' : types.Float, - 'java.lang.Double' : types.Float, - 'java.sql.Timestamp' : types.DateTime, - 'java.math.BigDecimal' : types.Numeric, - 'java.lang.Boolean' : mysql_bit_type} +field_type_map = { + 'text' : types.Text, + 'json' : types.JSON, + 'blob' : types.LargeBinary, # mediumblob + 'java.lang.String' : types.String, + 'java.lang.Integer' : types.Integer, + 'java.lang.Long' : types.Integer, + 'java.lang.Byte' : types.Integer, + 'java.lang.Short' : types.Integer, + 'java.util.Calendar' : types.Date, + 'java.util.Date' : types.Date, + 'java.lang.Float' : types.Float, + 'java.lang.Double' : types.Float, + 'java.sql.Timestamp' : types.DateTime, + 'java.math.BigDecimal' : types.Numeric, + 'java.lang.Boolean' : CustomBIT +} def make_tables(datamodel: Datamodel): return {td.table: make_table(datamodel, td) for td in datamodel.tables} @@ -65,7 +79,6 @@ def make_class(tabledef): return {td.name: make_class(td) for td in datamodel.tables} - def map_classes(datamodel: Datamodel, tables: List[Table], classes): def map_class(tabledef): From 4fb34be163977025d53bc9fcabae1353f1f5be73 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Tue, 21 Jan 2025 13:54:15 -0500 Subject: [PATCH 27/80] Use a filter chronostrat prop to apply chrono filter to age picklist --- .../lib/components/DataModel/collection.ts | 1 + .../js_src/lib/components/PickLists/fetch.ts | 3 ++- specifyweb/specify/api.py | 19 +++++++++++-------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/DataModel/collection.ts b/specifyweb/frontend/js_src/lib/components/DataModel/collection.ts index 9aa75af2d83..de889b2695d 100644 --- a/specifyweb/frontend/js_src/lib/components/DataModel/collection.ts +++ b/specifyweb/frontend/js_src/lib/components/DataModel/collection.ts @@ -193,6 +193,7 @@ export const fetchRows = async < readonly fields: FIELDS; readonly distinct?: boolean; readonly limit?: number; + readonly filterChronostrat?: boolean; }, /** * Advanced filters, not type-safe. diff --git a/specifyweb/frontend/js_src/lib/components/PickLists/fetch.ts b/specifyweb/frontend/js_src/lib/components/PickLists/fetch.ts index a5ce74f680a..f4fb195f439 100644 --- a/specifyweb/frontend/js_src/lib/components/PickLists/fetch.ts +++ b/specifyweb/frontend/js_src/lib/components/PickLists/fetch.ts @@ -14,7 +14,7 @@ import { deserializeResource, serializeResource, } from '../DataModel/serializers'; -import { strictGetTable } from '../DataModel/tables'; +import { strictGetTable, tables } from '../DataModel/tables'; import type { PickList, PickListItem, Tables } from '../DataModel/types'; import { softFail } from '../Errors/Crash'; import { format } from '../Formatters/formatters'; @@ -159,6 +159,7 @@ async function fetchFromField( fields: { [fieldName]: ['string', 'number', 'boolean', 'null'] }, distinct: true, domainFilter: true, + filterChronostrat: tableName === tables.GeologicTimePeriod.name.toLowerCase() && fieldName === "name", // Prop for age filter in QueryBuilder }).then((rows) => rows .map((row) => row[fieldName] ?? '') diff --git a/specifyweb/specify/api.py b/specifyweb/specify/api.py index ad2ddd4e16d..22dd396a305 100644 --- a/specifyweb/specify/api.py +++ b/specifyweb/specify/api.py @@ -216,11 +216,14 @@ class GetCollectionForm(forms.Form): orderby = forms.CharField(required=False) + filterchronostrat = forms.BooleanField(required=False) + defaults = dict( domainfilter=None, limit=0, offset=0, orderby=None, + filterchronostrat=False, ) def clean_limit(self): @@ -1010,14 +1013,13 @@ def apply_filters(logged_in_collection, params, model, control_params=GetCollect filters.update({param: val}) -#code repsonsible for issue 6086, this snipet is called to display the children of GeologicTimePeriod node. Need to refine to be applied only in the context of extended age query - # if model.__name__ == 'Geologictimeperiod': - # # Filter out invalid chronostrats - # filters.update({ - # 'startperiod__isnull': False, - # 'endperiod__isnull': False, - # 'startperiod__gte': F('endperiod') - # }) + if control_params['filterchronostrat'] == True: + # Filter out invalid chronostrats + filters.update({ + 'startperiod__isnull': False, + 'endperiod__isnull': False, + 'startperiod__gte': F('endperiod') + }) try: objs = model.objects.filter(**filters) @@ -1082,6 +1084,7 @@ class RowsForm(GetCollectionForm): orderby=None, distinct=False, fields=None, + filterchronostrat=False, ) def rows(request, model_name: str) -> HttpResponse: From 5991ee20e0be714b731cfc7c6a618c9ceb22047e Mon Sep 17 00:00:00 2001 From: Sharad S Date: Tue, 21 Jan 2025 14:14:48 -0500 Subject: [PATCH 28/80] Fix unit tests --- .../js_src/lib/components/PickLists/__tests__/fetch.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/PickLists/__tests__/fetch.test.ts b/specifyweb/frontend/js_src/lib/components/PickLists/__tests__/fetch.test.ts index 04cc8ced4c1..14ba1ab0c5a 100644 --- a/specifyweb/frontend/js_src/lib/components/PickLists/__tests__/fetch.test.ts +++ b/specifyweb/frontend/js_src/lib/components/PickLists/__tests__/fetch.test.ts @@ -182,7 +182,7 @@ describe('fetchPickListItems', () => { }); overrideAjax( - '/api/specify_rows/locality/?limit=0&domainfilter=true&distinct=true&fields=localityname', + '/api/specify_rows/locality/?limit=0&domainfilter=true&filterchronostrat=false&distinct=true&fields=localityname', [['abc']] ); test('entire column', async () => { From add6c58d57778efa572ffd80ff796628d8c942c7 Mon Sep 17 00:00:00 2001 From: Grant Fitzsimmons <37256050+grantfitzsimmons@users.noreply.github.com> Date: Tue, 21 Jan 2025 14:09:00 -0600 Subject: [PATCH 29/80] Update SECURITY.md --- SECURITY.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index b7fc838b8bd..1e0fe74bab1 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -28,9 +28,9 @@ or other issues for that application on the ### Specify 7 Please contact [support@specifysoftware.org](mailto:support@specifysoftware.org) -immediately if you encounter any security vulnerability in Specify 7 in addition -to creating a -[new bug report](https://github.com/specify/specify7/issues/new?assignees=&labels=type%3Abug%2C+pri%3Aunknown&template=bug_report.md&title=) +immediately if you encounter any security vulnerability in Specify 7. + +If it is **not** a security vulnerability, you can create a [new bug report](https://github.com/specify/specify7/issues/new?assignees=&labels=type%3Abug%2C+pri%3Aunknown&template=bug_report.md&title=) in the GitHub repository where it will be reviewed by the development team within 24 hours. From feab0b0e1323848c53b011e175372f5a562846ed Mon Sep 17 00:00:00 2001 From: Grant Fitzsimmons <37256050+grantfitzsimmons@users.noreply.github.com> Date: Tue, 21 Jan 2025 14:12:09 -0600 Subject: [PATCH 30/80] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index f288702d2fa..6577295a148 100644 --- a/LICENSE +++ b/LICENSE @@ -652,7 +652,7 @@ Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: - Copyright (C) + Specify 7 Copyright (C) 2024 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. From 3e16e836774873925ab927460b08882011287da4 Mon Sep 17 00:00:00 2001 From: Grant Fitzsimmons <37256050+grantfitzsimmons@users.noreply.github.com> Date: Tue, 21 Jan 2025 14:26:03 -0600 Subject: [PATCH 31/80] Update supported versions --- SECURITY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 1e0fe74bab1..270530c94d4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -15,9 +15,9 @@ questions you may have about configuration or deployment. | Version | Supported | | ------- | ------------------ | +| 7.10.x | :white_check_mark: | | 7.9.x | :white_check_mark: | -| 7.8.x | :white_check_mark: | -| < 7.8 | :x: | +| < 7.8.x | :x: | We support the latest version of Specify 6 only. You can report vulnerabilities or other issues for that application on the From 3d8b3b67ffca378236c4f009a627634debbb343b Mon Sep 17 00:00:00 2001 From: Jason Melton <64045831+melton-jason@users.noreply.github.com> Date: Wed, 22 Jan 2025 17:06:04 +0000 Subject: [PATCH 32/80] Lint code with ESLint and Prettier Triggered by 05eafa2de42b5bbc402387be4a194751d59a0069 on branch refs/heads/issue-5418 --- .../frontend/js_src/lib/components/Forms/SubView.tsx | 7 ++++--- .../frontend/js_src/lib/components/PickLists/fetch.ts | 4 +++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx b/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx index a31b661de35..090378ed19e 100644 --- a/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx +++ b/specifyweb/frontend/js_src/lib/components/Forms/SubView.tsx @@ -139,10 +139,11 @@ export function SubView({ return ( - {!RECURSIVE_RENDERING_EXCEPTIONS.has(parentResource.specifyTable) && + {(!RECURSIVE_RENDERING_EXCEPTIONS.has(parentResource.specifyTable) && parentContext - .map(({ relationship }) => relationship) - .includes(relationship) || collection === false ? undefined : ( + .map(({ relationship }) => relationship) + .includes(relationship)) || + collection === false ? undefined : ( <> {isButton && ( rows .map((row) => row[fieldName] ?? '') From 6285dcbac33c5d298eda5ec9e87c81ece64300b3 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Wed, 22 Jan 2025 17:08:32 -0500 Subject: [PATCH 33/80] Add default query mapping path to filter by COT tree def in QB search --- .../frontend/js_src/lib/components/QueryComboBox/index.tsx | 4 ++++ .../frontend/js_src/lib/components/SearchDialog/index.tsx | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx index 1e776d86977..8eca661e45c 100644 --- a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx @@ -550,6 +550,10 @@ export function QueryComboBox({ : fieldName === 'taxonTreeDefId' ? { field: 'definition', + queryBuilderFieldPath: [ + 'definition', + 'id', + ], isRelationship: true, operation: 'in', isNot: false, diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index ea01ebff46b..0760bfccf80 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -35,6 +35,7 @@ import type { QueryFieldFilter } from '../QueryBuilder/FieldFilter'; import { queryFieldFilters } from '../QueryBuilder/FieldFilter'; import { QueryFieldSpec } from '../QueryBuilder/fieldSpec'; import { QueryBuilder } from '../QueryBuilder/Wrapped'; +import { MappingPath } from '../WbPlanView/Mapper'; import { queryCbxExtendedSearch } from './helpers'; import { SelectRecordSets } from './SelectRecordSet'; @@ -42,6 +43,7 @@ const resourceLimit = 100; export type QueryComboBoxFilter = { readonly field: string & (keyof CommonFields | keyof SCHEMA['fields']); + readonly queryBuilderFieldPath?: MappingPath; readonly isRelationship: boolean; readonly isNot: boolean; readonly operation: QueryFieldFilter & ('between' | 'in' | 'less'); @@ -395,8 +397,8 @@ const toQueryFields = ( table: SpecifyTable, filters: RA> ): RA> => - filters.map(({ field, operation, isNot, value }) => - QueryFieldSpec.fromPath(table.name, [field]) + filters.map(({ field, queryBuilderFieldPath, operation, isNot, value }) => + QueryFieldSpec.fromPath(table.name, queryBuilderFieldPath ?? [field]) .toSpQueryField() .set('operStart', queryFieldFilters[operation].id) .set('isNot', isNot) From 6b402c4124a3543a4611b0ac4f68a9fa9c3febfc Mon Sep 17 00:00:00 2001 From: Sharad S Date: Wed, 22 Jan 2025 22:12:22 +0000 Subject: [PATCH 34/80] Lint code with ESLint and Prettier Triggered by 6285dcbac33c5d298eda5ec9e87c81ece64300b3 on branch refs/heads/issue-6098 --- .../frontend/js_src/lib/components/SearchDialog/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index 0760bfccf80..c6633066a53 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -35,7 +35,7 @@ import type { QueryFieldFilter } from '../QueryBuilder/FieldFilter'; import { queryFieldFilters } from '../QueryBuilder/FieldFilter'; import { QueryFieldSpec } from '../QueryBuilder/fieldSpec'; import { QueryBuilder } from '../QueryBuilder/Wrapped'; -import { MappingPath } from '../WbPlanView/Mapper'; +import type { MappingPath } from '../WbPlanView/Mapper'; import { queryCbxExtendedSearch } from './helpers'; import { SelectRecordSets } from './SelectRecordSet'; @@ -158,7 +158,7 @@ function testFilter( ? // Cast numbers to strings values.some((value) => { const fieldValue = resource.get(field); - // eslint-disable-next-line eqeqeq + return isRelationship ? value == strictIdFromUrl(fieldValue!).toString() : value == fieldValue; From 88b2d635097f3b2641d5f0275c4380497b7e3f75 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Wed, 22 Jan 2025 17:21:57 -0500 Subject: [PATCH 35/80] Re add eslint disable --- .../frontend/js_src/lib/components/SearchDialog/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index c6633066a53..645028f5b00 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -158,7 +158,7 @@ function testFilter( ? // Cast numbers to strings values.some((value) => { const fieldValue = resource.get(field); - + // eslint-disable-next-line eqeqeq return isRelationship ? value == strictIdFromUrl(fieldValue!).toString() : value == fieldValue; From 9cd74f2f9b9e147a15ea6a9afa55c6b17118f9b4 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Wed, 22 Jan 2025 22:25:27 +0000 Subject: [PATCH 36/80] Lint code with ESLint and Prettier Triggered by 88b2d635097f3b2641d5f0275c4380497b7e3f75 on branch refs/heads/issue-6098 --- .../frontend/js_src/lib/components/SearchDialog/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index 645028f5b00..0b7b3114280 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -158,7 +158,7 @@ function testFilter( ? // Cast numbers to strings values.some((value) => { const fieldValue = resource.get(field); - // eslint-disable-next-line eqeqeq + return isRelationship ? value == strictIdFromUrl(fieldValue!).toString() : value == fieldValue; From a315ed5f05770a833e6c40e7b95abbfd73edc090 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Wed, 22 Jan 2025 17:08:18 -0600 Subject: [PATCH 37/80] Possible new functions with process_boolean_field --- specifyweb/stored_queries/build_models.py | 68 +++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/specifyweb/stored_queries/build_models.py b/specifyweb/stored_queries/build_models.py index 2c0d7c36b1c..a6fdaca7a84 100644 --- a/specifyweb/stored_queries/build_models.py +++ b/specifyweb/stored_queries/build_models.py @@ -117,3 +117,71 @@ def make_relationship(reldef): for tabledef in datamodel.tables: map_class(tabledef) + + +# NOTE: Possible new functions with process_boolean_field +from sqlalchemy import inspect +from sqlalchemy.dialects.mysql import BIT +from sqlalchemy.types import Boolean + +def process_boolean_field(field, engine): + """ + Dynamically determines the type of a boolean field (BIT(1) or TINYINT) + and returns the appropriate SQLAlchemy type. + + Args: + field: The SQLAlchemy column object to process. + engine: The SQLAlchemy engine connected to the database. + + Returns: + The appropriate SQLAlchemy type (CustomBIT or Boolean). + """ + # Use SQLAlchemy's inspector to get column details + inspector = inspect(engine) + table_name = field.table.name + column_name = field.name + + # Get the column metadata from the table + columns = inspector.get_columns(table_name) + + for column in columns: + if column['name'] == column_name: + # Check for BIT type + if isinstance(column['type'], BIT): + return CustomBIT() + # Check for TINYINT type (interpreted as Boolean by SQLAlchemy) + elif isinstance(column['type'], Boolean): + return Boolean + else: + raise ValueError(f"Unsupported boolean column type: {column['type']}") + raise ValueError(f"Column {column_name} not found in table {table_name}.") + +def new_make_column(flddef: Field, engine): + # Dynamically process boolean fields + if flddef.type == 'java.lang.Boolean': + field_type = process_boolean_field(flddef, engine) + else: + field_type = field_type_map[flddef.type] + + if hasattr(flddef, 'length') and flddef.length and field_type in (types.Text, types.String): + field_type = field_type(flddef.length) + + return Column(flddef.column, + field_type, + index=flddef.indexed, + unique=flddef.unique, + nullable=not flddef.required) + +def new_make_table(datamodel: Datamodel, tabledef: Table, engine): + columns = [Column(tabledef.idColumn, types.Integer, primary_key=True)] + + # Pass the engine to `make_column` + columns.extend(make_column(field, engine) for field in tabledef.fields) + + for reldef in tabledef.relationships: + if reldef.type in ('many-to-one', 'one-to-one') and hasattr(reldef, 'column') and reldef.column: + fk = make_foreign_key(datamodel, reldef) + if fk is not None: + columns.append(fk) + + return Table_Sqlalchemy(tabledef.table, metadata, *columns) \ No newline at end of file From 6029f39ab879371291f65f66d0b1cb4b31a75685 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 14 Jan 2025 11:30:37 -0600 Subject: [PATCH 38/80] auto check is_resolved (cherry picked from commit 7bb138ee785e6421953ad19b8712436c05b82d0d) --- specifyweb/interactions/cog_preps.py | 154 +++++++++++++++++++-------- 1 file changed, 110 insertions(+), 44 deletions(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 16682f2b468..8ad054ee505 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -20,6 +20,7 @@ logger = logging.getLogger(__name__) + def is_consolidated_cog(cog: Optional[Collectionobjectgroup]) -> bool: """ Check if the CollectionObjectGroup is consolidated. @@ -31,6 +32,7 @@ def is_consolidated_cog(cog: Optional[Collectionobjectgroup]) -> bool: and cog.cogtype.type.lower().title() == "Consolidated" ) + def get_cog_consolidated_preps(cog: Collectionobjectgroup) -> List[Preparation]: """ Recursively get all the child CollectionObjectGroups, then get the leaf CollectionObjects, @@ -46,7 +48,8 @@ def get_cog_consolidated_preps(cog: Collectionobjectgroup) -> List[Preparation]: ).values_list("childcog", flat=True) consolidated_preps = [] for child_cog_id in child_cogs: - child_cog = Collectionobjectgroup.objects.filter(id=child_cog_id).first() + child_cog = Collectionobjectgroup.objects.filter( + id=child_cog_id).first() child_preps = get_cog_consolidated_preps(child_cog) consolidated_preps.extend(child_preps) @@ -57,10 +60,12 @@ def get_cog_consolidated_preps(cog: Collectionobjectgroup) -> List[Preparation]: # For each CollectionObject, get the preparations for co in collection_objects: - consolidated_preps.extend(Preparation.objects.filter(collectionobject=co)) + consolidated_preps.extend( + Preparation.objects.filter(collectionobject=co)) return consolidated_preps + def get_the_top_consolidated_parent_cog_of_prep(prep: Preparation) -> Optional[Collectionobjectgroup]: """ Get the topmost consolidated parent CollectionObjectGroup of the preparation. @@ -82,13 +87,15 @@ def get_the_top_consolidated_parent_cog_of_prep(prep: Preparation) -> Optional[C # Move up consolidated parent CollectionObjectGroups until the top consolidated CollectionObjectGroup is found while True: - cojo = Collectionobjectgroupjoin.objects.filter(childcog=top_cog).first() + cojo = Collectionobjectgroupjoin.objects.filter( + childcog=top_cog).first() if cojo is None or not is_consolidated_cog(cojo.parentcog): break top_cog = cojo.parentcog return top_cog + def get_all_sibling_preps_within_consolidated_cog(prep: Preparation) -> List[Preparation]: """ Get all the sibling preparations within the consolidated cog @@ -97,7 +104,7 @@ def get_all_sibling_preps_within_consolidated_cog(prep: Preparation) -> List[Pre top_consolidated_cog = get_the_top_consolidated_parent_cog_of_prep(prep) if top_consolidated_cog is None: return [prep] - + # Get all the sibling preparations sibling_preps = get_cog_consolidated_preps(top_consolidated_cog) @@ -106,18 +113,21 @@ def get_all_sibling_preps_within_consolidated_cog(prep: Preparation) -> List[Pre return sibling_preps + def is_cog_recordset(rs: Recordset) -> bool: """ Check if the recordset is a CollectionObjectGroup recordset """ return rs.dbtableid == get_table_id_by_model_name('Collectionobjectgroup') + def is_co_recordset(rs: Recordset) -> bool: """ Check if the recordset is a CollectionObjectGroup recordset """ return rs.dbtableid == get_table_id_by_model_name('Collectionobject') + def get_cogs_from_co_recordset(rs: Recordset) -> Optional[QuerySet[Collectionobjectgroup]]: """ Get the CollectionObjectGroups from the CollectionObject recordset @@ -125,19 +135,21 @@ def get_cogs_from_co_recordset(rs: Recordset) -> Optional[QuerySet[Collectionobj if not is_co_recordset(rs): return None - + # Subquery to get CollectionObjectIDs from the recordset co_subquery = Recordsetitem.objects.filter(recordset=rs).values('recordid') - + # Subquery to get parentcog IDs from Collectionobjectgroupjoin parent_cog_subquery = Collectionobjectgroupjoin.objects.filter( childco__in=Subquery(co_subquery) ).values('parentcog') - + # Main query to get Collectionobjectgroup objects - cogs = Collectionobjectgroup.objects.filter(id__in=Subquery(parent_cog_subquery)) + cogs = Collectionobjectgroup.objects.filter( + id__in=Subquery(parent_cog_subquery)) return cogs + def get_cogs_from_co_ids(co_ids: List[int]) -> Optional[QuerySet[Collectionobjectgroup]]: """ Get the CollectionObjectGroups from the CollectionObject IDs @@ -146,18 +158,21 @@ def get_cogs_from_co_ids(co_ids: List[int]) -> Optional[QuerySet[Collectionobjec parent_cog_subquery = Collectionobjectgroupjoin.objects.filter( childco__in=co_ids ).values('parentcog') - + # Main query to get Collectionobjectgroup objects - cogs = Collectionobjectgroup.objects.filter(id__in=Subquery(parent_cog_subquery)) + cogs = Collectionobjectgroup.objects.filter( + id__in=Subquery(parent_cog_subquery)) return cogs + def get_cog_consolidated_preps_co_ids(cog: Collectionobjectgroup) -> Set[Collectionobject]: preps = get_cog_consolidated_preps(cog) - + # Return set of distinct CollectionObjectIDs associated with the preparations return set(prep.collectionobject.id for prep in preps) -def add_consolidated_sibling_co_ids(request_co_ids: List[Any], id_fld: Optional[str]=None) -> List[Any]: + +def add_consolidated_sibling_co_ids(request_co_ids: List[Any], id_fld: Optional[str] = None) -> List[Any]: """ Get the consolidated sibling CO IDs of the COs in the list """ @@ -166,15 +181,18 @@ def add_consolidated_sibling_co_ids(request_co_ids: List[Any], id_fld: Optional[ # id_fld = 'id' id_fld = 'catalognumber' id_fld = id_fld.lower() - co_ids = Collectionobject.objects.filter(**{f"{id_fld}__in": request_co_ids}).values_list('id', flat=True) + co_ids = Collectionobject.objects.filter( + **{f"{id_fld}__in": request_co_ids}).values_list('id', flat=True) cogs = get_cogs_from_co_ids(co_ids) for cog in cogs: cog_sibling_co_ids.update(get_cog_consolidated_preps_co_ids(cog)) # cog_sibling_co_ids -= set(co_ids) - cog_sibling_co_idfld_ids = Collectionobject.objects.filter(id__in=cog_sibling_co_ids).values_list(id_fld, flat=True) + cog_sibling_co_idfld_ids = Collectionobject.objects.filter( + id__in=cog_sibling_co_ids).values_list(id_fld, flat=True) return list(set(request_co_ids).union(set(cog_sibling_co_idfld_ids))) + def get_consolidated_co_siblings_from_rs(rs: Recordset) -> Set[Collectionobject]: """ Get the consolidated sibling CO IDs of the COs in the recordset @@ -183,11 +201,13 @@ def get_consolidated_co_siblings_from_rs(rs: Recordset) -> Set[Collectionobject] if is_co_recordset(rs): cogs = get_cogs_from_co_recordset(rs) for cog in cogs: - cog_sibling_co_ids = cog_sibling_co_ids.union(get_cog_consolidated_preps_co_ids(cog)) + cog_sibling_co_ids = cog_sibling_co_ids.union( + get_cog_consolidated_preps_co_ids(cog)) # cog_sibling_co_ids -= set(rs.recordsetitems.values_list('recordid', flat=True)) return cog_sibling_co_ids + def get_co_ids_from_shared_cog_rs(rs: Recordset) -> Set[Collectionobject]: """ Get the CO IDs from the shared COGs in the recordset @@ -201,11 +221,13 @@ def get_co_ids_from_shared_cog_rs(rs: Recordset) -> Set[Collectionobject]: ) cog_co_ids = set().union(*[ - Collectionobjectgroupjoin.objects.filter(parentcog=cog).values_list("childco", flat=True) + Collectionobjectgroupjoin.objects.filter( + parentcog=cog).values_list("childco", flat=True) for cog in cogs ]) return cog_co_ids + def modify_prep_update_based_on_sibling_preps(original_prep_ids: Set[int], updated_prep_ids: Set[int]) -> Set[int]: """ Determine the difference between the preparation IDs original and updated prep. @@ -222,13 +244,16 @@ def modify_prep_update_based_on_sibling_preps(original_prep_ids: Set[int], updat # Create a map of each preparation ID to a list of sibling preparation IDs prep_to_sibling_preps = {} + def update_prep_to_sibling_preps(prep_ids, prep_to_sibling_preps): for prep_id in prep_ids: if prep_id not in prep_to_sibling_preps: try: prep = Preparation.objects.get(id=prep_id) - sibling_preps = get_all_sibling_preps_within_consolidated_cog(prep) - prep_to_sibling_preps[prep_id] = {p.id for p in sibling_preps} + sibling_preps = get_all_sibling_preps_within_consolidated_cog( + prep) + prep_to_sibling_preps[prep_id] = { + p.id for p in sibling_preps} except Preparation.DoesNotExist: prep_to_sibling_preps[prep_id] = set() @@ -245,6 +270,7 @@ def update_prep_to_sibling_preps(prep_ids, prep_to_sibling_preps): return modified_prep_ids + def modify_update_of_interaction_sibling_preps(original_interaction_obj, updated_interaction_data): """ Determine the difference between the preparation IDs in the Loanpreparations of the original and updated interactions. @@ -262,11 +288,11 @@ def modify_update_of_interaction_sibling_preps(original_interaction_obj, updated filter_fld = "loan" InteractionPrepModel = Loanpreparation elif 'loanreturnpreparations' in updated_interaction_data: - interaction_prep_name = "loanreturnpreparations" + interaction_prep_name = "loanreturnpreparations" filter_fld = "loanreturn" InteractionPrepModel = Loanreturnpreparation else: - return updated_interaction_data + return updated_interaction_data elif original_interaction_obj._meta.model_name == 'gift': interaction_prep_name = "giftpreparations" filter_fld = "gift" @@ -283,7 +309,8 @@ def modify_update_of_interaction_sibling_preps(original_interaction_obj, updated updated_prep_ids = set( [ # BUG: the preparation can be provided as an object in the request - strict_uri_to_model(interaction_prep["preparation"], "preparation")[1] + strict_uri_to_model( + interaction_prep["preparation"], "preparation")[1] for interaction_prep in interaction_prep_data if "preparation" in interaction_prep.keys() and interaction_prep["preparation"] is not None ] @@ -335,29 +362,37 @@ def modify_update_of_interaction_sibling_preps(original_interaction_obj, updated ) # Add back the unassociated preparation data - updated_interaction_data[interaction_prep_name].extend(unassociated_prep_data) + updated_interaction_data[interaction_prep_name].extend( + unassociated_prep_data) return updated_interaction_data + def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated_interaction_data): if 'loanpreparations' not in updated_interaction_data: return updated_interaction_data # Parse and map loan preparation data - map_prep_id_to_loan_prep_idx = {} # Map preparation ID to loan preparation index - map_prep_id_to_loan_prep_id = {} # Map preparation ID to loan preparation ID - map_prep_id_to_new_loan_return_prep_data = {} # Map preparation ID to new loan return preparation data - target_preps = set() # Preparations that the user explicitly requested to create a new loan return record - target_prep_ids = set() # Preparation IDs that the user explicitly requested to create a new loan return record + map_prep_id_to_loan_prep_idx = {} # Map preparation ID to loan preparation index + map_prep_id_to_loan_prep_id = {} # Map preparation ID to loan preparation ID + # Map preparation ID to new loan return preparation data + map_prep_id_to_new_loan_return_prep_data = {} + # Preparations that the user explicitly requested to create a new loan return record + target_preps = set() + # Preparation IDs that the user explicitly requested to create a new loan return record + target_prep_ids = set() loan_prep_idx = 0 for loan_prep_data in updated_interaction_data["loanpreparations"]: if type(loan_prep_data) is str: continue - loan_prep_id = int(loan_prep_data["id"]) if "id" in loan_prep_data.keys() else None - + loan_prep_id = int( + loan_prep_data["id"]) if "id" in loan_prep_data.keys() else None + # BUG: the preparation can be provided as a dict in the request - prep_uri = loan_prep_data["preparation"] if "preparation" in loan_prep_data.keys() else None - _, prep_id = strict_uri_to_model(prep_uri, "preparation") if prep_uri is not None else [None, None] + prep_uri = loan_prep_data["preparation"] if "preparation" in loan_prep_data.keys( + ) else None + _, prep_id = strict_uri_to_model( + prep_uri, "preparation") if prep_uri is not None else [None, None] map_prep_id_to_loan_prep_idx[prep_id] = loan_prep_idx loan_prep_idx += 1 loan_return_prep_data_lst = loan_prep_data["loanreturnpreparations"] @@ -373,7 +408,8 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated loan_return_prep_data = loan_return_prep_data_lst[0] # BUG: the loanpreparation can be provided as an object in the request - loan_return_loan_prep_id = strict_uri_to_model(loan_return_prep_data["loanpreparation"], "loanpreparation")[1] + loan_return_loan_prep_id = strict_uri_to_model( + loan_return_prep_data["loanpreparation"], "loanpreparation")[1] if loan_return_loan_prep_id == loan_prep_id: target_prep_ids.update({prep_id}) prep = Preparation.objects.filter(id=prep_id).first() @@ -382,29 +418,36 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated map_prep_id_to_loan_prep_id[prep_id] = loan_prep_id map_prep_id_to_new_loan_return_prep_data[prep_id] = loan_return_prep_data else: - loan_prep = Loanpreparation.objects.filter(id=loan_return_loan_prep_id).first() + loan_prep = Loanpreparation.objects.filter( + id=loan_return_loan_prep_id).first() prep = loan_prep.preparation if loan_prep is not None else None if prep is not None: target_prep_ids.update({prep.id}) target_preps.update({prep}) # Get the sibling preparations - map_sibling_prep_ids_to_original_prep_ids = {} # Map sibling preparation ID to original preparation IDs - consolidated_target_preps_with_siblings = set() # Set of consolidated target preparations with siblings + # Map sibling preparation ID to original preparation IDs + map_sibling_prep_ids_to_original_prep_ids = {} + # Set of consolidated target preparations with siblings + consolidated_target_preps_with_siblings = set() for target_prep in target_preps: - sibling_preps = get_all_sibling_preps_within_consolidated_cog(target_prep) + sibling_preps = get_all_sibling_preps_within_consolidated_cog( + target_prep) if sibling_preps is None or len(sibling_preps) == 0 or target_prep.id is None: continue consolidated_target_preps_with_siblings.update({target_prep}) for sibling_prep in sibling_preps: if sibling_prep.id not in map_sibling_prep_ids_to_original_prep_ids.keys(): - map_sibling_prep_ids_to_original_prep_ids[sibling_prep.id] = set({target_prep.id}) + map_sibling_prep_ids_to_original_prep_ids[sibling_prep.id] = set({ + target_prep.id}) else: - map_sibling_prep_ids_to_original_prep_ids[sibling_prep.id].update({target_prep.id}) + map_sibling_prep_ids_to_original_prep_ids[sibling_prep.id].update({ + target_prep.id}) sibling_prep_ids = set(map_sibling_prep_ids_to_original_prep_ids.keys()) added_prep_ids = sibling_prep_ids - target_prep_ids - new_loan_return_prep_ids = {prep_id for prep_id in added_prep_ids if prep_id in map_prep_id_to_loan_prep_idx.keys()} + new_loan_return_prep_ids = { + prep_id for prep_id in added_prep_ids if prep_id in map_prep_id_to_loan_prep_idx.keys()} # Set all the consolidated target loan returns to the max returned and resolved quantity for prep in consolidated_target_preps_with_siblings: @@ -432,7 +475,8 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated if len(orginal_prep_ids) == 1: original_prep_id = orginal_prep_ids.pop() original_loan_prep_idx = map_prep_id_to_loan_prep_idx[original_prep_id] - original_loan_prep_data = updated_interaction_data["loanpreparations"][original_loan_prep_idx] + original_loan_prep_data = updated_interaction_data[ + "loanpreparations"][original_loan_prep_idx] original_loan_return_data_lst = original_loan_prep_data["loanreturnpreparations"] original_loan_return_data = ( original_loan_return_data_lst[-1] @@ -441,10 +485,12 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated else None ) if original_loan_return_data is None: - logger.warning("No loan return preparation data found for this consolidated COG preparation.") + logger.warning( + "No loan return preparation data found for this consolidated COG preparation.") continue elif len(orginal_prep_ids) > 1: - logger.warning("Multiple partial loan returns found for this consolidated COG preparation.") + logger.warning( + "Multiple partial loan returns found for this consolidated COG preparation.") else: continue @@ -459,7 +505,7 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated # Add new loan return preparation data to the loan prep loan_prep_id = loan_prep_data["id"] - + # BUG: the discipline can be provided as an object in the request discipline_uri = ( loan_prep_data["discipline"] @@ -472,7 +518,7 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated else None ) # BUG: the receivedby can be provided as an object in the request - received_by_agent_uri = ( # Use the target agent, but review this, maybe use this sibling prep's loan agent? + received_by_agent_uri = ( # Use the target agent, but review this, maybe use this sibling prep's loan agent? original_loan_return_data["receivedby"] if "receivedby" in original_loan_return_data.keys() else None @@ -491,6 +537,26 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated "loanreturnpreparations" ].extend([new_loan_return_data]) + # Recalculate the total quantity returned and resolved for the loan preparation + # based on the modified loan return preparation data. + for loan_prep_idx in range(len(updated_interaction_data["loanpreparations"])): + loan_return_data = updated_interaction_data["loanpreparations"][loan_prep_idx]["loanreturnpreparations"] + total_quantity_returned = sum( + [loan_return["quantityreturned"] for loan_return in loan_return_data]) + total_quantity_resolved = sum( + [loan_return["quantityresolved"] for loan_return in loan_return_data]) + updated_interaction_data["loanpreparations"][loan_prep_idx]["quantityresolved"] = total_quantity_resolved + updated_interaction_data["loanpreparations"][loan_prep_idx]["quantityreturned"] = total_quantity_returned + + # Set the modified loan prep isresolved to True if all the preparations are resolved + prep_uri = updated_interaction_data["loanpreparations"][loan_prep_idx]["preparation"] + prep_id = strict_uri_to_model(prep_uri, "preparation")[1] + if prep_id in sibling_prep_ids or prep_id in new_loan_return_prep_ids or prep_id in target_prep_ids: + updated_interaction_data["loanpreparations"][loan_prep_idx]["isresolved"] = True + quantity = updated_interaction_data["loanpreparations"][loan_prep_idx]["quantity"] + if total_quantity_returned + total_quantity_resolved >= quantity: + updated_interaction_data["loanpreparations"][loan_prep_idx]["isresolved"] = True + # NOTE: Maybe handle removed sibling preparations after removing an existing loan return preparation return updated_interaction_data From 2e54afc5d8fdfc260e3f1646c53528a61a0f4393 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 14 Jan 2025 14:44:13 -0600 Subject: [PATCH 39/80] change resolved conditional (cherry picked from commit d1cf2efa1d2d45ca53328ada9b804099ff607733) --- specifyweb/interactions/cog_preps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 8ad054ee505..2796351425b 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -554,7 +554,7 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated if prep_id in sibling_prep_ids or prep_id in new_loan_return_prep_ids or prep_id in target_prep_ids: updated_interaction_data["loanpreparations"][loan_prep_idx]["isresolved"] = True quantity = updated_interaction_data["loanpreparations"][loan_prep_idx]["quantity"] - if total_quantity_returned + total_quantity_resolved >= quantity: + if total_quantity_resolved >= quantity: updated_interaction_data["loanpreparations"][loan_prep_idx]["isresolved"] = True # NOTE: Maybe handle removed sibling preparations after removing an existing loan return preparation From f5be2134d1a970d3a4c8c5874bea1e9f4915fbb9 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 14 Jan 2025 15:29:57 -0600 Subject: [PATCH 40/80] type cast quantity as int if str (cherry picked from commit a56d8d81c00ecc71328e2817fef8c9e3aec2220a) --- specifyweb/businessrules/rules/interaction_rules.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/specifyweb/businessrules/rules/interaction_rules.py b/specifyweb/businessrules/rules/interaction_rules.py index b17b78449cd..c30f972a0ab 100644 --- a/specifyweb/businessrules/rules/interaction_rules.py +++ b/specifyweb/businessrules/rules/interaction_rules.py @@ -32,8 +32,8 @@ def loanprep_quantity_must_be_lte_availability(ipreparation): if ipreparation.preparation is not None: available = get_availability( ipreparation.preparation, ipreparation.id, "loanpreparationid") or 0 - quantity = ipreparation.quantity or 0 - quantityresolved = ipreparation.quantityresolved or 0 + quantity = int(ipreparation.quantity) or 0 + quantityresolved = int(ipreparation.quantityresolved) or 0 if available < (quantity - quantityresolved): raise BusinessRuleException( f"loan preparation quantity exceeds availability ({ipreparation.id}: {quantity - quantityresolved} {available})", @@ -50,7 +50,7 @@ def giftprep_quantity_must_be_lte_availability(ipreparation): if ipreparation.preparation is not None: available = get_availability( ipreparation.preparation, ipreparation.id, "giftpreparationid") or 0 - quantity = ipreparation.quantity or 0 + quantity = int(ipreparation.quantity) or 0 if available < quantity: raise BusinessRuleException( f"gift preparation quantity exceeds availability ({ipreparation.id}: {quantity} {available})", @@ -66,7 +66,7 @@ def exchangeoutprep_quantity_must_be_lte_availability(ipreparation): if ipreparation.preparation is not None: available = get_availability( ipreparation.preparation, ipreparation.id, "exchangeoutprepid") or 0 - quantity = ipreparation.quantity or 0 + quantity = int(ipreparation.quantity) or 0 if available < quantity: raise BusinessRuleException( "exchangeout preparation quantity exceeds availability ({ipreparation.id}: {quantity} {available})", From 64325c41d5192517a7bcffd36092ba4f216e9e0e Mon Sep 17 00:00:00 2001 From: alec_dev Date: Wed, 15 Jan 2025 10:16:56 -0600 Subject: [PATCH 41/80] catch loanpreparations str case from co form (cherry picked from commit 2afe7fb446afbe7fee16a148bd345ed949a23068) --- specifyweb/interactions/cog_preps.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 2796351425b..e2c576c66cb 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -540,6 +540,8 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated # Recalculate the total quantity returned and resolved for the loan preparation # based on the modified loan return preparation data. for loan_prep_idx in range(len(updated_interaction_data["loanpreparations"])): + if type(updated_interaction_data["loanpreparations"]) is str: + continue loan_return_data = updated_interaction_data["loanpreparations"][loan_prep_idx]["loanreturnpreparations"] total_quantity_returned = sum( [loan_return["quantityreturned"] for loan_return in loan_return_data]) From 2d13845695118c195ee055d6e1fcfe6c7215fa1b Mon Sep 17 00:00:00 2001 From: alec_dev Date: Wed, 15 Jan 2025 11:56:38 -0600 Subject: [PATCH 42/80] fix unconsolidated isresolved logic (cherry picked from commit 96e43e93ae8e2748a435907666853fda6840431f) --- specifyweb/interactions/cog_preps.py | 1 - 1 file changed, 1 deletion(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index e2c576c66cb..16dc82c9571 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -554,7 +554,6 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated prep_uri = updated_interaction_data["loanpreparations"][loan_prep_idx]["preparation"] prep_id = strict_uri_to_model(prep_uri, "preparation")[1] if prep_id in sibling_prep_ids or prep_id in new_loan_return_prep_ids or prep_id in target_prep_ids: - updated_interaction_data["loanpreparations"][loan_prep_idx]["isresolved"] = True quantity = updated_interaction_data["loanpreparations"][loan_prep_idx]["quantity"] if total_quantity_resolved >= quantity: updated_interaction_data["loanpreparations"][loan_prep_idx]["isresolved"] = True From af42dfa03736d98fddcf3a2b98fee135afc78753 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Wed, 22 Jan 2025 17:46:10 -0600 Subject: [PATCH 43/80] Remove unused functions --- specifyweb/interactions/cog_preps.py | 15 ----- specifyweb/interactions/views.py | 92 +--------------------------- 2 files changed, 2 insertions(+), 105 deletions(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 16dc82c9571..13ef6d12ee4 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -193,21 +193,6 @@ def add_consolidated_sibling_co_ids(request_co_ids: List[Any], id_fld: Optional[ return list(set(request_co_ids).union(set(cog_sibling_co_idfld_ids))) -def get_consolidated_co_siblings_from_rs(rs: Recordset) -> Set[Collectionobject]: - """ - Get the consolidated sibling CO IDs of the COs in the recordset - """ - cog_sibling_co_ids = set() - if is_co_recordset(rs): - cogs = get_cogs_from_co_recordset(rs) - for cog in cogs: - cog_sibling_co_ids = cog_sibling_co_ids.union( - get_cog_consolidated_preps_co_ids(cog)) - # cog_sibling_co_ids -= set(rs.recordsetitems.values_list('recordid', flat=True)) - - return cog_sibling_co_ids - - def get_co_ids_from_shared_cog_rs(rs: Recordset) -> Set[Collectionobject]: """ Get the CO IDs from the shared COGs in the recordset diff --git a/specifyweb/interactions/views.py b/specifyweb/interactions/views.py index 6ddb21ea0c9..9a4aedbfeed 100644 --- a/specifyweb/interactions/views.py +++ b/specifyweb/interactions/views.py @@ -8,89 +8,20 @@ from specifyweb.interactions.cog_preps import ( get_all_sibling_preps_within_consolidated_cog, - get_cog_consolidated_preps, - get_consolidated_co_siblings_from_rs, get_co_ids_from_shared_cog_rs, - add_consolidated_sibling_co_ids, - remove_all_cog_sibling_preps_from_loan, + add_consolidated_sibling_co_ids ) from specifyweb.middleware.general import require_GET from specifyweb.permissions.permissions import check_table_permissions, table_permissions_checker from specifyweb.specify.api import get_resource, toJson, strict_uri_to_model -from specifyweb.specify.models import Collectionobject, Collectionobjectgroup, Loan, Loanpreparation, \ +from specifyweb.specify.models import Collectionobject, Loan, Loanpreparation, \ Loanreturnpreparation, Preparation, Recordset, Recordsetitem -from specifyweb.specify.models_by_table_id import get_model_by_table_id from specifyweb.specify.views import login_maybe_required from django.db.models import F, Q, Sum from django.db.models.functions import Coalesce from django.http import JsonResponse -def preps_available_rs_django(request, recordset_id): - # Get consolidated CO ids if the recordset is a COG - rs = Recordset.objects.filter(id=recordset_id).first() - cog_co_ids = get_consolidated_co_siblings_from_rs(rs) - - # Determine if isLoan is true - isLoan = request.POST.get('isLoan', 'false').lower() == 'true' - - # Base queryset from Preparation - queryset = ( - Preparation.objects - .filter( - # The determination condition: (d.iscurrent OR d.determinationid IS NULL) - # If there are no determinations, __isnull=True covers the NULL case. - # If there is a current determination, iscurrent=True covers that case. - Q(collectionobject__determinations__iscurrent=True) | Q(collectionobject__determinations__isnull=True), - # Filter by recordset or cog_co_ids - Q(collectionobject_id__in=Recordsetitem.objects.filter(recordsetid=recordset_id).values('recordid')) | - Q(collectionobject_id__in=cog_co_ids), - # Filter by collectionmemberid - collectionmemberid=request.specify_collection.id - ) - # If isLoan is true, filter by preptype__isloanable - .filter(preptype__isloanable=True if isLoan else Q()) - # Select related to reduce queries and ensure we have needed fields - .select_related('collectionobject', 'preptype') - .prefetch_related('collectionobject__determinations__taxon') # If needed, to access taxon fullname - # Grouping fields: - # co.catalognumber, co.collectionobjectid, t.fullname, t.taxonid, p.preparationid, pt.name, p.countamt - .values( - catalognumber=F('collectionobject__catalognumber'), - co_id=F('collectionobject__id'), - fullname=F('collectionobject__determinations__taxon__fullname'), - t_id=F('collectionobject__determinations__taxon__id'), - preparationid=F('id'), - preptype_name=F('preptype__name'), - countamt=F('countamt') - ) - # Annotate sums. Use related_name based on your models: - # According to provided models: - # loanpreparations -> preparation = FK - # giftpreparations -> preparation = FK - # exchangeoutpreps -> preparation = FK - .annotate( - Loaned=Sum(F('loanpreparations__quantity') - F('loanpreparations__quantityreturned')), - Gifted=Sum('giftpreparations__quantity'), - Exchanged=Sum('exchangeoutpreps__quantity'), - LoanQtyResolved=Sum(F('loanpreparations__quantity') - F('loanpreparations__quantityresolved')) - ) - # Compute Available - .annotate( - Available=F('countamt') - - Coalesce(F('LoanQtyResolved'), 0) - - Coalesce(F('Gifted'), 0) - - Coalesce(F('Exchanged'), 0) - ) - # Order by catalognumber (equivalent to ORDER BY 1) - .order_by('catalognumber') - ) - - # Convert to list of dicts for JSON response - rows = list(queryset) - - return JsonResponse(rows, safe=False) - @require_POST # NOTE: why is this a POST request? @login_maybe_required def preps_available_rs(request, recordset_id): @@ -395,25 +326,6 @@ def prep_interactions(request): return http.HttpResponse(toJson(rows), content_type='application/json') -@require_GET -@login_maybe_required -def cog_consolidated_preps(request: http.HttpRequest, cog_id: int) -> http.JsonResponse: - """ - Returns a list of all the consolidated preparations for a given collection - """ - cog = Collectionobjectgroup.objects.get(id=cog_id) - - consolidated_preps = get_cog_consolidated_preps(cog) - - return http.JsonResponse(consolidated_preps, safe=False) - -@require_POST -@login_maybe_required -def remove_cog_consolidated_preps(request: http.HttpRequest, prep_id: int, loan_id: int): - prep = Preparation.objects.get(id=prep_id) - loan = Loan.objects.get(id=loan_id) - remove_all_cog_sibling_preps_from_loan(prep, loan) - @require_POST @login_maybe_required def create_sibling_loan_preps(request: http.HttpRequest): From 09a76e8afe737d521376be8da8982fe0f466ec1b Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 23 Jan 2025 00:01:48 +0000 Subject: [PATCH 44/80] Lint code with ESLint and Prettier Triggered by 03cb675e9ea038936d016be366b6f15da78437e9 on branch refs/heads/issue-6141 --- .../frontend/js_src/lib/components/SearchDialog/index.tsx | 2 +- .../js_src/lib/components/WbPlanView/mappingPreview.ts | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index ea01ebff46b..15a45c2ff50 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -156,7 +156,7 @@ function testFilter( ? // Cast numbers to strings values.some((value) => { const fieldValue = resource.get(field); - // eslint-disable-next-line eqeqeq + return isRelationship ? value == strictIdFromUrl(fieldValue!).toString() : value == fieldValue; diff --git a/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingPreview.ts b/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingPreview.ts index 81a2687e2f9..863234316b1 100644 --- a/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingPreview.ts +++ b/specifyweb/frontend/js_src/lib/components/WbPlanView/mappingPreview.ts @@ -141,7 +141,7 @@ export function generateMappingPathPreview( // Show filedname or not const fieldNameFormatted = fieldsToHide.has(databaseFieldName) || - (databaseTableOrRankName !== 'CollectionObject' && + (databaseTableOrRankName !== 'CollectionObject' && databaseTableOrRankName !== 'childCog' && databaseFieldName === 'name' && !isAnyRank) @@ -156,9 +156,8 @@ export function generateMappingPathPreview( const fieldIsGeneric = genericFields.has(baseFieldName) || (fieldNameFormatted?.split(' ').length === 1 && - !nonGenericFields.has(baseFieldName) && - databaseTableOrRankName !== 'childCog' - ); + !nonGenericFields.has(baseFieldName) && + databaseTableOrRankName !== 'childCog'); const tableNameNonEmpty = fieldNameFormatted === undefined From 1e78a001aa2b30a27370fe8a75cc782db1df4d4f Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 23 Jan 2025 06:41:17 -0600 Subject: [PATCH 45/80] Only create remote_to_one resources after object is created Fixes #6139 Fixes #5190 --- specifyweb/specify/api.py | 177 ++++++++++++++++++++++++++------------ 1 file changed, 120 insertions(+), 57 deletions(-) diff --git a/specifyweb/specify/api.py b/specifyweb/specify/api.py index 22dd396a305..52c2c4a5365 100644 --- a/specifyweb/specify/api.py +++ b/specifyweb/specify/api.py @@ -7,7 +7,7 @@ import logging import re from typing import Any, Dict, List, Optional, Tuple, Iterable, Union, \ - Callable, TypedDict, cast + Callable, TypedDict, Literal, cast from urllib.parse import urlencode @@ -513,7 +513,7 @@ def create_obj(collection, agent, model, data: Dict[str, Any], parent_obj=None, data = cleanData(model, data, parent_relationship) obj = model() - _, remote_to_ones, _ = handle_fk_fields(collection, agent, obj, data) + _, _, handle_remote_to_ones = handle_fk_fields(collection, agent, obj, data) set_fields_from_data(obj, data) set_field_if_exists(obj, 'createdbyagent', agent) set_field_if_exists(obj, 'collectionmemberid', collection.id) @@ -526,9 +526,7 @@ def create_obj(collection, agent, model, data: Dict[str, Any], parent_obj=None, check_table_permissions(collection, agent, obj, "create") auditlog.insert(obj, agent, parent_obj) - for (field, related) in remote_to_ones: - setattr(related, field.name, obj) - related.save() + handle_remote_to_ones(obj) handle_to_many(collection, agent, obj, data) return obj @@ -605,8 +603,7 @@ def reorder_fields_for_embedding(cls, data: Dict[str, Any]) -> Iterable[Tuple[st for key in data.keys() - {put_first}: yield (key, data[key]) - -def handle_fk_fields(collection, agent, obj, data: Dict[str, Any]) -> Tuple[List, List, List[FieldChangeInfo]]: +def handle_fk_fields(collection, agent, obj, data: Dict[str, Any]) -> Tuple[List, List[FieldChangeInfo], Callable[[Any], None]]: """Where 'obj' is a Django model instance and 'data' is a dict, set foreign key fields in the object from the provided data. """ @@ -622,54 +619,122 @@ def handle_fk_fields(collection, agent, obj, data: Dict[str, Any]) -> Tuple[List field = obj._meta.get_field(field_name) if not field.many_to_one and not field.one_to_one: continue - old_related = get_related_or_none(obj, field_name) - dependent = is_dependent_field(obj, field_name) - old_related_id = None if old_related is None else old_related.id - new_related_id = None - - if val is None: - setattr(obj, field_name, None) - rel_obj = None - if dependent and old_related: - dependents_to_delete.append(old_related) - - elif isinstance(val, field.related_model): - # The related value was patched into the data by a parent object. - setattr(obj, field_name, val) - rel_obj = val - new_related_id = val.id - - elif isinstance(val, str): - # The related object is given by a URI reference. - assert not dependent, "didn't get inline data for dependent field %s in %s: %r" % (field_name, obj, val) - fk_model, fk_id = strict_uri_to_model(val, field.related_model.__name__) - rel_obj = get_object_or_404(fk_model, id=fk_id) - setattr(obj, field_name, rel_obj) - new_related_id = fk_id - - elif hasattr(val, 'items'): # i.e. it's a dict of some sort - # The related object is represented by a nested dict of data. - rel_model = field.related_model - datamodel_field = obj.specify_model.get_relationship(field_name) - rel_obj = update_or_create_resource(collection, agent, rel_model, val, obj if dependent else None, datamodel_field) - - setattr(obj, field_name, rel_obj) - if dependent and old_related and old_related.id != rel_obj.id: - dependents_to_delete.append(old_related) - new_related_id = rel_obj.id - data[field_name] = _obj_to_data(rel_obj, read_checker) + if field.concrete: + some_remote_to_ones = [] + extra_data, some_dependents_to_delete, some_dirty = _handle_fk_field(collection, agent, obj, field, val, read_checker) else: - raise Exception(f'bad foreign key field in data: {field_name}') - - if str(old_related_id) != str(new_related_id): - dirty.append({'field_name': field_name, 'old_value': old_related_id, 'new_value': new_related_id}) + extra_data = dict() + some_dependents_to_delete, some_dirty, some_remote_to_ones = _handle_remote_fk_field(obj, field, val, read_checker) - # If the field is remote, the obj must be set on the remote side once - # the obj exists - if not field.concrete and rel_obj is not None: - remote_to_ones.append((field.remote_field, rel_obj)) + data.update(extra_data) + dirty += some_dirty + dependents_to_delete += some_dependents_to_delete + remote_to_ones += some_remote_to_ones + + def _set_remote_to_ones(created_obj): + for field, related_data, is_dependent in remote_to_ones: + related_data[field.name] = created_obj + rel_obj = update_or_create_resource(collection, agent, field.model, related_data, created_obj if is_dependent else None) + setattr(obj, field.remote_field.name, rel_obj) + + return dependents_to_delete, dirty, _set_remote_to_ones + +def _handle_fk_field(collection, agent, obj, field, value, read_checker): + field_name = field.name + old_related = get_related_or_none(obj, field_name) + dependent = is_dependent_field(obj, field_name) + old_related_id = None if old_related is None else old_related.id + new_related_id = None + + dependents_to_delete = [] + dirty: List[FieldChangeInfo] = [] + data = dict() + + if value is None: + setattr(obj, field_name, None) + rel_obj = None + if dependent and old_related: + dependents_to_delete.append(old_related) + + elif isinstance(value, field.related_model): + # The related value was patched into the data by a parent object. + setattr(obj, field_name, value) + rel_obj = value + new_related_id = value.id + + elif isinstance(value, str): + # The related object is given by a URI reference. + assert not dependent, "didn't get inline data for dependent field %s in %s: %r" % (field_name, obj, value) + fk_model, fk_id = strict_uri_to_model(value, field.related_model.__name__) + rel_obj = get_object_or_404(fk_model, id=fk_id) + setattr(obj, field_name, rel_obj) + new_related_id = fk_id + + elif hasattr(value, 'items'): # i.e. it's a dict of some sort + # The related object is represented by a nested dict of data. + rel_model = field.related_model + datamodel_field = obj.specify_model.get_relationship(field_name) + rel_obj = update_or_create_resource(collection, agent, rel_model, value, obj if dependent else None, datamodel_field) + + setattr(obj, field_name, rel_obj) + if dependent and old_related and old_related.id != rel_obj.id: + dependents_to_delete.append(old_related) + new_related_id = rel_obj.id + data[field_name] = _obj_to_data(rel_obj, read_checker) + else: + raise Exception(f'bad foreign key field in data: {field_name}') + + if str(old_related_id) != str(new_related_id): + dirty.append({'field_name': field_name, 'old_value': old_related_id, 'new_value': new_related_id}) + return data, dependents_to_delete, dirty + +def _handle_remote_fk_field(obj, field, value, read_checker): + field_name = field.name + old_related = get_related_or_none(obj, field_name) + dependent = is_dependent_field(obj, field_name) + old_related_id = None if old_related is None else old_related.id + new_related_id = None - return dependents_to_delete, remote_to_ones, dirty + remote_to_ones = [] + dependents_to_delete = [] + dirty: List[FieldChangeInfo] = [] + + if value is None: + rel_data = None + setattr(obj, field_name, None) + if dependent and old_related: + dependents_to_delete.append(old_related) + + elif isinstance(value, field.related_model): + # The related value was patched into the data by a parent object. + setattr(obj, field_name, value) + rel_data = _obj_to_data(value, read_checker) + new_related_id = value.id + + elif isinstance(value, str): + # The related object is given by a URI reference. + assert not dependent, "didn't get inline data for dependent field %s in %s: %r" % (field_name, obj, value) + fk_model, fk_id = strict_uri_to_model(value, field.related_model.__name__) + rel_obj = get_object_or_404(fk_model, id=fk_id) + setattr(obj, field_name, rel_obj) + rel_data = _obj_to_data(rel_obj, read_checker) + new_related_id = rel_obj.pk + + elif hasattr(value, 'items'): # i.e. it's a dict of some sort + # The related object is represented by a nested dict of data. + rel_data = value + new_related_id = value.get("id", None) + if dependent and old_related and new_related_id and old_related.id != new_related_id: + dependents_to_delete.append(old_related) + else: + raise Exception(f'bad foreign key field in data: {field_name}') + + if str(old_related_id) != str(new_related_id): + dirty.append({'field_name': field_name, 'old_value': old_related_id, 'new_value': new_related_id}) + + if not rel_data is None: + remote_to_ones.append((field.remote_field, rel_data, dependent)) + return dependents_to_delete, dirty, remote_to_ones def handle_to_many(collection, agent, obj, data: Dict[str, Any]) -> None: """For every key in the dict 'data' which is a *-to-many field in the @@ -705,7 +770,7 @@ def handle_to_many(collection, agent, obj, data: Dict[str, Any]) -> None: def _handle_dependent_to_many(collection, agent, obj, field, value): if not isinstance(value, list): assert isinstance(value, list), "didn't get inline data for dependent field %s in %s: %r" % (field.name, obj, value) - + rel_model = field.related_model ids = [] # Ids not in this list will be deleted at the end. @@ -831,7 +896,7 @@ def update_obj(collection, agent, name: str, id, version, data: Dict[str, Any], check_table_permissions(collection, agent, obj, "update") data = cleanData(obj.__class__, data, parent_relationship) - dependents_to_delete, remote_to_ones, fk_dirty = handle_fk_fields(collection, agent, obj, data) + dependents_to_delete, fk_dirty, handle_remote_to_ones = handle_fk_fields(collection, agent, obj, data) dirty = fk_dirty + set_fields_from_data(obj, data) check_field_permissions(collection, agent, obj, [d['field_name'] for d in dirty], "update") @@ -849,9 +914,7 @@ def update_obj(collection, agent, name: str, id, version, data: Dict[str, Any], auditlog.update(obj, agent, parent_obj, dirty) for dep in dependents_to_delete: delete_obj(dep, parent_obj=obj, collection=collection, agent=agent) - for (field, related) in remote_to_ones: - setattr(related, field.name, obj) - related.save() + handle_remote_to_ones(obj) handle_to_many(collection, agent, obj, data) return obj From 0c88861517a59b9fc3dcb4ea66d7b93c06a2b280 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 23 Jan 2025 06:43:12 -0600 Subject: [PATCH 46/80] Add tests for remote_to_one relationships in the api --- specifyweb/specify/tests/test_api.py | 86 ++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/specifyweb/specify/tests/test_api.py b/specifyweb/specify/tests/test_api.py index 0c0aa22a489..b1876dae413 100644 --- a/specifyweb/specify/tests/test_api.py +++ b/specifyweb/specify/tests/test_api.py @@ -690,6 +690,92 @@ def test_skipping_redundant_resources(self): accession = api.create_obj(self.collection, self.agent, 'Accession', accession_data) self.assertFalse(models.Accession.objects.filter(accessionnumber=redundant_accession_number).exists()) self.assertFalse(models.Collectionobject.objects.filter(catalognumber=redundant_catalog_number).exists()) + +class InlineApiRemoteToOneTests(ApiTests): + def setUp(self): + super(InlineApiRemoteToOneTests, self).setUp() + cog_type_picklist = Picklist.objects.create( + name=SYSTEM_COGTYPES_PICKLIST, + issystem=True, + type=0, + readonly=True, + collection=self.collection + ) + Picklistitem.objects.create( + title='Discrete', + value='Discrete', + picklist=cog_type_picklist + ) + self.cogtype = models.Collectionobjectgrouptype.objects.create( + name="Discrete", type="Discrete", collection=self.collection + ) + self.cog_parent = models.Collectionobjectgroup.objects.create( + name="Parent", + cogtype=self.cogtype, + collection=self.collection, + ) + + def test_setting_remote_to_one_from_new(self): + co_data = { + "catalognumber": f'num-{len(self.collectionobjects)}', + "cojo": { + "isPrimary": True, + "isSubstrate": False, + "parentCog": api.uri_for_model("Collectionobjectgroup", self.cog_parent.id) + }, + 'collection': api.uri_for_model('Collection', self.collection.id), + } + co = api.create_obj(self.collection, self.agent, "Collectionobject", co_data) + cojo = models.Collectionobjectgroupjoin.objects.get(parentcog_id=self.cog_parent.id, childco=co) + self.assertEqual(co.cojo, cojo) + + def test_setting_remote_to_one_from_existing(self): + existing_co = self.collectionobjects[0] + co_data = { + **api.obj_to_data(existing_co), + "cojo": { + "isPrimary": True, + "isSubstrate": False, + "parentCog": api.uri_for_model("Collectionobjectgroup", self.cog_parent.id) + }, + } + co = api.update_obj(self.collection, self.agent, "Collectionobject", existing_co.id, existing_co.version, co_data) + cojo = models.Collectionobjectgroupjoin.objects.get(parentcog_id=self.cog_parent.id, childco=co) + self.assertEqual(co.cojo, cojo) + + def test_creating_independent_from_remote_one_to_one(self): + new_parent_name = "ParentTwo" + co_data = { + "catalognumber": f'num-{len(self.collectionobjects)}', + "cojo": { + "isPrimary": True, + "isSubstrate": False, + "parentCog": { + "name": new_parent_name, + "cogtype": api.uri_for_model("Collectionobjectgrouptype", self.cogtype.id), + 'collection': api.uri_for_model('Collection', self.collection.id) + } + }, + 'collection': api.uri_for_model('Collection', self.collection.id), + } + co = api.create_obj(self.collection, self.agent, "Collectionobject", co_data) + cojo = models.Collectionobjectgroupjoin.objects.get(parentcog__name=new_parent_name, childco=co) + + self.assertEqual(co.cojo, cojo) + self.assertEqual(co.cojo.parentcog.name, new_parent_name) + + def test_unsetting_dependent_remote_one_to_one(self): + existing_co = self.collectionobjects[1] + cojo = models.Collectionobjectgroupjoin.objects.create(isprimary=False, parentcog=self.cog_parent,childco=existing_co) + existing_co.refresh_from_db() + self.assertEqual(existing_co.cojo, cojo) + co_data = { + **api.obj_to_data(existing_co), + "cojo": None, + } + co = api.update_obj(self.collection, self.agent, "Collectionobject", existing_co.id, existing_co.version, co_data) + self.assertIsNone(api.get_related_or_none(co, "cojo")) + self.assertFalse(models.Collectionobjectgroupjoin.objects.filter(childco_id=co.id).exists()) # version control on inlined resources should be tested From 99351952dff38ad4b82e7cdad77786b9a75bf334 Mon Sep 17 00:00:00 2001 From: melton-jason Date: Thu, 23 Jan 2025 06:43:52 -0600 Subject: [PATCH 47/80] Add tests for co child parity businessrule --- specifyweb/businessrules/tests/test_cojo.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/specifyweb/businessrules/tests/test_cojo.py b/specifyweb/businessrules/tests/test_cojo.py index 0c28acfacde..e1952a13d8f 100644 --- a/specifyweb/businessrules/tests/test_cojo.py +++ b/specifyweb/businessrules/tests/test_cojo.py @@ -1,4 +1,5 @@ -from specifyweb.specify.models import Collectionobjectgroup, Collectionobjectgroupjoin, Collectionobjectgrouptype, Picklist, Picklistitem +from specifyweb.specify.models import Collectionobjectgroup, Collectionobjectgroupjoin, Collectionobjectgrouptype +from specifyweb.businessrules.exceptions import BusinessRuleException from specifyweb.specify.tests.test_api import DefaultsSetup class CoJoTest(DefaultsSetup): @@ -58,3 +59,21 @@ def test_cojo_rules_enforcement(self): self.assertTrue(cojo_2.issubstrate) self.assertFalse(cojo_3.isprimary) self.assertFalse(cojo_3.issubstrate) + + with self.assertRaises(BusinessRuleException): + Collectionobjectgroupjoin.objects.create( + isprimary=False, + issubstrate=False, + parentcog=cog_1, + childcog=cog_4, + childco=self.collectionobjects[0] + ) + + with self.assertRaises(BusinessRuleException): + Collectionobjectgroupjoin.objects.create( + isprimary=False, + issubstrate=False, + parentcog=cog_1, + childcog=None, + childco=None + ) From 5d8fafaa1cbd0acc75100399ce9675ccbf6dc7e6 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Thu, 23 Jan 2025 07:21:04 -0800 Subject: [PATCH 48/80] Clear cache when chnaging collection Fixes #6116 --- .../lib/components/RouterCommands/SwitchCollection.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/RouterCommands/SwitchCollection.tsx b/specifyweb/frontend/js_src/lib/components/RouterCommands/SwitchCollection.tsx index f88cc481a03..aeb54a2407e 100644 --- a/specifyweb/frontend/js_src/lib/components/RouterCommands/SwitchCollection.tsx +++ b/specifyweb/frontend/js_src/lib/components/RouterCommands/SwitchCollection.tsx @@ -7,6 +7,7 @@ import { useAsyncState } from '../../hooks/useAsyncState'; import { toLocalUrl } from '../../utils/ajax/helpers'; import { ping } from '../../utils/ajax/ping'; import { formatUrl } from '../Router/queryString'; +import { clearAllCache } from './CacheBuster'; export const switchCollection = ( navigate: SafeNavigateFunction, @@ -40,7 +41,9 @@ export function SwitchCollectionCommand(): null { method: 'POST', body: collectionId!.toString(), errorMode: 'dismissible', - }).then(() => globalThis.location.replace(nextUrl)), + }) + .then(clearAllCache) + .then(() => globalThis.location.replace(nextUrl)), [collectionId, nextUrl] ), true From 8f839ea5db0902e3f014f52c436fdf03fe39decf Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 17:37:52 +0000 Subject: [PATCH 49/80] Lint code with ESLint and Prettier Triggered by bc31484bb538d187961348226326e60331155713 on branch refs/heads/issue-6022 --- .../frontend/js_src/lib/components/SearchDialog/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx index ea01ebff46b..15a45c2ff50 100644 --- a/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/SearchDialog/index.tsx @@ -156,7 +156,7 @@ function testFilter( ? // Cast numbers to strings values.some((value) => { const fieldValue = resource.get(field); - // eslint-disable-next-line eqeqeq + return isRelationship ? value == strictIdFromUrl(fieldValue!).toString() : value == fieldValue; From 39dee4c8f307bc66689a2185d90dd709ce096509 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 12:18:54 -0600 Subject: [PATCH 50/80] import fix --- specifyweb/stored_queries/build_models.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/specifyweb/stored_queries/build_models.py b/specifyweb/stored_queries/build_models.py index a6fdaca7a84..2577ebe0496 100644 --- a/specifyweb/stored_queries/build_models.py +++ b/specifyweb/stored_queries/build_models.py @@ -119,9 +119,8 @@ def make_relationship(reldef): map_class(tabledef) -# NOTE: Possible new functions with process_boolean_field +# NOTE: Possible new functions with process_boolean_field, use database connection to check column type from sqlalchemy import inspect -from sqlalchemy.dialects.mysql import BIT from sqlalchemy.types import Boolean def process_boolean_field(field, engine): @@ -147,7 +146,7 @@ def process_boolean_field(field, engine): for column in columns: if column['name'] == column_name: # Check for BIT type - if isinstance(column['type'], BIT): + if isinstance(column['type'], mysql_bit_type): return CustomBIT() # Check for TINYINT type (interpreted as Boolean by SQLAlchemy) elif isinstance(column['type'], Boolean): From 76caef5ec521f9b5fba19d7a2bd133bdb32fa4cb Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 12:41:58 -0600 Subject: [PATCH 51/80] comment out unused code --- specifyweb/stored_queries/build_models.py | 130 +++++++++++----------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/specifyweb/stored_queries/build_models.py b/specifyweb/stored_queries/build_models.py index 2577ebe0496..1ad7160f893 100644 --- a/specifyweb/stored_queries/build_models.py +++ b/specifyweb/stored_queries/build_models.py @@ -119,68 +119,68 @@ def make_relationship(reldef): map_class(tabledef) -# NOTE: Possible new functions with process_boolean_field, use database connection to check column type -from sqlalchemy import inspect -from sqlalchemy.types import Boolean - -def process_boolean_field(field, engine): - """ - Dynamically determines the type of a boolean field (BIT(1) or TINYINT) - and returns the appropriate SQLAlchemy type. - - Args: - field: The SQLAlchemy column object to process. - engine: The SQLAlchemy engine connected to the database. - - Returns: - The appropriate SQLAlchemy type (CustomBIT or Boolean). - """ - # Use SQLAlchemy's inspector to get column details - inspector = inspect(engine) - table_name = field.table.name - column_name = field.name - - # Get the column metadata from the table - columns = inspector.get_columns(table_name) - - for column in columns: - if column['name'] == column_name: - # Check for BIT type - if isinstance(column['type'], mysql_bit_type): - return CustomBIT() - # Check for TINYINT type (interpreted as Boolean by SQLAlchemy) - elif isinstance(column['type'], Boolean): - return Boolean - else: - raise ValueError(f"Unsupported boolean column type: {column['type']}") - raise ValueError(f"Column {column_name} not found in table {table_name}.") - -def new_make_column(flddef: Field, engine): - # Dynamically process boolean fields - if flddef.type == 'java.lang.Boolean': - field_type = process_boolean_field(flddef, engine) - else: - field_type = field_type_map[flddef.type] - - if hasattr(flddef, 'length') and flddef.length and field_type in (types.Text, types.String): - field_type = field_type(flddef.length) - - return Column(flddef.column, - field_type, - index=flddef.indexed, - unique=flddef.unique, - nullable=not flddef.required) - -def new_make_table(datamodel: Datamodel, tabledef: Table, engine): - columns = [Column(tabledef.idColumn, types.Integer, primary_key=True)] - - # Pass the engine to `make_column` - columns.extend(make_column(field, engine) for field in tabledef.fields) - - for reldef in tabledef.relationships: - if reldef.type in ('many-to-one', 'one-to-one') and hasattr(reldef, 'column') and reldef.column: - fk = make_foreign_key(datamodel, reldef) - if fk is not None: - columns.append(fk) - - return Table_Sqlalchemy(tabledef.table, metadata, *columns) \ No newline at end of file +# # NOTE: Possible new functions with process_boolean_field, use database connection to check column type +# from sqlalchemy import inspect +# from sqlalchemy.types import Boolean + +# def process_boolean_field(field, engine): +# """ +# Dynamically determines the type of a boolean field (BIT(1) or TINYINT) +# and returns the appropriate SQLAlchemy type. + +# Args: +# field: The SQLAlchemy column object to process. +# engine: The SQLAlchemy engine connected to the database. + +# Returns: +# The appropriate SQLAlchemy type (CustomBIT or Boolean). +# """ +# # Use SQLAlchemy's inspector to get column details +# inspector = inspect(engine) +# table_name = field.table.name +# column_name = field.name + +# # Get the column metadata from the table +# columns = inspector.get_columns(table_name) + +# for column in columns: +# if column['name'] == column_name: +# # Check for BIT type +# if isinstance(column['type'], mysql_bit_type): +# return CustomBIT() +# # Check for TINYINT type (interpreted as Boolean by SQLAlchemy) +# elif isinstance(column['type'], Boolean): +# return Boolean +# else: +# raise ValueError(f"Unsupported boolean column type: {column['type']}") +# raise ValueError(f"Column {column_name} not found in table {table_name}.") + +# def new_make_column(flddef: Field, engine): +# # Dynamically process boolean fields +# if flddef.type == 'java.lang.Boolean': +# field_type = process_boolean_field(flddef, engine) +# else: +# field_type = field_type_map[flddef.type] + +# if hasattr(flddef, 'length') and flddef.length and field_type in (types.Text, types.String): +# field_type = field_type(flddef.length) + +# return Column(flddef.column, +# field_type, +# index=flddef.indexed, +# unique=flddef.unique, +# nullable=not flddef.required) + +# def new_make_table(datamodel: Datamodel, tabledef: Table, engine): +# columns = [Column(tabledef.idColumn, types.Integer, primary_key=True)] + +# # Pass the engine to `make_column` +# columns.extend(make_column(field, engine) for field in tabledef.fields) + +# for reldef in tabledef.relationships: +# if reldef.type in ('many-to-one', 'one-to-one') and hasattr(reldef, 'column') and reldef.column: +# fk = make_foreign_key(datamodel, reldef) +# if fk is not None: +# columns.append(fk) + +# return Table_Sqlalchemy(tabledef.table, metadata, *columns) \ No newline at end of file From 956976ae49ebcd74f56f0d0dd41cfe9c65fb04b2 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 12:57:08 -0600 Subject: [PATCH 52/80] fix loanreturnpreparations key error --- specifyweb/interactions/cog_preps.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 13ef6d12ee4..0558d8bc7fc 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -380,7 +380,11 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated prep_uri, "preparation") if prep_uri is not None else [None, None] map_prep_id_to_loan_prep_idx[prep_id] = loan_prep_idx loan_prep_idx += 1 - loan_return_prep_data_lst = loan_prep_data["loanreturnpreparations"] + loan_return_prep_data_lst = ( + loan_prep_data["loanreturnpreparations"] + if "loanreturnpreparations" in loan_prep_data.keys() + else [] + ) # Continue if the loan preparation has no new loan return preparation data, # or if there are more than one loan return preparation data (consolidated COG prep have no partial returns) @@ -527,7 +531,14 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated for loan_prep_idx in range(len(updated_interaction_data["loanpreparations"])): if type(updated_interaction_data["loanpreparations"]) is str: continue - loan_return_data = updated_interaction_data["loanpreparations"][loan_prep_idx]["loanreturnpreparations"] + loan_return_data = ( + updated_interaction_data["loanpreparations"][loan_prep_idx][ + "loanreturnpreparations" + ] + if "loanreturnpreparations" + in updated_interaction_data["loanpreparations"][loan_prep_idx].keys() + else [] + ) total_quantity_returned = sum( [loan_return["quantityreturned"] for loan_return in loan_return_data]) total_quantity_resolved = sum( From a0b296a9192802fd2c46ab6cee7b4a0d1cfb35f8 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 13:06:57 -0600 Subject: [PATCH 53/80] remove secondary solution --- specifyweb/stored_queries/build_models.py | 67 ----------------------- 1 file changed, 67 deletions(-) diff --git a/specifyweb/stored_queries/build_models.py b/specifyweb/stored_queries/build_models.py index 1ad7160f893..2c0d7c36b1c 100644 --- a/specifyweb/stored_queries/build_models.py +++ b/specifyweb/stored_queries/build_models.py @@ -117,70 +117,3 @@ def make_relationship(reldef): for tabledef in datamodel.tables: map_class(tabledef) - - -# # NOTE: Possible new functions with process_boolean_field, use database connection to check column type -# from sqlalchemy import inspect -# from sqlalchemy.types import Boolean - -# def process_boolean_field(field, engine): -# """ -# Dynamically determines the type of a boolean field (BIT(1) or TINYINT) -# and returns the appropriate SQLAlchemy type. - -# Args: -# field: The SQLAlchemy column object to process. -# engine: The SQLAlchemy engine connected to the database. - -# Returns: -# The appropriate SQLAlchemy type (CustomBIT or Boolean). -# """ -# # Use SQLAlchemy's inspector to get column details -# inspector = inspect(engine) -# table_name = field.table.name -# column_name = field.name - -# # Get the column metadata from the table -# columns = inspector.get_columns(table_name) - -# for column in columns: -# if column['name'] == column_name: -# # Check for BIT type -# if isinstance(column['type'], mysql_bit_type): -# return CustomBIT() -# # Check for TINYINT type (interpreted as Boolean by SQLAlchemy) -# elif isinstance(column['type'], Boolean): -# return Boolean -# else: -# raise ValueError(f"Unsupported boolean column type: {column['type']}") -# raise ValueError(f"Column {column_name} not found in table {table_name}.") - -# def new_make_column(flddef: Field, engine): -# # Dynamically process boolean fields -# if flddef.type == 'java.lang.Boolean': -# field_type = process_boolean_field(flddef, engine) -# else: -# field_type = field_type_map[flddef.type] - -# if hasattr(flddef, 'length') and flddef.length and field_type in (types.Text, types.String): -# field_type = field_type(flddef.length) - -# return Column(flddef.column, -# field_type, -# index=flddef.indexed, -# unique=flddef.unique, -# nullable=not flddef.required) - -# def new_make_table(datamodel: Datamodel, tabledef: Table, engine): -# columns = [Column(tabledef.idColumn, types.Integer, primary_key=True)] - -# # Pass the engine to `make_column` -# columns.extend(make_column(field, engine) for field in tabledef.fields) - -# for reldef in tabledef.relationships: -# if reldef.type in ('many-to-one', 'one-to-one') and hasattr(reldef, 'column') and reldef.column: -# fk = make_foreign_key(datamodel, reldef) -# if fk is not None: -# columns.append(fk) - -# return Table_Sqlalchemy(tabledef.table, metadata, *columns) \ No newline at end of file From 1bf1d16910c6b4bfff987f176ee074afdf95aaf1 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 13:15:12 -0600 Subject: [PATCH 54/80] handle preparation key error --- specifyweb/interactions/cog_preps.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 0558d8bc7fc..aca5f5fd8b6 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -547,7 +547,12 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated updated_interaction_data["loanpreparations"][loan_prep_idx]["quantityreturned"] = total_quantity_returned # Set the modified loan prep isresolved to True if all the preparations are resolved - prep_uri = updated_interaction_data["loanpreparations"][loan_prep_idx]["preparation"] + prep_uri = ( + updated_interaction_data["loanpreparations"][loan_prep_idx]["preparation"] + if "preparation" + in updated_interaction_data["loanpreparations"][loan_prep_idx].keys() + else None + ) prep_id = strict_uri_to_model(prep_uri, "preparation")[1] if prep_id in sibling_prep_ids or prep_id in new_loan_return_prep_ids or prep_id in target_prep_ids: quantity = updated_interaction_data["loanpreparations"][loan_prep_idx]["quantity"] From be98e8f4e213431015998244264ce80c9fb05d4b Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 13:39:05 -0600 Subject: [PATCH 55/80] handle null prep_uri --- specifyweb/interactions/cog_preps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index aca5f5fd8b6..f677eba0270 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -553,7 +553,7 @@ def modify_update_of_loan_return_sibling_preps(original_interaction_obj, updated in updated_interaction_data["loanpreparations"][loan_prep_idx].keys() else None ) - prep_id = strict_uri_to_model(prep_uri, "preparation")[1] + prep_id = strict_uri_to_model(prep_uri, "preparation")[1] if prep_uri is not None else None if prep_id in sibling_prep_ids or prep_id in new_loan_return_prep_ids or prep_id in target_prep_ids: quantity = updated_interaction_data["loanpreparations"][loan_prep_idx]["quantity"] if total_quantity_resolved >= quantity: From d64f805bd9284986ac400d889ebb6c7e47306770 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 16:04:39 -0600 Subject: [PATCH 56/80] try new docker fix --- Dockerfile | 2 +- specifyweb/interactions/cog_preps.py | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 278fa24e23f..2190d61107b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -60,7 +60,7 @@ COPY --chown=specify:specify requirements.txt /home/specify/ WORKDIR /opt/specify7 RUN python3.8 -m venv ve \ - && ve/bin/pip install --no-cache-dir -r /home/specify/requirements.txt + && ve/bin/pip install -v --no-cache-dir -r /home/specify/requirements.txt RUN ve/bin/pip install --no-cache-dir gunicorn COPY --from=build-frontend /home/node/dist specifyweb/frontend/static/js diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index 13ef6d12ee4..f0548b9d1bb 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -1,4 +1,3 @@ -import re import logging from typing import Any, List, Optional, Set from django.db.models import Subquery From 4e7a1814e2d90d41f2a4e9fef19651e1a4d50c72 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 16:18:21 -0600 Subject: [PATCH 57/80] fix pycryptodome dependencies --- Dockerfile | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 2190d61107b..1a2e411f264 100644 --- a/Dockerfile +++ b/Dockerfile @@ -48,12 +48,17 @@ RUN apt-get update \ ca-certificates \ curl \ git \ - libldap2-dev \ - libmariadbclient-dev \ libsasl2-dev \ + libsasl2-modules-gssapi-mit \ + libldap2-dev \ + libssl-dev \ + libgmp-dev \ + libffi-dev \ python3.8-venv \ python3.8-distutils \ - python3.8-dev + python3.8-dev \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* USER specify COPY --chown=specify:specify requirements.txt /home/specify/ From acbf45367b2ee7e0c27de48f1f0d14b824c6aa1b Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 16:23:04 -0600 Subject: [PATCH 58/80] pip pycryptodome fix --- Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dockerfile b/Dockerfile index 1a2e411f264..43dbe3af3f5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -65,6 +65,8 @@ COPY --chown=specify:specify requirements.txt /home/specify/ WORKDIR /opt/specify7 RUN python3.8 -m venv ve \ + && ve/bin/pip install --no-cache-dir --upgrade pip setuptools wheel \ + && ve/bin/pip install --no-cache-dir --only-binary=:all: pycryptodome==3.14.1 \ && ve/bin/pip install -v --no-cache-dir -r /home/specify/requirements.txt RUN ve/bin/pip install --no-cache-dir gunicorn From 7e226d31338723f8a27a94269247987eea4d1046 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 16:23:56 -0600 Subject: [PATCH 59/80] try default-libmysqlclient-dev --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 43dbe3af3f5..11eba490d2d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,6 +57,7 @@ RUN apt-get update \ python3.8-venv \ python3.8-distutils \ python3.8-dev \ + default-libmysqlclient-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* @@ -66,7 +67,6 @@ COPY --chown=specify:specify requirements.txt /home/specify/ WORKDIR /opt/specify7 RUN python3.8 -m venv ve \ && ve/bin/pip install --no-cache-dir --upgrade pip setuptools wheel \ - && ve/bin/pip install --no-cache-dir --only-binary=:all: pycryptodome==3.14.1 \ && ve/bin/pip install -v --no-cache-dir -r /home/specify/requirements.txt RUN ve/bin/pip install --no-cache-dir gunicorn From c98d279116da5d398b403b65093d21a480108ba2 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Thu, 23 Jan 2025 16:37:41 -0600 Subject: [PATCH 60/80] trigger backend test --- specifyweb/interactions/cog_preps.py | 1 + 1 file changed, 1 insertion(+) diff --git a/specifyweb/interactions/cog_preps.py b/specifyweb/interactions/cog_preps.py index f0548b9d1bb..13ef6d12ee4 100644 --- a/specifyweb/interactions/cog_preps.py +++ b/specifyweb/interactions/cog_preps.py @@ -1,3 +1,4 @@ +import re import logging from typing import Any, List, Optional, Set from django.db.models import Subquery From e245b47fb05733013cb7610ed091fd6a5aa2235f Mon Sep 17 00:00:00 2001 From: alec_dev Date: Fri, 24 Jan 2025 10:12:09 -0600 Subject: [PATCH 61/80] Dockerfile build fix --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 11eba490d2d..6c946ef85b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,7 +57,7 @@ RUN apt-get update \ python3.8-venv \ python3.8-distutils \ python3.8-dev \ - default-libmysqlclient-dev \ + libmariadbclient-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* From 4a7a0ea6cc166f6096466778f347969ff3d58eb0 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Fri, 24 Jan 2025 10:11:04 -0800 Subject: [PATCH 62/80] Clear cache on logout --- .../js_src/lib/components/Header/UserTools.tsx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx b/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx index 28b5ebaee67..a90681acd6a 100644 --- a/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx +++ b/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx @@ -18,6 +18,7 @@ import { userInformation } from '../InitialContext/userInformation'; import { Dialog, LoadingScreen } from '../Molecules/Dialog'; import { OverlayContext } from '../Router/Router'; import { locationToState } from '../Router/RouterState'; +import { clearAllCache } from '../RouterCommands/CacheBuster'; import { MenuButton } from './index'; import { useUserTools } from './menuItemProcessing'; @@ -144,6 +145,18 @@ function UserToolsColumn({ const isExternalLink = isExternalUrl(url); // Make links to another entrypoint trigger page reload const LinkComponent = isExternalLink ? Link.NewTab : Link.Default; + + const handleClick = async (): Promise => { + if (url === '/accounts/logout/') { + await clearAllCache(); + } + }; + + const handleOnClick = ():void => { + handleClick().catch((error) => { + console.error('Error occurred during cache clearing:', error); + }); + }; return (
  • {icon} {title} From b75c34650d56ea8a3a200ec3c811918a20af8799 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Fri, 24 Jan 2025 12:57:34 -0600 Subject: [PATCH 63/80] try pycryptodome upgrade from 3.15.0 to 3.21.0 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index d85e6e1ba9f..a2b56244cdb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,7 +4,7 @@ Django==3.2.15 mysqlclient==2.1.1 SQLAlchemy==1.2.11 requests==2.32.2 -pycryptodome==3.15.0 +pycryptodome==3.21.0 PyJWT==2.3.0 django-auth-ldap==1.2.15 jsonschema==3.2.0 From e501d990704cb96756f7a269eadf945e906c95a3 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Fri, 24 Jan 2025 11:15:13 -0800 Subject: [PATCH 64/80] Create a onClick for userTools --- .../frontend/js_src/lib/components/Core/Main.tsx | 1 + .../js_src/lib/components/Header/UserTools.tsx | 16 ++-------------- .../lib/components/Header/userToolDefinitions.ts | 8 ++++++++ 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/Core/Main.tsx b/specifyweb/frontend/js_src/lib/components/Core/Main.tsx index 63f43aeeb04..9f9383537b4 100644 --- a/specifyweb/frontend/js_src/lib/components/Core/Main.tsx +++ b/specifyweb/frontend/js_src/lib/components/Core/Main.tsx @@ -25,6 +25,7 @@ export type MenuItem = { readonly enabled?: () => Promise | boolean; readonly icon: JSX.Element; readonly name: string; + readonly onClick?: () => Promise; }; /* diff --git a/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx b/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx index a90681acd6a..e0112ed9034 100644 --- a/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx +++ b/specifyweb/frontend/js_src/lib/components/Header/UserTools.tsx @@ -18,7 +18,6 @@ import { userInformation } from '../InitialContext/userInformation'; import { Dialog, LoadingScreen } from '../Molecules/Dialog'; import { OverlayContext } from '../Router/Router'; import { locationToState } from '../Router/RouterState'; -import { clearAllCache } from '../RouterCommands/CacheBuster'; import { MenuButton } from './index'; import { useUserTools } from './menuItemProcessing'; @@ -141,22 +140,11 @@ function UserToolsColumn({

    {groupName}

      - {userTools.map(({ title, url, icon }) => { + {userTools.map(({ title, url, icon, onClick }) => { const isExternalLink = isExternalUrl(url); // Make links to another entrypoint trigger page reload const LinkComponent = isExternalLink ? Link.NewTab : Link.Default; - const handleClick = async (): Promise => { - if (url === '/accounts/logout/') { - await clearAllCache(); - } - }; - - const handleOnClick = ():void => { - handleClick().catch((error) => { - console.error('Error occurred during cache clearing:', error); - }); - }; return (
    • {icon} {title} diff --git a/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts b/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts index ab9e8ea752a..22cfe0219bc 100644 --- a/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts +++ b/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts @@ -19,6 +19,7 @@ import { hasTablePermission, hasToolPermission, } from '../Permissions/helpers'; +import { clearAllCache } from '../RouterCommands/CacheBuster'; import { filterMenuItems } from './menuItemProcessing'; const rawUserTools = ensure>>>()({ @@ -28,6 +29,13 @@ const rawUserTools = ensure>>>()({ url: '/accounts/logout/', icon: icons.logout, enabled: () => userInformation.isauthenticated, + onClick: async () => clearAllCache() + .then(() => { + console.log('Cache cleared successfully.'); + }) + .catch((error) => { + console.error('Error occurred during cache clearing:', error); + }), }, changePassword: { title: userText.changePassword(), From 198199fecc7af285aa7ab1bf1cce12a1a904e821 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Fri, 24 Jan 2025 19:19:23 +0000 Subject: [PATCH 65/80] Lint code with ESLint and Prettier Triggered by e501d990704cb96756f7a269eadf945e906c95a3 on branch refs/heads/issue-6116 --- .../lib/components/Header/userToolDefinitions.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts b/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts index 22cfe0219bc..cc1172d414d 100644 --- a/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts +++ b/specifyweb/frontend/js_src/lib/components/Header/userToolDefinitions.ts @@ -29,13 +29,14 @@ const rawUserTools = ensure>>>()({ url: '/accounts/logout/', icon: icons.logout, enabled: () => userInformation.isauthenticated, - onClick: async () => clearAllCache() - .then(() => { - console.log('Cache cleared successfully.'); - }) - .catch((error) => { - console.error('Error occurred during cache clearing:', error); - }), + onClick: async () => + clearAllCache() + .then(() => { + console.log('Cache cleared successfully.'); + }) + .catch((error) => { + console.error('Error occurred during cache clearing:', error); + }), }, changePassword: { title: userText.changePassword(), From 0c78559b2b59e36fb84b7ee66f35da196fd2c99d Mon Sep 17 00:00:00 2001 From: alec_dev Date: Fri, 24 Jan 2025 13:50:12 -0600 Subject: [PATCH 66/80] Update django-auth-ldap from 1.2.15 to 1.2.17 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a2b56244cdb..23eb098ddaa 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,6 +6,6 @@ SQLAlchemy==1.2.11 requests==2.32.2 pycryptodome==3.21.0 PyJWT==2.3.0 -django-auth-ldap==1.2.15 +django-auth-ldap==1.2.17 jsonschema==3.2.0 typing-extensions==4.3.0 From e92e5b5658ff0fd5b4ae10724c1a7a146f1b4053 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Mon, 27 Jan 2025 16:05:17 -0500 Subject: [PATCH 67/80] Filter taxon only when field relates to Taxon --- .../frontend/js_src/lib/components/QueryComboBox/helpers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/QueryComboBox/helpers.ts b/specifyweb/frontend/js_src/lib/components/QueryComboBox/helpers.ts index eb6c3196106..7e64bdf7240 100644 --- a/specifyweb/frontend/js_src/lib/components/QueryComboBox/helpers.ts +++ b/specifyweb/frontend/js_src/lib/components/QueryComboBox/helpers.ts @@ -147,7 +147,7 @@ export function getQueryComboBoxConditions({ * Filter values by tree definition if provided through context. * Used for filtering Taxon values by COT tree definition. */ - if (treeDefinition !== undefined) { + if (treeDefinition !== undefined && relatedTable === tables.Taxon) { fields.push( QueryFieldSpec.fromPath(tables.Taxon.name, ['definition', 'id']) .toSpQueryField() From 57a052c4589be3c6c02b9c62846ec05abead3698 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 10:52:55 -0600 Subject: [PATCH 68/80] try handling null appVersion when getting altKeyName --- .../js_src/lib/components/Preferences/UserDefinitions.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx index f3856c2fee4..f729df0cd31 100644 --- a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx +++ b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx @@ -64,7 +64,7 @@ const isDarkMode = ({ isRedirecting, }: PreferencesVisibilityContext): boolean => isDarkMode || isRedirecting; -const altKeyName = globalThis.navigator?.appVersion.includes('Mac') +const altKeyName = globalThis.navigator?.appVersion?.includes('Mac') ? 'Option' : 'Alt'; From c73d10b07bf6955a5cf9bb9a988517ab1f83576d Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 11:20:37 -0600 Subject: [PATCH 69/80] replace deprecated navigator.appVersion with navigator.userAgent --- .../js_src/lib/components/Preferences/UserDefinitions.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx index f729df0cd31..5184e499575 100644 --- a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx +++ b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx @@ -64,7 +64,7 @@ const isDarkMode = ({ isRedirecting, }: PreferencesVisibilityContext): boolean => isDarkMode || isRedirecting; -const altKeyName = globalThis.navigator?.appVersion?.includes('Mac') +const altKeyName = globalThis.navigator?.userAgent?.includes('Mac') ? 'Option' : 'Alt'; From dacec9eaf8ac679dcb10281fde89c28a5419eabc Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 11:32:40 -0600 Subject: [PATCH 70/80] navigator may not be defined in some environments, like non-browser environments --- .../js_src/lib/components/Preferences/UserDefinitions.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx index 5184e499575..0554d5015a7 100644 --- a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx +++ b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx @@ -64,7 +64,8 @@ const isDarkMode = ({ isRedirecting, }: PreferencesVisibilityContext): boolean => isDarkMode || isRedirecting; -const altKeyName = globalThis.navigator?.userAgent?.includes('Mac') +// navigator may not be defined in some environments, like non-browser environments +const altKeyName = typeof navigator !== 'undefined' && navigator?.userAgent?.includes('Mac') ? 'Option' : 'Alt'; From 7089427342897910c7d42eb4d004ce010584ca98 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 17:36:17 +0000 Subject: [PATCH 71/80] Lint code with ESLint and Prettier Triggered by dacec9eaf8ac679dcb10281fde89c28a5419eabc on branch refs/heads/issue-6129 --- .../js_src/lib/components/Preferences/UserDefinitions.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx index 0554d5015a7..044bbd9fc25 100644 --- a/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx +++ b/specifyweb/frontend/js_src/lib/components/Preferences/UserDefinitions.tsx @@ -64,7 +64,7 @@ const isDarkMode = ({ isRedirecting, }: PreferencesVisibilityContext): boolean => isDarkMode || isRedirecting; -// navigator may not be defined in some environments, like non-browser environments +// Navigator may not be defined in some environments, like non-browser environments const altKeyName = typeof navigator !== 'undefined' && navigator?.userAgent?.includes('Mac') ? 'Option' : 'Alt'; From 76b5d662d8ff75008beaea4990ad44700279ae08 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 12:04:16 -0600 Subject: [PATCH 72/80] change libsasl2-modules-gssapi-mit to libsasl2-modules --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 6c946ef85b1..f27ee5ad6b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -49,7 +49,7 @@ RUN apt-get update \ curl \ git \ libsasl2-dev \ - libsasl2-modules-gssapi-mit \ + libsasl2-modules \ libldap2-dev \ libssl-dev \ libgmp-dev \ From 5aab6ee3f32990d5009225d8814a5fb14ef77de0 Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 14:01:34 -0600 Subject: [PATCH 73/80] trigger weblate localization workflow --- specifyweb/frontend/js_src/lib/localization/common.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/localization/common.ts b/specifyweb/frontend/js_src/lib/localization/common.ts index 8206e95ea66..b524a6a007d 100644 --- a/specifyweb/frontend/js_src/lib/localization/common.ts +++ b/specifyweb/frontend/js_src/lib/localization/common.ts @@ -15,7 +15,7 @@ export const commonText = createDictionary({ translators. `, 'en-us': 'Specify 7', - 'ru-ru': 'Specify 7', + //'ru-ru': 'Specify 7', 'es-es': 'Specify 7', 'fr-fr': 'Specify 7', 'uk-ua': 'Вкажіть 7', From bad8e594f3395e4b656db00ccce03102c69a741c Mon Sep 17 00:00:00 2001 From: alec_dev Date: Tue, 28 Jan 2025 14:48:04 -0600 Subject: [PATCH 74/80] add temp localization to trigger workflow --- specifyweb/frontend/js_src/lib/localization/common.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/localization/common.ts b/specifyweb/frontend/js_src/lib/localization/common.ts index b524a6a007d..b2586bf66f7 100644 --- a/specifyweb/frontend/js_src/lib/localization/common.ts +++ b/specifyweb/frontend/js_src/lib/localization/common.ts @@ -15,7 +15,7 @@ export const commonText = createDictionary({ translators. `, 'en-us': 'Specify 7', - //'ru-ru': 'Specify 7', + 'ru-ru': 'Specify 7', 'es-es': 'Specify 7', 'fr-fr': 'Specify 7', 'uk-ua': 'Вкажіть 7', @@ -736,6 +736,7 @@ export const commonText = createDictionary({ }, zoom: { 'en-us': 'Zoom', + 'fr-fr': 'Zoom', }, unzoom: { 'en-us': 'Unzoom', From 3cdf6e9f8f7aff4698b00951fe9b771f368fb1c7 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Wed, 29 Jan 2025 17:39:43 -0500 Subject: [PATCH 75/80] Block save on invalid determinations --- .../components/DataModel/businessRuleDefs.ts | 52 ++++++++----------- .../components/DataModel/businessRuleUtils.ts | 1 + .../js_src/lib/localization/resources.ts | 4 ++ 3 files changed, 27 insertions(+), 30 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts b/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts index b92b36ae863..0fd4d207122 100644 --- a/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts +++ b/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts @@ -1,10 +1,10 @@ import { resourcesText } from '../../localization/resources'; -import { f } from '../../utils/functools'; import type { BusinessRuleResult } from './businessRules'; import { COG_PRIMARY_KEY, COG_TOITSELF, CURRENT_DETERMINATION_KEY, + DETERMINATION_TAXON_KEY, ensureSingleCollectionObjectCheck, hasNoCurrentDetermination, } from './businessRuleUtils'; @@ -19,7 +19,6 @@ import { updateLoanPrep, } from './interactionBusinessRules'; import type { SpecifyResource } from './legacyTypes'; -import { fetchResource, idFromUrl } from './resource'; import { setSaveBlockers } from './saveBlockers'; import { schema } from './schema'; import type { Collection } from './specifyTable'; @@ -170,38 +169,31 @@ export const businessRuleDefs: MappedBusinessRuleDefs = { }, fieldChecks: { collectionObjectType: async (resource): Promise => { - /* - * TEST: write tests for this - * Delete all determinations - */ const determinations = resource.getDependentResource('determinations'); - const currentDetermination = determinations?.models.find( - (determination) => determination.get('isCurrent') + if (determinations === undefined || determinations.models.length === 0) + return; + + const taxons = await Promise.all( + determinations.models.map((det) => det.rgetPromise('taxon')) ); + const coType = await resource.rgetPromise('collectionObjectType'); + const coTypeTreeDef = coType.get('taxonTreeDef'); - const taxonId = idFromUrl(currentDetermination?.get('taxon') ?? ''); - const COTypeID = idFromUrl(resource.get('collectionObjectType') ?? ''); - if ( - taxonId !== undefined && - COTypeID !== undefined && - currentDetermination !== undefined && - determinations !== undefined - ) - await f - .all({ - fetchedTaxon: fetchResource('Taxon', taxonId), - fetchedCOType: fetchResource('CollectionObjectType', COTypeID), - }) - .then(({ fetchedTaxon, fetchedCOType }) => { - const taxonTreeDefinition = fetchedTaxon.definition; - const COTypeTreeDefinition = fetchedCOType.taxonTreeDef; + // Block save when a Determination -> Taxon does not belong to the COType's tree definition + determinations.models.forEach((determination, index) => { + const taxon = taxons[index]; + const taxonTreeDef = taxon?.get('definition'); + const isValid = + typeof taxonTreeDef === 'string' && taxonTreeDef === coTypeTreeDef; + + setSaveBlockers( + determination, + determination.specifyTable.field.taxon, + isValid ? [] : [resourcesText.invalidDeterminationTaxon()], + DETERMINATION_TAXON_KEY + ); + }); - if (taxonTreeDefinition !== COTypeTreeDefinition) - resource.set('determinations', []); - }) - .catch((error) => { - console.error('Error fetching resources:', error); - }); return undefined; }, }, diff --git a/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleUtils.ts b/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleUtils.ts index be05d2c23aa..554d4c7ac96 100644 --- a/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleUtils.ts +++ b/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleUtils.ts @@ -7,6 +7,7 @@ export const CURRENT_DETERMINATION_KEY = 'determination-isCurrent'; export const COG_TOITSELF = 'cog-toItself'; export const PARENTCOG_KEY = 'cog-parentCog'; export const COG_PRIMARY_KEY = 'cog-isPrimary'; +export const DETERMINATION_TAXON_KEY = 'determination-Taxon'; /** * diff --git a/specifyweb/frontend/js_src/lib/localization/resources.ts b/specifyweb/frontend/js_src/lib/localization/resources.ts index 568dc4972fd..e1f570f1581 100644 --- a/specifyweb/frontend/js_src/lib/localization/resources.ts +++ b/specifyweb/frontend/js_src/lib/localization/resources.ts @@ -846,4 +846,8 @@ export const resourcesText = createDictionary({ 'en-us': 'A Consolidated Collection Object Group must have a primary Collection Object child', }, + invalidDeterminationTaxon: { + 'en-us': + 'Determination does not belong to the taxon tree associated with the Collection Object Type', + }, } as const); From 95caccf145a2afcabbdfb7aab5c978d530ff644f Mon Sep 17 00:00:00 2001 From: Sharad S Date: Wed, 29 Jan 2025 22:43:24 +0000 Subject: [PATCH 76/80] Lint code with ESLint and Prettier Triggered by 3cdf6e9f8f7aff4698b00951fe9b771f368fb1c7 on branch refs/heads/issue-6097 --- .../js_src/lib/components/DataModel/businessRuleDefs.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts b/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts index 0fd4d207122..a89856b6e9a 100644 --- a/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts +++ b/specifyweb/frontend/js_src/lib/components/DataModel/businessRuleDefs.ts @@ -174,7 +174,7 @@ export const businessRuleDefs: MappedBusinessRuleDefs = { return; const taxons = await Promise.all( - determinations.models.map((det) => det.rgetPromise('taxon')) + determinations.models.map(async (det) => det.rgetPromise('taxon')) ); const coType = await resource.rgetPromise('collectionObjectType'); const coTypeTreeDef = coType.get('taxonTreeDef'); From fb92bc999b81a116b0bb04b4ac6f2121743adb75 Mon Sep 17 00:00:00 2001 From: Sharad S Date: Thu, 30 Jan 2025 10:26:19 -0500 Subject: [PATCH 77/80] Add unit test --- .../DataModel/__tests__/businessRules.test.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/specifyweb/frontend/js_src/lib/components/DataModel/__tests__/businessRules.test.ts b/specifyweb/frontend/js_src/lib/components/DataModel/__tests__/businessRules.test.ts index 73955b9c7be..f8cba708515 100644 --- a/specifyweb/frontend/js_src/lib/components/DataModel/__tests__/businessRules.test.ts +++ b/specifyweb/frontend/js_src/lib/components/DataModel/__tests__/businessRules.test.ts @@ -131,6 +131,41 @@ describe('Collection Object business rules', () => { }; overrideAjax(otherCollectionObjectTypeUrl, otherCollectionObjectType); + test('CollectionObject -> determinations: Save blocked when a determination does not belong to COT tree', async () => { + const collectionObject = getBaseCollectionObject(); + collectionObject.set( + 'collectionObjectType', + getResourceApiUrl('CollectionObjectType', 1) + ); + + const determination = + collectionObject.getDependentResource('determinations')?.models[0]; + + const { result } = renderHook(() => + useSaveBlockers(determination, tables.Determination.getField('Taxon')) + ); + + await act(async () => { + await collectionObject?.businessRuleManager?.checkField( + 'collectionObjectType' + ); + }); + expect(result.current[0]).toStrictEqual([ + resourcesText.invalidDeterminationTaxon(), + ]); + + collectionObject.set( + 'collectionObjectType', + getResourceApiUrl('CollectionObjectType', 2) + ); + await act(async () => { + await collectionObject?.businessRuleManager?.checkField( + 'collectionObjectType' + ); + }); + expect(result.current[0]).toStrictEqual([]); + }); + test('CollectionObject -> determinations: New determinations are current by default', async () => { const collectionObject = getBaseCollectionObject(); const determinations = From eee2038c2febcc81a8cf6b4c4fc3900966e5fda8 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Mon, 3 Feb 2025 13:30:00 -0800 Subject: [PATCH 78/80] Prevent from choosing other tree node parent in treeViewer Fixes #6189 --- .../lib/components/QueryComboBox/index.tsx | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx index 8eca661e45c..d197842b99e 100644 --- a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx @@ -264,25 +264,27 @@ export function QueryComboBox({ (typeof typeSearch === 'object' ? typeSearch?.table : undefined) ?? field.relatedTable; - const [fetchedTreeDefinition] = useAsyncState( - React.useCallback( - async () => - resource?.specifyTable === tables.Determination && - resource.collection?.related?.specifyTable === tables.CollectionObject - ? (resource.collection?.related as SpecifyResource) - .rgetPromise('collectionObjectType') - .then( - ( - collectionObjectType: - | SpecifyResource - | undefined - ) => collectionObjectType?.get('taxonTreeDef') - ) - : undefined, - [resource, resource?.collection?.related?.get('collectionObjectType')] - ), - false - ); + const [fetchedTreeDefinition] = useAsyncState( + React.useCallback(async () => { + if (resource?.specifyTable === tables.Determination) { + return resource.collection?.related?.specifyTable === tables.CollectionObject + ? (resource.collection?.related as SpecifyResource) + .rgetPromise('collectionObjectType') + .then( + ( + collectionObjectType: + | SpecifyResource + | undefined + ) => collectionObjectType?.get('taxonTreeDef') + ) + : undefined; + } else if (resource?.specifyTable === tables.Taxon) { + return resource.get('definition'); + } + return undefined; + }, [resource, resource?.collection?.related?.get('collectionObjectType')]), + false + ); // Tree Definition passed by a parent QCBX in the component tree const parentTreeDefinition = React.useContext(TreeDefinitionContext); From e8a33ea80a35b3a1a5abcb70c3b39111e9dbef43 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Mon, 3 Feb 2025 13:43:37 -0800 Subject: [PATCH 79/80] Prevent from adding node to wrong tree --- .../frontend/js_src/lib/components/QueryComboBox/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx index d197842b99e..6a47a733371 100644 --- a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx @@ -279,8 +279,8 @@ export function QueryComboBox({ ) : undefined; } else if (resource?.specifyTable === tables.Taxon) { - return resource.get('definition'); - } + return resource.get('definition') || resource.independentResources?.parent?.get('definition'); + } return undefined; }, [resource, resource?.collection?.related?.get('collectionObjectType')]), false From eefcc9f6dd04a971c06de87c92e1702d6199e9c9 Mon Sep 17 00:00:00 2001 From: Caroline D <108160931+CarolineDenis@users.noreply.github.com> Date: Tue, 4 Feb 2025 06:42:14 -0800 Subject: [PATCH 80/80] Add type assertion --- .../frontend/js_src/lib/components/QueryComboBox/index.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx index 6a47a733371..81f98171382 100644 --- a/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx +++ b/specifyweb/frontend/js_src/lib/components/QueryComboBox/index.tsx @@ -279,7 +279,9 @@ export function QueryComboBox({ ) : undefined; } else if (resource?.specifyTable === tables.Taxon) { - return resource.get('definition') || resource.independentResources?.parent?.get('definition'); + const definition = resource.get('definition') + const parentDefinition = (resource?.independentResources?.parent as SpecifyResource)?.get?.('definition'); + return definition || parentDefinition; } return undefined; }, [resource, resource?.collection?.related?.get('collectionObjectType')]),