ass="lines-num lines-num-new"> 166
+    if (loadingMore || !hasMore) return;
167
+    setLoadingMore(true);
168
+    const nextPage = page + 1;
169
+    await fetchObservationsPage(nextPage, false);
170
+  }
171
+
172
+  const observationQuery = `
173
+    SELECT o.id, o.field_id, o.crop_id, o.obs_type, o.note, o.severity, o.observed_at,
174
+           f.name as field_name, c.crop_name as crop_name,
175
+           i.uri as image_uri
176
+    FROM observations o
177
+    LEFT JOIN fields f ON f.id = o.field_id
178
+    LEFT JOIN crops c ON c.id = o.crop_id
179
+    LEFT JOIN images i ON i.id = (
180
+      SELECT id FROM images WHERE observation_id = o.id ORDER BY created_at DESC LIMIT 1
181
+    )
182
+    ORDER BY o.observed_at DESC
183
+    LIMIT ? OFFSET ?;`;
184
+
185
+  async function handleSave() {
186
+    const parsedSeverity = severity.trim() ? Number(severity) : null;
187
+    const nextErrors: { field?: string; severity?: string } = {};
188
+    if (!selectedFieldId) {
189
+      nextErrors.field = t('observations.fieldRequired');
190
+    }
191
+    if (severity.trim() && !Number.isFinite(parsedSeverity)) {
192
+      nextErrors.severity = t('observations.severityInvalid');
193
+    }
194
+    setNewErrors(nextErrors);
195
+    if (Object.keys(nextErrors).length > 0) {
196
+      setStatus(nextErrors.field ?? nextErrors.severity ?? t('observations.fieldRequired'));
197
+      return false;
198
+    }
199
+    try {
200
+      const db = await dbPromise;
201
+      const now = new Date().toISOString();
202
+      const result = await db.runAsync(
203
+        'INSERT INTO observations (field_id, crop_id, obs_type, note, severity, observed_at) VALUES (?, ?, ?, ?, ?, ?);',
204
+        selectedFieldId,
205
+        selectedCropId,
206
+        type.trim() || null,
207
+        note.trim() || null,
208
+        parsedSeverity,
209
+        now
210
+      );
211
+      const newId = result.lastInsertRowId;
212
+      if (photoUri && newId) {
213
+        await db.runAsync(
214
+          'INSERT INTO images (observation_id, uri, created_at) VALUES (?, ?, ?);',
215
+          newId,
216
+          photoUri,
217
+          now
218
+        );
219
+      }
220
+      setNote('');
221
+      setSeverity('');
222
+      setPhotoUri(null);
223
+      setNewErrors({});
224
+      setStatus(t('observations.saved'));
225
+      await fetchObservationsPage(1, true);
226
+      return true;
227
+    } catch (error) {
228
+      setStatus(`Error: ${String(error)}`);
229
+      return false;
230
+    }
231
+  }
232
+
233
+  async function handleDelete(id: number) {
234
+    try {
235
+      const db = await dbPromise;
236
+      await db.runAsync('DELETE FROM images WHERE observation_id = ?;', id);
237
+      await db.runAsync('DELETE FROM observations WHERE id = ?;', id);
238
+      await fetchObservationsPage(1, true);
239
+    } catch (error) {
240
+      setStatus(`Error: ${String(error)}`);
241
+    }
242
+  }
243
+
244
+  function startEdit(obs: ObservationRow) {
245
+    setEditingId(obs.id);
246
+    setEditFieldId(obs.field_id ?? null);
247
+    setEditCropId(obs.crop_id ?? null);
248
+    setEditType(obs.obs_type ?? '');
249
+    setEditSeverity(obs.severity !== null ? String(obs.severity) : '');
250
+    setEditNote(obs.note ?? '');
251
+    setEditPhotoUri(obs.image_uri ?? null);
252
+    setEditErrors({});
253
+    setEditModalOpen(true);
254
+  }
255
+
256
+  function cancelEdit() {
257
+    setEditingId(null);
258
+    setEditFieldId(null);
259
+    setEditCropId(null);
260
+    setEditType('');
261
+    setEditSeverity('');
262
+    setEditNote('');
263
+    setEditPhotoUri(null);
264
+    setEditErrors({});
265
+    setEditModalOpen(false);
266
+  }
267
+
268
+  async function handleUpdate() {
269
+    if (!editingId) return;
270
+    const parsedSeverity = editSeverity.trim() ? Number(editSeverity) : null;
271
+    const nextErrors: { field?: string; severity?: string } = {};
272
+    if (!editFieldId) {
273
+      nextErrors.field = t('observations.fieldRequired');
274
+    }
275
+    if (editSeverity.trim() && !Number.isFinite(parsedSeverity)) {
276
+      nextErrors.severity = t('observations.severityInvalid');
277
+    }
278
+    setEditErrors(nextErrors);
279
+    if (Object.keys(nextErrors).length > 0) {
280
+      setStatus(nextErrors.field ?? nextErrors.severity ?? t('observations.fieldRequired'));
281
+      return;
282
+    }
283
+    try {
284
+      const db = await dbPromise;
285
+      await db.runAsync(
286
+        'UPDATE observations SET field_id = ?, crop_id = ?, obs_type = ?, note = ?, severity = ? WHERE id = ?;',
287
+        editFieldId,
288
+        editCropId,
289
+        editType.trim() || null,
290
+        editNote.trim() || null,
291
+        parsedSeverity,
292
+        editingId
293
+      );
294
+      await db.runAsync('DELETE FROM images WHERE observation_id = ?;', editingId);
295
+      if (editPhotoUri) {
296
+        await db.runAsync(
297
+          'INSERT INTO images (observation_id, uri, created_at) VALUES (?, ?, ?);',
298
+          editingId,
299
+          editPhotoUri,
300
+          new Date().toISOString()
301
+        );
302
+      }
303
+      setEditModalOpen(false);
304
+      setEditingId(null);
305
+      setEditErrors({});
306
+      setStatus(t('observations.saved'));
307
+      await fetchObservationsPage(1, true);
308
+    } catch (error) {
309
+      setStatus(`Error: ${String(error)}`);
310
+    }
311
+  }
312
+
313
+  const inputStyle = [
314
+    styles.input,
315
+    { borderColor: palette.border, backgroundColor: palette.input, color: palette.text },
316
+  ];
317
+
318
+  return (
319
+    <>
320
+      <FlatList
321
+        data={observations}
322
+        keyExtractor={(item) => String(item.id)}
323
+        onEndReached={handleLoadMore}
324
+        onEndReachedThreshold={0.4}
325
+        renderItem={({ item }) => (
326
+          <Pressable onPress={() => startEdit(item)}>
327
+          <ThemedView style={[styles.card, { backgroundColor: palette.card, borderColor: palette.border }]}>
328
+              <ThemedText type="subtitle">{item.obs_type || t('observations.untitled')}</ThemedText>
329
+              <ThemedText style={styles.meta}>
330
+                {item.field_name || t('observations.noField')} ·{' '}
331
+                {item.crop_name || t('observations.noCrop')}
332
+              </ThemedText>
333
+              {item.severity !== null ? (
334
+                <ThemedText style={styles.meta}>
335
+                  {t('observations.severityLabel')} {item.severity}
336
+                </ThemedText>
337
+              ) : null}
338
+              {item.note ? <ThemedText>{item.note}</ThemedText> : null}
339
+              {item.image_uri ? (
340
+                <Image
341
+                  source={{ uri: item.image_uri }}
342
+                  style={styles.photoPreview}
343
+                  resizeMode="cover"
344
+                />
345
+              ) : null}
346
+              {item.observed_at ? (
347
+                <ThemedText style={styles.meta}>{formatDate(item.observed_at)}</ThemedText>
348
+              ) : null}
349
+              <View style={styles.buttonRow}>
350
+                <IconButton
351
+                  name="trash"
352
+                  onPress={() => handleDelete(item.id)}
353
+                  accessibilityLabel={t('observations.delete')}
354
+                  variant="danger"
355
+                />
356
+              </View>
357
+            </ThemedView>
358
+          </Pressable>
359
+        )}
360
+        ItemSeparatorComponent={() => <View style={styles.separator} />}
361
+        ListHeaderComponent={
362
+          <View>
363
+            <ThemedView style={styles.hero}>
364
+              <Image source={require('@/assets/images/observations.jpg')} style={styles.heroImage} />
365
+            </ThemedView>
366
+            <ThemedView style={styles.titleContainer}>
367
+              <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
368
+                {t('observations.title')}
369
+              </ThemedText>
370
+            </ThemedView>
371
+
372
+            {status ? (
373
+              <ThemedView style={styles.section}>
374
+                <ThemedText>{status}</ThemedText>
375
+              </ThemedView>
376
+            ) : null}
377
+            <ThemedView style={styles.section}>
378
+              <Pressable
379
+                style={styles.newButton}
380
+                onPress={() => {
381
+                  setNewErrors({});
382
+                  setNewModalOpen(true);
383
+                }}>
384
+                <IconSymbol size={18} name="plus.circle.fill" color="#2F7D4F" />
385
+                <ThemedText style={styles.newButtonText}>{t('observations.new')}</ThemedText>
386
+              </Pressable>
387
+            </ThemedView>
388
+          </View>
389
+        }
390
+        ListFooterComponent={
391
+          <View style={styles.footer}>
392
+            {loadingMore ? <ActivityIndicator /> : null}
393
+          </View>
394
+        }
395
+      />
396
+
397
+      <Modal transparent visible={fieldModalOpen} animationType="fade">
398
+        <Pressable
399
+          style={styles.modalOverlay}
400
+          onPress={() => {
401
+            setFieldModalOpen(false);
402
+            setReopenSheetAfterSelect(false);
403
+            setEditReopenAfterSelect(false);
404
+          }}>
405
+          <View style={[styles.modalCard, { backgroundColor: palette.card, borderColor: palette.border }]}>
406
+            <ThemedText type="subtitle">{t('observations.selectField')}</ThemedText>
407
+            <FlatList
408
+              data={fields}
409
+              keyExtractor={(item) => String(item.id)}
410
+              renderItem={({ item }) => (
411
+                <Pressable
412
+                  onPress={() => {
413
+                    if (editReopenAfterSelect) {
414
+                      setEditFieldId(item.id);
415
+                      setEditCropId(null);
416
+                      setEditErrors((prev) => ({ ...prev, field: undefined }));
417
+                      setEditModalOpen(true);
418
+                      setEditReopenAfterSelect(false);
419
+                    } else {
420
+                      setSelectedFieldId(item.id);
421
+                      setSelectedCropId(null);
422
+                      setNewErrors((prev) => ({ ...prev, field: undefined }));
423
+                      setNewModalOpen(true);
424
+                      setReopenSheetAfterSelect(false);
425
+                    }
426
+                    setFieldModalOpen(false);
427
+                  }}
428
+                  style={styles.modalItem}>
429
+                  <ThemedText>{item.name || t('observations.untitled')}</ThemedText>
430
+                </Pressable>
431
+              )}
432
+            />
433
+          </View>
434
+        </Pressable>
435
+      </Modal>
436
+
437
+      <Modal transparent visible={cropModalOpen} animationType="fade">
438
+        <Pressable
439
+          style={styles.modalOverlay}
440
+          onPress={() => {
441
+            setCropModalOpen(false);
442
+            setReopenSheetAfterSelect(false);
443
+            setEditReopenAfterSelect(false);
444
+          }}>
445
+          <View style={[styles.modalCard, { backgroundColor: palette.card, borderColor: palette.border }]}>
446
+            <ThemedText type="subtitle">{t('observations.selectCrop')}</ThemedText>
447
+            <FlatList
448
+              data={crops.filter((item) => !selectedFieldId || item.field_id === selectedFieldId)}
449
+              keyExtractor={(item) => String(item.id)}
450
+              renderItem={({ item }) => (
451
+                <Pressable
452
+                  onPress={() => {
453
+                    if (editReopenAfterSelect) {
454
+                      setEditCropId(item.id);
455
+                      setEditModalOpen(true);
456
+                      setEditReopenAfterSelect(false);
457
+                    } else {
458
+                      setSelectedCropId(item.id);
459
+                      setNewModalOpen(true);
460
+                      setReopenSheetAfterSelect(false);
461
+                    }
462
+                    setCropModalOpen(false);
463
+                  }}
464
+                  style={styles.modalItem}>
465
+                  <ThemedText>{item.crop_name || t('observations.untitled')}</ThemedText>
466
+                </Pressable>
467
+              )}
468
+              ListEmptyComponent={
469
+                <ThemedText style={styles.meta}>{t('observations.noCrop')}</ThemedText>
470
+              }
471
+            />
472
+          </View>
473
+        </Pressable>
474
+      </Modal>
475
+
476
+      <Modal transparent visible={newModalOpen} animationType="slide">
477
+        <View style={styles.sheetOverlay}>
478
+          <Pressable style={styles.sheetBackdrop} onPress={() => setNewModalOpen(false)} />
479
+          <KeyboardAvoidingView
480
+            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
481
+            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
482
+            style={styles.keyboardAvoid}>
483
+            <View style={[styles.sheet, { backgroundColor: palette.card, borderColor: palette.border }]}>
484
+              <FlatList
485
+                data={[{ key: 'new' }]}
486
+                keyExtractor={(item) => item.key}
487
+                contentContainerStyle={styles.sheetListContent}
488
+                renderItem={() => (
489
+                  <View style={styles.sheetContent}>
490
+                  <ThemedText type="subtitle">{t('observations.new')}</ThemedText>
491
+                  <ThemedText>
492
+                    {t('observations.field')}
493
+                    <ThemedText style={styles.requiredMark}> *</ThemedText>
494
+                  </ThemedText>
495
+                  <ThemedButton
496
+                    title={selectedField?.name || t('observations.selectField')}
497
+                    onPress={() => {
498
+                      setReopenSheetAfterSelect(true);
499
+                      setNewModalOpen(false);
500
+                      setFieldModalOpen(true);
501
+                    }}
502
+                    variant="secondary"
503
+                  />
504
+                  {newErrors.field ? (
505
+                    <ThemedText style={styles.errorText}>{newErrors.field}</ThemedText>
506
+                  ) : null}
507
+                  <ThemedText>{t('observations.crop')}</ThemedText>
508
+                  <ThemedButton
509
+                    title={selectedCrop?.crop_name || t('observations.selectCrop')}
510
+                    onPress={() => {
511
+                      setReopenSheetAfterSelect(true);
512
+                      setNewModalOpen(false);
513
+                      setCropModalOpen(true);
514
+                    }}
515
+                    variant="secondary"
516
+                  />
517
+                  <ThemedText>{t('observations.type')}</ThemedText>
518
+                  <View style={styles.chipRow}>
519
+                    {presetTypes.map((preset) => {
520
+                      const label = t(`observations.type.${preset.key}`);
521
+                      const normalized = type.trim().toLowerCase();
522
+                      const isActive =
523
+                        label.toLowerCase() === normalized ||
524
+                        preset.value.toLowerCase() === normalized;
525
+                      return (
526
+                        <Pressable
527
+                          key={preset.key}
528
+                          onPress={() => setType(label)}
529
+                          style={[styles.chip, isActive && styles.chipActive]}>
530
+                          <ThemedText style={isActive ? styles.chipTextActive : styles.chipText}>
531
+                            {label}
532
+                          </ThemedText>
533
+                        </Pressable>
534
+                      );
535
+                    })}
536
+                  </View>
537
+                  <TextInput
538
+                    value={type}
539
+                    onChangeText={setType}
540
+                    placeholder={t('observations.typePlaceholder')}
541
+                    style={inputStyle}
542
+                  />
543
+                  <ThemedText>{t('observations.severity')}</ThemedText>
544
+                  <TextInput
545
+                    value={severity}
546
+                    onChangeText={(value) => {
547
+                      setSeverity(value);
548
+                      if (newErrors.severity) {
549
+                        setNewErrors((prev) => ({ ...prev, severity: undefined }));
550
+                      }
551
+                    }}
552
+                    placeholder={t('observations.severityPlaceholder')}
553
+                    style={inputStyle}
554
+                    keyboardType="numeric"
555
+                  />
556
+                  {newErrors.severity ? (
557
+                    <ThemedText style={styles.errorText}>{newErrors.severity}</ThemedText>
558
+                  ) : null}
559
+                  <ThemedText>{t('observations.note')}</ThemedText>
560
+                  <TextInput
561
+                    value={note}
562
+                    onChangeText={setNote}
563
+                    placeholder={t('observations.notePlaceholder')}
564
+                    style={inputStyle}
565
+                    multiline
566
+                  />
567
+                  <ThemedText>{t('observations.photo')}</ThemedText>
568
+                  {photoUri ? (
569
+                    <Image source={{ uri: photoUri }} style={styles.photoPreview} resizeMode="cover" />
570
+                  ) : (
571
+                    <ThemedText style={styles.photoPlaceholder}>{t('observations.noPhoto')}</ThemedText>
572
+                  )}
573
+                  <View style={styles.photoRow}>
574
+                    <ThemedButton
575
+                      title={t('observations.pickPhoto')}
576
+                      onPress={() => handlePickPhoto(setPhotoUri)}
577
+                      variant="secondary"
578
+                    />
579
+                    <ThemedButton
580
+                      title={t('observations.takePhoto')}
581
+                      onPress={() =>
582
+                        handleTakePhoto(setPhotoUri, (code) =>
583
+                          setStatus(
584
+                            code === 'cameraDenied'
585
+                              ? t('tasks.cameraDenied')
586
+                              : t('tasks.cameraError')
587
+                          )
588
+                        )
589
+                      }
590
+                      variant="secondary"
591
+                    />
592
+                  </View>
593
+                  <View style={styles.modalActions}>
594
+                    <ThemedButton
595
+                      title={t('observations.cancel')}
596
+                      onPress={() => setNewModalOpen(false)}
597
+                      variant="secondary"
598
+                    />
599
+                    <ThemedButton
600
+                      title={t('observations.save')}
601
+                      onPress={async () => {
602
+                        const ok = await handleSave();
603
+                        if (ok) setNewModalOpen(false);
604
+                      }}
605
+                    />
606
+                  </View>
607
+                  <View style={styles.sheetFooter} />
608
+                </View>
609
+                )}
610
+              />
611
+            </View>
612
+          </KeyboardAvoidingView>
613
+        </View>
614
+      </Modal>
615
+
616
+      <Modal transparent visible={editModalOpen} animationType="slide">
617
+        <View style={styles.sheetOverlay}>
618
+          <Pressable style={styles.sheetBackdrop} onPress={cancelEdit} />
619
+          <KeyboardAvoidingView
620
+            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
621
+            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
622
+            style={styles.keyboardAvoid}>
623
+            <View style={[styles.sheet, { backgroundColor: palette.card, borderColor: palette.border }]}>
624
+              <FlatList
625
+                data={[{ key: 'edit' }]}
626
+                keyExtractor={(item) => item.key}
627
+                contentContainerStyle={styles.sheetListContent}
628
+                renderItem={() => (
629
+                  <View style={styles.sheetContent}>
630
+                  <ThemedText type="subtitle">{t('observations.edit')}</ThemedText>
631
+                  <ThemedText>
632
+                    {t('observations.field')}
633
+                    <ThemedText style={styles.requiredMark}> *</ThemedText>
634
+                  </ThemedText>
635
+                  <ThemedButton
636
+                    title={selectedEditField?.name || t('observations.selectField')}
637
+                    onPress={() => {
638
+                      setEditReopenAfterSelect(true);
639
+                      setEditModalOpen(false);
640
+                      setFieldModalOpen(true);
641
+                    }}
642
+                    variant="secondary"
643
+                  />
644
+                  {editErrors.field ? (
645
+                    <ThemedText style={styles.errorText}>{editErrors.field}</ThemedText>
646
+                  ) : null}
647
+                  <ThemedText>{t('observations.crop')}</ThemedText>
648
+                  <ThemedButton
649
+                    title={selectedEditCrop?.crop_name || t('observations.selectCrop')}
650
+                    onPress={() => {
651
+                      setEditReopenAfterSelect(true);
652
+                      setEditModalOpen(false);
653
+                      setCropModalOpen(true);
654
+                    }}
655
+                    variant="secondary"
656
+                  />
657
+                  <ThemedText>{t('observations.type')}</ThemedText>
658
+                  <View style={styles.chipRow}>
659
+                    {presetTypes.map((preset) => {
660
+                      const label = t(`observations.type.${preset.key}`);
661
+                      const normalized = editType.trim().toLowerCase();
662
+                      const isActive =
663
+                        label.toLowerCase() === normalized ||
664
+                        preset.value.toLowerCase() === normalized;
665
+                      return (
666
+                        <Pressable
667
+                          key={`edit-${preset.key}`}
668
+                          onPress={() => setEditType(label)}
669
+                          style={[styles.chip, isActive && styles.chipActive]}>
670
+                          <ThemedText style={isActive ? styles.chipTextActive : styles.chipText}>
671
+                            {label}
672
+                          </ThemedText>
673
+                        </Pressable>
674
+                      );
675
+                    })}
676
+                  </View>
677
+                  <TextInput
678
+                    value={editType}
679
+                    onChangeText={setEditType}
680
+                    placeholder={t('observations.typePlaceholder')}
681
+                    style={inputStyle}
682
+                  />
683
+                  <ThemedText>{t('observations.severity')}</ThemedText>
684
+                  <TextInput
685
+                    value={editSeverity}
686
+                    onChangeText={(value) => {
687
+                      setEditSeverity(value);
688
+                      if (editErrors.severity) {
689
+                        setEditErrors((prev) => ({ ...prev, severity: undefined }));
690
+                      }
691
+                    }}
692
+                    placeholder={t('observations.severityPlaceholder')}
693
+                    style={inputStyle}
694
+                    keyboardType="numeric"
695
+                  />
696
+                  {editErrors.severity ? (
697
+                    <ThemedText style={styles.errorText}>{editErrors.severity}</ThemedText>
698
+                  ) : null}
699
+                  <ThemedText>{t('observations.note')}</ThemedText>
700
+                  <TextInput
701
+                    value={editNote}
702
+                    onChangeText={setEditNote}
703
+                    placeholder={t('observations.notePlaceholder')}
704
+                    style={inputStyle}
705
+                    multiline
706
+                  />
707
+                  <ThemedText>{t('observations.photo')}</ThemedText>
708
+                  {editPhotoUri ? (
709
+                    <Image
710
+                      source={{ uri: editPhotoUri }}
711
+                      style={styles.photoPreview}
712
+                      resizeMode="cover"
713
+                    />
714
+                  ) : (
715
+                    <ThemedText style={styles.photoPlaceholder}>
716
+                      {t('observations.noPhoto')}
717
+                    </ThemedText>
718
+                  )}
719
+                  <View style={styles.photoRow}>
720
+                    <ThemedButton
721
+                      title={t('observations.pickPhoto')}
722
+                      onPress={() => handlePickPhoto(setEditPhotoUri)}
723
+                      variant="secondary"
724
+                    />
725
+                    <ThemedButton
726
+                      title={t('observations.takePhoto')}
727
+                      onPress={() =>
728
+                        handleTakePhoto(setEditPhotoUri, (code) =>
729
+                          setStatus(
730
+                            code === 'cameraDenied'
731
+                              ? t('tasks.cameraDenied')
732
+                              : t('tasks.cameraError')
733
+                          )
734
+                        )
735
+                      }
736
+                      variant="secondary"
737
+                    />
738
+                  </View>
739
+                  <View style={styles.modalActions}>
740
+                    <ThemedButton
741
+                      title={t('observations.cancel')}
742
+                      onPress={cancelEdit}
743
+                      variant="secondary"
744
+                    />
745
+                    <ThemedButton title={t('observations.update')} onPress={handleUpdate} />
746
+                  </View>
747
+                  <View style={styles.sheetFooter} />
748
+                </View>
749
+                )}
750
+              />
751
+            </View>
752
+          </KeyboardAvoidingView>
753
+        </View>
754
+      </Modal>
755
+    </>
756
+  );
757
+}
758
+
759
+function formatDate(value: string) {
760
+  try {
761
+    return new Date(value).toLocaleString();
762
+  } catch {
763
+    return value;
764
+  }
765
+}
766
+
767
+async function handlePickPhoto(setter: (value: string | null) => void) {
768
+  const result = await ImagePicker.launchImageLibraryAsync({
769
+    mediaTypes: getImageMediaTypes(),
770
+    quality: 1,
771
+  });
772
+  if (result.canceled) return;
773
+  const asset = result.assets[0];
774
+  console.log('[Observations] Picked photo:', asset.uri);
775
+  setter(asset.uri);
776
+}
777
+
778
+async function handleTakePhoto(
779
+  setter: (value: string | null) => void,
780
+  onError?: (msg: string) => void
781
+) {
782
+  try {
783
+    const permission = await ImagePicker.requestCameraPermissionsAsync();
784
+    if (!permission.granted) {
785
+      onError?.('cameraDenied');
786
+      return;
787
+    }
788
+    const result = await ImagePicker.launchCameraAsync({ quality: 1 });
789
+    if (result.canceled) return;
790
+    const asset = result.assets[0];
791
+    console.log('[Observations] Captured photo:', asset.uri);
792
+    setter(asset.uri);
793
+  } catch {
794
+    onError?.('cameraError');
795
+  }
796
+}
797
+
798
+function getImageMediaTypes() {
799
+  const mediaType = (ImagePicker as { MediaType?: { Image?: unknown; Images?: unknown } })
800
+    .MediaType;
801
+  return mediaType?.Image ?? mediaType?.Images ?? ['images'];
802
+}
803
+
804
+const styles = StyleSheet.create({
805
+  hero: {
806
+    backgroundColor: '#E8E6DA',
807
+    aspectRatio: 16 / 9,
808
+    width: '100%',
809
+  },
810
+  heroImage: {
811
+    width: '100%',
812
+    height: '100%',
813
+  },
814
+  titleContainer: {
815
+    gap: 8,
816
+    paddingHorizontal: 16,
817
+    paddingVertical: 12,
818
+  },
819
+  section: {
820
+    gap: 8,
821
+    marginBottom: 16,
822
+    paddingHorizontal: 16,
823
+  },
824
+  card: {
825
+    borderRadius: 12,
826
+    borderWidth: 1,
827
+    borderColor: '#C6C6C6',
828
+    padding: 12,
829
+    marginHorizontal: 16,
830
+    gap: 6,
831
+    backgroundColor: '#FFFFFF',
832
+  },
833
+  meta: {
834
+    opacity: 0.7,
835
+  },
836
+  input: {
837
+    borderRadius: 10,
838
+    borderWidth: 1,
839
+    borderColor: '#B9B9B9',
840
+    paddingHorizontal: 12,
841
+    paddingVertical: 10,
842
+    fontSize: 15,
843
+  },
844
+  requiredMark: {
845
+    color: '#C0392B',
846
+    fontWeight: '700',
847
+  },
848
+  errorText: {
849
+    color: '#C0392B',
850
+    fontSize: 12,
851
+  },
852
+  buttonRow: {
853
+    alignSelf: 'flex-start',
854
+  },
855
+  separator: {
856
+    height: 12,
857
+  },
858
+  footer: {
859
+    height: 24,
860
+  },
861
+  modalOverlay: {
862
+    flex: 1,
863
+    backgroundColor: 'rgba(0,0,0,0.3)',
864
+    justifyContent: 'center',
865
+    padding: 16,
866
+  },
867
+  modalCard: {
868
+    borderRadius: 12,
869
+    borderWidth: 1,
870
+    borderColor: '#C6C6C6',
871
+    padding: 16,
872
+    backgroundColor: '#FFFFFF',
873
+    gap: 8,
874
+    maxHeight: '70%',
875
+  },
876
+  modalItem: {
877
+    paddingVertical: 8,
878
+  },
879
+  newButton: {
880
+    flexDirection: 'row',
881
+    alignItems: 'center',
882
+    gap: 8,
883
+    borderRadius: 10,
884
+    borderWidth: 1,
885
+    borderColor: '#B9B9B9',
886
+    paddingHorizontal: 12,
887
+    paddingVertical: 10,
888
+    alignSelf: 'flex-start',
889
+  },
890
+  newButtonText: {
891
+    fontSize: 15,
892
+    fontWeight: '600',
893
+  },
894
+  modalActions: {
895
+    flexDirection: 'row',
896
+    justifyContent: 'space-between',
897
+    gap: 12,
898
+  },
899
+  chipRow: {
900
+    flexDirection: 'row',
901
+    flexWrap: 'wrap',
902
+    gap: 8,
903
+  },
904
+  chip: {
905
+    borderRadius: 999,
906
+    borderWidth: 1,
907
+    borderColor: '#C6C6C6',
908
+    paddingHorizontal: 12,
909
+    paddingVertical: 6,
910
+  },
911
+  chipActive: {
912
+    borderColor: '#2F7D4F',
913
+    backgroundColor: '#E7F3EA',
914
+  },
915
+  chipText: {
916
+    fontSize: 13,
917
+  },
918
+  chipTextActive: {
919
+    fontSize: 13,
920
+    color: '#2F7D4F',
921
+    fontWeight: '600',
922
+  },
923
+  photoRow: {
924
+    flexDirection: 'row',
925
+    gap: 12,
926
+  },
927
+  photoPlaceholder: {
928
+    opacity: 0.6,
929
+  },
930
+  photoPreview: {
931
+    width: '100%',
932
+    height: 160,
933
+    borderRadius: 12,
934
+  },
935
+  sheetOverlay: {
936
+    flex: 1,
937
+    backgroundColor: 'rgba(0,0,0,0.3)',
938
+    justifyContent: 'flex-end',
939
+  },
940
+  sheetBackdrop: {
941
+    ...StyleSheet.absoluteFillObject,
942
+  },
943
+  sheet: {
944
+    borderTopLeftRadius: 16,
945
+    borderTopRightRadius: 16,
946
+    borderWidth: 1,
947
+    borderColor: '#C6C6C6',
948
+    padding: 16,
949
+    backgroundColor: '#FFFFFF',
950
+    gap: 10,
951
+    maxHeight: '85%',
952
+  },
953
+  sheetContent: {
954
+    gap: 10,
955
+    paddingBottom: 8,
956
+  },
957
+  sheetListContent: {
958
+    paddingBottom: 80,
959
+  },
960
+  sheetFooter: {
961
+    height: 24,
962
+  },
963
+  keyboardAvoid: {
964
+    width: '100%',
965
+    flex: 1,
966
+    justifyContent: 'flex-end',
967
+  },
968
+});

File diff suppressed because it is too large
+ 1139 - 0
app/sales.tsx


+ 166 - 0
app/task-history.tsx

@@ -0,0 +1,166 @@
1
+import { useEffect, useState } from 'react';
2
+import { ActivityIndicator, FlatList, StyleSheet, View } from 'react-native';
3
+import { Image } from 'expo-image';
4
+
5
+import { ThemedText } from '@/components/themed-text';
6
+import { ThemedView } from '@/components/themed-view';
7
+import { Colors, Fonts } from '@/constants/theme';
8
+import { useTranslation } from '@/localization/i18n';
9
+import { dbPromise, initCoreTables } from '@/services/db';
10
+import { useColorScheme } from '@/hooks/use-color-scheme';
11
+
12
+type EntryRow = {
13
+  id: number;
14
+  name: string;
15
+  status: string | null;
16
+  notes: string | null;
17
+  completed_at: string | null;
18
+};
19
+
20
+export default function TaskHistoryScreen() {
21
+  const { t } = useTranslation();
22
+  const theme = useColorScheme() ?? 'light';
23
+  const palette = Colors[theme];
24
+  const pageSize = 12;
25
+  const [entries, setEntries] = useState<EntryRow[]>([]);
26
+  const [status, setStatus] = useState(t('tasks.loading'));
27
+  const [page, setPage] = useState(1);
28
+  const [hasMore, setHasMore] = useState(true);
29
+  const [loadingMore, setLoadingMore] = useState(false);
30
+
31
+  useEffect(() => {
32
+    let isActive = true;
33
+
34
+    async function loadEntries() {
35
+      await fetchEntriesPage(1, true, isActive);
36
+    }
37
+
38
+    loadEntries();
39
+    return () => {
40
+      isActive = false;
41
+    };
42
+  }, [t]);
43
+
44
+  async function fetchEntriesPage(pageToLoad: number, replace: boolean, isActive = true) {
45
+    try {
46
+      await initCoreTables();
47
+      const db = await dbPromise;
48
+      const rows = await db.getAllAsync<EntryRow>(
49
+        `SELECT e.id, t.name, e.status, e.notes, e.completed_at
50
+         FROM daily_task_entries e
51
+         JOIN daily_tasks t ON t.id = e.task_id
52
+         ORDER BY e.completed_at DESC
53
+         LIMIT ? OFFSET ?;`,
54
+        pageSize,
55
+        (pageToLoad - 1) * pageSize
56
+      );
57
+      if (!isActive) return;
58
+      setEntries((prev) => (replace ? rows : [...prev, ...rows]));
59
+      setHasMore(rows.length === pageSize);
60
+      setPage(pageToLoad);
61
+      if (replace) {
62
+        setStatus(rows.length === 0 ? t('tasks.historyEmpty') : '');
63
+      }
64
+    } catch (error) {
65
+      if (isActive) setStatus(`Error: ${String(error)}`);
66
+    } finally {
67
+      if (isActive) setLoadingMore(false);
68
+    }
69
+  }
70
+
71
+  async function handleLoadMore() {
72
+    if (loadingMore || !hasMore) return;
73
+    setLoadingMore(true);
74
+    const nextPage = page + 1;
75
+    await fetchEntriesPage(nextPage, false);
76
+  }
77
+
78
+  return (
79
+    <FlatList
80
+      data={entries}
81
+      keyExtractor={(item) => String(item.id)}
82
+      onEndReached={handleLoadMore}
83
+      onEndReachedThreshold={0.4}
84
+      renderItem={({ item }) => (
85
+        <ThemedView style={[styles.card, { backgroundColor: palette.card, borderColor: palette.border }]}>
86
+          <ThemedText type="subtitle">{item.name}</ThemedText>
87
+          <ThemedText style={styles.meta}>
88
+            {item.completed_at ? formatDate(item.completed_at) : '-'}
89
+          </ThemedText>
90
+          {item.notes ? <ThemedText>{item.notes}</ThemedText> : null}
91
+        </ThemedView>
92
+      )}
93
+      ItemSeparatorComponent={() => <View style={styles.separator} />}
94
+      ListHeaderComponent={
95
+        <View>
96
+          <ThemedView style={styles.hero}>
97
+            <Image source={require('@/assets/images/dailytask.jpg')} style={styles.heroImage} />
98
+          </ThemedView>
99
+          <ThemedView style={styles.titleContainer}>
100
+            <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
101
+              {t('tasks.historyTitle')}
102
+            </ThemedText>
103
+          </ThemedView>
104
+          {status ? (
105
+            <ThemedView style={styles.section}>
106
+              <ThemedText>{status}</ThemedText>
107
+            </ThemedView>
108
+          ) : null}
109
+        </View>
110
+      }
111
+      ListFooterComponent={
112
+        <View style={styles.footer}>
113
+          {loadingMore ? <ActivityIndicator /> : null}
114
+        </View>
115
+      }
116
+    />
117
+  );
118
+}
119
+
120
+function formatDate(value: string) {
121
+  try {
122
+    return new Date(value).toLocaleString();
123
+  } catch {
124
+    return value;
125
+  }
126
+}
127
+
128
+const styles = StyleSheet.create({
129
+  hero: {
130
+    backgroundColor: '#E8E6DA',
131
+    aspectRatio: 16 / 9,
132
+    width: '100%',
133
+  },
134
+  heroImage: {
135
+    width: '100%',
136
+    height: '100%',
137
+  },
138
+  titleContainer: {
139
+    gap: 8,
140
+    paddingHorizontal: 16,
141
+    paddingVertical: 12,
142
+  },
143
+  section: {
144
+    gap: 8,
145
+    marginBottom: 16,
146
+    paddingHorizontal: 16,
147
+  },
148
+  card: {
149
+    borderRadius: 12,
150
+    borderWidth: 1,
151
+    borderColor: '#C6C6C6',
152
+    padding: 12,
153
+    marginHorizontal: 16,
154
+    gap: 6,
155
+    backgroundColor: '#FFFFFF',
156
+  },
157
+  meta: {
158
+    opacity: 0.7,
159
+  },
160
+  separator: {
161
+    height: 12,
162
+  },
163
+  footer: {
164
+    height: 24,
165
+  },
166
+});

+ 455 - 0
app/tasks.tsx

@@ -0,0 +1,455 @@
1
+import { useEffect, useMemo, useState } from 'react';
2
+import {
3
+  ActivityIndicator,
4
+  FlatList,
5
+  KeyboardAvoidingView,
6
+  Platform,
7
+  StyleSheet,
8
+  TextInput,
9
+  View,
10
+} from 'react-native';
11
+import { Image } from 'expo-image';
12
+import * as ImageManipulator from 'expo-image-manipulator';
13
+import * as ImagePicker from 'expo-image-picker';
14
+import { Link } from 'expo-router';
15
+
16
+import { ThemedText } from '@/components/themed-text';
17
+import { ThemedView } from '@/components/themed-view';
18
+import { Colors, Fonts } from '@/constants/theme';
19
+import { ThemedButton } from '@/components/themed-button';
20
+import { useTranslation } from '@/localization/i18n';
21
+import { dbPromise, initCoreTables } from '@/services/db';
22
+import { useColorScheme } from '@/hooks/use-color-scheme';
23
+
24
+type TaskRow = {
25
+  id: number;
26
+  name: string;
27
+  description: string | null;
28
+  entry_id: number | null;
29
+  status: string | null;
30
+  notes: string | null;
31
+  meta_json: string | null;
32
+};
33
+
34
+export default function DailyTasksScreen() {
35
+  const { t } = useTranslation();
36
+  const theme = useColorScheme() ?? 'light';
37
+  const palette = Colors[theme];
38
+  const defaultTasks = [
39
+    {
40
+      name: t('tasks.default.fieldCheck'),
41
+      description: t('tasks.default.fieldCheckDesc'),
42
+      default_time: '08:00',
43
+    },
44
+    {
45
+      name: t('tasks.default.scouting'),
46
+      description: t('tasks.default.scoutingDesc'),
47
+      default_time: '10:00',
48
+    },
49
+    {
50
+      name: t('tasks.default.sensors'),
51
+      description: t('tasks.default.sensorsDesc'),
52
+      default_time: '15:00',
53
+    },
54
+  ];
55
+  const pageSize = 10;
56
+  const [tasks, setTasks] = useState<TaskRow[]>([]);
57
+  const [status, setStatus] = useState(t('tasks.loading'));
58
+  const [notesByTaskId, setNotesByTaskId] = useState<Record<number, string>>({});
59
+  const [photoByTaskId, setPhotoByTaskId] = useState<Record<number, string>>({});
60
+  const [page, setPage] = useState(1);
61
+  const [hasMore, setHasMore] = useState(true);
62
+  const [loadingMore, setLoadingMore] = useState(false);
63
+
64
+  const todayKey = useMemo(() => new Date().toISOString().slice(0, 10), []);
65
+
66
+  useEffect(() => {
67
+    let isActive = true;
68
+
69
+    async function loadTasks() {
70
+      try {
71
+        await initCoreTables();
72
+        const db = await dbPromise;
73
+        await ensureDefaultTasks(db, defaultTasks);
74
+        await fetchTasksPage(1, true, isActive);
75
+      } catch (error) {
76
+        if (isActive) setStatus(`Error: ${String(error)}`);
77
+      }
78
+    }
79
+
80
+    loadTasks();
81
+    return () => {
82
+      isActive = false;
83
+    };
84
+  }, [t, todayKey]);
85
+
86
+  async function fetchTasksPage(pageToLoad: number, replace: boolean, isActive = true) {
87
+    try {
88
+      const db = await dbPromise;
89
+      const rows = await db.getAllAsync<TaskRow>(
90
+        `SELECT t.id, t.name, t.description,
91
+                e.id as entry_id, e.status, e.notes, e.meta_json
92
+         FROM daily_tasks t
93
+         LEFT JOIN daily_task_entries e
94
+           ON e.task_id = t.id
95
+          AND substr(e.completed_at, 1, 10) = ?
96
+         WHERE t.is_active = 1
97
+         ORDER BY t.id ASC
98
+         LIMIT ? OFFSET ?;`,
99
+        todayKey,
100
+        pageSize,
101
+        (pageToLoad - 1) * pageSize
102
+      );
103
+      if (!isActive) return;
104
+      setTasks((prev) => (replace ? rows : [...prev, ...rows]));
105
+      setHasMore(rows.length === pageSize);
106
+      setPage(pageToLoad);
107
+      if (replace) {
108
+        setStatus(rows.length === 0 ? t('tasks.empty') : '');
109
+      }
110
+      setNotesByTaskId((prev) => {
111
+        const next = replace ? {} : { ...prev };
112
+        rows.forEach((row) => {
113
+          if (row.notes) next[row.id] = row.notes;
114
+        });
115
+        return next;
116
+      });
117
+      setPhotoByTaskId((prev) => {
118
+        const next = replace ? {} : { ...prev };
119
+        rows.forEach((row) => {
120
+          const meta = parseTaskMeta(row.meta_json);
121
+          if (meta.photoUri) next[row.id] = meta.photoUri;
122
+        });
123
+        return next;
124
+      });
125
+    } catch (error) {
126
+      if (isActive) setStatus(`Error: ${String(error)}`);
127
+    } finally {
128
+      if (isActive) setLoadingMore(false);
129
+    }
130
+  }
131
+
132
+  async function handleLoadMore() {
133
+    if (loadingMore || !hasMore) return;
134
+    setLoadingMore(true);
135
+    const nextPage = page + 1;
136
+    await fetchTasksPage(nextPage, false);
137
+  }
138
+
139
+  async function handleComplete(task: TaskRow) {
140
+    try {
141
+      const db = await dbPromise;
142
+      const now = new Date().toISOString();
143
+      const notes = (notesByTaskId[task.id] ?? '').trim();
144
+      const metaJson = serializeTaskMeta({
145
+        photoUri: photoByTaskId[task.id],
146
+      });
147
+      if (task.entry_id) {
148
+        await db.runAsync('DELETE FROM daily_task_entries WHERE id = ?;', task.entry_id);
149
+      } else {
150
+        await db.runAsync(
151
+          'INSERT INTO daily_task_entries (task_id, field_id, notes, status, completed_at, created_at, meta_json) VALUES (?, NULL, ?, ?, ?, ?, ?);',
152
+          task.id,
153
+          notes,
154
+          'done',
155
+          now,
156
+          now,
157
+          metaJson
158
+        );
159
+      }
160
+      await fetchTasksPage(1, true);
161
+    } catch (error) {
162
+      setStatus(`Error: ${String(error)}`);
163
+    }
164
+  }
165
+
166
+  async function handlePickPhoto(task: TaskRow) {
167
+    const result = await ImagePicker.launchImageLibraryAsync({
168
+      mediaTypes: getImageMediaTypes(),
169
+      quality: 1,
170
+    });
171
+    if (result.canceled) return;
172
+    const asset = result.assets[0];
173
+    console.log('[Tasks] Picked photo:', asset.uri);
174
+    const normalized = await normalizeImageUri(asset.uri);
175
+    console.log('[Tasks] Normalized photo:', normalized);
176
+    await persistTaskPhoto(task, normalized, setPhotoByTaskId);
177
+  }
178
+
179
+  async function handleTakePhoto(task: TaskRow) {
180
+    try {
181
+      const permission = await ImagePicker.requestCameraPermissionsAsync();
182
+      if (!permission.granted) {
183
+        setStatus(t('tasks.cameraDenied'));
184
+        return;
185
+      }
186
+      const result = await ImagePicker.launchCameraAsync({
187
+        quality: 1,
188
+      });
189
+      if (result.canceled) return;
190
+      const asset = result.assets[0];
191
+      console.log('[Tasks] Captured photo:', asset.uri);
192
+      const normalized = await normalizeImageUri(asset.uri);
193
+      console.log('[Tasks] Normalized photo:', normalized);
194
+      await persistTaskPhoto(task, normalized, setPhotoByTaskId);
195
+    } catch (error) {
196
+      setStatus(t('tasks.cameraError'));
197
+    }
198
+  }
199
+
200
+  return (
201
+    <KeyboardAvoidingView
202
+      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
203
+      keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
204
+      style={styles.keyboardAvoid}>
205
+      <FlatList
206
+        data={tasks}
207
+        keyExtractor={(item) => String(item.id)}
208
+        keyboardShouldPersistTaps="handled"
209
+        keyboardDismissMode="on-drag"
210
+        contentContainerStyle={styles.listContent}
211
+        renderItem={({ item }) => {
212
+        const isDone = Boolean(item.entry_id);
213
+        return (
214
+          <ThemedView
215
+            style={[styles.card, { backgroundColor: palette.card, borderColor: palette.border }]}>
216
+            <ThemedView style={styles.cardHeader}>
217
+              <ThemedText type="subtitle" style={[styles.taskTitle, { color: palette.tint }]}>
218
+                {item.name}
219
+              </ThemedText>
220
+              <ThemedText style={styles.badge}>
221
+                {isDone ? t('tasks.done') : t('tasks.pending')}
222
+              </ThemedText>
223
+            </ThemedView>
224
+            {item.description ? (
225
+              <ThemedText style={styles.description}>{item.description}</ThemedText>
226
+            ) : null}
227
+            <ThemedText style={styles.photoLabel}>{t('tasks.photo')}</ThemedText>
228
+            {photoByTaskId[item.id] ? (
229
+              <Image
230
+                source={{ uri: photoByTaskId[item.id] }}
231
+                style={styles.photoPreview}
232
+                contentFit="cover"
233
+              />
234
+            ) : null}
235
+            <View style={styles.photoRow}>
236
+              <ThemedButton
237
+                title={t('tasks.pickPhoto')}
238
+                onPress={() => handlePickPhoto(item)}
239
+                variant="secondary"
240
+              />
241
+              <ThemedButton
242
+                title={t('tasks.takePhoto')}
243
+                onPress={() => handleTakePhoto(item)}
244
+                variant="secondary"
245
+              />
246
+            </View>
247
+            <TextInput
248
+              value={notesByTaskId[item.id] ?? ''}
249
+              onChangeText={(value) =>
250
+                setNotesByTaskId((prev) => ({ ...prev, [item.id]: value }))
251
+              }
252
+              placeholder={t('tasks.notePlaceholder')}
253
+              style={[
254
+                styles.input,
255
+                { borderColor: palette.border, backgroundColor: palette.input, color: palette.text },
256
+              ]}
257
+              multiline
258
+            />
259
+            <View style={styles.buttonRow}>
260
+              <ThemedButton
261
+                title={isDone ? t('tasks.undo') : t('tasks.complete')}
262
+                onPress={() => handleComplete(item)}
263
+              />
264
+            </View>
265
+          </ThemedView>
266
+        );
267
+      }}
268
+        ItemSeparatorComponent={() => <View style={styles.separator} />}
269
+        ListHeaderComponent={
270
+        <View>
271
+          <ThemedView style={styles.hero}>
272
+            <Image source={require('@/assets/images/dailytask.jpg')} style={styles.heroImage} />
273
+          </ThemedView>
274
+          <ThemedView style={styles.titleContainer}>
275
+            <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
276
+              {t('tasks.title')}
277
+            </ThemedText>
278
+            <ThemedText style={styles.subtitle}>{t('tasks.subtitle')}</ThemedText>
279
+            <Link href="/task-history" push>
280
+              <ThemedText type="link">{t('tasks.historyTitle')}</ThemedText>
281
+            </Link>
282
+          </ThemedView>
283
+
284
+          {status ? (
285
+            <ThemedView style={styles.section}>
286
+              <ThemedText>{status}</ThemedText>
287
+            </ThemedView>
288
+          ) : null}
289
+        </View>
290
+      }
291
+        onEndReached={handleLoadMore}
292
+        onEndReachedThreshold={0.4}
293
+        ListFooterComponent={
294
+          <View style={styles.footer}>
295
+            {loadingMore ? <ActivityIndicator /> : null}
296
+          </View>
297
+        }
298
+      />
299
+    </KeyboardAvoidingView>
300
+  );
301
+}
302
+
303
+async function ensureDefaultTasks(
304
+  db: Awaited<typeof dbPromise>,
305
+  tasks: { name: string; description: string; default_time: string }[]
306
+) {
307
+  const row = await db.getFirstAsync<{ count: number }>(
308
+    'SELECT COUNT(*) as count FROM daily_tasks;'
309
+  );
310
+  if (row?.count && row.count > 0) return;
311
+  const now = new Date().toISOString();
312
+  for (const task of tasks) {
313
+    await db.runAsync(
314
+      'INSERT INTO daily_tasks (name, description, default_time, is_active, created_at) VALUES (?, ?, ?, 1, ?);',
315
+      task.name,
316
+      task.description,
317
+      task.default_time,
318
+      now
319
+    );
320
+  }
321
+}
322
+
323
+async function persistTaskPhoto(
324
+  task: TaskRow,
325
+  uri: string,
326
+  setPhotoByTaskId: (photos: Record<number, string>) => void
327
+) {
328
+  setPhotoByTaskId((prev) => ({ ...prev, [task.id]: uri }));
329
+  if (!task.entry_id) return;
330
+  const db = await dbPromise;
331
+  const metaJson = serializeTaskMeta({ photoUri: uri });
332
+  await db.runAsync(
333
+    'UPDATE daily_task_entries SET meta_json = ? WHERE id = ?;',
334
+    metaJson,
335
+    task.entry_id
336
+  );
337
+}
338
+
339
+function parseTaskMeta(raw: string | null) {
340
+  if (!raw) return {} as { photoUri?: string };
341
+  try {
342
+    return JSON.parse(raw) as { photoUri?: string };
343
+  } catch {
344
+    return {} as { photoUri?: string };
345
+  }
346
+}
347
+
348
+function serializeTaskMeta(meta: { photoUri?: string }) {
349
+  if (!meta.photoUri) return null;
350
+  return JSON.stringify(meta);
351
+}
352
+
353
+function getImageMediaTypes() {
354
+  const mediaType = (ImagePicker as { MediaType?: { Image?: unknown; Images?: unknown } })
355
+    .MediaType;
356
+  return mediaType?.Image ?? mediaType?.Images ?? ['images'];
357
+}
358
+
359
+async function normalizeImageUri(uri: string) {
360
+  try {
361
+    const result = await ImageManipulator.manipulateAsync(
362
+      uri,
363
+      [],
364
+      { compress: 1, format: ImageManipulator.SaveFormat.JPEG }
365
+    );
366
+    return result.uri;
367
+  } catch {
368
+    return uri;
369
+  }
370
+}
371
+
372
+const styles = StyleSheet.create({
373
+  hero: {
374
+    backgroundColor: '#E8E6DA',
375
+    aspectRatio: 16 / 9,
376
+    width: '100%',
377
+  },
378
+  heroImage: {
379
+    width: '100%',
380
+    height: '100%',
381
+  },
382
+  titleContainer: {
383
+    gap: 8,
384
+    paddingHorizontal: 16,
385
+    paddingVertical: 12,
386
+  },
387
+  subtitle: {
388
+    opacity: 0.7,
389
+  },
390
+  section: {
391
+    gap: 8,
392
+    marginBottom: 16,
393
+    paddingHorizontal: 16,
394
+  },
395
+  card: {
396
+    borderRadius: 12,
397
+    borderWidth: 1,
398
+    borderColor: '#C6C6C6',
399
+    padding: 12,
400
+    marginHorizontal: 16,
401
+    marginBottom: 12,
402
+    gap: 8,
403
+    backgroundColor: '#FFFFFF',
404
+  },
405
+  cardHeader: {
406
+    flexDirection: 'row',
407
+    justifyContent: 'space-between',
408
+    gap: 8,
409
+  },
410
+  description: {
411
+    opacity: 0.8,
412
+  },
413
+  photoLabel: {
414
+    opacity: 0.7,
415
+  },
416
+  photoPreview: {
417
+    height: 160,
418
+    width: '100%',
419
+    borderRadius: 12,
420
+  },
421
+  photoRow: {
422
+    flexDirection: 'row',
423
+    gap: 8,
424
+  },
425
+  badge: {
426
+    fontSize: 12,
427
+    opacity: 0.7,
428
+  },
429
+  taskTitle: {
430
+    color: '#2F7D4F',
431
+  },
432
+  input: {
433
+    borderRadius: 10,
434
+    borderWidth: 1,
435
+    borderColor: '#B9B9B9',
436
+    paddingHorizontal: 12,
437
+    paddingVertical: 10,
438
+    fontSize: 15,
439
+  },
440
+  buttonRow: {
441
+    alignSelf: 'flex-start',
442
+  },
443
+  separator: {
444
+    height: 12,
445
+  },
446
+  footer: {
447
+    height: 24,
448
+  },
449
+  keyboardAvoid: {
450
+    flex: 1,
451
+  },
452
+  listContent: {
453
+    paddingBottom: 80,
454
+  },
455
+});

+ 17 - 0
assets/class_names.json

@@ -0,0 +1,17 @@
1
+[
2
+  "Pepper__bell___Bacterial_spot",
3
+  "Pepper__bell___healthy",
4
+  "Potato___Early_blight",
5
+  "Potato___Late_blight",
6
+  "Potato___healthy",
7
+  "Tomato_Bacterial_spot",
8
+  "Tomato_Early_blight",
9
+  "Tomato_Late_blight",
10
+  "Tomato_Leaf_Mold",
11
+  "Tomato_Septoria_leaf_spot",
12
+  "Tomato_Spider_mites_Two_spotted_spider_mite",
13
+  "Tomato__Target_Spot",
14
+  "Tomato__Tomato_YellowLeaf__Curl_Virus",
15
+  "Tomato__Tomato_mosaic_virus",
16
+  "Tomato_healthy"
17
+]

二進制
assets/images/adaptive-icon copy.png


二進制
assets/images/adaptive-icon.png


二進制
assets/images/android-icon-background.png


二進制
assets/images/android-icon-foreground.png


二進制
assets/images/android-icon-monochrome.png


二進制
assets/images/blogpost.jpg


二進制
assets/images/costrecords.jpg


二進制
assets/images/crops.jpg


二進制
assets/images/dailytask.jpg


二進制
assets/images/favicon.png


二進制
assets/images/fields.jpg


二進制
assets/images/harvestrecord.jpg


二進制
assets/images/home.jpg


二進制
assets/images/icon.png


二進制
assets/images/leafscan.jpg


二進制
assets/images/logbook.jpg


二進制
assets/images/observations.jpg


二進制
assets/images/partial-react-logo.png


二進制
assets/images/profile.jpg


二進制
assets/images/react-logo.png


二進制
assets/images/react-logo@2x.png


二進制
assets/images/react-logo@3x.png


二進制
assets/images/salerecords.jpg


二進制
assets/images/splash-icon.png


二進制
assets/images/splash-sf.jpg


二進制
assets/images/userprofile.jpg


二進制
assets/models/tinyyolov2-8.onnx


二進制
assets/plantvillage_mnv3s_224.onnx


二進制
assets/plantvillage_mnv3s_best.pth


+ 25 - 0
components/external-link.tsx

@@ -0,0 +1,25 @@
1
+import { Href, Link } from 'expo-router';
2
+import { openBrowserAsync, WebBrowserPresentationStyle } from 'expo-web-browser';
3
+import { type ComponentProps } from 'react';
4
+
5
+type Props = Omit<ComponentProps<typeof Link>, 'href'> & { href: Href & string };
6
+
7
+export function ExternalLink({ href, ...rest }: Props) {
8
+  return (
9
+    <Link
10
+      target="_blank"
11
+      {...rest}
12
+      href={href}
13
+      onPress={async (event) => {
14
+        if (process.env.EXPO_OS !== 'web') {
15
+          // Prevent the default behavior of linking to the default browser on native.
16
+          event.preventDefault();
17
+          // Open the link in an in-app browser.
18
+          await openBrowserAsync(href, {
19
+            presentationStyle: WebBrowserPresentationStyle.AUTOMATIC,
20
+          });
21
+        }
22
+      }}
23
+    />
24
+  );
25
+}

+ 18 - 0
components/haptic-tab.tsx

@@ -0,0 +1,18 @@
1
+import { BottomTabBarButtonProps } from '@react-navigation/bottom-tabs';
2
+import { PlatformPressable } from '@react-navigation/elements';
3
+import * as Haptics from 'expo-haptics';
4
+
5
+export function HapticTab(props: BottomTabBarButtonProps) {
6
+  return (
7
+    <PlatformPressable
8
+      {...props}
9
+      onPressIn={(ev) => {
10
+        if (process.env.EXPO_OS === 'ios') {
11
+          // Add a soft haptic feedback when pressing down on the tabs.
12
+          Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
13
+        }
14
+        props.onPressIn?.(ev);
15
+      }}
16
+    />
17
+  );
18
+}

+ 0 - 0
components/hello-wave.tsx


Some files were not shown because too many files changed in this diff

tum/whitesports - Gogs: Simplico Git Service

Nessuna descrizione

class-wp-comment.php 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. /**
  3. * Comment API: WP_Comment class
  4. *
  5. * @package WordPress
  6. * @subpackage Comments
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Core class used to organize comments as instantiated objects with defined members.
  11. *
  12. * @since 4.4.0
  13. */
  14. final class WP_Comment {
  15. /**
  16. * Comment ID.
  17. *
  18. * A numeric string, for compatibility reasons.
  19. *
  20. * @since 4.4.0
  21. * @var string
  22. */
  23. public $comment_ID;
  24. /**
  25. * ID of the post the comment is associated with.
  26. *
  27. * A numeric string, for compatibility reasons.
  28. *
  29. * @since 4.4.0
  30. * @var string
  31. */
  32. public $comment_post_ID = 0;
  33. /**
  34. * Comment author name.
  35. *
  36. * @since 4.4.0
  37. * @var string
  38. */
  39. public $comment_author = '';
  40. /**
  41. * Comment author email address.
  42. *
  43. * @since 4.4.0
  44. * @var string
  45. */
  46. public $comment_author_email = '';
  47. /**
  48. * Comment author URL.
  49. *
  50. * @since 4.4.0
  51. * @var string
  52. */
  53. public $comment_author_url = '';
  54. /**
  55. * Comment author IP address (IPv4 format).
  56. *
  57. * @since 4.4.0
  58. * @var string
  59. */
  60. public $comment_author_IP = '';
  61. /**
  62. * Comment date in YYYY-MM-DD HH:MM:SS format.
  63. *
  64. * @since 4.4.0
  65. * @var string
  66. */
  67. public $comment_date = '0000-00-00 00:00:00';
  68. /**
  69. * Comment GMT date in YYYY-MM-DD HH::MM:SS format.
  70. *
  71. * @since 4.4.0
  72. * @var string
  73. */
  74. public $comment_date_gmt = '0000-00-00 00:00:00';
  75. /**
  76. * Comment content.
  77. *
  78. * @since 4.4.0
  79. * @var string
  80. */
  81. public $comment_content;
  82. /**
  83. * Comment karma count.
  84. *
  85. * A numeric string, for compatibility reasons.
  86. *
  87. * @since 4.4.0
  88. * @var string
  89. */
  90. public $comment_karma = 0;
  91. /**
  92. * Comment approval status.
  93. *
  94. * @since 4.4.0
  95. * @var string
  96. */
  97. public $comment_approved = '1';
  98. /**
  99. * Comment author HTTP user agent.
  100. *
  101. * @since 4.4.0
  102. * @var string
  103. */
  104. public $comment_agent = '';
  105. /**
  106. * Comment type.
  107. *
  108. * @since 4.4.0
  109. * @since 5.5.0 Default value changed to `comment`.
  110. * @var string
  111. */
  112. public $comment_type = 'comment';
  113. /**
  114. * Parent comment ID.
  115. *
  116. * A numeric string, for compatibility reasons.
  117. *
  118. * @since 4.4.0
  119. * @var string
  120. */
  121. public $comment_parent = 0;
  122. /**
  123. * Comment author ID.
  124. *
  125. * A numeric string, for compatibility reasons.
  126. *
  127. * @since 4.4.0
  128. * @var string
  129. */
  130. public $user_id = 0;
  131. /**
  132. * Comment children.
  133. *
  134. * @since 4.4.0
  135. * @var array
  136. */
  137. protected $children;
  138. /**
  139. * Whether children have been populated for this comment object.
  140. *
  141. * @since 4.4.0
  142. * @var bool
  143. */
  144. protected $populated_children = false;
  145. /**
  146. * Post fields.
  147. *
  148. * @since 4.4.0
  149. * @var array
  150. */
  151. protected $post_fields = array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_content_filtered', 'post_parent', 'guid', 'menu_order', 'post_type', 'post_mime_type', 'comment_count' );
  152. /**
  153. * Retrieves a WP_Comment instance.
  154. *
  155. * @since 4.4.0
  156. *
  157. * @global wpdb $wpdb WordPress database abstraction object.
  158. *
  159. * @param int $id Comment ID.
  160. * @return WP_Comment|false Comment object, otherwise false.
  161. */
  162. public static function get_instance( $id ) {
  163. global $wpdb;
  164. $comment_id = (int) $id;
  165. if ( ! $comment_id ) {
  166. return false;
  167. }
  168. $_comment = wp_cache_get( $comment_id, 'comment' );
  169. if ( ! $_comment ) {
  170. $_comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id ) );
  171. if ( ! $_comment ) {
  172. return false;
  173. }
  174. wp_cache_add( $_comment->comment_ID, $_comment, 'comment' );
  175. }
  176. return new WP_Comment( $_comment );
  177. }
  178. /**
  179. * Constructor.
  180. *
  181. * Populates properties with object vars.
  182. *
  183. * @since 4.4.0
  184. *
  185. * @param WP_Comment $comment Comment object.
  186. */
  187. public function __construct( $comment ) {
  188. foreach ( get_object_vars( $comment ) as $key => $value ) {
  189. $this->$key = $value;
  190. }
  191. }
  192. /**
  193. * Convert object to array.
  194. *
  195. * @since 4.4.0
  196. *
  197. * @return array Object as array.
  198. */
  199. public function to_array() {
  200. return get_object_vars( $this );
  201. }
  202. /**
  203. * Get the children of a comment.
  204. *
  205. * @since 4.4.0
  206. *
  207. * @param array $args {
  208. * Array of arguments used to pass to get_comments() and determine format.
  209. *
  210. * @type string $format Return value format. 'tree' for a hierarchical tree, 'flat' for a flattened array.
  211. * Default 'tree'.
  212. * @type string $status Comment status to limit results by. Accepts 'hold' (`comment_status=0`),
  213. * 'approve' (`comment_status=1`), 'all', or a custom comment status.
  214. * Default 'all'.
  215. * @type string $hierarchical Whether to include comment descendants in the results.
  216. * 'threaded' returns a tree, with each comment's children
  217. * stored in a `children` property on the `WP_Comment` object.
  218. * 'flat' returns a flat array of found comments plus their children.
  219. * Pass `false` to leave out descendants.
  220. * The parameter is ignored (forced to `false`) when `$fields` is 'ids' or 'counts'.
  221. * Accepts 'threaded', 'flat', or false. Default: 'threaded'.
  222. * @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
  223. * or 'meta_value_num', `$meta_key` must also be defined.
  224. * To sort by a specific `$meta_query` clause, use that
  225. * clause's array key. Accepts 'comment_agent',
  226. * 'comment_approved', 'comment_author',
  227. * 'comment_author_email', 'comment_author_IP',
  228. * 'comment_author_url', 'comment_content', 'comment_date',
  229. * 'comment_date_gmt', 'comment_ID', 'comment_karma',
  230. * 'comment_parent', 'comment_post_ID', 'comment_type',
  231. * 'user_id', 'comment__in', 'meta_value', 'meta_value_num',
  232. * the value of $meta_key, and the array keys of
  233. * `$meta_query`. Also accepts false, an empty array, or
  234. * 'none' to disable `ORDER BY` clause.
  235. * }
  236. * @return WP_Comment[] Array of `WP_Comment` objects.
  237. */
  238. public function get_children( $args = array() ) {
  239. $defaults = array(
  240. 'format' => 'tree',
  241. 'status' => 'all',
  242. 'hierarchical' => 'threaded',
  243. 'orderby' => '',
  244. );
  245. $_args = wp_parse_args( $args, $defaults );
  246. $_args['parent'] = $this->comment_ID;
  247. if ( is_null( $this->children ) ) {
  248. if ( $this->populated_children ) {
  249. $this->children = array();
  250. } else {
  251. $this->children = get_comments( $_args );
  252. }
  253. }
  254. if ( 'flat' === $_args['format'] ) {
  255. $children = array();
  256. foreach ( $this->children as $child ) {
  257. $child_args = $_args;
  258. $child_args['format'] = 'flat';
  259. // get_children() resets this value automatically.
  260. unset( $child_args['parent'] );
  261. $children = array_merge( $children, array( $child ), $child->get_children( $child_args ) );
  262. }
  263. } else {
  264. $children = $this->children;
  265. }
  266. return $children;
  267. }
  268. /**
  269. * Add a child to the comment.
  270. *
  271. * Used by `WP_Comment_Query` when bulk-filling descendants.
  272. *
  273. * @since 4.4.0
  274. *
  275. * @param WP_Comment $child Child comment.
  276. */
  277. public function add_child( WP_Comment $child ) {
  278. $this->children[ $child->comment_ID ] = $child;
  279. }
  280. /**
  281. * Get a child comment by ID.
  282. *
  283. * @since 4.4.0
  284. *
  285. * @param int $child_id ID of the child.
  286. * @return WP_Comment|false Returns the comment object if found, otherwise false.
  287. */
  288. public function get_child( $child_id ) {
  289. if ( isset( $this->children[ $child_id ] ) ) {
  290. return $this->children[ $child_id ];
  291. }
  292. return false;
  293. }
  294. /**
  295. * Set the 'populated_children' flag.
  296. *
  297. * This flag is important for ensuring that calling `get_children()` on a childless comment will not trigger
  298. * unneeded database queries.
  299. *
  300. * @since 4.4.0
  301. *
  302. * @param bool $set Whether the comment's children have already been populated.
  303. */
  304. public function populated_children( $set ) {
  305. $this->populated_children = (bool) $set;
  306. }
  307. /**
  308. * Check whether a non-public property is set.
  309. *
  310. * If `$name` matches a post field, the comment post will be loaded and the post's value checked.
  311. *
  312. * @since 4.4.0
  313. *
  314. * @param string $name Property name.
  315. * @return bool
  316. */
  317. public function __isset( $name ) {
  318. if ( in_array( $name, $this->post_fields, true ) && 0 !== (int) $this->comment_post_ID ) {
  319. $post = get_post( $this->comment_post_ID );
  320. return property_exists( $post, $name );
  321. }
  322. }
  323. /**
  324. * Magic getter.
  325. *
  326. * If `$name` matches a post field, the comment post will be loaded and the post's value returned.
  327. *
  328. * @since 4.4.0
  329. *
  330. * @param string $name
  331. * @return mixed
  332. */
  333. public function __get( $name ) {
  334. if ( in_array( $name, $this->post_fields, true ) ) {
  335. $post = get_post( $this->comment_post_ID );
  336. return $post->$name;
  337. }
  338. }
  339. }