96 lines
3.0 KiB
Python
96 lines
3.0 KiB
Python
"""
|
|
Group Model - Abstraktionsschicht für Datenbankzugriffe
|
|
"""
|
|
from cmbnet.db import get_db
|
|
|
|
|
|
class GroupModel:
|
|
@staticmethod
|
|
def get_all_by_tenant(tenant_id):
|
|
db = get_db()
|
|
return db.execute(
|
|
'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id',
|
|
(tenant_id,)
|
|
).fetchall()
|
|
|
|
@staticmethod
|
|
def get_by_id(group_id, tenant_id):
|
|
db = get_db()
|
|
return db.execute(
|
|
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
|
(group_id, tenant_id)
|
|
).fetchone()
|
|
|
|
@staticmethod
|
|
def get_by_account_id(account_id, tenant_id):
|
|
db = get_db()
|
|
return db.execute(
|
|
'''SELECT g.* FROM groups g
|
|
JOIN group_accounts ga
|
|
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
|
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
|
(account_id, tenant_id)
|
|
).fetchone()
|
|
|
|
@staticmethod
|
|
def get_account_ids_for_group(group_id, tenant_id):
|
|
db = get_db()
|
|
rows = db.execute(
|
|
'''SELECT account_id FROM group_accounts
|
|
WHERE group_id = ? AND tenant_id = ?
|
|
ORDER BY account_id''',
|
|
(group_id, tenant_id)
|
|
).fetchall()
|
|
return [row['account_id'] for row in rows]
|
|
|
|
@staticmethod
|
|
def get_account_ids_by_group(tenant_id):
|
|
db = get_db()
|
|
rows = db.execute(
|
|
'''SELECT group_id, account_id FROM group_accounts
|
|
WHERE tenant_id = ?
|
|
ORDER BY group_id, account_id''',
|
|
(tenant_id,)
|
|
).fetchall()
|
|
result = {}
|
|
for row in rows:
|
|
result.setdefault(row['group_id'], []).append(row['account_id'])
|
|
return result
|
|
|
|
@staticmethod
|
|
def create(tenant_id, aliasname, state='offen'):
|
|
db = get_db()
|
|
cursor = db.execute(
|
|
'INSERT INTO groups (tenant_id, aliasname, state) VALUES (?, ?, ?)',
|
|
(tenant_id, aliasname, state)
|
|
)
|
|
db.commit()
|
|
return cursor.lastrowid
|
|
|
|
@staticmethod
|
|
def update(group_id, tenant_id, **kwargs):
|
|
db = get_db()
|
|
allowed = ['aliasname', 'state', 'last_lat', 'last_lon', 'last_pos_at']
|
|
updates = []
|
|
values = []
|
|
for k, v in kwargs.items():
|
|
if k in allowed:
|
|
updates.append(f'{k} = ?')
|
|
values.append(v)
|
|
if not updates:
|
|
return
|
|
updates.append('updated_at = CURRENT_TIMESTAMP')
|
|
values.extend([group_id, tenant_id])
|
|
db.execute(f'UPDATE groups SET {", ".join(updates)} WHERE id = ? AND tenant_id = ?', values)
|
|
db.commit()
|
|
|
|
@staticmethod
|
|
def delete(group_id, tenant_id):
|
|
db = get_db()
|
|
db.execute(
|
|
'DELETE FROM group_accounts WHERE group_id = ? AND tenant_id = ?',
|
|
(group_id, tenant_id)
|
|
)
|
|
db.execute('DELETE FROM groups WHERE id = ? AND tenant_id = ?', (group_id, tenant_id))
|
|
db.commit()
|