61 lines
No EOL
2.3 KiB
Python
61 lines
No EOL
2.3 KiB
Python
from typing import List, Optional, TYPE_CHECKING
|
||
if TYPE_CHECKING:
|
||
from .inventory import Inventory
|
||
|
||
from sqlalchemy import Identity, Integer, Unicode
|
||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||
|
||
from . import db
|
||
|
||
class Item(db.Model):
|
||
__tablename__ = 'Items'
|
||
|
||
id: Mapped[int] = mapped_column("ID", Integer, Identity(start=1, increment=1), primary_key=True)
|
||
description: Mapped[Optional[str]] = mapped_column("Description", Unicode(255), nullable=True)
|
||
category: Mapped[Optional[str]] = mapped_column("Category", Unicode(255), nullable=True)
|
||
|
||
inventory: Mapped[List['Inventory']] = relationship('Inventory', back_populates='item')
|
||
|
||
def __init__(self, description: Optional[str] = None, category: Optional[str] = None):
|
||
self.description = description
|
||
self.category = category
|
||
|
||
def __repr__(self):
|
||
return f"<Item(id={self.id}, description={repr(self.description)}, category={repr(self.category)})>"
|
||
|
||
def serialize(self):
|
||
return {
|
||
'id': self.id,
|
||
'name': self.description,
|
||
'category': self.category
|
||
}
|
||
|
||
@classmethod
|
||
def sync_from_state(cls, submitted_items: list[dict]):
|
||
"""
|
||
Syncs the Items table with the provided list of dictionaries.
|
||
Adds new items and removes items that are not in the list.
|
||
"""
|
||
submitted = {
|
||
str(item.get("name", "")).strip()
|
||
for item in submitted_items
|
||
if isinstance(item, dict) and str(item.get("name", "")).strip()
|
||
}
|
||
|
||
existing_query = db.session.query(cls)
|
||
existing = {item.description: item for item in existing_query.all()}
|
||
|
||
existing_descriptions = set(existing.keys())
|
||
|
||
print(f"Existing items: {existing_descriptions}")
|
||
print(f"Submitted items: {submitted}")
|
||
print(f"items to add: {submitted - existing_descriptions}")
|
||
print(f"items to remove: {existing_descriptions - submitted}")
|
||
|
||
for description in submitted - existing_descriptions:
|
||
db.session.add(cls(description=description))
|
||
print(f"➕ Adding item: {description}")
|
||
|
||
for description in existing_descriptions - submitted:
|
||
db.session.delete(existing[description])
|
||
print(f"🗑️ Removing item: {description}") |