feat: Implement routines feature with CRUD operations and child assignment
All checks were successful
Chore App Build, Test, and Push Docker Images / build-and-push (push) Successful in 3m0s
All checks were successful
Chore App Build, Test, and Push Docker Images / build-and-push (push) Successful in 3m0s
- Add backend routines management with add, get, update, delete, and list functionalities. - Create models for Routine, RoutineItem, RoutineSchedule, and RoutineExtension. - Develop event types for routine confirmation and modification. - Implement frontend components for routine assignment, confirmation dialog, and routine management views. - Add unit tests for routine API and integration tests for routine CRUD flow. - Create end-to-end test plan for routines feature covering parent and child interactions.
This commit is contained in:
@@ -10,7 +10,7 @@ from api.pending_confirmation import PendingConfirmationResponse
|
||||
from api.reward_status import RewardStatus
|
||||
from api.utils import send_event_for_current_user, get_validated_user_id
|
||||
import api.child_action_helpers as chore_actions
|
||||
from db.db import child_db, task_db, reward_db, pending_reward_db, pending_confirmations_db, users_db
|
||||
from db.db import child_db, task_db, reward_db, routine_db, pending_reward_db, pending_confirmations_db, users_db
|
||||
from db.tracking import insert_tracking_event
|
||||
from db.child_overrides import get_override, delete_override, delete_overrides_for_child
|
||||
from events.types.child_chore_confirmation import ChildChoreConfirmation
|
||||
@@ -35,6 +35,8 @@ from utils.digest_token import create_action_token
|
||||
from collections import defaultdict
|
||||
from db.chore_schedules import get_schedule
|
||||
from db.task_extensions import get_extension_for_child_task
|
||||
from db.routine_schedules import delete_schedules_for_child as delete_routine_schedules_for_child
|
||||
from db.routine_extensions import delete_extensions_for_child as delete_routine_extensions_for_child
|
||||
import logging
|
||||
|
||||
child_api = Blueprint('child_api', __name__)
|
||||
@@ -163,6 +165,14 @@ def delete_child(id):
|
||||
deleted_count = delete_overrides_for_child(id)
|
||||
if deleted_count > 0:
|
||||
logger.info(f"Cascade deleted {deleted_count} overrides for child {id}")
|
||||
|
||||
# Cascade delete routine schedule/extension rows for this child.
|
||||
delete_routine_schedules_for_child(id)
|
||||
delete_routine_extensions_for_child(id)
|
||||
|
||||
# Remove pending routine confirmations for this child.
|
||||
PendingQuery = Query()
|
||||
pending_confirmations_db.remove((PendingQuery.child_id == id) & (PendingQuery.entity_type == 'routine'))
|
||||
|
||||
if child_db.remove((ChildQuery.id == id) & (ChildQuery.user_id == user_id)):
|
||||
resp = send_event_for_current_user(Event(EventType.CHILD_MODIFIED.value, ChildModified(id, ChildModified.OPERATION_DELETE)))
|
||||
@@ -1104,6 +1114,7 @@ def list_pending_confirmations():
|
||||
|
||||
RewardQuery = Query()
|
||||
TaskQuery = Query()
|
||||
RoutineQuery = Query()
|
||||
ChildQuery = Query()
|
||||
|
||||
for pr in pending_items:
|
||||
@@ -1122,8 +1133,12 @@ def list_pending_confirmations():
|
||||
# Look up entity details based on type
|
||||
if pending.entity_type == 'reward':
|
||||
entity_result = reward_db.get((RewardQuery.id == pending.entity_id) & ((RewardQuery.user_id == user_id) | (RewardQuery.user_id == None)))
|
||||
else:
|
||||
elif pending.entity_type == 'chore':
|
||||
entity_result = task_db.get((TaskQuery.id == pending.entity_id) & ((TaskQuery.user_id == user_id) | (TaskQuery.user_id == None)))
|
||||
elif pending.entity_type == 'routine':
|
||||
entity_result = routine_db.get((RoutineQuery.id == pending.entity_id) & ((RoutineQuery.user_id == user_id) | (RoutineQuery.user_id == None)))
|
||||
else:
|
||||
entity_result = None
|
||||
|
||||
if not entity_result:
|
||||
continue
|
||||
|
||||
@@ -2,7 +2,7 @@ from flask import Blueprint, request, jsonify
|
||||
from tinydb import Query
|
||||
from api.utils import get_validated_user_id, send_event_for_current_user
|
||||
from api.error_codes import ErrorCodes
|
||||
from db.db import child_db, task_db, reward_db
|
||||
from db.db import child_db, task_db, reward_db, routine_db
|
||||
from db.child_overrides import (
|
||||
insert_override,
|
||||
get_override,
|
||||
@@ -52,8 +52,8 @@ def set_child_override(child_id):
|
||||
return jsonify({'error': 'custom_value is required', 'code': ErrorCodes.MISSING_FIELD, 'field': 'custom_value'}), 400
|
||||
|
||||
# Validate entity_type
|
||||
if entity_type not in ['task', 'reward']:
|
||||
return jsonify({'error': 'entity_type must be "task" or "reward"', 'code': ErrorCodes.INVALID_VALUE, 'field': 'entity_type'}), 400
|
||||
if entity_type not in ['task', 'reward', 'routine']:
|
||||
return jsonify({'error': 'entity_type must be "task", "reward", or "routine"', 'code': ErrorCodes.INVALID_VALUE, 'field': 'entity_type'}), 400
|
||||
|
||||
# Validate custom_value range
|
||||
if not isinstance(custom_value, int) or custom_value < 0 or custom_value > 10000:
|
||||
@@ -74,7 +74,7 @@ def set_child_override(child_id):
|
||||
if entity_id not in assigned_tasks:
|
||||
return jsonify({'error': 'Task not assigned to child', 'code': ErrorCodes.ENTITY_NOT_ASSIGNED}), 404
|
||||
|
||||
else: # reward
|
||||
elif entity_type == 'reward':
|
||||
EntityQuery = Query()
|
||||
entity_result = reward_db.search(
|
||||
(EntityQuery.id == entity_id) &
|
||||
@@ -87,6 +87,19 @@ def set_child_override(child_id):
|
||||
assigned_rewards = child_dict.get('rewards', [])
|
||||
if entity_id not in assigned_rewards:
|
||||
return jsonify({'error': 'Reward not assigned to child', 'code': ErrorCodes.ENTITY_NOT_ASSIGNED}), 404
|
||||
|
||||
else: # routine
|
||||
EntityQuery = Query()
|
||||
entity_result = routine_db.search(
|
||||
(EntityQuery.id == entity_id) &
|
||||
((EntityQuery.user_id == user_id) | (EntityQuery.user_id == None))
|
||||
)
|
||||
if not entity_result:
|
||||
return jsonify({'error': 'Routine not found', 'code': 'ROUTINE_NOT_FOUND'}), 404
|
||||
|
||||
assigned_routines = child_dict.get('routines', [])
|
||||
if entity_id not in assigned_routines:
|
||||
return jsonify({'error': 'Routine not assigned to child', 'code': ErrorCodes.ENTITY_NOT_ASSIGNED}), 404
|
||||
|
||||
# Create and insert override
|
||||
try:
|
||||
|
||||
528
backend/api/child_routine_api.py
Normal file
528
backend/api/child_routine_api.py
Normal file
@@ -0,0 +1,528 @@
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from tinydb import Query
|
||||
|
||||
from api.error_codes import ErrorCodes
|
||||
from api.utils import get_validated_user_id, send_event_for_current_user
|
||||
from db.child_overrides import delete_override, get_override
|
||||
from db.db import child_db, pending_confirmations_db, routine_db, users_db
|
||||
from db.routine_extensions import delete_extension_for_child_routine, get_extension_for_child_routine
|
||||
from db.routine_items import get_items_for_routine
|
||||
from db.routine_schedules import delete_schedule, get_schedule
|
||||
from events.types.child_routine_confirmation import ChildRoutineConfirmation
|
||||
from events.types.child_routines_set import ChildRoutinesSet
|
||||
from events.types.event import Event
|
||||
from events.types.event_types import EventType
|
||||
from models.child import Child
|
||||
from models.pending_confirmation import PendingConfirmation
|
||||
from models.routine import Routine
|
||||
from utils.digest_token import create_action_token
|
||||
from utils.push_sender import send_push_to_user
|
||||
|
||||
child_routine_api = Blueprint('child_routine_api', __name__)
|
||||
|
||||
|
||||
def _is_iso_timestamp_today_utc(timestamp: str | None, today_utc: str) -> bool:
|
||||
return bool(timestamp) and timestamp[:10] == today_utc
|
||||
|
||||
|
||||
def _is_epoch_timestamp_today_utc(epoch_ts, today_utc: str) -> bool:
|
||||
if epoch_ts is None:
|
||||
return False
|
||||
try:
|
||||
return datetime.fromtimestamp(float(epoch_ts), timezone.utc).strftime('%Y-%m-%d') == today_utc
|
||||
except (TypeError, ValueError, OSError):
|
||||
return False
|
||||
|
||||
|
||||
class ChildRoutine:
|
||||
def __init__(self, name, points, image_id, _id):
|
||||
self.id = _id
|
||||
self.name = name
|
||||
self.points = points
|
||||
self.image_id = image_id
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'name': self.name,
|
||||
'points': self.points,
|
||||
'image_id': self.image_id,
|
||||
}
|
||||
|
||||
|
||||
def _validate_child_for_user(child_id: str, user_id: str):
|
||||
child_q = Query()
|
||||
result = child_db.search((child_q.id == child_id) & (child_q.user_id == user_id))
|
||||
return Child.from_dict(result[0]) if result else None
|
||||
|
||||
|
||||
def _resolve_routine_for_user(routine_id: str, user_id: str):
|
||||
routine_q = Query()
|
||||
routine_result = routine_db.get(
|
||||
(routine_q.id == routine_id) & ((routine_q.user_id == user_id) | (routine_q.user_id == None))
|
||||
)
|
||||
return Routine.from_dict(routine_result) if routine_result else None
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/assign-routine', methods=['POST'])
|
||||
def assign_routine_to_child(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
routine_id = data.get('routine_id')
|
||||
if not routine_id:
|
||||
return jsonify({'error': 'routine_id is required', 'code': ErrorCodes.MISSING_FIELD}), 400
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
routine = _resolve_routine_for_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
routine_ids = list(child.routines)
|
||||
if routine_id not in routine_ids:
|
||||
routine_ids.append(routine_id)
|
||||
child_db.update({'routines': routine_ids}, Query().id == id)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(EventType.CHILD_ROUTINES_SET.value, ChildRoutinesSet(id, routine_ids))
|
||||
)
|
||||
return jsonify({'message': f'Routine {routine_id} assigned to {child.name}.'}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/remove-routine', methods=['POST'])
|
||||
def remove_routine_from_child(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
routine_id = data.get('routine_id')
|
||||
if not routine_id:
|
||||
return jsonify({'error': 'routine_id is required', 'code': ErrorCodes.MISSING_FIELD}), 400
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
routine_ids = list(child.routines)
|
||||
if routine_id not in routine_ids:
|
||||
return jsonify({'error': 'Routine not assigned to child', 'code': ErrorCodes.ENTITY_NOT_ASSIGNED}), 400
|
||||
|
||||
routine_ids.remove(routine_id)
|
||||
child_db.update({'routines': routine_ids}, Query().id == id)
|
||||
|
||||
override = get_override(id, routine_id)
|
||||
if override and override.entity_type == 'routine':
|
||||
delete_override(id, routine_id)
|
||||
|
||||
delete_schedule(id, routine_id)
|
||||
delete_extension_for_child_routine(id, routine_id)
|
||||
|
||||
pending_q = Query()
|
||||
pending_confirmations_db.remove(
|
||||
(pending_q.child_id == id) & (pending_q.entity_id == routine_id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(EventType.CHILD_ROUTINES_SET.value, ChildRoutinesSet(id, routine_ids))
|
||||
)
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(id, routine_id, ChildRoutineConfirmation.OPERATION_RESET)
|
||||
)
|
||||
)
|
||||
return jsonify({'message': f'Routine {routine_id} removed from {child.name}.'}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/set-routines', methods=['PUT'])
|
||||
def set_child_routines(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
routine_ids = data.get('routine_ids')
|
||||
if not isinstance(routine_ids, list):
|
||||
return jsonify({'error': 'routine_ids must be a list'}), 400
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
routine_q = Query()
|
||||
valid_ids = []
|
||||
for rid in dict.fromkeys(routine_ids):
|
||||
if routine_db.get((routine_q.id == rid) & ((routine_q.user_id == user_id) | (routine_q.user_id == None))):
|
||||
valid_ids.append(rid)
|
||||
|
||||
old_ids = set(child.routines)
|
||||
new_ids = set(valid_ids)
|
||||
unassigned_ids = old_ids - new_ids
|
||||
|
||||
pending_q = Query()
|
||||
for rid in unassigned_ids:
|
||||
override = get_override(id, rid)
|
||||
if override and override.entity_type == 'routine':
|
||||
delete_override(id, rid)
|
||||
|
||||
delete_schedule(id, rid)
|
||||
delete_extension_for_child_routine(id, rid)
|
||||
|
||||
pending_confirmations_db.remove(
|
||||
(pending_q.child_id == id) & (pending_q.entity_id == rid) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
|
||||
child_db.update({'routines': valid_ids}, Query().id == id)
|
||||
send_event_for_current_user(Event(EventType.CHILD_ROUTINES_SET.value, ChildRoutinesSet(id, valid_ids)))
|
||||
|
||||
return jsonify({'message': f'Routines set for child {id}.', 'routine_ids': valid_ids, 'count': len(valid_ids)}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/list-routines', methods=['GET'])
|
||||
def list_child_routines(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
routine_q = Query()
|
||||
pending_q = Query()
|
||||
today_utc = datetime.now(timezone.utc).strftime('%Y-%m-%d')
|
||||
|
||||
child_routines = []
|
||||
for rid in child.routines:
|
||||
routine_record = routine_db.get((routine_q.id == rid) & ((routine_q.user_id == user_id) | (routine_q.user_id == None)))
|
||||
if not routine_record:
|
||||
continue
|
||||
|
||||
routine = Routine.from_dict(routine_record)
|
||||
override = get_override(id, rid)
|
||||
custom_value = override.custom_value if override and override.entity_type == 'routine' else None
|
||||
|
||||
cr = ChildRoutine(routine.name, routine.points, routine.image_id, routine.id)
|
||||
cr_dict = cr.to_dict()
|
||||
if custom_value is not None:
|
||||
cr_dict['custom_value'] = custom_value
|
||||
|
||||
schedule = get_schedule(id, rid)
|
||||
cr_dict['schedule'] = schedule.to_dict() if schedule else None
|
||||
|
||||
extension = get_extension_for_child_routine(id, rid)
|
||||
cr_dict['extension_date'] = extension.date if extension else None
|
||||
|
||||
items = get_items_for_routine(rid)
|
||||
cr_dict['items'] = [item.to_dict() for item in items]
|
||||
|
||||
pending = pending_confirmations_db.get(
|
||||
(pending_q.child_id == id) & (pending_q.entity_id == rid) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
if pending:
|
||||
status = pending.get('status')
|
||||
approved_at = pending.get('approved_at')
|
||||
created_at = pending.get('created_at')
|
||||
|
||||
if status == 'approved' and _is_iso_timestamp_today_utc(approved_at, today_utc):
|
||||
cr_dict['pending_status'] = 'approved'
|
||||
cr_dict['approved_at'] = approved_at
|
||||
elif status == 'pending' and _is_epoch_timestamp_today_utc(created_at, today_utc):
|
||||
cr_dict['pending_status'] = 'pending'
|
||||
cr_dict['approved_at'] = None
|
||||
else:
|
||||
pending_id = pending.get('id')
|
||||
if pending_id:
|
||||
pending_confirmations_db.remove(pending_q.id == pending_id)
|
||||
cr_dict['pending_status'] = None
|
||||
cr_dict['approved_at'] = None
|
||||
else:
|
||||
cr_dict['pending_status'] = None
|
||||
cr_dict['approved_at'] = None
|
||||
|
||||
child_routines.append(cr_dict)
|
||||
|
||||
return jsonify({'routines': child_routines}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/list-assignable-routines', methods=['GET'])
|
||||
def list_assignable_routines(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
assigned_ids = set(child.routines)
|
||||
all_routines = [r for r in routine_db.all() if r and r.get('id') and r.get('id') not in assigned_ids]
|
||||
|
||||
name_to_routines = defaultdict(list)
|
||||
for routine in all_routines:
|
||||
name_to_routines[routine.get('name')].append(routine)
|
||||
|
||||
filtered_routines = []
|
||||
for _, routines in name_to_routines.items():
|
||||
user_routines = [r for r in routines if r.get('user_id') is not None]
|
||||
if len(user_routines) == 0:
|
||||
filtered_routines.append(routines[0])
|
||||
elif len(user_routines) == 1:
|
||||
filtered_routines.append(user_routines[0])
|
||||
else:
|
||||
filtered_routines.extend(user_routines)
|
||||
|
||||
assignable = [
|
||||
ChildRoutine(r.get('name'), r.get('points'), r.get('image_id'), r.get('id')).to_dict()
|
||||
for r in filtered_routines
|
||||
]
|
||||
return jsonify({'routines': assignable, 'count': len(assignable)}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/confirm-routine', methods=['POST'])
|
||||
def confirm_routine(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
routine_id = data.get('routine_id')
|
||||
if not routine_id:
|
||||
return jsonify({'error': 'routine_id is required', 'code': ErrorCodes.MISSING_FIELD}), 400
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
if routine_id not in child.routines:
|
||||
return jsonify({'error': 'Routine not assigned to child', 'code': ErrorCodes.ENTITY_NOT_ASSIGNED}), 400
|
||||
|
||||
routine = _resolve_routine_for_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
pending_q = Query()
|
||||
existing = pending_confirmations_db.get(
|
||||
(pending_q.child_id == id) & (pending_q.entity_id == routine_id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
if existing:
|
||||
today_utc = datetime.now(timezone.utc).strftime('%Y-%m-%d')
|
||||
if existing.get('status') == 'pending':
|
||||
if _is_epoch_timestamp_today_utc(existing.get('created_at'), today_utc):
|
||||
return jsonify({'error': 'Routine already pending confirmation', 'code': 'ROUTINE_ALREADY_PENDING'}), 400
|
||||
pending_id = existing.get('id')
|
||||
if pending_id:
|
||||
pending_confirmations_db.remove(pending_q.id == pending_id)
|
||||
if existing.get('status') == 'approved':
|
||||
approved_at = existing.get('approved_at', '')
|
||||
if _is_iso_timestamp_today_utc(approved_at, today_utc):
|
||||
return jsonify({'error': 'Routine already completed today', 'code': 'ROUTINE_ALREADY_COMPLETED'}), 400
|
||||
pending_id = existing.get('id')
|
||||
if pending_id:
|
||||
pending_confirmations_db.remove(pending_q.id == pending_id)
|
||||
|
||||
confirmation = PendingConfirmation(
|
||||
child_id=id,
|
||||
entity_id=routine_id,
|
||||
entity_type='routine',
|
||||
user_id=user_id,
|
||||
)
|
||||
pending_confirmations_db.insert(confirmation.to_dict())
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(id, routine_id, ChildRoutineConfirmation.OPERATION_PENDING)
|
||||
)
|
||||
)
|
||||
|
||||
push_user = users_db.get(Query().id == user_id)
|
||||
if push_user and push_user.get('push_notifications_enabled', True):
|
||||
try:
|
||||
approve_token = create_action_token(user_id, id, routine_id, 'routine', 'approve')
|
||||
deny_token = create_action_token(user_id, id, routine_id, 'routine', 'deny')
|
||||
push_payload = {
|
||||
'type': 'routine_confirmed',
|
||||
'title': 'Routine Pending',
|
||||
'body': f'{child.name} completed {routine.name}',
|
||||
'user_id': user_id,
|
||||
'child_id': id,
|
||||
'child_name': child.name,
|
||||
'entity_id': routine_id,
|
||||
'entity_type': 'routine',
|
||||
'entity_name': routine.name,
|
||||
'approve_token': approve_token.id,
|
||||
'deny_token': deny_token.id,
|
||||
}
|
||||
send_push_to_user(user_id, push_payload)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return jsonify({'message': f'Routine {routine.name} confirmed by {child.name}.', 'confirmation_id': confirmation.id}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/cancel-routine-confirmation', methods=['POST'])
|
||||
def cancel_routine_confirmation(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
routine_id = data.get('routine_id')
|
||||
if not routine_id:
|
||||
return jsonify({'error': 'routine_id is required', 'code': ErrorCodes.MISSING_FIELD}), 400
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
pending_q = Query()
|
||||
existing = pending_confirmations_db.get(
|
||||
(pending_q.child_id == id) & (pending_q.entity_id == routine_id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.status == 'pending') &
|
||||
(pending_q.user_id == user_id)
|
||||
)
|
||||
if not existing:
|
||||
return jsonify({'error': 'No pending confirmation found', 'code': 'PENDING_NOT_FOUND'}), 400
|
||||
|
||||
pending_confirmations_db.remove(
|
||||
(pending_q.child_id == id) & (pending_q.entity_id == routine_id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.status == 'pending') &
|
||||
(pending_q.user_id == user_id)
|
||||
)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(id, routine_id, ChildRoutineConfirmation.OPERATION_RESET)
|
||||
)
|
||||
)
|
||||
return jsonify({'message': 'Routine confirmation cancelled.'}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/approve-routine/<confirmation_id>', methods=['POST'])
|
||||
def approve_routine(id, confirmation_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
pending_q = Query()
|
||||
confirmation = pending_confirmations_db.get(
|
||||
(pending_q.id == confirmation_id) & (pending_q.child_id == id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
if not confirmation:
|
||||
return jsonify({'error': 'Pending confirmation not found', 'code': 'PENDING_NOT_FOUND'}), 404
|
||||
|
||||
if confirmation.get('status') != 'pending':
|
||||
return jsonify({'error': 'Confirmation is already resolved', 'code': 'ALREADY_RESOLVED'}), 400
|
||||
|
||||
routine_id = confirmation.get('entity_id')
|
||||
routine = _resolve_routine_for_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
override = get_override(id, routine_id)
|
||||
points_value = override.custom_value if override and override.entity_type == 'routine' else routine.points
|
||||
|
||||
new_points = max(0, child.points + points_value)
|
||||
child_db.update({'points': new_points}, Query().id == id)
|
||||
|
||||
approved_at = datetime.now(timezone.utc).isoformat()
|
||||
pending_confirmations_db.update(
|
||||
{'status': 'approved', 'approved_at': approved_at},
|
||||
pending_q.id == confirmation_id
|
||||
)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(id, routine_id, ChildRoutineConfirmation.OPERATION_APPROVED)
|
||||
)
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'message': f'Routine {routine.name} approved for {child.name}.',
|
||||
'points': new_points,
|
||||
'id': child.id,
|
||||
}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/reject-routine/<confirmation_id>', methods=['POST'])
|
||||
def reject_routine(id, confirmation_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
pending_q = Query()
|
||||
confirmation = pending_confirmations_db.get(
|
||||
(pending_q.id == confirmation_id) & (pending_q.child_id == id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
if not confirmation:
|
||||
return jsonify({'error': 'Pending confirmation not found', 'code': 'PENDING_NOT_FOUND'}), 404
|
||||
|
||||
if confirmation.get('status') != 'pending':
|
||||
return jsonify({'error': 'Confirmation is already resolved', 'code': 'ALREADY_RESOLVED'}), 400
|
||||
|
||||
pending_confirmations_db.update({'status': 'rejected', 'approved_at': None}, pending_q.id == confirmation_id)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(id, confirmation.get('entity_id'), ChildRoutineConfirmation.OPERATION_REJECTED)
|
||||
)
|
||||
)
|
||||
|
||||
return jsonify({'message': 'Routine confirmation rejected.'}), 200
|
||||
|
||||
|
||||
@child_routine_api.route('/child/<id>/reset-routine/<confirmation_id>', methods=['POST'])
|
||||
def reset_routine(id, confirmation_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
child = _validate_child_for_user(id, user_id)
|
||||
if not child:
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
pending_q = Query()
|
||||
confirmation = pending_confirmations_db.get(
|
||||
(pending_q.id == confirmation_id) & (pending_q.child_id == id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
if not confirmation:
|
||||
return jsonify({'error': 'Pending confirmation not found', 'code': 'PENDING_NOT_FOUND'}), 404
|
||||
|
||||
routine_id = confirmation.get('entity_id')
|
||||
pending_confirmations_db.remove(pending_q.id == confirmation_id)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(id, routine_id, ChildRoutineConfirmation.OPERATION_RESET)
|
||||
)
|
||||
)
|
||||
return jsonify({'message': 'Routine reset to available.'}), 200
|
||||
185
backend/api/routine_api.py
Normal file
185
backend/api/routine_api.py
Normal file
@@ -0,0 +1,185 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from tinydb import Query
|
||||
|
||||
from api.utils import send_event_for_current_user, get_validated_user_id
|
||||
from db.db import routine_db, child_db, pending_confirmations_db
|
||||
from db.child_overrides import delete_overrides_for_entity
|
||||
from db.routine_items import delete_for_routine
|
||||
from db.routine_schedules import delete_schedules_for_routine
|
||||
from db.routine_extensions import delete_extensions_for_routine
|
||||
from events.types.event import Event
|
||||
from events.types.event_types import EventType
|
||||
from events.types.routine_modified import RoutineModified
|
||||
from events.types.child_routines_set import ChildRoutinesSet
|
||||
from models.routine import Routine
|
||||
|
||||
routine_api = Blueprint('routine_api', __name__)
|
||||
|
||||
|
||||
@routine_api.route('/routine/add', methods=['PUT'])
|
||||
def add_routine():
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
name = data.get('name')
|
||||
points = data.get('points')
|
||||
image = data.get('image_id', '')
|
||||
|
||||
if not name or points is None:
|
||||
return jsonify({'error': 'Name and points are required'}), 400
|
||||
|
||||
routine = Routine(name=name, points=points, image_id=image, user_id=user_id)
|
||||
routine_db.insert(routine.to_dict())
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(routine.id, RoutineModified.OPERATION_ADD))
|
||||
)
|
||||
return jsonify({'message': f'Routine {name} added.', 'routine': routine.to_dict()}), 201
|
||||
|
||||
|
||||
@routine_api.route('/routine/<id>', methods=['GET'])
|
||||
def get_routine(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
q = Query()
|
||||
result = routine_db.search((q.id == id) & ((q.user_id == user_id) | (q.user_id == None)))
|
||||
if not result:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
return jsonify(result[0]), 200
|
||||
|
||||
|
||||
@routine_api.route('/routine/list', methods=['GET'])
|
||||
def list_routines():
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
ids_param = request.args.get('ids')
|
||||
q = Query()
|
||||
routines = routine_db.search((q.user_id == user_id) | (q.user_id == None))
|
||||
|
||||
if ids_param is not None:
|
||||
if ids_param.strip() == '':
|
||||
routines = []
|
||||
else:
|
||||
ids = set(ids_param.split(','))
|
||||
routines = [routine for routine in routines if routine.get('id') in ids]
|
||||
|
||||
user_routines = {r['name'].strip().lower(): r for r in routines if r.get('user_id') == user_id}
|
||||
filtered_routines = []
|
||||
for routine in routines:
|
||||
if routine.get('user_id') is None and routine['name'].strip().lower() in user_routines:
|
||||
continue
|
||||
filtered_routines.append(routine)
|
||||
|
||||
user_created = sorted(
|
||||
[r for r in filtered_routines if r.get('user_id') == user_id],
|
||||
key=lambda x: x['name'].lower(),
|
||||
)
|
||||
default_items = sorted(
|
||||
[r for r in filtered_routines if r.get('user_id') is None],
|
||||
key=lambda x: x['name'].lower(),
|
||||
)
|
||||
|
||||
return jsonify({'routines': user_created + default_items}), 200
|
||||
|
||||
|
||||
@routine_api.route('/routine/<id>/edit', methods=['PUT'])
|
||||
def edit_routine(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
q = Query()
|
||||
existing = routine_db.get((q.id == id) & ((q.user_id == user_id) | (q.user_id == None)))
|
||||
if not existing:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
routine = Routine.from_dict(existing)
|
||||
data = request.get_json(force=True) or {}
|
||||
is_dirty = False
|
||||
|
||||
if 'name' in data:
|
||||
name = data.get('name', '').strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'Name cannot be empty'}), 400
|
||||
routine.name = name
|
||||
is_dirty = True
|
||||
|
||||
if 'points' in data:
|
||||
points = data.get('points')
|
||||
if not isinstance(points, int) or points <= 0:
|
||||
return jsonify({'error': 'Points must be a positive integer'}), 400
|
||||
routine.points = points
|
||||
is_dirty = True
|
||||
|
||||
if 'image_id' in data:
|
||||
routine.image_id = data.get('image_id', '')
|
||||
is_dirty = True
|
||||
|
||||
if not is_dirty:
|
||||
return jsonify({'error': 'No valid fields to update'}), 400
|
||||
|
||||
if routine.user_id is None:
|
||||
new_routine = Routine(name=routine.name, points=routine.points, image_id=routine.image_id, user_id=user_id)
|
||||
routine_db.insert(new_routine.to_dict())
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(new_routine.id, RoutineModified.OPERATION_ADD))
|
||||
)
|
||||
return jsonify(new_routine.to_dict()), 200
|
||||
|
||||
routine_db.update(routine.to_dict(), q.id == id)
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(id, RoutineModified.OPERATION_EDIT))
|
||||
)
|
||||
return jsonify(routine.to_dict()), 200
|
||||
|
||||
|
||||
@routine_api.route('/routine/<id>', methods=['DELETE'])
|
||||
def delete_routine(id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
q = Query()
|
||||
routine = routine_db.get(q.id == id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
if routine.get('user_id') is None:
|
||||
return jsonify({'error': 'System routines cannot be deleted.'}), 403
|
||||
|
||||
removed = routine_db.remove((q.id == id) & (q.user_id == user_id))
|
||||
if not removed:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
delete_overrides_for_entity(id)
|
||||
delete_for_routine(id)
|
||||
delete_schedules_for_routine(id)
|
||||
delete_extensions_for_routine(id)
|
||||
|
||||
pending_q = Query()
|
||||
pending_confirmations_db.remove(
|
||||
(pending_q.entity_id == id) & (pending_q.entity_type == 'routine') & (pending_q.user_id == user_id)
|
||||
)
|
||||
|
||||
child_q = Query()
|
||||
children = child_db.search(child_q.user_id == user_id)
|
||||
for child in children:
|
||||
routine_ids = child.get('routines', [])
|
||||
if id in routine_ids:
|
||||
routine_ids = [rid for rid in routine_ids if rid != id]
|
||||
child_db.update({'routines': routine_ids}, child_q.id == child.get('id'))
|
||||
send_event_for_current_user(
|
||||
Event(EventType.CHILD_ROUTINES_SET.value, ChildRoutinesSet(child.get('id'), routine_ids))
|
||||
)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(id, RoutineModified.OPERATION_DELETE))
|
||||
)
|
||||
return jsonify({'message': f'Routine {id} deleted.'}), 200
|
||||
126
backend/api/routine_item_api.py
Normal file
126
backend/api/routine_item_api.py
Normal file
@@ -0,0 +1,126 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from tinydb import Query
|
||||
|
||||
from api.utils import get_validated_user_id, send_event_for_current_user
|
||||
from db.db import routine_db
|
||||
from db.routine_items import add_item, delete_item, get_item, get_items_for_routine, update_item
|
||||
from events.types.event import Event
|
||||
from events.types.event_types import EventType
|
||||
from events.types.routine_modified import RoutineModified
|
||||
from models.routine_item import RoutineItem
|
||||
|
||||
routine_item_api = Blueprint('routine_item_api', __name__)
|
||||
|
||||
|
||||
def _validate_routine_owned_by_user(routine_id: str, user_id: str):
|
||||
q = Query()
|
||||
return routine_db.get((q.id == routine_id) & ((q.user_id == user_id) | (q.user_id == None)))
|
||||
|
||||
|
||||
@routine_item_api.route('/routine/<routine_id>/item/add', methods=['PUT'])
|
||||
def add_routine_item(routine_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
routine = _validate_routine_owned_by_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
name = data.get('name', '').strip()
|
||||
image_id = data.get('image_id')
|
||||
|
||||
if not name:
|
||||
return jsonify({'error': 'name is required'}), 400
|
||||
|
||||
existing_items = get_items_for_routine(routine_id)
|
||||
order = data.get('order', len(existing_items))
|
||||
|
||||
item = RoutineItem(routine_id=routine_id, name=name, image_id=image_id, order=order)
|
||||
add_item(item)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(routine_id, RoutineModified.OPERATION_EDIT))
|
||||
)
|
||||
return jsonify(item.to_dict()), 201
|
||||
|
||||
|
||||
@routine_item_api.route('/routine/<routine_id>/item/<item_id>/edit', methods=['PUT'])
|
||||
def edit_routine_item(routine_id, item_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
routine = _validate_routine_owned_by_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
existing = get_item(item_id)
|
||||
if not existing or existing.routine_id != routine_id:
|
||||
return jsonify({'error': 'Item not found'}), 404
|
||||
|
||||
data = request.get_json(force=True) or {}
|
||||
is_dirty = False
|
||||
|
||||
if 'name' in data:
|
||||
name = data.get('name', '').strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'name cannot be empty'}), 400
|
||||
existing.name = name
|
||||
is_dirty = True
|
||||
|
||||
if 'image_id' in data:
|
||||
existing.image_id = data.get('image_id')
|
||||
is_dirty = True
|
||||
|
||||
if 'order' in data:
|
||||
order = data.get('order')
|
||||
if not isinstance(order, int) or order < 0:
|
||||
return jsonify({'error': 'order must be a non-negative integer'}), 400
|
||||
existing.order = order
|
||||
is_dirty = True
|
||||
|
||||
if not is_dirty:
|
||||
return jsonify({'error': 'No valid fields to update'}), 400
|
||||
|
||||
update_item(existing)
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(routine_id, RoutineModified.OPERATION_EDIT))
|
||||
)
|
||||
return jsonify(existing.to_dict()), 200
|
||||
|
||||
|
||||
@routine_item_api.route('/routine/<routine_id>/item/<item_id>', methods=['DELETE'])
|
||||
def delete_routine_item(routine_id, item_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
routine = _validate_routine_owned_by_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
item = get_item(item_id)
|
||||
if not item or item.routine_id != routine_id:
|
||||
return jsonify({'error': 'Item not found'}), 404
|
||||
|
||||
delete_item(item_id)
|
||||
send_event_for_current_user(
|
||||
Event(EventType.ROUTINE_MODIFIED.value, RoutineModified(routine_id, RoutineModified.OPERATION_EDIT))
|
||||
)
|
||||
return jsonify({'message': 'Item deleted'}), 200
|
||||
|
||||
|
||||
@routine_item_api.route('/routine/<routine_id>/items', methods=['GET'])
|
||||
def list_routine_items(routine_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': 'UNAUTHORIZED'}), 401
|
||||
|
||||
routine = _validate_routine_owned_by_user(routine_id, user_id)
|
||||
if not routine:
|
||||
return jsonify({'error': 'Routine not found'}), 404
|
||||
|
||||
items = [item.to_dict() for item in get_items_for_routine(routine_id)]
|
||||
return jsonify({'items': items, 'count': len(items)}), 200
|
||||
178
backend/api/routine_schedule_api.py
Normal file
178
backend/api/routine_schedule_api.py
Normal file
@@ -0,0 +1,178 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from tinydb import Query
|
||||
|
||||
from api.error_codes import ErrorCodes
|
||||
from api.utils import get_validated_user_id, send_event_for_current_user
|
||||
from db.db import child_db, pending_confirmations_db
|
||||
from db.routine_extensions import add_extension, delete_extension_for_child_routine, get_extension
|
||||
from db.routine_schedules import delete_schedule, get_schedule, upsert_schedule
|
||||
from events.types.child_routine_confirmation import ChildRoutineConfirmation
|
||||
from events.types.event import Event
|
||||
from events.types.event_types import EventType
|
||||
from events.types.routine_schedule_modified import RoutineScheduleModified
|
||||
from events.types.routine_time_extended import RoutineTimeExtended
|
||||
from models.routine_extension import RoutineExtension
|
||||
from models.routine_schedule import RoutineSchedule
|
||||
|
||||
routine_schedule_api = Blueprint('routine_schedule_api', __name__)
|
||||
|
||||
|
||||
def _validate_child(child_id: str, user_id: str):
|
||||
q = Query()
|
||||
result = child_db.search((q.id == child_id) & (q.user_id == user_id))
|
||||
return result[0] if result else None
|
||||
|
||||
|
||||
@routine_schedule_api.route('/child/<child_id>/routine/<routine_id>/schedule', methods=['GET'])
|
||||
def get_routine_schedule(child_id, routine_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
if not _validate_child(child_id, user_id):
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
schedule = get_schedule(child_id, routine_id)
|
||||
if not schedule:
|
||||
return jsonify({'error': 'Schedule not found'}), 404
|
||||
|
||||
return jsonify(schedule.to_dict()), 200
|
||||
|
||||
|
||||
@routine_schedule_api.route('/child/<child_id>/routine/<routine_id>/schedule', methods=['PUT'])
|
||||
def set_routine_schedule(child_id, routine_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
if not _validate_child(child_id, user_id):
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
mode = data.get('mode')
|
||||
if mode not in ('days', 'interval'):
|
||||
return jsonify({'error': 'mode must be "days" or "interval"', 'code': ErrorCodes.INVALID_VALUE}), 400
|
||||
|
||||
enabled = data.get('enabled', True)
|
||||
if not isinstance(enabled, bool):
|
||||
return jsonify({'error': 'enabled must be a boolean', 'code': ErrorCodes.INVALID_VALUE}), 400
|
||||
|
||||
if mode == 'days':
|
||||
day_configs = data.get('day_configs', [])
|
||||
if not isinstance(day_configs, list):
|
||||
return jsonify({'error': 'day_configs must be a list', 'code': ErrorCodes.INVALID_VALUE}), 400
|
||||
|
||||
schedule = RoutineSchedule(
|
||||
child_id=child_id,
|
||||
routine_id=routine_id,
|
||||
mode='days',
|
||||
day_configs=day_configs,
|
||||
default_hour=data.get('default_hour', 8),
|
||||
default_minute=data.get('default_minute', 0),
|
||||
default_has_deadline=data.get('default_has_deadline', True),
|
||||
enabled=enabled,
|
||||
)
|
||||
else:
|
||||
interval_days = data.get('interval_days', 2)
|
||||
anchor_date = data.get('anchor_date', '')
|
||||
interval_has_deadline = data.get('interval_has_deadline', True)
|
||||
interval_hour = data.get('interval_hour', 0)
|
||||
interval_minute = data.get('interval_minute', 0)
|
||||
|
||||
if not isinstance(interval_days, int) or not (1 <= interval_days <= 7):
|
||||
return jsonify({'error': 'interval_days must be an integer between 1 and 7', 'code': ErrorCodes.INVALID_VALUE}), 400
|
||||
|
||||
schedule = RoutineSchedule(
|
||||
child_id=child_id,
|
||||
routine_id=routine_id,
|
||||
mode='interval',
|
||||
interval_days=interval_days,
|
||||
anchor_date=anchor_date,
|
||||
interval_has_deadline=interval_has_deadline,
|
||||
interval_hour=interval_hour,
|
||||
interval_minute=interval_minute,
|
||||
enabled=enabled,
|
||||
)
|
||||
|
||||
delete_extension_for_child_routine(child_id, routine_id)
|
||||
upsert_schedule(schedule)
|
||||
|
||||
pending_q = Query()
|
||||
pending_routines = pending_confirmations_db.search(
|
||||
(pending_q.child_id == child_id) & (pending_q.entity_id == routine_id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.status == 'pending')
|
||||
)
|
||||
for _ in pending_routines:
|
||||
pending_confirmations_db.remove(
|
||||
(pending_q.child_id == child_id) & (pending_q.entity_id == routine_id) &
|
||||
(pending_q.entity_type == 'routine') & (pending_q.status == 'pending')
|
||||
)
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.CHILD_ROUTINE_CONFIRMATION.value,
|
||||
ChildRoutineConfirmation(child_id, routine_id, ChildRoutineConfirmation.OPERATION_RESET)
|
||||
)
|
||||
)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.ROUTINE_SCHEDULE_MODIFIED.value,
|
||||
RoutineScheduleModified(child_id, routine_id, RoutineScheduleModified.OPERATION_SET)
|
||||
)
|
||||
)
|
||||
|
||||
return jsonify(schedule.to_dict()), 200
|
||||
|
||||
|
||||
@routine_schedule_api.route('/child/<child_id>/routine/<routine_id>/schedule', methods=['DELETE'])
|
||||
def delete_routine_schedule(child_id, routine_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
if not _validate_child(child_id, user_id):
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
removed = delete_schedule(child_id, routine_id)
|
||||
if not removed:
|
||||
return jsonify({'error': 'Schedule not found'}), 404
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.ROUTINE_SCHEDULE_MODIFIED.value,
|
||||
RoutineScheduleModified(child_id, routine_id, RoutineScheduleModified.OPERATION_DELETED)
|
||||
)
|
||||
)
|
||||
return jsonify({'message': 'Schedule deleted'}), 200
|
||||
|
||||
|
||||
@routine_schedule_api.route('/child/<child_id>/routine/<routine_id>/extend', methods=['POST'])
|
||||
def extend_routine_time(child_id, routine_id):
|
||||
user_id = get_validated_user_id()
|
||||
if not user_id:
|
||||
return jsonify({'error': 'Unauthorized', 'code': ErrorCodes.UNAUTHORIZED}), 401
|
||||
|
||||
if not _validate_child(child_id, user_id):
|
||||
return jsonify({'error': 'Child not found', 'code': ErrorCodes.CHILD_NOT_FOUND}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
date = data.get('date')
|
||||
if not date or not isinstance(date, str):
|
||||
return jsonify({'error': 'date is required (ISO date string)', 'code': ErrorCodes.MISSING_FIELD}), 400
|
||||
|
||||
existing = get_extension(child_id, routine_id, date)
|
||||
if existing:
|
||||
return jsonify({'error': 'Routine already extended for this date', 'code': 'ALREADY_EXTENDED'}), 409
|
||||
|
||||
delete_extension_for_child_routine(child_id, routine_id)
|
||||
extension = RoutineExtension(child_id=child_id, routine_id=routine_id, date=date)
|
||||
add_extension(extension)
|
||||
|
||||
send_event_for_current_user(
|
||||
Event(
|
||||
EventType.ROUTINE_TIME_EXTENDED.value,
|
||||
RoutineTimeExtended(child_id, routine_id)
|
||||
)
|
||||
)
|
||||
|
||||
return jsonify(extension.to_dict()), 200
|
||||
Reference in New Issue
Block a user