afnrmdhn commited on
Commit
d1f773f
·
1 Parent(s): 37b3183

add books endpoints

Browse files
Files changed (1) hide show
  1. api/routes/books.py +193 -76
api/routes/books.py CHANGED
@@ -4,6 +4,7 @@ Public endpoints for listing and filtering books in the catalog.
4
 
5
  import json
6
  import math
 
7
  from pathlib import Path
8
  import sys
9
 
@@ -18,51 +19,134 @@ from utils.logger import get_logger
18
  logger = get_logger(__name__)
19
  books_bp = Blueprint('books', __name__)
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  @books_bp.route('/books/filters', methods=['GET'])
22
  def get_book_filters():
23
  """
24
  Returns unique values for filtering options: jenjang, kelas, and mata_pelajaran.
25
- Iterates over the in-memory book_metadata_map for speed.
26
  """
27
  try:
28
- book_metadata_map = current_app.config.get('book_metadata_map', {})
29
-
30
- jenjang_set = set()
31
- kelas_set = set()
32
- mapel_set = set()
33
-
34
- for book in book_metadata_map.values():
35
- jenjang = book.get('jenjang')
36
- if jenjang and isinstance(jenjang, str) and jenjang.strip():
37
- jenjang_set.add(jenjang.strip())
38
-
39
- kelas = book.get('kelas')
40
- if kelas and isinstance(kelas, str) and kelas.strip():
41
- kelas_set.add(kelas.strip())
42
-
43
- mapel = book.get('mata_pelajaran')
44
- if mapel and isinstance(mapel, str) and mapel.strip():
45
- mapel_set.add(mapel.strip())
46
-
47
- response = jsonify({
48
- "jenjang": sorted(list(jenjang_set)),
49
- "kelas": sorted(list(kelas_set)),
50
- "mata_pelajaran": sorted(list(mapel_set))
51
- })
52
-
53
- # Add Cache-Control header for aggressive caching (1 day)
54
- response.headers["Cache-Control"] = "public, max-age=86400"
55
  return response, 200
56
 
57
  except Exception as e:
58
  logger.error(f"Failed to fetch book filters: {e}", exc_info=True)
59
  return jsonify({"error": "Internal server error reading filters"}), 500
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  @books_bp.route('/books', methods=['GET'])
62
  def get_public_books():
63
  """
64
  Returns a paginated and filtered list of books from the source-of-truth ledger.
65
  Supports filtering by 'jenjang', 'kelas', 'mata_pelajaran' and generic 'search'.
 
66
  """
67
  try:
68
  page = int(request.args.get('page', 1))
@@ -79,8 +163,9 @@ def get_public_books():
79
  if page < 1 or limit < 1:
80
  return jsonify({"error": "Invalid pagination parameters"}), 400
81
 
82
- if not RAW_DATA_FILE.exists():
83
- return jsonify({
 
84
  "books": [],
85
  "total_books": 0,
86
  "total_pages": 0,
@@ -88,71 +173,103 @@ def get_public_books():
88
  }), 200
89
 
90
  all_books = []
91
- with open(RAW_DATA_FILE, 'r', encoding='utf-8') as f:
92
- for line in f:
93
- if line.strip():
94
- try:
95
- book_data = json.loads(line)
96
-
97
- # Apply filters
98
- if search_query:
99
- title = book_data.get('judul_buku', book_data.get('title', '')).lower()
100
- book_id = book_data.get('book_id', '').lower()
101
- if search_query not in title and search_query not in book_id:
102
- continue
103
-
104
- if jenjang_filter:
105
- b_jenjang = book_data.get('jenjang', '').lower()
106
- if jenjang_filter not in b_jenjang:
107
- continue
108
-
109
- if kelas_filter:
110
- b_kelas = book_data.get('kelas', '').lower()
111
- # Exact match or substring depending on preference, we use exact for 'kelas' to be safer
112
- # or substring for flexibility. E.g. "1" matches "Kelas 1".
113
- if kelas_filter != b_kelas and kelas_filter not in b_kelas:
114
- continue
115
-
116
- if mapel_filter:
117
- b_mapel = book_data.get('mata_pelajaran', '').lower()
118
- if mapel_filter not in b_mapel:
119
- continue
120
-
121
- all_books.append(book_data)
122
- except json.JSONDecodeError:
123
- continue
124
-
125
- total_books = len(all_books)
126
- total_pages = math.ceil(total_books / limit)
127
-
128
- # Exact slicing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  start_idx = (page - 1) * limit
130
  end_idx = start_idx + limit
131
- paginated_books = all_books[start_idx:end_idx]
132
 
133
  # Apply field filtering if requested
134
  result_books = []
135
  for book in paginated_books:
136
- # Ensure book_id is present
137
- if 'book_id' not in book and 'id' in book:
138
- book['book_id'] = book['id']
139
-
140
  if fields_list:
141
  filtered_book = {}
142
  for field in fields_list:
143
  val = book.get(field)
144
  if val is not None:
145
  filtered_book[field] = val
 
 
 
 
 
146
  result_books.append(filtered_book)
147
  else:
148
  result_books.append(book)
149
 
150
- return jsonify({
 
 
 
 
151
  "books": result_books,
152
- "total_books": total_books,
 
153
  "total_pages": total_pages,
154
  "current_page": page
155
- }), 200
 
 
 
 
 
 
156
 
157
  except Exception as e:
158
  logger.error(f"Failed to fetch public books: {e}", exc_info=True)
 
4
 
5
  import json
6
  import math
7
+ import threading
8
  from pathlib import Path
9
  import sys
10
 
 
19
  logger = get_logger(__name__)
20
  books_bp = Blueprint('books', __name__)
21
 
22
+ _filter_options = None
23
+ _book_stats = None
24
+ _cache_lock = threading.Lock()
25
+
26
+ def _compute_filter_options():
27
+ book_metadata_map = current_app.config.get('book_metadata_map', {})
28
+
29
+ jenjang_set = set()
30
+ kelas_set = set()
31
+ mapel_set = set()
32
+
33
+ for book in book_metadata_map.values():
34
+ jenjang = book.get('jenjang')
35
+ if jenjang and isinstance(jenjang, str) and jenjang.strip():
36
+ jenjang_set.add(jenjang.strip())
37
+
38
+ kelas = book.get('kelas')
39
+ if kelas and isinstance(kelas, str) and kelas.strip():
40
+ kelas_set.add(kelas.strip())
41
+
42
+ mapel = book.get('mata_pelajaran')
43
+ if mapel and isinstance(mapel, str) and mapel.strip():
44
+ mapel_set.add(mapel.strip())
45
+
46
+ # Sort kelas numerically, others alphabetically
47
+ sorted_kelas = []
48
+ for k in kelas_set:
49
+ try:
50
+ sorted_kelas.append((int(k), k))
51
+ except ValueError:
52
+ # If there's a non-numeric class like "TK", push to end or handle appropriately
53
+ sorted_kelas.append((999, k))
54
+ sorted_kelas.sort(key=lambda x: (x[0], x[1]))
55
+ sorted_kelas_list = [k[1] for k in sorted_kelas]
56
+
57
+ return {
58
+ "jenjang": sorted(list(jenjang_set)),
59
+ "kelas": sorted_kelas_list,
60
+ "mata_pelajaran": sorted(list(mapel_set))
61
+ }
62
+
63
+ def _get_filter_options():
64
+ global _filter_options
65
+ if _filter_options is not None:
66
+ return _filter_options
67
+ with _cache_lock:
68
+ if _filter_options is None:
69
+ _filter_options = _compute_filter_options()
70
+ return _filter_options
71
+
72
+ def _compute_book_stats():
73
+ book_metadata_map = current_app.config.get('book_metadata_map', {})
74
+
75
+ stats = {
76
+ "jenjang": {},
77
+ "mata_pelajaran": {},
78
+ "kelas": {},
79
+ "total_books": len(book_metadata_map)
80
+ }
81
+
82
+ for book in book_metadata_map.values():
83
+ jenjang = book.get('jenjang')
84
+ if jenjang and isinstance(jenjang, str) and jenjang.strip():
85
+ j_val = jenjang.strip()
86
+ stats["jenjang"][j_val] = stats["jenjang"].get(j_val, 0) + 1
87
+
88
+ mapel = book.get('mata_pelajaran')
89
+ if mapel and isinstance(mapel, str) and mapel.strip():
90
+ m_val = mapel.strip()
91
+ stats["mata_pelajaran"][m_val] = stats["mata_pelajaran"].get(m_val, 0) + 1
92
+
93
+ kelas = book.get('kelas')
94
+ if kelas and isinstance(kelas, str) and kelas.strip():
95
+ k_val = kelas.strip()
96
+ stats["kelas"][k_val] = stats["kelas"].get(k_val, 0) + 1
97
+
98
+ return stats
99
+
100
+ def _get_book_stats():
101
+ global _book_stats
102
+ if _book_stats is not None:
103
+ return _book_stats
104
+ with _cache_lock:
105
+ if _book_stats is None:
106
+ _book_stats = _compute_book_stats()
107
+ return _book_stats
108
+
109
+
110
  @books_bp.route('/books/filters', methods=['GET'])
111
  def get_book_filters():
112
  """
113
  Returns unique values for filtering options: jenjang, kelas, and mata_pelajaran.
114
+ Iterates over the in-memory book_metadata_map for speed and caches it.
115
  """
116
  try:
117
+ filters = _get_filter_options()
118
+ response = jsonify(filters)
119
+ # Add Cache-Control header for caching (1 hour)
120
+ response.headers["Cache-Control"] = "public, max-age=3600"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  return response, 200
122
 
123
  except Exception as e:
124
  logger.error(f"Failed to fetch book filters: {e}", exc_info=True)
125
  return jsonify({"error": "Internal server error reading filters"}), 500
126
 
127
+ @books_bp.route('/books/stats', methods=['GET'])
128
+ def get_book_stats():
129
+ """
130
+ Returns distribution counts per dimension (for treemap visualization).
131
+ Iterates over the in-memory book_metadata_map for speed and caches it.
132
+ """
133
+ try:
134
+ stats = _get_book_stats()
135
+ response = jsonify(stats)
136
+ response.headers["Cache-Control"] = "public, max-age=3600"
137
+ return response, 200
138
+
139
+ except Exception as e:
140
+ logger.error(f"Failed to fetch book stats: {e}", exc_info=True)
141
+ return jsonify({"error": "Internal server error reading stats"}), 500
142
+
143
+
144
  @books_bp.route('/books', methods=['GET'])
145
  def get_public_books():
146
  """
147
  Returns a paginated and filtered list of books from the source-of-truth ledger.
148
  Supports filtering by 'jenjang', 'kelas', 'mata_pelajaran' and generic 'search'.
149
+ Reads from the in-memory book_metadata_map for speed.
150
  """
151
  try:
152
  page = int(request.args.get('page', 1))
 
163
  if page < 1 or limit < 1:
164
  return jsonify({"error": "Invalid pagination parameters"}), 400
165
 
166
+ book_metadata_map = current_app.config.get('book_metadata_map', {})
167
+ if not book_metadata_map:
168
+ return jsonify({
169
  "books": [],
170
  "total_books": 0,
171
  "total_pages": 0,
 
173
  }), 200
174
 
175
  all_books = []
176
+
177
+ for book_data in book_metadata_map.values():
178
+ # Apply exact filters (AND logic)
179
+ if jenjang_filter:
180
+ b_jenjang = book_data.get('jenjang', '').lower()
181
+ if jenjang_filter not in b_jenjang:
182
+ continue
183
+
184
+ if kelas_filter:
185
+ b_kelas = book_data.get('kelas', '').lower()
186
+ if kelas_filter != b_kelas and kelas_filter not in b_kelas:
187
+ continue
188
+
189
+ if mapel_filter:
190
+ b_mapel = book_data.get('mata_pelajaran', '').lower()
191
+ if mapel_filter not in b_mapel:
192
+ continue
193
+
194
+ # Apply search logic and scoring
195
+ score = 0
196
+ if search_query:
197
+ title_lower = book_data.get('judul_buku', book_data.get('title', '')).lower()
198
+ mapel_lower = book_data.get('mata_pelajaran', '').lower()
199
+ jenjang_lower = book_data.get('jenjang', '').lower()
200
+ tipe_lower = book_data.get('tipe', '').lower()
201
+
202
+ if search_query == title_lower:
203
+ score = 3
204
+ elif search_query in title_lower:
205
+ score = 2
206
+ elif (search_query in mapel_lower or
207
+ search_query in jenjang_lower or
208
+ search_query in tipe_lower):
209
+ score = 1
210
+ else:
211
+ score = 0 # No match
212
+
213
+ if score == 0:
214
+ continue # Exclude if there's a search query but no match
215
+
216
+ # Use a dict copy to avoid mutating the global in-memory cache
217
+ book_dict = dict(book_data)
218
+ # Ensure book_id is present
219
+ if 'book_id' not in book_dict and 'id' in book_dict:
220
+ book_dict['book_id'] = book_dict['id']
221
+
222
+ all_books.append((score, book_dict))
223
+
224
+ # Sort the results: first by score (descending), then alphabetically by judul_buku (ascending)
225
+ all_books.sort(key=lambda x: (-x[0], x[1].get('judul_buku', x[1].get('title', '')).lower()))
226
+
227
+ # Extract just the book dicts after sorting
228
+ sorted_books = [book for score, book in all_books]
229
+
230
+ total_books = len(sorted_books)
231
+ total_pages = math.ceil(total_books / limit) if limit > 0 else 0
232
+
233
+ # Exact slicing for pagination
234
  start_idx = (page - 1) * limit
235
  end_idx = start_idx + limit
236
+ paginated_books = sorted_books[start_idx:end_idx]
237
 
238
  # Apply field filtering if requested
239
  result_books = []
240
  for book in paginated_books:
 
 
 
 
241
  if fields_list:
242
  filtered_book = {}
243
  for field in fields_list:
244
  val = book.get(field)
245
  if val is not None:
246
  filtered_book[field] = val
247
+ # Make sure book_id is always present if fields are requested?
248
+ # Let's add it if requested or we assume the frontend requests it.
249
+ # Standard practice is to always include the primary key if available.
250
+ if 'book_id' not in filtered_book and 'book_id' in book:
251
+ filtered_book['book_id'] = book['book_id']
252
  result_books.append(filtered_book)
253
  else:
254
  result_books.append(book)
255
 
256
+ # Get total overall books from stats (not just filtered)
257
+ stats = _get_book_stats()
258
+ overall_total_books = stats.get('total_books', 0)
259
+
260
+ response = jsonify({
261
  "books": result_books,
262
+ "total_books": total_books, # Total books matching the filter/search
263
+ "total_overall_books": overall_total_books, # Total books in catalog
264
  "total_pages": total_pages,
265
  "current_page": page
266
+ })
267
+
268
+ # Optional: set Cache-Control no-store for paginated responses
269
+ # (Though Flask's default is no cache, explicitly setting it is good practice)
270
+ response.headers["Cache-Control"] = "no-store"
271
+
272
+ return response, 200
273
 
274
  except Exception as e:
275
  logger.error(f"Failed to fetch public books: {e}", exc_info=True)