Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
ui: Add total number of reports in web report
Clémence Lesné107eb463058b
diff --git a/main.py b/main.pyindex 65bdb09..dfe4643 100644--- a/main.py+++ b/main.py@@ -152,7 +152,7 @@ async def report_get(phone_number: Optional[Union[PhoneNumber, Literal[""]]] = None,) -> HTMLResponse:count = 100- calls = (+ calls, total = (await _db.call_asearch_all(count=count,phone_number=phone_number or None,@@ -165,6 +165,7 @@ async def report_get(calls=calls or [],count=count,phone_number=phone_number,+ total=total,version=CONFIG.version,)render = html_minify(render) # Minify HTML@@ -196,14 +197,15 @@ async def report_single_get(call_id: UUID) -> HTMLResponse:return HTMLResponse(content=render)+# TODO: Add total (int) and calls (list) as a wrapper for the list of calls@api.get("/call",description="Search all calls by phone number.",name="Search calls",)async def call_search_get(phone_number: PhoneNumber) -> list[CallGetModel]:- calls = await _db.call_asearch_all(phone_number=phone_number, count=1) or []- output = [CallGetModel.model_validate(call) for call in calls]+ calls, _ = await _db.call_asearch_all(phone_number=phone_number, count=1)+ output = [CallGetModel.model_validate(call) for call in calls or []]return outputdiff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex d3fecae..ad0826e 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -1,3 +1,4 @@+import asynciofrom azure.core.exceptions import ServiceResponseErrorfrom azure.cosmos.aio import CosmosClient, ContainerProxyfrom azure.cosmos.exceptions import CosmosHttpResponseError@@ -136,8 +137,19 @@ class CosmosDbStore(IStore):self,count: int,phone_number: Optional[str] = None,- ) -> Optional[list[CallStateModel]]:+ ) -> tuple[Optional[list[CallStateModel]], int]:_logger.debug(f"Searching calls, for {phone_number} and count {count}")+ calls, total = await asyncio.gather(+ self._call_asearch_all_calls_worker(count, phone_number),+ self._call_asearch_all_total_worker(phone_number),+ )+ return calls, total++ async def _call_asearch_all_calls_worker(+ self,+ count: int,+ phone_number: Optional[str] = None,+ ) -> Optional[list[CallStateModel]]:calls: list[CallStateModel] = []try:async with self._use_db() as db:@@ -165,6 +177,26 @@ class CosmosDbStore(IStore):_logger.error(f"Error accessing CosmosDB, {e}")return calls+ async def _call_asearch_all_total_worker(+ self,+ phone_number: Optional[str] = None,+ ) -> int:+ try:+ async with self._use_db() as db:+ items = db.query_items(+ query=f"SELECT VALUE COUNT(1) FROM c {"WHERE STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""}",+ parameters=[+ {+ "name": "@phone_number",+ "value": phone_number,+ },+ ],+ )+ total: int = await anext(items) # type: ignore+ except CosmosHttpResponseError as e:+ _logger.error(f"Error accessing CosmosDB, {e}")+ return total if total else 0+@asynccontextmanagerasync def _use_db(self) -> AsyncGenerator[ContainerProxy, None]:"""diff --git a/persistence/istore.py b/persistence/istore.pyindex ba74d75..a0ffda6 100644--- a/persistence/istore.py+++ b/persistence/istore.py@@ -28,5 +28,5 @@ class IStore(ABC):self,count: int,phone_number: Optional[str] = None,- ) -> Optional[list[CallStateModel]]:+ ) -> tuple[Optional[list[CallStateModel]], int]:passdiff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex 15d7ea5..8687653 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -10,6 +10,7 @@ from persistence.istore import IStorefrom pydantic import ValidationErrorfrom typing import AsyncGenerator, Optionalfrom uuid import UUID+import asyncioimport os@@ -96,8 +97,19 @@ class SqliteStore(IStore):self,count: int,phone_number: Optional[str] = None,- ) -> Optional[list[CallStateModel]]:+ ) -> tuple[Optional[list[CallStateModel]], int]:_logger.debug(f"Searching calls, for {phone_number} and count {count}")+ calls, total = await asyncio.gather(+ self._call_asearch_all_calls_worker(count, phone_number),+ self._call_asearch_all_total_worker(phone_number),+ )+ return calls, total++ async def _call_asearch_all_calls_worker(+ self,+ count: int,+ phone_number: Optional[str] = None,+ ) -> Optional[list[CallStateModel]]:calls: list[CallStateModel] = []async with self._use_db() as db:cursor = await db.execute(@@ -106,6 +118,8 @@ class SqliteStore(IStore):phone_number, # data.phone_numberphone_number, # data.claim.policyholder_phonecount, # limit+ ) if phone_number else (+ count, # limit),)rows = await cursor.fetchall()@@ -118,6 +132,21 @@ class SqliteStore(IStore):_logger.debug(f"Parsing error: {e.errors()}")return calls+ async def _call_asearch_all_total_worker(+ self,+ phone_number: Optional[str] = None,+ ) -> int:+ async with self._use_db() as db:+ cursor = await db.execute(+ f"SELECT COUNT(*) FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""}",+ (+ phone_number, # data.phone_number+ phone_number, # data.claim.policyholder_phone+ ) if phone_number else (),+ )+ row = await cursor.fetchone()+ return int(row[0]) if row else 0+async def _init_db(self, db: SQLiteConnection):"""Initialize the database.diff --git a/public_website/list.html.jinja b/public_website/list.html.jinjaindex 1c09de1..3c6a31a 100644--- a/public_website/list.html.jinja+++ b/public_website/list.html.jinja@@ -32,5 +32,11 @@ History for {{ phone_number or 'all numbers' }}</a>{% endfor %}</div>-<div class="col-span-full px-4 text-neutral-600 dark:text-neutral-400">The {{ count }} first results are displayed.</div>+<div class="col-span-full px-4 text-neutral-600 dark:text-neutral-400">+ {% if total < count %}+ All {{ total }} results are displayed.+ {% else %}+ The {{ count }} first results over {{ total }} are displayed.+ {% endif %}+</div>{% endblock %}diff --git a/tests/store.py b/tests/store.pyindex 17b6ee4..e27cf3b 100644--- a/tests/store.py+++ b/tests/store.py@@ -42,7 +42,8 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> Noassume(callnot in (- await db.call_asearch_all(phone_number=call.phone_number, count=1) or []+ (await db.call_asearch_all(phone_number=call.phone_number, count=1))[0]+ or []))@@ -56,5 +57,8 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No# Check search allassume(call- in (await db.call_asearch_all(phone_number=call.phone_number, count=1) or [])+ in (+ (await db.call_asearch_all(phone_number=call.phone_number, count=1))[0]+ or []+ ))