Writer beginnings
This commit is contained in:
@@ -18,7 +18,10 @@ from sqlalchemy.exc import ArgumentError
|
||||
from typing import Any, List, ClassVar
|
||||
from pathlib import Path
|
||||
from sqlalchemy.orm.relationships import _RelationshipDeclared
|
||||
|
||||
from frontend import select_save_file
|
||||
from tools import report_result, list_sort_dict
|
||||
from backend.excel import writers
|
||||
|
||||
# NOTE: Load testing environment
|
||||
if 'pytest' in sys.modules:
|
||||
@@ -241,6 +244,7 @@ class BaseClass(Base):
|
||||
allowed = [k for k, v in cls.__dict__.items() if isinstance(v, InstrumentedAttribute) or isinstance(v, hybrid_property)]
|
||||
# and not isinstance(v.property, _RelationshipDeclared)]
|
||||
sanitized_kwargs = {k: v for k, v in kwargs.items() if k in allowed}
|
||||
outside_kwargs = {k: v for k, v in kwargs.items() if k not in allowed}
|
||||
logger.debug(f"Sanitized kwargs: {sanitized_kwargs}")
|
||||
instance = cls.query(**sanitized_kwargs)
|
||||
if not instance or isinstance(instance, list):
|
||||
@@ -258,6 +262,7 @@ class BaseClass(Base):
|
||||
setattr(instance, k, v.to_sql())
|
||||
else:
|
||||
logger.error(f"Could not set {k} due to {e}")
|
||||
instance._misc_info.update(outside_kwargs)
|
||||
logger.info(f"Instance from query or create: {instance}, new: {new}")
|
||||
return instance, new
|
||||
|
||||
@@ -309,10 +314,16 @@ class BaseClass(Base):
|
||||
check = False
|
||||
if check:
|
||||
logger.debug("Got uselist")
|
||||
query = query.filter(attr.contains(v))
|
||||
try:
|
||||
query = query.filter(attr.contains(v))
|
||||
except ArgumentError:
|
||||
continue
|
||||
else:
|
||||
logger.debug("Single item.")
|
||||
query = query.filter(attr == v)
|
||||
try:
|
||||
query = query.filter(attr == v)
|
||||
except ArgumentError:
|
||||
continue
|
||||
if k in singles:
|
||||
logger.warning(f"{k} is in singles. Returning only one value.")
|
||||
limit = 1
|
||||
@@ -496,7 +507,10 @@ class BaseClass(Base):
|
||||
value = json.dumps(value)
|
||||
except TypeError:
|
||||
value = str(value)
|
||||
self._misc_info.update({key: value})
|
||||
try:
|
||||
self._misc_info.update({key: value})
|
||||
except AttributeError:
|
||||
self._misc_info = {key: value}
|
||||
return
|
||||
try:
|
||||
field_type = getattr(self.__class__, key)
|
||||
@@ -623,6 +637,17 @@ class BaseClass(Base):
|
||||
if dlg.exec():
|
||||
pass
|
||||
|
||||
def export(self, obj, output_filepath: str|Path|None=None):
|
||||
if not hasattr(self, "template_file"):
|
||||
logger.error(f"Export not implemented for {self.__class__.__name__}")
|
||||
return
|
||||
pyd = self.to_pydantic()
|
||||
if not output_filepath:
|
||||
output_filepath = select_save_file(obj=obj, default_name=pyd.construct_filename(), extension="xlsx")
|
||||
Writer = getattr(writers, f"{self.__class__.__name__}Writer")
|
||||
writer = Writer(output_filepath=output_filepath, pydant_obj=pyd, range_dict=self.range_dict)
|
||||
workbook = writer
|
||||
|
||||
|
||||
class LogMixin(Base):
|
||||
tracking_exclusion: ClassVar = ['artic_technician', 'clientsubmissionsampleassociation',
|
||||
|
||||
@@ -15,6 +15,8 @@ from operator import itemgetter
|
||||
from pprint import pformat
|
||||
from pandas import DataFrame
|
||||
from sqlalchemy.ext.hybrid import hybrid_property
|
||||
|
||||
from frontend import select_save_file
|
||||
from . import Base, BaseClass, Reagent, SubmissionType, KitType, ClientLab, Contact, LogMixin, Procedure, kittype_procedure
|
||||
from sqlalchemy import Column, String, TIMESTAMP, INTEGER, ForeignKey, JSON, FLOAT, case, func, Table, Sequence
|
||||
from sqlalchemy.orm import relationship, validates, Query
|
||||
@@ -158,6 +160,14 @@ class ClientSubmission(BaseClass, LogMixin):
|
||||
offset = None
|
||||
return cls.execute_query(query=query, limit=limit, offset=offset, **kwargs)
|
||||
|
||||
@property
|
||||
def template_file(self):
|
||||
return self.submissiontype.template_file
|
||||
|
||||
@property
|
||||
def range_dict(self):
|
||||
return self.submissiontype.info_map
|
||||
|
||||
@classmethod
|
||||
def submissions_to_df(cls, submissiontype: str | None = None, limit: int = 0,
|
||||
chronologic: bool = True, page: int = 1, page_size: int = 250) -> pd.DataFrame:
|
||||
@@ -318,12 +328,12 @@ class ClientSubmission(BaseClass, LogMixin):
|
||||
logger.debug(f"Sample: {sample.id}")
|
||||
if sample not in run.sample:
|
||||
assoc = run.add_sample(sample)
|
||||
assoc.save()
|
||||
# assoc.save()
|
||||
run.save()
|
||||
else:
|
||||
logger.warning("Run cancelled.")
|
||||
obj.set_data()
|
||||
|
||||
|
||||
def edit(self, obj):
|
||||
logger.debug("Edit")
|
||||
|
||||
@@ -352,6 +362,9 @@ class ClientSubmission(BaseClass, LogMixin):
|
||||
output['expanded'] = ["clientlab", "contact", "submissiontype"]
|
||||
return output
|
||||
|
||||
def to_pydantic(self, filepath: Path|str|None=None, **kwargs):
|
||||
output = super().to_pydantic(filepath=filepath, **kwargs)
|
||||
return output
|
||||
|
||||
class Run(BaseClass, LogMixin):
|
||||
"""
|
||||
@@ -1266,6 +1279,15 @@ class Run(BaseClass, LogMixin):
|
||||
self.set_attribute(key='comment', value=comment)
|
||||
self.save(original=False)
|
||||
|
||||
def export(self, obj, output_filepath: str|Path|None=None):
|
||||
|
||||
clientsubmission_pyd = self.clientsubmission.to_pydantic()
|
||||
if not output_filepath:
|
||||
output_filepath = select_save_file(obj=obj, default_name=clientsubmission_pyd.construct_filename(), extension="xlsx")
|
||||
Writer = getattr(writers, "ClientSubmissionWriter")
|
||||
writer = Writer(output_filepath=output_filepath, pydant_obj=pyd, range_dict=self.range_dict)
|
||||
workbook = writer.
|
||||
|
||||
def backup(self, obj=None, fname: Path | None = None, full_backup: bool = False):
|
||||
"""
|
||||
Exports xlsx info files for this instance.
|
||||
@@ -1890,8 +1912,8 @@ class RunSampleAssociation(BaseClass):
|
||||
# id = Column(INTEGER, unique=True, nullable=False) #: id to be used for inheriting purposes
|
||||
sample_id = Column(INTEGER, ForeignKey("_sample.id"), primary_key=True) #: id of associated sample
|
||||
run_id = Column(INTEGER, ForeignKey("_run.id"), primary_key=True) #: id of associated procedure
|
||||
row = Column(INTEGER) #: row on the 96 well plate
|
||||
column = Column(INTEGER) #: column on the 96 well plate
|
||||
# row = Column(INTEGER) #: row on the 96 well plate
|
||||
# column = Column(INTEGER) #: column on the 96 well plate
|
||||
# misc_info = Column(JSON)
|
||||
|
||||
# NOTE: reference to the Submission object
|
||||
|
||||
Reference in New Issue
Block a user