Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/backend/InvenTree/InvenTree/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,13 @@ def get_serializer_info(self, serializer):
if name in model_default_values:
serializer_info[name]['default'] = model_default_values[name]

model = relation.model_field.related_model
if hasattr(model, 'import_as_fields'):
serializer_info[name]['import_as'] = [
f'{model.__name__}.{field}'
for field in model.import_as_fields()
]

except AttributeError:
pass

Expand Down
20 changes: 20 additions & 0 deletions src/backend/InvenTree/importer/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections import OrderedDict
from typing import Optional

from django.apps import apps
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.validators import FileExtensionValidator
Expand Down Expand Up @@ -313,6 +314,25 @@ def import_data(self) -> None:
commit=False,
)

for key in row.data:
Copy link
Member

Choose a reason for hiding this comment

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

Looks like you still have some hard-coded fields here - the "import_as" fields should not have to be called out by name.

if f'_import_as_{key}' in self.field_overrides:
row_value = row.data.get(key)
import_as = self.field_overrides.get(f'_import_as_{key}')
results_with_pk = []

if import_as == 'Part.IPN':
Part = apps.get_model('part', 'Part')
results_with_pk = Part.objects.filter(IPN=row_value)

elif import_as == 'Part.name':
Part = apps.get_model('part', 'Part')
results_with_pk = Part.objects.filter(name=row_value)

if results_with_pk.count() == 1:
results_with_pk = results_with_pk.first()
# Update the value in the row
row.data[key] = results_with_pk.pk

row.valid = row.validate(commit=False)
imported_rows.append(row)

Expand Down
5 changes: 5 additions & 0 deletions src/backend/InvenTree/part/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2674,6 +2674,11 @@ def is_part_low_on_stock(self):
"""Returns True if the total stock for this part is less than the minimum stock level."""
return self.get_stock_count() < self.minimum_stock

@staticmethod
def import_as_fields():
"""Return a list of potential ID fields for import."""
return ['id', 'IPN', 'name']
Copy link
Member

Choose a reason for hiding this comment

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

Nice, this is a simple way to specify the import-as options



@receiver(post_save, sender=Part, dispatch_uid='part_post_save_log')
def after_save_part(sender, instance: Part, created, **kwargs):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,79 @@ function ImporterDefaultField({
);
}

function ImporterPartImportAsSelect({
Copy link
Member

Choose a reason for hiding this comment

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

This should be ImporterImportAsSelect - it is not specific to importing parts, it should be generic across any type of import

column,
session
}: Readonly<{
column: any;
session: ImportSessionState;
}>) {
const api = useApi();
const [importAsValue, setImportAsValue] = useState<string>('');
const importAsKey = `_import_as_${column.field}`;

useEffect(() => {
const defaultValue =
column.import_as && column.import_as.length > 0
? column.import_as[0]
: '';
const value = session.fieldOverrides?.[importAsKey] ?? defaultValue;
setImportAsValue(value);
}, [session.fieldOverrides, column.field]);

const onChange = useCallback(
(value: any) => {
const importSettings = {
...session.fieldOverrides,
[importAsKey]: value
};

api
.patch(apiUrl(ApiEndpoints.import_session_list, session.sessionId), {
field_overrides: importSettings
})
.then((response) => {
const value = response.data?.field_overrides?.[importAsKey] ?? '';
setImportAsValue(value);
})
.catch((error) => {
// TODO: Error message?
});
},
[column]
);

if (!column.import_as || !Array.isArray(column.import_as)) {
return null;
}

const options = column.import_as.map((option: any) => ({
value: option,
label: option
}));

return (
<Select
data={options}
placeholder={t`Import as`}
value={importAsValue}
onChange={onChange}
size='sm'
w={180}
/>
);
}

function ImporterColumnTableRow({
session,
column,
options
options,
showImportAsColumn
}: Readonly<{
session: ImportSessionState;
column: any;
options: any;
showImportAsColumn: boolean;
}>) {
return (
<Table.Tr key={column.label ?? column.field}>
Expand All @@ -155,6 +220,11 @@ function ImporterColumnTableRow({
<Table.Td>
<ImporterColumn column={column} options={options} />
</Table.Td>
{showImportAsColumn && (
<Table.Td>
<ImporterPartImportAsSelect column={column} session={session} />
</Table.Td>
)}
<Table.Td>
<ImporterDefaultField fieldName={column.field} session={session} />
</Table.Td>
Expand Down Expand Up @@ -199,6 +269,15 @@ export default function ImporterColumnSelector({
];
}, [session.availableColumns]);

const showImportAsColumn = useMemo(() => {
return session.columnMappings.some(
(column: any) =>
column.import_as &&
Array.isArray(column.import_as) &&
column.import_as.length > 0
);
}, [session.columnMappings]);

return (
<Stack gap='xs'>
<Paper shadow='xs' p='xs'>
Expand All @@ -224,6 +303,7 @@ export default function ImporterColumnSelector({
<Table.Th>{t`Database Field`}</Table.Th>
<Table.Th>{t`Field Description`}</Table.Th>
<Table.Th>{t`Imported Column`}</Table.Th>
{showImportAsColumn && <Table.Th>{t`Import as`}</Table.Th>}
<Table.Th>{t`Default Value`}</Table.Th>
</Table.Tr>
</Table.Thead>
Expand All @@ -235,6 +315,7 @@ export default function ImporterColumnSelector({
session={session}
column={column}
options={columnOptions}
showImportAsColumn={showImportAsColumn}
/>
);
})}
Expand Down
Loading