| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209 |
- import { useCallback, useEffect, useMemo, useState } from 'react';
- import {
- Alert,
- FlatList,
- Image,
- InteractionManager,
- KeyboardAvoidingView,
- Modal,
- Pressable,
- StyleSheet,
- TextInput,
- View,
- Platform,
- } from 'react-native';
- import DateTimePicker from '@react-native-community/datetimepicker';
- import * as ImagePicker from 'expo-image-picker';
- import { ResizeMode, Video } from 'expo-av';
- import { ThemedText } from '@/components/themed-text';
- import { ThemedView } from '@/components/themed-view';
- import { ThemedButton } from '@/components/themed-button';
- import { IconButton } from '@/components/icon-button';
- import { IconSymbol } from '@/components/ui/icon-symbol';
- import { Colors, Fonts } from '@/constants/theme';
- import { useTranslation } from '@/localization/i18n';
- import { dbPromise, initCoreTables } from '@/services/db';
- import { ZoomImageModal } from '@/components/zoom-image-modal';
- import { useLocalSearchParams, useRouter } from 'expo-router';
- import { useFocusEffect, useNavigation } from '@react-navigation/native';
- import { useColorScheme } from '@/hooks/use-color-scheme';
- type FieldRow = {
- id: number;
- name: string | null;
- };
- type CropRow = {
- id: number;
- field_id: number | null;
- crop_name: string | null;
- };
- type CostRow = {
- id: number;
- field_id: number | null;
- crop_id: number | null;
- category: string | null;
- amount: number | null;
- currency: string | null;
- vendor: string | null;
- notes: string | null;
- spent_at: string | null;
- photo_uri: string | null;
- field_name: string | null;
- crop_name: string | null;
- };
- export default function CostsScreen() {
- const { t } = useTranslation();
- const router = useRouter();
- const navigation = useNavigation();
- const params = useLocalSearchParams<{ from?: string | string[] }>();
- const theme = useColorScheme() ?? 'light';
- const palette = Colors[theme];
- const fromParam = Array.isArray(params.from) ? params.from[0] : params.from;
- const categoryPresets = ['seed', 'fertilizer', 'labor', 'fuel', 'equipment', 'transport', 'misc'];
- const [currency, setCurrency] = useState('THB');
- const [costs, setCosts] = useState<CostRow[]>([]);
- const [fields, setFields] = useState<FieldRow[]>([]);
- const [crops, setCrops] = useState<CropRow[]>([]);
- const [status, setStatus] = useState(t('costs.loading'));
- const [newModalOpen, setNewModalOpen] = useState(false);
- const [fieldModalOpen, setFieldModalOpen] = useState(false);
- const [cropModalOpen, setCropModalOpen] = useState(false);
- const [reopenSheetAfterSelect, setReopenSheetAfterSelect] = useState(false);
- const [fieldModalTarget, setFieldModalTarget] = useState<'new' | 'edit'>('new');
- const [cropModalTarget, setCropModalTarget] = useState<'new' | 'edit'>('new');
- const [editModalOpen, setEditModalOpen] = useState(false);
- const [editingId, setEditingId] = useState<number | null>(null);
- const [selectedFieldId, setSelectedFieldId] = useState<number | null>(null);
- const [selectedCropId, setSelectedCropId] = useState<number | null>(null);
- useEffect(() => {
- navigation.setOptions({
- headerLeft: () => (
- <Pressable
- onPress={() => {
- if (fromParam === 'logbook') {
- router.replace('/logbook');
- return;
- }
- if (fromParam === 'home') {
- router.replace('/');
- return;
- }
- router.back();
- }}
- hitSlop={10}
- style={{ paddingHorizontal: 8 }}>
- <IconSymbol name="chevron.left" size={20} color={palette.text} />
- </Pressable>
- ),
- });
- }, [fromParam, navigation, palette.text, router]);
- const [category, setCategory] = useState('');
- const [amount, setAmount] = useState('');
- const [vendor, setVendor] = useState('');
- const [notes, setNotes] = useState('');
- const [spentDate, setSpentDate] = useState('');
- const [showSpentPicker, setShowSpentPicker] = useState(false);
- const [photoUri, setPhotoUri] = useState<string | null>(null);
- const [errors, setErrors] = useState<{ field?: string; amount?: string }>({});
- const [editFieldId, setEditFieldId] = useState<number | null>(null);
- const [editCropId, setEditCropId] = useState<number | null>(null);
- const [editCategory, setEditCategory] = useState('');
- const [editAmount, setEditAmount] = useState('');
- const [editVendor, setEditVendor] = useState('');
- const [editNotes, setEditNotes] = useState('');
- const [editSpentDate, setEditSpentDate] = useState('');
- const [showEditSpentPicker, setShowEditSpentPicker] = useState(false);
- const [editPhotoUri, setEditPhotoUri] = useState<string | null>(null);
- const [zoomUri, setZoomUri] = useState<string | null>(null);
- const [pendingZoomUri, setPendingZoomUri] = useState<string | null>(null);
- const [editErrors, setEditErrors] = useState<{ field?: string; amount?: string }>({});
- const selectedField = useMemo(
- () => fields.find((item) => item.id === selectedFieldId),
- [fields, selectedFieldId]
- );
- const selectedCrop = useMemo(
- () => crops.find((item) => item.id === selectedCropId),
- [crops, selectedCropId]
- );
- const selectedEditField = useMemo(
- () => fields.find((item) => item.id === editFieldId),
- [fields, editFieldId]
- );
- const selectedEditCrop = useMemo(
- () => crops.find((item) => item.id === editCropId),
- [crops, editCropId]
- );
- useEffect(() => {
- let isActive = true;
- async function loadData() {
- try {
- await initCoreTables();
- const db = await dbPromise;
- const profileRow = await db.getFirstAsync<{ currency: string | null }>(
- 'SELECT currency FROM user_profile WHERE id = 1;'
- );
- const fieldRows = await db.getAllAsync<FieldRow>(
- 'SELECT id, name FROM fields ORDER BY name ASC;'
- );
- const cropRows = await db.getAllAsync<CropRow>(
- 'SELECT id, field_id, crop_name FROM crops ORDER BY id DESC;'
- );
- const costRows = await db.getAllAsync<CostRow>(
- `SELECT c.id, c.field_id, c.crop_id, c.category, c.amount, c.currency, c.vendor, c.notes,
- c.spent_at, c.photo_uri, f.name as field_name, cr.crop_name as crop_name
- FROM costs c
- LEFT JOIN fields f ON f.id = c.field_id
- LEFT JOIN crops cr ON cr.id = c.crop_id
- ORDER BY c.spent_at DESC;`
- );
- if (!isActive) return;
- setCurrency(profileRow?.currency ?? 'THB');
- setFields(fieldRows);
- setCrops(cropRows);
- setCosts(costRows);
- setStatus(costRows.length === 0 ? t('costs.empty') : '');
- } catch (error) {
- if (isActive) setStatus(`Error: ${String(error)}`);
- }
- }
- loadData();
- return () => {
- isActive = false;
- };
- }, [t]);
- const fetchCostsPage = useCallback(async () => {
- try {
- const db = await dbPromise;
- const profileRow = await db.getFirstAsync<{ currency: string | null }>(
- 'SELECT currency FROM user_profile WHERE id = 1;'
- );
- const costRows = await db.getAllAsync<CostRow>(
- `SELECT c.id, c.field_id, c.crop_id, c.category, c.amount, c.currency, c.vendor, c.notes,
- c.spent_at, c.photo_uri, f.name as field_name, cr.crop_name as crop_name
- FROM costs c
- LEFT JOIN fields f ON f.id = c.field_id
- LEFT JOIN crops cr ON cr.id = c.crop_id
- ORDER BY c.spent_at DESC;`
- );
- setCurrency(profileRow?.currency ?? 'THB');
- setCosts(costRows);
- setStatus(costRows.length === 0 ? t('costs.empty') : '');
- } catch (error) {
- setStatus(`Error: ${String(error)}`);
- }
- }, [t]);
- useFocusEffect(
- useCallback(() => {
- fetchCostsPage();
- }, [fetchCostsPage])
- );
- useEffect(() => {
- if (!newModalOpen && !editModalOpen && pendingZoomUri) {
- const uri = pendingZoomUri;
- setPendingZoomUri(null);
- InteractionManager.runAfterInteractions(() => {
- setTimeout(() => setZoomUri(uri), 150);
- });
- }
- }, [newModalOpen, editModalOpen, pendingZoomUri]);
- async function handleSave() {
- const parsedAmount = amount.trim() ? Number(amount) : null;
- const nextErrors: { field?: string; amount?: string } = {};
- if (!selectedFieldId) nextErrors.field = t('costs.fieldRequired');
- if (!parsedAmount || !Number.isFinite(parsedAmount)) nextErrors.amount = t('costs.amountInvalid');
- setErrors(nextErrors);
- if (Object.keys(nextErrors).length > 0) {
- setStatus(nextErrors.field ?? nextErrors.amount ?? t('costs.fieldRequired'));
- return false;
- }
- try {
- const db = await dbPromise;
- const now = new Date().toISOString();
- await db.runAsync(
- 'INSERT INTO costs (field_id, crop_id, category, amount, currency, vendor, notes, spent_at, photo_uri, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
- selectedFieldId,
- selectedCropId,
- category.trim() || null,
- parsedAmount,
- currency,
- vendor.trim() || null,
- notes.trim() || null,
- spentDate.trim() || now,
- photoUri,
- now
- );
- resetNewForm();
- setStatus(t('costs.saved'));
- const costRows = await db.getAllAsync<CostRow>(
- `SELECT c.id, c.field_id, c.crop_id, c.category, c.amount, c.currency, c.vendor, c.notes,
- c.spent_at, c.photo_uri, f.name as field_name, cr.crop_name as crop_name
- FROM costs c
- LEFT JOIN fields f ON f.id = c.field_id
- LEFT JOIN crops cr ON cr.id = c.crop_id
- ORDER BY c.spent_at DESC;`
- );
- setCosts(costRows);
- return true;
- } catch (error) {
- setStatus(`Error: ${String(error)}`);
- return false;
- }
- }
- async function handleUpdate() {
- if (!editingId) return;
- const parsedAmount = editAmount.trim() ? Number(editAmount) : null;
- const nextErrors: { field?: string; amount?: string } = {};
- if (!editFieldId) nextErrors.field = t('costs.fieldRequired');
- if (!parsedAmount || !Number.isFinite(parsedAmount)) nextErrors.amount = t('costs.amountInvalid');
- setEditErrors(nextErrors);
- if (Object.keys(nextErrors).length > 0) {
- setStatus(nextErrors.field ?? nextErrors.amount ?? t('costs.fieldRequired'));
- return;
- }
- try {
- const db = await dbPromise;
- const now = new Date().toISOString();
- await db.runAsync(
- 'UPDATE costs SET field_id = ?, crop_id = ?, category = ?, amount = ?, currency = ?, vendor = ?, notes = ?, spent_at = ?, photo_uri = ? WHERE id = ?;',
- editFieldId,
- editCropId,
- editCategory.trim() || null,
- parsedAmount,
- currency,
- editVendor.trim() || null,
- editNotes.trim() || null,
- editSpentDate.trim() || now,
- editPhotoUri,
- editingId
- );
- setEditModalOpen(false);
- setEditingId(null);
- const costRows = await db.getAllAsync<CostRow>(
- `SELECT c.id, c.field_id, c.crop_id, c.category, c.amount, c.currency, c.vendor, c.notes,
- c.spent_at, c.photo_uri, f.name as field_name, cr.crop_name as crop_name
- FROM costs c
- LEFT JOIN fields f ON f.id = c.field_id
- LEFT JOIN crops cr ON cr.id = c.crop_id
- ORDER BY c.spent_at DESC;`
- );
- setCosts(costRows);
- } catch (error) {
- setStatus(`Error: ${String(error)}`);
- }
- }
- function startEdit(item: CostRow) {
- router.push(`/costs/${item.id}`);
- }
- function cancelEdit() {
- setEditingId(null);
- setEditFieldId(null);
- setEditCropId(null);
- setEditCategory('');
- setEditAmount('');
- setEditVendor('');
- setEditNotes('');
- setEditSpentDate('');
- setEditPhotoUri(null);
- setEditErrors({});
- setEditModalOpen(false);
- }
- function resetNewForm() {
- setSelectedFieldId(null);
- setSelectedCropId(null);
- setCategory('');
- setAmount('');
- setVendor('');
- setNotes('');
- setSpentDate('');
- setPhotoUri(null);
- setErrors({});
- }
- function confirmDelete(id: number) {
- Alert.alert(t('costs.deleteTitle'), t('costs.deleteMessage'), [
- { text: t('costs.cancel'), style: 'cancel' },
- { text: t('costs.delete'), style: 'destructive', onPress: () => handleDelete(id) },
- ]);
- }
- async function handleDelete(id: number) {
- try {
- const db = await dbPromise;
- await db.runAsync('DELETE FROM costs WHERE id = ?;', id);
- const costRows = await db.getAllAsync<CostRow>(
- `SELECT c.id, c.field_id, c.crop_id, c.category, c.amount, c.currency, c.vendor, c.notes,
- c.spent_at, c.photo_uri, f.name as field_name, cr.crop_name as crop_name
- FROM costs c
- LEFT JOIN fields f ON f.id = c.field_id
- LEFT JOIN crops cr ON cr.id = c.crop_id
- ORDER BY c.spent_at DESC;`
- );
- setCosts(costRows);
- setStatus(costRows.length === 0 ? t('costs.empty') : '');
- } catch (error) {
- setStatus(`Error: ${String(error)}`);
- }
- }
- const inputStyle = [
- styles.input,
- { borderColor: palette.border, backgroundColor: palette.input, color: palette.text },
- ];
- return (
- <>
- <FlatList
- data={costs}
- keyExtractor={(item) => String(item.id)}
- renderItem={({ item }) => (
- <Pressable onPress={() => startEdit(item)}>
- <ThemedView style={[styles.card, { backgroundColor: palette.card, borderColor: palette.border }]}>
- <View style={styles.cardHeader}>
- <ThemedText type="subtitle">
- {item.category || t('costs.untitled')}
- </ThemedText>
- <IconButton
- name="trash"
- onPress={() => confirmDelete(item.id)}
- accessibilityLabel={t('costs.delete')}
- variant="danger"
- />
- </View>
- <ThemedText style={styles.meta}>
- {item.field_name || t('costs.noField')}
- </ThemedText>
- {item.crop_name ? <ThemedText style={styles.meta}>{item.crop_name}</ThemedText> : null}
- {item.spent_at ? (
- <ThemedText style={styles.meta}>{formatDate(item.spent_at)}</ThemedText>
- ) : null}
- {item.amount !== null ? (
- <ThemedText>
- {item.amount} {item.currency || currency}
- </ThemedText>
- ) : null}
- {normalizeMediaUri(item.photo_uri) ? (
- isVideoUri(normalizeMediaUri(item.photo_uri) as string) ? (
- <Video
- source={{ uri: normalizeMediaUri(item.photo_uri) as string }}
- style={styles.videoPreview}
- useNativeControls
- resizeMode={ResizeMode.CONTAIN}
- isMuted
- />
- ) : (
- <Pressable onPress={() => setZoomUri(normalizeMediaUri(item.photo_uri) as string)}>
- <Image
- source={{ uri: normalizeMediaUri(item.photo_uri) as string }}
- style={styles.listPhoto}
- resizeMode="contain"
- />
- </Pressable>
- )
- ) : null}
- {item.vendor ? <ThemedText>{item.vendor}</ThemedText> : null}
- {item.notes ? <ThemedText>{item.notes}</ThemedText> : null}
- </ThemedView>
- </Pressable>
- )}
- ItemSeparatorComponent={() => <View style={styles.separator} />}
- ListHeaderComponent={
- <View>
- <ThemedView style={styles.hero}>
- <Image source={require('@/assets/images/costrecords.jpg')} style={styles.heroImage} />
- </ThemedView>
- <ThemedView style={styles.titleContainer}>
- <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
- {t('costs.title')}
- </ThemedText>
- </ThemedView>
- {status ? (
- <ThemedView style={styles.section}>
- <ThemedText>{status}</ThemedText>
- </ThemedView>
- ) : null}
- <ThemedView style={styles.section}>
- <Pressable style={styles.newButton} onPress={() => router.push('/costs/new')}>
- <IconSymbol size={18} name="plus.circle.fill" color="#2F7D4F" />
- <ThemedText style={styles.newButtonText}>{t('costs.new')}</ThemedText>
- </Pressable>
- </ThemedView>
- </View>
- }
- ListFooterComponent={<View style={styles.footer} />}
- />
- <Modal transparent visible={fieldModalOpen} animationType="fade">
- <Pressable
- style={styles.modalOverlay}
- onPress={() => {
- setFieldModalOpen(false);
- setReopenSheetAfterSelect(false);
- }}>
- <View style={[styles.modalCard, { backgroundColor: palette.card, borderColor: palette.border }]}>
- <ThemedText type="subtitle">{t('costs.selectField')}</ThemedText>
- <FlatList
- data={fields}
- keyExtractor={(item) => String(item.id)}
- renderItem={({ item }) => (
- <Pressable
- onPress={() => {
- if (fieldModalTarget === 'edit') {
- setEditFieldId(item.id);
- setEditErrors((prev) => ({ ...prev, field: undefined }));
- if (reopenSheetAfterSelect) setEditModalOpen(true);
- } else {
- setSelectedFieldId(item.id);
- setErrors((prev) => ({ ...prev, field: undefined }));
- if (reopenSheetAfterSelect) setNewModalOpen(true);
- }
- setFieldModalOpen(false);
- setReopenSheetAfterSelect(false);
- }}
- style={styles.modalItem}>
- <ThemedText>{item.name || t('costs.untitled')}</ThemedText>
- </Pressable>
- )}
- />
- </View>
- </Pressable>
- </Modal>
- <Modal transparent visible={cropModalOpen} animationType="fade">
- <Pressable
- style={styles.modalOverlay}
- onPress={() => {
- setCropModalOpen(false);
- setReopenSheetAfterSelect(false);
- }}>
- <View style={[styles.modalCard, { backgroundColor: palette.card, borderColor: palette.border }]}>
- <ThemedText type="subtitle">{t('costs.selectCrop')}</ThemedText>
- <FlatList
- data={crops.filter((item) => {
- const targetField = cropModalTarget === 'edit' ? editFieldId : selectedFieldId;
- return !targetField || item.field_id === targetField;
- })}
- keyExtractor={(item) => String(item.id)}
- renderItem={({ item }) => (
- <Pressable
- onPress={() => {
- if (cropModalTarget === 'edit') {
- setEditCropId(item.id);
- if (reopenSheetAfterSelect) setEditModalOpen(true);
- } else {
- setSelectedCropId(item.id);
- if (reopenSheetAfterSelect) setNewModalOpen(true);
- }
- setCropModalOpen(false);
- setReopenSheetAfterSelect(false);
- }}
- style={styles.modalItem}>
- <ThemedText>{item.crop_name || t('costs.untitled')}</ThemedText>
- </Pressable>
- )}
- ListEmptyComponent={<ThemedText style={styles.meta}>{t('costs.noCrop')}</ThemedText>}
- />
- </View>
- </Pressable>
- </Modal>
- <Modal transparent visible={newModalOpen} animationType="slide">
- <View style={styles.sheetOverlay}>
- <Pressable style={styles.sheetBackdrop} onPress={() => setNewModalOpen(false)} />
- <KeyboardAvoidingView
- behavior={Platform.OS === 'ios' ? 'padding' : undefined}
- keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
- style={styles.keyboardAvoid}>
- <View style={[styles.sheet, { backgroundColor: palette.card, borderColor: palette.border }]}>
- <FlatList
- data={[{ key: 'new' }]}
- keyExtractor={(item) => item.key}
- contentContainerStyle={styles.sheetListContent}
- renderItem={() => (
- <View style={styles.sheetContent}>
- <ThemedText type="subtitle">{t('costs.new')}</ThemedText>
- <ThemedText>
- {t('costs.field')}
- <ThemedText style={styles.requiredMark}> *</ThemedText>
- </ThemedText>
- <ThemedButton
- title={selectedField?.name || t('costs.selectField')}
- onPress={() => {
- setReopenSheetAfterSelect(true);
- setFieldModalTarget('new');
- setNewModalOpen(false);
- setFieldModalOpen(true);
- }}
- variant="secondary"
- />
- {errors.field ? (
- <ThemedText style={styles.errorText}>{errors.field}</ThemedText>
- ) : null}
- <ThemedText>{t('costs.crop')}</ThemedText>
- <ThemedButton
- title={selectedCrop?.crop_name || t('costs.selectCrop')}
- onPress={() => {
- setReopenSheetAfterSelect(true);
- setCropModalTarget('new');
- setNewModalOpen(false);
- setCropModalOpen(true);
- }}
- variant="secondary"
- />
- <ThemedText>{t('costs.category')}</ThemedText>
- <View style={styles.chipRow}>
- {categoryPresets.map((preset) => {
- const label = t(`costs.category.${preset}`);
- const normalized = category.trim().toLowerCase();
- const isActive = label.toLowerCase() === normalized || preset === normalized;
- return (
- <Pressable
- key={preset}
- onPress={() => setCategory(label)}
- style={[styles.chip, isActive && styles.chipActive]}>
- <ThemedText style={isActive ? styles.chipTextActive : styles.chipText}>
- {label}
- </ThemedText>
- </Pressable>
- );
- })}
- </View>
- <TextInput
- value={category}
- onChangeText={setCategory}
- placeholder={t('costs.categoryPlaceholder')}
- style={inputStyle}
- />
- <ThemedText>
- {t('costs.amount')} ({currency})
- <ThemedText style={styles.requiredMark}> *</ThemedText>
- </ThemedText>
- <TextInput
- value={amount}
- onChangeText={(value) => {
- setAmount(value);
- if (errors.amount) {
- setErrors((prev) => ({ ...prev, amount: undefined }));
- }
- }}
- placeholder={t('costs.amountPlaceholder')}
- style={inputStyle}
- keyboardType="decimal-pad"
- />
- {errors.amount ? (
- <ThemedText style={styles.errorText}>{errors.amount}</ThemedText>
- ) : null}
- <ThemedText>{t('costs.vendor')}</ThemedText>
- <TextInput
- value={vendor}
- onChangeText={setVendor}
- placeholder={t('costs.vendorPlaceholder')}
- style={inputStyle}
- />
- <ThemedText>{t('costs.date')}</ThemedText>
- <Pressable onPress={() => setShowSpentPicker(true)} style={styles.dateInput}>
- <ThemedText style={styles.dateValue}>
- {spentDate ? formatDateLabel(spentDate) : t('costs.datePlaceholder')}
- </ThemedText>
- </Pressable>
- {showSpentPicker ? (
- <>
- {Platform.OS === 'ios' ? (
- <View style={styles.pickerRow}>
- <ThemedButton
- title={t('crops.today')}
- onPress={() => {
- setSpentDate(toDateOnly(new Date()));
- setShowSpentPicker(false);
- }}
- variant="secondary"
- />
- <ThemedButton
- title={t('crops.done')}
- onPress={() => setShowSpentPicker(false)}
- variant="secondary"
- />
- </View>
- ) : null}
- <DateTimePicker
- value={spentDate ? new Date(spentDate) : new Date()}
- mode="date"
- display={Platform.OS === 'ios' ? 'inline' : 'calendar'}
- onChange={(event, date) => {
- if (date) setSpentDate(toDateOnly(date));
- if (Platform.OS !== 'ios') setShowSpentPicker(false);
- }}
- />
- </>
- ) : null}
- <ThemedText>{t('costs.notes')}</ThemedText>
- <TextInput
- value={notes}
- onChangeText={setNotes}
- placeholder={t('costs.notesPlaceholder')}
- style={inputStyle}
- multiline
- />
- <ThemedText>{t('costs.addMedia')}</ThemedText>
- {normalizeMediaUri(photoUri) ? (
- isVideoUri(normalizeMediaUri(photoUri) as string) ? (
- <Video
- source={{ uri: normalizeMediaUri(photoUri) as string }}
- style={styles.videoPreview}
- useNativeControls
- resizeMode={ResizeMode.CONTAIN}
- isMuted
- />
- ) : (
- <Pressable
- onPress={() => {
- setPendingZoomUri(normalizeMediaUri(photoUri) as string);
- setNewModalOpen(false);
- }}>
- <Image
- source={{ uri: normalizeMediaUri(photoUri) as string }}
- style={styles.photoPreview}
- resizeMode="contain"
- />
- </Pressable>
- )
- ) : (
- <ThemedText style={styles.photoPlaceholder}>{t('costs.noPhoto')}</ThemedText>
- )}
- <View style={styles.photoRow}>
- <ThemedButton
- title={t('costs.pickFromGallery')}
- onPress={() => handlePickPhoto(setPhotoUri)}
- variant="secondary"
- />
- <ThemedButton
- title={t('costs.takeMedia')}
- onPress={() =>
- handleTakePhoto(setPhotoUri, (code) =>
- setStatus(
- code === 'cameraDenied'
- ? t('tasks.cameraDenied')
- : t('tasks.cameraError')
- )
- )
- }
- variant="secondary"
- />
- </View>
- <View style={styles.modalActions}>
- <ThemedButton
- title={t('costs.cancel')}
- onPress={() => setNewModalOpen(false)}
- variant="secondary"
- />
- <ThemedButton
- title={t('costs.save')}
- onPress={async () => {
- const ok = await handleSave();
- if (ok) setNewModalOpen(false);
- }}
- />
- </View>
- <View style={styles.sheetFooter} />
- </View>
- )}
- />
- </View>
- </KeyboardAvoidingView>
- </View>
- </Modal>
- <Modal transparent visible={editModalOpen} animationType="slide">
- <View style={styles.sheetOverlay}>
- <Pressable style={styles.sheetBackdrop} onPress={cancelEdit} />
- <KeyboardAvoidingView
- behavior={Platform.OS === 'ios' ? 'padding' : undefined}
- keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
- style={styles.keyboardAvoid}>
- <View style={[styles.sheet, { backgroundColor: palette.card, borderColor: palette.border }]}>
- <FlatList
- data={[{ key: 'edit' }]}
- keyExtractor={(item) => item.key}
- contentContainerStyle={styles.sheetListContent}
- renderItem={() => (
- <View style={styles.sheetContent}>
- <ThemedText type="subtitle">{t('costs.edit')}</ThemedText>
- <ThemedText>
- {t('costs.field')}
- <ThemedText style={styles.requiredMark}> *</ThemedText>
- </ThemedText>
- <ThemedButton
- title={selectedEditField?.name || t('costs.selectField')}
- onPress={() => {
- setReopenSheetAfterSelect(true);
- setFieldModalTarget('edit');
- setEditModalOpen(false);
- setFieldModalOpen(true);
- }}
- variant="secondary"
- />
- {editErrors.field ? (
- <ThemedText style={styles.errorText}>{editErrors.field}</ThemedText>
- ) : null}
- <ThemedText>{t('costs.crop')}</ThemedText>
- <ThemedButton
- title={selectedEditCrop?.crop_name || t('costs.selectCrop')}
- onPress={() => {
- setReopenSheetAfterSelect(true);
- setCropModalTarget('edit');
- setEditModalOpen(false);
- setCropModalOpen(true);
- }}
- variant="secondary"
- />
- <ThemedText>{t('costs.category')}</ThemedText>
- <View style={styles.chipRow}>
- {categoryPresets.map((preset) => {
- const label = t(`costs.category.${preset}`);
- const normalized = editCategory.trim().toLowerCase();
- const isActive = label.toLowerCase() === normalized || preset === normalized;
- return (
- <Pressable
- key={`edit-${preset}`}
- onPress={() => setEditCategory(label)}
- style={[styles.chip, isActive && styles.chipActive]}>
- <ThemedText style={isActive ? styles.chipTextActive : styles.chipText}>
- {label}
- </ThemedText>
- </Pressable>
- );
- })}
- </View>
- <TextInput
- value={editCategory}
- onChangeText={setEditCategory}
- placeholder={t('costs.categoryPlaceholder')}
- style={inputStyle}
- />
- <ThemedText>
- {t('costs.amount')} ({currency})
- <ThemedText style={styles.requiredMark}> *</ThemedText>
- </ThemedText>
- <TextInput
- value={editAmount}
- onChangeText={(value) => {
- setEditAmount(value);
- if (editErrors.amount) {
- setEditErrors((prev) => ({ ...prev, amount: undefined }));
- }
- }}
- placeholder={t('costs.amountPlaceholder')}
- style={inputStyle}
- keyboardType="decimal-pad"
- />
- {editErrors.amount ? (
- <ThemedText style={styles.errorText}>{editErrors.amount}</ThemedText>
- ) : null}
- <ThemedText>{t('costs.vendor')}</ThemedText>
- <TextInput
- value={editVendor}
- onChangeText={setEditVendor}
- placeholder={t('costs.vendorPlaceholder')}
- style={inputStyle}
- />
- <ThemedText>{t('costs.date')}</ThemedText>
- <Pressable onPress={() => setShowEditSpentPicker(true)} style={styles.dateInput}>
- <ThemedText style={styles.dateValue}>
- {editSpentDate ? formatDateLabel(editSpentDate) : t('costs.datePlaceholder')}
- </ThemedText>
- </Pressable>
- {showEditSpentPicker ? (
- <>
- {Platform.OS === 'ios' ? (
- <View style={styles.pickerRow}>
- <ThemedButton
- title={t('crops.today')}
- onPress={() => {
- setEditSpentDate(toDateOnly(new Date()));
- setShowEditSpentPicker(false);
- }}
- variant="secondary"
- />
- <ThemedButton
- title={t('crops.done')}
- onPress={() => setShowEditSpentPicker(false)}
- variant="secondary"
- />
- </View>
- ) : null}
- <DateTimePicker
- value={editSpentDate ? new Date(editSpentDate) : new Date()}
- mode="date"
- display={Platform.OS === 'ios' ? 'inline' : 'calendar'}
- onChange={(event, date) => {
- if (date) setEditSpentDate(toDateOnly(date));
- if (Platform.OS !== 'ios') setShowEditSpentPicker(false);
- }}
- />
- </>
- ) : null}
- <ThemedText>{t('costs.notes')}</ThemedText>
- <TextInput
- value={editNotes}
- onChangeText={setEditNotes}
- placeholder={t('costs.notesPlaceholder')}
- style={inputStyle}
- multiline
- />
- <ThemedText>{t('costs.addMedia')}</ThemedText>
- {normalizeMediaUri(editPhotoUri) ? (
- isVideoUri(normalizeMediaUri(editPhotoUri) as string) ? (
- <Video
- source={{ uri: normalizeMediaUri(editPhotoUri) as string }}
- style={styles.videoPreview}
- useNativeControls
- resizeMode={ResizeMode.CONTAIN}
- isMuted
- />
- ) : (
- <Pressable
- onPress={() => {
- setPendingZoomUri(normalizeMediaUri(editPhotoUri) as string);
- setEditModalOpen(false);
- }}>
- <Image
- source={{ uri: normalizeMediaUri(editPhotoUri) as string }}
- style={styles.photoPreview}
- resizeMode="contain"
- />
- </Pressable>
- )
- ) : (
- <ThemedText style={styles.photoPlaceholder}>{t('costs.noPhoto')}</ThemedText>
- )}
- <View style={styles.photoRow}>
- <ThemedButton
- title={t('costs.pickFromGallery')}
- onPress={() => handlePickPhoto(setEditPhotoUri)}
- variant="secondary"
- />
- <ThemedButton
- title={t('costs.takeMedia')}
- onPress={() =>
- handleTakePhoto(setEditPhotoUri, (code) =>
- setStatus(
- code === 'cameraDenied'
- ? t('tasks.cameraDenied')
- : t('tasks.cameraError')
- )
- )
- }
- variant="secondary"
- />
- </View>
- <View style={styles.modalActions}>
- <ThemedButton
- title={t('costs.cancel')}
- onPress={cancelEdit}
- variant="secondary"
- />
- <ThemedButton title={t('costs.update')} onPress={handleUpdate} />
- </View>
- <View style={styles.sheetFooter} />
- </View>
- )}
- />
- </View>
- </KeyboardAvoidingView>
- </View>
- </Modal>
- <ZoomImageModal
- uri={zoomUri}
- visible={Boolean(zoomUri)}
- onClose={() => setZoomUri(null)}
- />
- </>
- );
- }
- function formatDate(value: string) {
- try {
- return new Date(value).toLocaleString();
- } catch {
- return value;
- }
- }
- function formatDateLabel(value: string) {
- try {
- return new Date(value).toISOString().slice(0, 10);
- } catch {
- return value;
- }
- }
- function toDateOnly(date: Date) {
- return date.toISOString().slice(0, 10);
- }
- async function handlePickPhoto(setter: (value: string | null) => void) {
- const result = await ImagePicker.launchImageLibraryAsync({
- mediaTypes: getMediaTypes(),
- quality: 1,
- });
- if (result.canceled) return;
- const asset = result.assets[0];
- setter(asset.uri);
- }
- async function handleTakePhoto(
- setter: (value: string | null) => void,
- onError?: (msg: string) => void
- ) {
- try {
- const permission = await ImagePicker.requestCameraPermissionsAsync();
- if (!permission.granted) {
- onError?.('cameraDenied');
- return;
- }
- const result = await ImagePicker.launchCameraAsync({
- mediaTypes: getMediaTypes(),
- quality: 1,
- });
- if (result.canceled) return;
- const asset = result.assets[0];
- setter(asset.uri);
- } catch {
- onError?.('cameraError');
- }
- }
- function getMediaTypes() {
- const mediaType = (ImagePicker as {
- MediaType?: { Image?: unknown; Images?: unknown; Video?: unknown; Videos?: unknown };
- }).MediaType;
- const imageType = mediaType?.Image ?? mediaType?.Images;
- const videoType = mediaType?.Video ?? mediaType?.Videos;
- if (imageType && videoType) {
- return [imageType, videoType];
- }
- return imageType ?? videoType ?? ['images', 'videos'];
- }
- function isVideoUri(uri: string) {
- return /\.(mp4|mov|m4v|webm|avi|mkv)(\?.*)?$/i.test(uri);
- }
- function normalizeMediaUri(uri?: string | null) {
- if (typeof uri !== 'string') return null;
- const trimmed = uri.trim();
- return trimmed ? trimmed : null;
- }
- const styles = StyleSheet.create({
- hero: {
- backgroundColor: '#E8E6DA',
- aspectRatio: 16 / 9,
- width: '100%',
- },
- heroImage: {
- width: '100%',
- height: '100%',
- },
- titleContainer: {
- gap: 8,
- paddingHorizontal: 16,
- paddingVertical: 12,
- },
- section: {
- gap: 8,
- marginBottom: 16,
- paddingHorizontal: 16,
- },
- newButton: {
- flexDirection: 'row',
- alignItems: 'center',
- gap: 8,
- borderRadius: 10,
- borderWidth: 1,
- borderColor: '#B9B9B9',
- paddingHorizontal: 12,
- paddingVertical: 10,
- alignSelf: 'flex-start',
- },
- newButtonText: {
- fontSize: 15,
- fontWeight: '600',
- },
- card: {
- borderRadius: 12,
- borderWidth: 1,
- borderColor: '#C6C6C6',
- padding: 12,
- marginHorizontal: 16,
- gap: 6,
- backgroundColor: '#FFFFFF',
- },
- cardHeader: {
- flexDirection: 'row',
- alignItems: 'center',
- justifyContent: 'space-between',
- gap: 8,
- },
- meta: {
- opacity: 0.7,
- },
- separator: {
- height: 12,
- },
- footer: {
- height: 24,
- },
- modalOverlay: {
- flex: 1,
- backgroundColor: 'rgba(0,0,0,0.3)',
- justifyContent: 'center',
- padding: 16,
- },
- modalCard: {
- borderRadius: 12,
- borderWidth: 1,
- borderColor: '#C6C6C6',
- padding: 16,
- backgroundColor: '#FFFFFF',
- gap: 8,
- maxHeight: '70%',
- },
- modalItem: {
- paddingVertical: 8,
- },
- input: {
- borderRadius: 10,
- borderWidth: 1,
- borderColor: '#B9B9B9',
- paddingHorizontal: 12,
- paddingVertical: 10,
- fontSize: 15,
- },
- modalActions: {
- flexDirection: 'row',
- justifyContent: 'space-between',
- gap: 12,
- },
- sheetOverlay: {
- flex: 1,
- backgroundColor: 'rgba(0,0,0,0.3)',
- justifyContent: 'flex-end',
- },
- sheetBackdrop: {
- ...StyleSheet.absoluteFillObject,
- },
- sheet: {
- borderTopLeftRadius: 16,
- borderTopRightRadius: 16,
- borderWidth: 1,
- borderColor: '#C6C6C6',
- padding: 16,
- backgroundColor: '#FFFFFF',
- gap: 10,
- maxHeight: '85%',
- },
- sheetContent: {
- gap: 10,
- },
- sheetListContent: {
- paddingBottom: 80,
- },
- sheetFooter: {
- height: 24,
- },
- keyboardAvoid: {
- width: '100%',
- flex: 1,
- justifyContent: 'flex-end',
- },
- photoRow: {
- flexDirection: 'row',
- gap: 12,
- },
- photoPreview: {
- width: '100%',
- height: 200,
- borderRadius: 12,
- },
- listPhoto: {
- width: '100%',
- height: 160,
- borderRadius: 10,
- },
- videoPreview: {
- width: '100%',
- height: 200,
- borderRadius: 12,
- backgroundColor: '#1C1C1C',
- },
- photoPlaceholder: {
- opacity: 0.6,
- },
- dateInput: {
- borderRadius: 10,
- borderWidth: 1,
- borderColor: '#B9B9B9',
- paddingHorizontal: 12,
- paddingVertical: 10,
- },
- dateValue: {
- fontSize: 15,
- opacity: 0.9,
- },
- pickerRow: {
- flexDirection: 'row',
- gap: 8,
- },
- chipRow: {
- flexDirection: 'row',
- flexWrap: 'wrap',
- gap: 8,
- },
- chip: {
- borderRadius: 999,
- borderWidth: 1,
- borderColor: '#C6C6C6',
- paddingHorizontal: 10,
- paddingVertical: 4,
- },
- chipActive: {
- borderColor: '#2F7D4F',
- backgroundColor: '#E7F3EA',
- },
- chipText: {
- fontSize: 12,
- },
- chipTextActive: {
- fontSize: 12,
- color: '#2F7D4F',
- fontWeight: '600',
- },
- requiredMark: {
- color: '#C0392B',
- fontWeight: '700',
- },
- errorText: {
- color: '#C0392B',
- fontSize: 12,
- },
- });
|