from sqlalchemy.orm import Session from sqlalchemy import desc from models.template_models import Template, TemplateField, TemplateFieldMapping, TemplateRecognitionHistory from schemas.template_schemas import TemplateCreate, TemplateFieldCreate, TemplateFieldMappingCreate class TemplateRepository: def __init__(self, db: Session): self.db = db def get_template(self, template_id: int): return self.db.query(Template).filter(Template.pk_template_id == template_id).first() def get_templates(self, skip: int = 0, limit: int = 100): return self.db.query(Template).offset(skip).limit(limit).all() def create_template(self, template_data: TemplateCreate): db_template = Template(template_name=template_data.template_name) self.db.add(db_template) self.db.commit() self.db.refresh(db_template) # Create fields if provided for field in template_data.fields: db_field = TemplateField( fk_template_id=db_template.pk_template_id, field_label=field.field_label, field_type=field.field_type, display_order=field.display_order, required_flag=field.required_flag ) self.db.add(db_field) self.db.commit() self.db.refresh(db_template) return db_template def add_template_field(self, template_id: int, field_data: TemplateFieldCreate): db_field = TemplateField( fk_template_id=template_id, field_label=field_data.field_label, field_type=field_data.field_type, display_order=field_data.display_order, required_flag=field_data.required_flag ) self.db.add(db_field) self.db.commit() self.db.refresh(db_field) return db_field def delete_template(self, template_id: int): template = self.get_template(template_id) if template: self.db.delete(template) self.db.commit() return True return False def save_mapping(self, template_id: int, mappings: list[TemplateFieldMappingCreate]): saved_mappings = [] for mapping in mappings: db_mapping = TemplateFieldMapping( fk_template_id=template_id, fk_template_field_id=mapping.fk_template_field_id, fk_document_data_id=mapping.fk_document_data_id, page_no=mapping.page_no, x_coordinate=mapping.x_coordinate, y_coordinate=mapping.y_coordinate, width=mapping.width, height=mapping.height, mapping_confidence=mapping.mapping_confidence ) self.db.add(db_mapping) saved_mappings.append(db_mapping) self.db.commit() return saved_mappings