bmc_hub/app/workflows/preview.py

40 lines
2.9 KiB
Python
Raw Normal View History

"""Read-only billing prediction for a time registration that has not been saved."""
from .service import transaction, load_case_context, json_safe
from .integration import active_for_customer
from .classification import enrich_entity_context
from .engine import evaluate
def preview_case_billing(case_id, minutes=30, description='', time_type='support'):
with transaction() as cursor:
context = load_case_context(case_id, cursor)
if context.get('deleted_at'):
raise ValueError('Case not found')
if not active_for_customer(context.get('customer_id')):
return {'status': 'draft', 'method': 'draft', 'reason': 'workflows_inactive'}
context.pop('subject', None)
context.update(entity_type='time_entry', time_id=None,
case_title=context.get('titel'), case_description=context.get('beskrivelse'),
hours=minutes / 60, original_hours=minutes / 60,
description=description, time_type=time_type, status='pending', worked_date=None)
customer_id = context.get('customer_id')
if customer_id:
cursor.execute("SELECT * FROM customer_fixed_price_agreements WHERE customer_id=%s AND status IN ('active','pending_cancellation') AND start_date<=COALESCE(%s::date,CURRENT_DATE) AND (end_date IS NULL OR end_date>=COALESCE(%s::date,CURRENT_DATE)) AND (cancellation_effective_date IS NULL OR cancellation_effective_date>COALESCE(%s::date,CURRENT_DATE))", (int(customer_id), None, None, None))
context['agreements'] = cursor.fetchall()
cursor.execute("SELECT * FROM tticket_prepaid_cards WHERE customer_id=%s AND status='active' AND (expires_at IS NULL OR expires_at>now())", (int(customer_id),))
context['cards'] = cursor.fetchall()
else:
context['agreements'], context['cards'] = [], []
context['has_active_agreement'] = bool(context['agreements'])
context['has_active_card'] = bool(context['cards'])
context['remaining_card_hours'] = context['cards'][0].get('remaining_hours') if len(context['cards']) == 1 else (0 if not context['cards'] else None)
context['has_available_card'] = any(float(card.get('remaining_hours') or 0) > 0 for card in context['cards'])
context = enrich_entity_context(cursor, json_safe(context), 'time_entry', None)
cursor.execute('SELECT w.*,v.id AS version_id,v.definition FROM bmc_workflows w JOIN bmc_workflow_versions v ON v.id=w.active_version_id AND v.workflow_id=w.id WHERE w.enabled=TRUE')
result = evaluate(cursor.fetchall(), context, 'time.created')
prediction = {key: result.get(key) for key in ('status', 'method', 'reason')}
for key in ('agreement_id', 'card_id'):
if result.get('decision', {}).get(key) is not None:
prediction[key] = result['decision'][key]
return prediction