Get the latest selected-paper batch for a user. Returns: Dict with push_id / selection_time / papers, or None when no selection exists.
(user_id: str)
| 1465 | |
| 1466 | |
| 1467 | def get_latest_selected_papers(user_id: str) -> Optional[Dict]: |
| 1468 | """ |
| 1469 | Get the latest selected-paper batch for a user. |
| 1470 | |
| 1471 | Returns: |
| 1472 | Dict with push_id / selection_time / papers, or None when no selection exists. |
| 1473 | """ |
| 1474 | conn = get_connection() |
| 1475 | cursor = conn.cursor() |
| 1476 | |
| 1477 | clear_after_log_id = _get_latest_selection_clear_log_id(cursor, user_id) |
| 1478 | latest_batch_sql = """ |
| 1479 | SELECT push_id, MAX(timestamp) AS timestamp |
| 1480 | FROM behavior_logs |
| 1481 | WHERE user_id = ? |
| 1482 | AND action = 'selected' |
| 1483 | """ |
| 1484 | latest_batch_params: List[Any] = [user_id] |
| 1485 | if clear_after_log_id is not None: |
| 1486 | latest_batch_sql += " AND id > ?" |
| 1487 | latest_batch_params.append(clear_after_log_id) |
| 1488 | latest_batch_sql += """ |
| 1489 | GROUP BY push_id |
| 1490 | ORDER BY timestamp DESC, push_id DESC |
| 1491 | LIMIT 1 |
| 1492 | """ |
| 1493 | cursor.execute(latest_batch_sql, latest_batch_params) |
| 1494 | |
| 1495 | row = cursor.fetchone() |
| 1496 | if not row: |
| 1497 | conn.close() |
| 1498 | return None |
| 1499 | |
| 1500 | push_id = row["push_id"] |
| 1501 | selection_time = row["timestamp"] |
| 1502 | |
| 1503 | cursor.execute( |
| 1504 | """ |
| 1505 | SELECT p.*, bl.id AS behavior_log_id, bl.metadata AS bl_metadata, |
| 1506 | push_bl.metadata AS push_metadata |
| 1507 | FROM papers p |
| 1508 | JOIN behavior_logs bl ON p.id = bl.paper_id |
| 1509 | LEFT JOIN behavior_logs push_bl |
| 1510 | ON push_bl.user_id = bl.user_id |
| 1511 | AND push_bl.push_id = bl.push_id |
| 1512 | AND push_bl.paper_id = bl.paper_id |
| 1513 | AND push_bl.action = 'pushed' |
| 1514 | WHERE bl.user_id = ? |
| 1515 | AND bl.push_id = ? |
| 1516 | AND bl.action = 'selected' |
| 1517 | ORDER BY bl.id ASC |
| 1518 | """, |
| 1519 | (user_id, push_id), |
| 1520 | ) |
| 1521 | |
| 1522 | papers = [ |
| 1523 | _build_paper_dict( |
| 1524 | row, |