Нет описания

setup.tsx 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  1. import { useEffect, useRef, useState } from 'react';
  2. import { KeyboardAvoidingView, Platform, Pressable, StyleSheet, TextInput, View } from 'react-native';
  3. import { Image } from 'expo-image';
  4. import { Asset } from 'expo-asset';
  5. import * as ImagePicker from 'expo-image-picker';
  6. import * as FileSystem from 'expo-file-system/legacy';
  7. import * as Sharing from 'expo-sharing';
  8. import ParallaxScrollView from '@/components/parallax-scroll-view';
  9. import { ThemedText } from '@/components/themed-text';
  10. import { ThemedView } from '@/components/themed-view';
  11. import { IconSymbol } from '@/components/ui/icon-symbol';
  12. import { Colors, Fonts } from '@/constants/theme';
  13. import { useTranslation } from '@/localization/i18n';
  14. import { dbPromise, initCoreTables } from '@/services/db';
  15. import { ThemedButton } from '@/components/themed-button';
  16. import { useColorScheme } from '@/hooks/use-color-scheme';
  17. type Profile = {
  18. name: string;
  19. farmName: string;
  20. location: string;
  21. photoUri: string;
  22. language: 'en' | 'th';
  23. currency: string;
  24. };
  25. const emptyProfile: Profile = {
  26. name: '',
  27. farmName: '',
  28. location: '',
  29. photoUri: '',
  30. language: 'en',
  31. currency: 'THB',
  32. };
  33. type DemoBackup = {
  34. user_profile: Array<{
  35. id: number;
  36. name: string | null;
  37. farm_name: string | null;
  38. location: string | null;
  39. photo_uri: string | null;
  40. language: string | null;
  41. currency: string | null;
  42. created_at: string | null;
  43. updated_at: string | null;
  44. }>;
  45. fields: Array<{
  46. id: number;
  47. name: string | null;
  48. area_ha: number | null;
  49. boundary_geojson: string | null;
  50. notes: string | null;
  51. photo_uri: string | null;
  52. created_at: string | null;
  53. updated_at: string | null;
  54. }>;
  55. crops: Array<{
  56. id: number;
  57. field_id: number | null;
  58. crop_name: string | null;
  59. variety: string | null;
  60. planting_date: string | null;
  61. expected_harvest_date: string | null;
  62. photo_uri: string | null;
  63. }>;
  64. observations: Array<{
  65. id: number;
  66. field_id: number | null;
  67. crop_id: number | null;
  68. obs_type: string | null;
  69. note: string | null;
  70. severity: number | null;
  71. lat: number | null;
  72. lng: number | null;
  73. observed_at: string | null;
  74. }>;
  75. images: Array<{
  76. id: number;
  77. observation_id: number | null;
  78. uri: string | null;
  79. thumbnail_uri: string | null;
  80. width: number | null;
  81. height: number | null;
  82. created_at: string | null;
  83. }>;
  84. daily_tasks: Array<{
  85. id: number;
  86. name: string | null;
  87. description: string | null;
  88. default_time: string | null;
  89. is_active: number | null;
  90. created_at: string | null;
  91. }>;
  92. daily_task_entries: Array<{
  93. id: number;
  94. task_id: number | null;
  95. field_id: number | null;
  96. notes: string | null;
  97. status: string | null;
  98. completed_at: string | null;
  99. created_at: string | null;
  100. meta_json: string | null;
  101. }>;
  102. ml_inferences: Array<{
  103. id: number;
  104. image_id: number | null;
  105. model_name: string | null;
  106. model_version: string | null;
  107. top_label: string | null;
  108. top_score: number | null;
  109. scores_json: string | null;
  110. created_at: string | null;
  111. }>;
  112. harvests: Array<{
  113. id: number;
  114. field_id: number | null;
  115. crop_id: number | null;
  116. harvested_at: string | null;
  117. quantity: number | null;
  118. unit: string | null;
  119. notes: string | null;
  120. photo_uri: string | null;
  121. created_at: string | null;
  122. }>;
  123. sales: Array<{
  124. id: number;
  125. harvest_id: number | null;
  126. field_id: number | null;
  127. crop_id: number | null;
  128. sold_at: string | null;
  129. quantity: number | null;
  130. unit: string | null;
  131. price: number | null;
  132. buyer: string | null;
  133. notes: string | null;
  134. created_at: string | null;
  135. }>;
  136. costs: Array<{
  137. id: number;
  138. field_id: number | null;
  139. crop_id: number | null;
  140. category: string | null;
  141. amount: number | null;
  142. currency: string | null;
  143. vendor: string | null;
  144. notes: string | null;
  145. spent_at: string | null;
  146. photo_uri: string | null;
  147. created_at: string | null;
  148. }>;
  149. };
  150. export default function SetupScreen() {
  151. const { language, setLanguage, t } = useTranslation();
  152. const theme = useColorScheme() ?? 'light';
  153. const palette = Colors[theme];
  154. const currencyPresets = ['THB', 'USD', 'EUR', 'JPY'];
  155. const [profile, setProfile] = useState<Profile>(emptyProfile);
  156. const [status, setStatus] = useState(t('setup.loading'));
  157. const [saveIndicator, setSaveIndicator] = useState('');
  158. const [snackbarVisible, setSnackbarVisible] = useState(false);
  159. const [snackbarMessage, setSnackbarMessage] = useState('');
  160. const demoBackupRef = useRef<DemoBackup | null>(null);
  161. const snackbarTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  162. useEffect(() => {
  163. let isActive = true;
  164. async function init() {
  165. await initCoreTables();
  166. const db = await dbPromise;
  167. const row = await db.getFirstAsync<{
  168. name: string | null;
  169. farm_name: string | null;
  170. location: string | null;
  171. photo_uri: string | null;
  172. language: string | null;
  173. currency: string | null;
  174. }>(
  175. 'SELECT name, farm_name, location, photo_uri, language, currency FROM user_profile WHERE id = 1;'
  176. );
  177. if (!isActive) return;
  178. if (row) {
  179. const storedLanguage =
  180. row.language === 'th' || row.language === 'en' ? row.language : language;
  181. if (storedLanguage !== language) {
  182. setLanguage(storedLanguage);
  183. }
  184. setProfile({
  185. name: row.name ?? '',
  186. farmName: row.farm_name ?? '',
  187. location: row.location ?? '',
  188. photoUri: row.photo_uri ?? '',
  189. language: storedLanguage,
  190. currency: row.currency ?? 'THB',
  191. });
  192. setStatus(t('setup.loaded'));
  193. } else {
  194. setProfile((prev) => ({ ...prev, language, currency: 'THB' }));
  195. setStatus(t('setup.none'));
  196. }
  197. }
  198. init().catch((error) => {
  199. if (isActive) setStatus(`Error: ${String(error)}`);
  200. });
  201. return () => {
  202. isActive = false;
  203. if (snackbarTimerRef.current) {
  204. clearTimeout(snackbarTimerRef.current);
  205. }
  206. };
  207. }, []);
  208. async function handleSave() {
  209. setStatus(t('setup.saving'));
  210. try {
  211. const db = await dbPromise;
  212. const now = new Date().toISOString();
  213. await db.runAsync(
  214. 'INSERT OR REPLACE INTO user_profile (id, name, farm_name, location, photo_uri, language, currency, created_at, updated_at) VALUES (1, ?, ?, ?, ?, ?, ?, COALESCE((SELECT created_at FROM user_profile WHERE id = 1), ?), ?);',
  215. profile.name.trim(),
  216. profile.farmName.trim(),
  217. profile.location.trim(),
  218. profile.photoUri,
  219. profile.language,
  220. profile.currency.trim(),
  221. now,
  222. now
  223. );
  224. setStatus(t('setup.saved'));
  225. setSaveIndicator(t('setup.saveIndicator'));
  226. setTimeout(() => setSaveIndicator(''), 2000);
  227. } catch (error) {
  228. setStatus(`Error: ${String(error)}`);
  229. }
  230. }
  231. async function handleInsertDemoData() {
  232. try {
  233. await initCoreTables();
  234. const db = await dbPromise;
  235. const fieldCount = await db.getFirstAsync<{ count: number }>(
  236. 'SELECT COUNT(*) as count FROM fields;'
  237. );
  238. if (fieldCount?.count && fieldCount.count > 0) {
  239. showSnackbar(t('setup.demoExists'));
  240. return;
  241. }
  242. const now = new Date();
  243. const nowIso = now.toISOString();
  244. const day = 24 * 60 * 60 * 1000;
  245. const toDateOnly = (date: Date) => date.toISOString().slice(0, 10);
  246. const [fieldImageUri, cropImageUri, observationImageUri] = await loadDemoImageUris();
  247. const fieldRows = [
  248. {
  249. name: t('demo.field.north'),
  250. area: 2.4,
  251. notes: t('demo.field.northNote'),
  252. photoUri: fieldImageUri,
  253. },
  254. {
  255. name: t('demo.field.river'),
  256. area: 1.2,
  257. notes: t('demo.field.riverNote'),
  258. photoUri: fieldImageUri,
  259. },
  260. {
  261. name: t('demo.field.greenhouse'),
  262. area: 0.4,
  263. notes: t('demo.field.greenhouseNote'),
  264. photoUri: fieldImageUri,
  265. },
  266. {
  267. name: t('demo.field.orchard'),
  268. area: 1.8,
  269. notes: t('demo.field.orchardNote'),
  270. photoUri: fieldImageUri,
  271. },
  272. {
  273. name: t('demo.field.terrace'),
  274. area: 0.9,
  275. notes: t('demo.field.terraceNote'),
  276. photoUri: fieldImageUri,
  277. },
  278. ];
  279. const extraFieldCount = 100;
  280. for (let i = 0; i < extraFieldCount; i += 1) {
  281. const seed = fieldRows[i % fieldRows.length];
  282. fieldRows.push({
  283. name: `${seed.name} ${i + 2}`,
  284. area: Number((seed.area + (i % 3) * 0.2).toFixed(2)),
  285. notes: seed.notes,
  286. photoUri: fieldImageUri,
  287. });
  288. }
  289. const fieldIds: number[] = [];
  290. for (const field of fieldRows) {
  291. const result = await db.runAsync(
  292. 'INSERT INTO fields (name, area_ha, notes, photo_uri, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?);',
  293. field.name,
  294. field.area,
  295. field.notes,
  296. field.photoUri,
  297. nowIso,
  298. nowIso
  299. );
  300. if (result.lastInsertRowId) fieldIds.push(Number(result.lastInsertRowId));
  301. }
  302. const cropTemplates = [
  303. {
  304. name: t('demo.crop.tomato'),
  305. variety: t('demo.crop.tomatoVariety'),
  306. },
  307. {
  308. name: t('demo.crop.rice'),
  309. variety: t('demo.crop.riceVariety'),
  310. },
  311. {
  312. name: t('demo.crop.lettuce'),
  313. variety: t('demo.crop.lettuceVariety'),
  314. },
  315. {
  316. name: t('demo.crop.chili'),
  317. variety: t('demo.crop.chiliVariety'),
  318. },
  319. {
  320. name: t('demo.crop.cabbage'),
  321. variety: t('demo.crop.cabbageVariety'),
  322. },
  323. ];
  324. const cropRows = fieldIds.slice(0, cropTemplates.length).map((fieldId, index) => {
  325. const template = cropTemplates[index];
  326. return {
  327. fieldId,
  328. name: template.name,
  329. variety: template.variety,
  330. planting: toDateOnly(new Date(now.getTime() - (30 + index * 7) * day)),
  331. harvest: toDateOnly(new Date(now.getTime() + (25 + index * 5) * day)),
  332. photoUri: cropImageUri,
  333. };
  334. });
  335. const extraCropCount = 120;
  336. for (let i = 0; i < extraCropCount; i += 1) {
  337. const template = cropTemplates[i % cropTemplates.length];
  338. cropRows.push({
  339. fieldId: fieldIds[i % fieldIds.length],
  340. name: `${template.name} ${i + 2}`,
  341. variety: template.variety,
  342. planting: toDateOnly(new Date(now.getTime() - (10 + i * 3) * day)),
  343. harvest: toDateOnly(new Date(now.getTime() + (20 + i * 4) * day)),
  344. photoUri: cropImageUri,
  345. });
  346. }
  347. const cropIds: number[] = [];
  348. for (const crop of cropRows) {
  349. if (!crop.fieldId) continue;
  350. const result = await db.runAsync(
  351. 'INSERT INTO crops (field_id, crop_name, variety, planting_date, expected_harvest_date, photo_uri) VALUES (?, ?, ?, ?, ?, ?);',
  352. crop.fieldId,
  353. crop.name,
  354. crop.variety,
  355. crop.planting,
  356. crop.harvest,
  357. crop.photoUri
  358. );
  359. if (result.lastInsertRowId) cropIds.push(Number(result.lastInsertRowId));
  360. }
  361. const observationNotes = [
  362. t('demo.observation.scoutingNote'),
  363. t('demo.observation.diseaseNote'),
  364. t('demo.observation.irrigationNote'),
  365. t('demo.observation.pestNote'),
  366. t('demo.observation.nutrientNote'),
  367. ];
  368. const observationTypes = [
  369. t('observations.type.scouting'),
  370. t('observations.type.disease'),
  371. t('observations.type.irrigation'),
  372. t('observations.type.pest'),
  373. t('observations.type.nutrients'),
  374. ];
  375. const observationRows = [
  376. {
  377. fieldId: fieldIds[0],
  378. cropId: cropIds[0],
  379. type: t('observations.type.scouting'),
  380. note: t('demo.observation.scoutingNote'),
  381. severity: 2,
  382. observedAt: new Date(now.getTime() - 2 * day).toISOString(),
  383. },
  384. {
  385. fieldId: fieldIds[1],
  386. cropId: cropIds[1],
  387. type: t('observations.type.disease'),
  388. note: t('demo.observation.diseaseNote'),
  389. severity: 5,
  390. observedAt: new Date(now.getTime() - day).toISOString(),
  391. },
  392. {
  393. fieldId: fieldIds[2],
  394. cropId: cropIds[2],
  395. type: t('observations.type.irrigation'),
  396. note: t('demo.observation.irrigationNote'),
  397. severity: null,
  398. observedAt: nowIso,
  399. },
  400. {
  401. fieldId: fieldIds[3],
  402. cropId: cropIds[3],
  403. type: t('observations.type.pest'),
  404. note: t('demo.observation.pestNote'),
  405. severity: 3,
  406. observedAt: new Date(now.getTime() - 3 * day).toISOString(),
  407. },
  408. {
  409. fieldId: fieldIds[4],
  410. cropId: cropIds[4],
  411. type: t('observations.type.nutrients'),
  412. note: t('demo.observation.nutrientNote'),
  413. severity: 4,
  414. observedAt: new Date(now.getTime() - 4 * day).toISOString(),
  415. },
  416. ];
  417. const extraObservationCount = 160;
  418. for (let i = 0; i < extraObservationCount; i += 1) {
  419. observationRows.push({
  420. fieldId: fieldIds[i % fieldIds.length],
  421. cropId: cropIds[i % cropIds.length],
  422. type: observationTypes[i % observationTypes.length],
  423. note: observationNotes[i % observationNotes.length],
  424. severity: (i % 5) + 1,
  425. observedAt: new Date(now.getTime() - (i + 5) * day).toISOString(),
  426. });
  427. }
  428. for (const obs of observationRows) {
  429. if (!obs.fieldId) continue;
  430. const result = await db.runAsync(
  431. 'INSERT INTO observations (field_id, crop_id, obs_type, note, severity, observed_at) VALUES (?, ?, ?, ?, ?, ?);',
  432. obs.fieldId,
  433. obs.cropId ?? null,
  434. obs.type,
  435. obs.note,
  436. obs.severity,
  437. obs.observedAt
  438. );
  439. if (observationImageUri && result.lastInsertRowId) {
  440. await db.runAsync(
  441. 'INSERT INTO images (observation_id, uri, created_at) VALUES (?, ?, ?);',
  442. result.lastInsertRowId,
  443. observationImageUri,
  444. obs.observedAt
  445. );
  446. }
  447. }
  448. const taskCount = await db.getFirstAsync<{ count: number }>(
  449. 'SELECT COUNT(*) as count FROM daily_tasks;'
  450. );
  451. if (!taskCount?.count) {
  452. const defaultTasks = [
  453. { name: t('tasks.default.fieldCheck'), description: t('tasks.default.fieldCheckDesc'), time: '08:00' },
  454. { name: t('tasks.default.scouting'), description: t('tasks.default.scoutingDesc'), time: '10:00' },
  455. { name: t('tasks.default.sensors'), description: t('tasks.default.sensorsDesc'), time: '15:00' },
  456. ];
  457. for (const task of defaultTasks) {
  458. await db.runAsync(
  459. 'INSERT INTO daily_tasks (name, description, default_time, is_active, created_at) VALUES (?, ?, ?, 1, ?);',
  460. task.name,
  461. task.description,
  462. task.time,
  463. nowIso
  464. );
  465. }
  466. }
  467. const taskRows = await db.getAllAsync<{ id: number; name: string }>(
  468. 'SELECT id, name FROM daily_tasks WHERE is_active = 1 ORDER BY id ASC LIMIT 3;'
  469. );
  470. const taskNotes = [t('demo.task.note'), t('demo.task.note2'), t('demo.task.note3')];
  471. let entryIndex = 0;
  472. for (let dayOffset = 0; dayOffset < 120; dayOffset += 1) {
  473. for (let i = 0; i < taskRows.length; i += 1) {
  474. const entryTime = new Date(now.getTime() - (dayOffset + i) * day).toISOString();
  475. await db.runAsync(
  476. 'INSERT INTO daily_task_entries (task_id, field_id, notes, status, completed_at, created_at, meta_json) VALUES (?, ?, ?, ?, ?, ?, ?);',
  477. taskRows[i].id,
  478. fieldIds[0] ?? null,
  479. taskNotes[entryIndex % taskNotes.length],
  480. 'done',
  481. entryTime,
  482. entryTime,
  483. null
  484. );
  485. entryIndex += 1;
  486. }
  487. }
  488. const harvestRows = [
  489. {
  490. fieldId: fieldIds[0],
  491. cropId: cropIds[0],
  492. date: new Date(now.getTime() - 5 * day).toISOString(),
  493. qty: 120,
  494. unit: 'kg',
  495. notes: t('demo.harvest.note1'),
  496. },
  497. {
  498. fieldId: fieldIds[1],
  499. cropId: cropIds[1],
  500. date: new Date(now.getTime() - 3 * day).toISOString(),
  501. qty: 260,
  502. unit: 'kg',
  503. notes: t('demo.harvest.note2'),
  504. },
  505. {
  506. fieldId: fieldIds[2],
  507. cropId: cropIds[2],
  508. date: new Date(now.getTime() - 2 * day).toISOString(),
  509. qty: 40,
  510. unit: 'kg',
  511. notes: t('demo.harvest.note3'),
  512. },
  513. ];
  514. const extraHarvestCount = 100;
  515. for (let i = 0; i < extraHarvestCount; i += 1) {
  516. harvestRows.push({
  517. fieldId: fieldIds[i % fieldIds.length],
  518. cropId: cropIds[i % cropIds.length],
  519. date: new Date(now.getTime() - (7 + i) * day).toISOString(),
  520. qty: 30 + i * 12,
  521. unit: 'kg',
  522. notes: [t('demo.harvest.note1'), t('demo.harvest.note2'), t('demo.harvest.note3')][
  523. i % 3
  524. ],
  525. });
  526. }
  527. const harvestIds: number[] = [];
  528. for (const harvest of harvestRows) {
  529. if (!harvest.fieldId || !harvest.cropId) continue;
  530. const result = await db.runAsync(
  531. 'INSERT INTO harvests (field_id, crop_id, harvested_at, quantity, unit, notes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);',
  532. harvest.fieldId,
  533. harvest.cropId,
  534. harvest.date,
  535. harvest.qty,
  536. harvest.unit,
  537. harvest.notes,
  538. nowIso
  539. );
  540. if (result.lastInsertRowId) harvestIds.push(Number(result.lastInsertRowId));
  541. }
  542. const saleRows = [
  543. {
  544. harvestId: harvestIds[0] ?? null,
  545. fieldId: fieldIds[0],
  546. cropId: cropIds[0],
  547. date: new Date(now.getTime() - 4 * day).toISOString(),
  548. qty: 80,
  549. unit: 'kg',
  550. price: 35,
  551. buyer: t('demo.sale.buyer1'),
  552. notes: t('demo.sale.note1'),
  553. },
  554. {
  555. harvestId: harvestIds[1] ?? null,
  556. fieldId: fieldIds[1],
  557. cropId: cropIds[1],
  558. date: new Date(now.getTime() - 2 * day).toISOString(),
  559. qty: 150,
  560. unit: 'kg',
  561. price: 28,
  562. buyer: t('demo.sale.buyer2'),
  563. notes: t('demo.sale.note2'),
  564. },
  565. {
  566. harvestId: harvestIds[2] ?? null,
  567. fieldId: fieldIds[2],
  568. cropId: cropIds[2],
  569. date: new Date(now.getTime() - day).toISOString(),
  570. qty: 25,
  571. unit: 'kg',
  572. price: 40,
  573. buyer: t('demo.sale.buyer3'),
  574. notes: t('demo.sale.note3'),
  575. },
  576. ];
  577. const extraSaleCount = Math.min(harvestIds.length, 120);
  578. for (let i = 0; i < extraSaleCount; i += 1) {
  579. saleRows.push({
  580. harvestId: harvestIds[i] ?? null,
  581. fieldId: fieldIds[i % fieldIds.length],
  582. cropId: cropIds[i % cropIds.length],
  583. date: new Date(now.getTime() - (3 + i) * day).toISOString(),
  584. qty: 20 + i * 8,
  585. unit: 'kg',
  586. price: 25 + i * 2,
  587. buyer: [t('demo.sale.buyer1'), t('demo.sale.buyer2'), t('demo.sale.buyer3')][i % 3],
  588. notes: [t('demo.sale.note1'), t('demo.sale.note2'), t('demo.sale.note3')][i % 3],
  589. });
  590. }
  591. for (const sale of saleRows) {
  592. if (!sale.fieldId || !sale.cropId) continue;
  593. await db.runAsync(
  594. 'INSERT INTO sales (harvest_id, field_id, crop_id, sold_at, quantity, unit, price, buyer, notes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
  595. sale.harvestId,
  596. sale.fieldId,
  597. sale.cropId,
  598. sale.date,
  599. sale.qty,
  600. sale.unit,
  601. sale.price,
  602. sale.buyer,
  603. sale.notes,
  604. nowIso
  605. );
  606. }
  607. const costRows = [
  608. {
  609. fieldId: fieldIds[0],
  610. cropId: cropIds[0],
  611. category: t('costs.category.seed'),
  612. amount: 1200,
  613. vendor: t('demo.cost.vendor1'),
  614. notes: t('demo.cost.note1'),
  615. date: new Date(now.getTime() - 6 * day).toISOString(),
  616. },
  617. {
  618. fieldId: fieldIds[1],
  619. cropId: cropIds[1],
  620. category: t('costs.category.fertilizer'),
  621. amount: 950,
  622. vendor: t('demo.cost.vendor2'),
  623. notes: t('demo.cost.note2'),
  624. date: new Date(now.getTime() - 4 * day).toISOString(),
  625. },
  626. {
  627. fieldId: fieldIds[2],
  628. cropId: cropIds[2],
  629. category: t('costs.category.labor'),
  630. amount: 600,
  631. vendor: t('demo.cost.vendor3'),
  632. notes: t('demo.cost.note3'),
  633. date: new Date(now.getTime() - 2 * day).toISOString(),
  634. },
  635. ];
  636. const extraCostCount = 140;
  637. const costCategories = [
  638. t('costs.category.seed'),
  639. t('costs.category.fertilizer'),
  640. t('costs.category.labor'),
  641. t('costs.category.fuel'),
  642. t('costs.category.equipment'),
  643. t('costs.category.transport'),
  644. t('costs.category.misc'),
  645. ];
  646. for (let i = 0; i < extraCostCount; i += 1) {
  647. costRows.push({
  648. fieldId: fieldIds[i % fieldIds.length],
  649. cropId: cropIds[i % cropIds.length],
  650. category: costCategories[i % costCategories.length],
  651. amount: 250 + i * 75,
  652. vendor: [t('demo.cost.vendor1'), t('demo.cost.vendor2'), t('demo.cost.vendor3')][i % 3],
  653. notes: [t('demo.cost.note1'), t('demo.cost.note2'), t('demo.cost.note3')][i % 3],
  654. date: new Date(now.getTime() - (8 + i) * day).toISOString(),
  655. });
  656. }
  657. for (const cost of costRows) {
  658. if (!cost.fieldId) continue;
  659. await db.runAsync(
  660. 'INSERT INTO costs (field_id, crop_id, category, amount, currency, vendor, notes, spent_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',
  661. cost.fieldId,
  662. cost.cropId ?? null,
  663. cost.category,
  664. cost.amount,
  665. profile.currency || 'THB',
  666. cost.vendor,
  667. cost.notes,
  668. cost.date,
  669. nowIso
  670. );
  671. }
  672. showSnackbar(t('setup.demoInserted'));
  673. } catch (error) {
  674. showSnackbar(`${t('setup.demoError')} ${String(error)}`);
  675. }
  676. }
  677. async function handleClearDemoData() {
  678. try {
  679. await initCoreTables();
  680. const db = await dbPromise;
  681. demoBackupRef.current = await fetchDemoBackup(db);
  682. await db.execAsync(
  683. [
  684. 'DELETE FROM ml_inferences;',
  685. 'DELETE FROM images;',
  686. 'DELETE FROM observations;',
  687. 'DELETE FROM crops;',
  688. 'DELETE FROM sales;',
  689. 'DELETE FROM harvests;',
  690. 'DELETE FROM costs;',
  691. 'DELETE FROM daily_task_entries;',
  692. 'DELETE FROM daily_tasks;',
  693. 'DELETE FROM fields;',
  694. ].join('\n')
  695. );
  696. showSnackbar(t('setup.demoClearedUndo'));
  697. } catch (error) {
  698. showSnackbar(`${t('setup.demoClearError')} ${String(error)}`);
  699. }
  700. }
  701. async function handlePickPhoto() {
  702. const result = await ImagePicker.launchImageLibraryAsync({
  703. mediaTypes: getImageMediaTypes(),
  704. quality: 1,
  705. });
  706. if (result.canceled) return;
  707. const asset = result.assets[0];
  708. setProfile((prev) => ({ ...prev, photoUri: asset.uri }));
  709. }
  710. async function handleExportData() {
  711. try {
  712. await initCoreTables();
  713. const db = await dbPromise;
  714. const backup = await fetchDemoBackup(db);
  715. const payload = buildCsvExport(backup);
  716. const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  717. const fileUri = `${FileSystem.documentDirectory}smartfarming-export-${timestamp}.csv`;
  718. await FileSystem.writeAsStringAsync(fileUri, payload);
  719. const canShare = await Sharing.isAvailableAsync();
  720. if (canShare) {
  721. await Sharing.shareAsync(fileUri, {
  722. mimeType: 'text/csv',
  723. dialogTitle: t('setup.exportTitle'),
  724. UTI: 'public.comma-separated-values-text',
  725. });
  726. showSnackbar(t('setup.exported'));
  727. } else {
  728. showSnackbar(`${t('setup.exported')} ${fileUri}`);
  729. }
  730. } catch (error) {
  731. showSnackbar(`${t('setup.exportError')} ${String(error)}`);
  732. }
  733. }
  734. function updateLanguage(nextLanguage: 'en' | 'th') {
  735. setLanguage(nextLanguage);
  736. setProfile((prev) => ({ ...prev, language: nextLanguage }));
  737. }
  738. function showSnackbar(message: string) {
  739. setSnackbarMessage(message);
  740. setSnackbarVisible(true);
  741. if (snackbarTimerRef.current) {
  742. clearTimeout(snackbarTimerRef.current);
  743. }
  744. snackbarTimerRef.current = setTimeout(() => {
  745. setSnackbarVisible(false);
  746. demoBackupRef.current = null;
  747. }, 5000);
  748. }
  749. async function handleUndoClear() {
  750. const backup = demoBackupRef.current;
  751. if (!backup) return;
  752. try {
  753. const db = await dbPromise;
  754. await restoreDemoBackup(db, backup);
  755. showSnackbar(t('setup.demoUndoDone'));
  756. } catch (error) {
  757. showSnackbar(`${t('setup.demoUndoError')} ${String(error)}`);
  758. } finally {
  759. demoBackupRef.current = null;
  760. setSnackbarVisible(false);
  761. if (snackbarTimerRef.current) {
  762. clearTimeout(snackbarTimerRef.current);
  763. }
  764. }
  765. }
  766. const inputStyle = [
  767. styles.input,
  768. { borderColor: palette.border, backgroundColor: palette.input, color: palette.text },
  769. ];
  770. return (
  771. <View style={styles.screen}>
  772. <KeyboardAvoidingView
  773. behavior={Platform.OS === 'ios' ? 'padding' : undefined}
  774. keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
  775. style={styles.keyboardAvoid}>
  776. <ParallaxScrollView
  777. headerBackgroundColor={{ light: '#E2E9DF', dark: '#262A24' }}
  778. headerImage={
  779. <Image
  780. source={require('@/assets/images/userprofile.jpg')}
  781. style={styles.headerImage}
  782. contentFit="cover"
  783. />
  784. }>
  785. <ThemedView style={styles.titleContainer}>
  786. <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
  787. {t('setup.title')}
  788. </ThemedText>
  789. </ThemedView>
  790. <ThemedView style={styles.section}>
  791. <ThemedText type="subtitle">{t('setup.profile')}</ThemedText>
  792. {status && status !== t('setup.saved') && status !== t('setup.loaded') ? (
  793. <ThemedText>{status}</ThemedText>
  794. ) : null}
  795. </ThemedView>
  796. <ThemedView style={styles.section}>
  797. <ThemedText>{t('setup.photo')}</ThemedText>
  798. <View style={styles.photoWrap}>
  799. {profile.photoUri ? (
  800. <Image source={{ uri: profile.photoUri }} style={styles.photo} contentFit="cover" />
  801. ) : (
  802. <ThemedText>{t('setup.noPhoto')}</ThemedText>
  803. )}
  804. </View>
  805. <View style={styles.buttonRow}>
  806. <ThemedButton title={t('setup.uploadPhoto')} onPress={handlePickPhoto} />
  807. </View>
  808. </ThemedView>
  809. <ThemedView style={styles.section}>
  810. <ThemedText>{t('setup.name')}</ThemedText>
  811. <TextInput
  812. value={profile.name}
  813. onChangeText={(name) => setProfile((prev) => ({ ...prev, name }))}
  814. placeholder={t('setup.name')}
  815. style={inputStyle}
  816. />
  817. </ThemedView>
  818. <ThemedView style={styles.section}>
  819. <ThemedText>{t('setup.farmName')}</ThemedText>
  820. <TextInput
  821. value={profile.farmName}
  822. onChangeText={(farmName) => setProfile((prev) => ({ ...prev, farmName }))}
  823. placeholder={t('setup.farmName')}
  824. style={inputStyle}
  825. />
  826. </ThemedView>
  827. <ThemedView style={styles.section}>
  828. <ThemedText>{t('setup.location')}</ThemedText>
  829. <TextInput
  830. value={profile.location}
  831. onChangeText={(location) => setProfile((prev) => ({ ...prev, location }))}
  832. placeholder={t('setup.location')}
  833. style={inputStyle}
  834. />
  835. </ThemedView>
  836. <ThemedView style={styles.section}>
  837. <ThemedText>{t('setup.language')}</ThemedText>
  838. <View style={styles.languageRow}>
  839. <ThemedButton
  840. title={t('setup.lang.en')}
  841. onPress={() => updateLanguage('en')}
  842. variant={profile.language === 'en' ? 'primary' : 'secondary'}
  843. />
  844. <ThemedButton
  845. title={t('setup.lang.th')}
  846. onPress={() => updateLanguage('th')}
  847. variant={profile.language === 'th' ? 'primary' : 'secondary'}
  848. />
  849. </View>
  850. </ThemedView>
  851. <ThemedView style={styles.section}>
  852. <ThemedText>{t('setup.currency')}</ThemedText>
  853. <View style={styles.currencyRow}>
  854. {currencyPresets.map((code) => {
  855. const isActive = profile.currency === code;
  856. return (
  857. <Pressable
  858. key={code}
  859. onPress={() => setProfile((prev) => ({ ...prev, currency: code }))}
  860. style={[
  861. styles.currencyChip,
  862. { borderColor: palette.border },
  863. isActive && {
  864. borderColor: palette.success,
  865. backgroundColor: palette.surface,
  866. },
  867. ]}>
  868. <ThemedText style={isActive ? styles.currencyTextActive : styles.currencyText}>
  869. {t(`setup.currency.${code.toLowerCase()}`)}
  870. </ThemedText>
  871. </Pressable>
  872. );
  873. })}
  874. </View>
  875. <TextInput
  876. value={profile.currency}
  877. onChangeText={(currency) => setProfile((prev) => ({ ...prev, currency }))}
  878. placeholder={t('setup.currencyPlaceholder')}
  879. style={inputStyle}
  880. />
  881. </ThemedView>
  882. <View style={styles.section}>
  883. <ThemedText type="subtitle">{t('setup.exportTitle')}</ThemedText>
  884. <ThemedText>{t('setup.exportHint')}</ThemedText>
  885. <View style={styles.buttonRow}>
  886. <ThemedButton title={t('setup.exportButton')} onPress={handleExportData} />
  887. </View>
  888. </View>
  889. <View style={styles.section}>
  890. <ThemedText type="subtitle">{t('setup.demoTitle')}</ThemedText>
  891. <ThemedText>{t('setup.demoHint')}</ThemedText>
  892. <View style={styles.demoRow}>
  893. <ThemedButton title={t('setup.demoButton')} onPress={handleInsertDemoData} />
  894. <ThemedButton
  895. title={t('setup.demoClearButton')}
  896. onPress={handleClearDemoData}
  897. variant="secondary"
  898. />
  899. </View>
  900. </View>
  901. <View style={styles.buttonRow}>
  902. <ThemedButton title={t('setup.save')} onPress={handleSave} />
  903. {saveIndicator ? (
  904. <ThemedText style={styles.saveIndicator}>{saveIndicator}</ThemedText>
  905. ) : null}
  906. </View>
  907. <View style={styles.keyboardSpacer} />
  908. </ParallaxScrollView>
  909. </KeyboardAvoidingView>
  910. {snackbarVisible ? (
  911. <View style={styles.snackbar}>
  912. <ThemedText style={styles.snackbarText}>{snackbarMessage}</ThemedText>
  913. <Pressable style={styles.snackbarAction} onPress={handleUndoClear}>
  914. <ThemedText style={styles.snackbarActionText}>{t('setup.demoUndo')}</ThemedText>
  915. </Pressable>
  916. </View>
  917. ) : null}
  918. </View>
  919. );
  920. }
  921. function getImageMediaTypes() {
  922. const mediaType = (ImagePicker as { MediaType?: { Image?: unknown; Images?: unknown } })
  923. .MediaType;
  924. return mediaType?.Image ?? mediaType?.Images ?? ['images'];
  925. }
  926. function buildCsvExport(backup: DemoBackup) {
  927. const header = 'table,data_json';
  928. const rows: string[] = [header];
  929. const tables: Array<{ name: string; rows: unknown[] }> = [
  930. { name: 'user_profile', rows: backup.user_profile ?? [] },
  931. { name: 'fields', rows: backup.fields },
  932. { name: 'crops', rows: backup.crops },
  933. { name: 'observations', rows: backup.observations },
  934. { name: 'images', rows: backup.images },
  935. { name: 'ml_inferences', rows: backup.ml_inferences },
  936. { name: 'daily_tasks', rows: backup.daily_tasks },
  937. { name: 'daily_task_entries', rows: backup.daily_task_entries },
  938. { name: 'harvests', rows: backup.harvests },
  939. { name: 'sales', rows: backup.sales },
  940. { name: 'costs', rows: backup.costs },
  941. ];
  942. for (const table of tables) {
  943. for (const row of table.rows) {
  944. const json = JSON.stringify(row);
  945. rows.push(`${csvEscape(table.name)},${csvEscape(json)}`);
  946. }
  947. }
  948. return rows.join('\n');
  949. }
  950. function csvEscape(value: string) {
  951. const escaped = value.replace(/"/g, '""');
  952. return `"${escaped}"`;
  953. }
  954. const styles = StyleSheet.create({
  955. screen: {
  956. flex: 1,
  957. },
  958. keyboardAvoid: {
  959. flex: 1,
  960. },
  961. keyboardSpacer: {
  962. height: 80,
  963. },
  964. headerImage: {
  965. width: '100%',
  966. height: '100%',
  967. },
  968. titleContainer: {
  969. flexDirection: 'row',
  970. gap: 8,
  971. },
  972. section: {
  973. gap: 8,
  974. marginBottom: 16,
  975. },
  976. languageRow: {
  977. flexDirection: 'row',
  978. gap: 12,
  979. },
  980. currencyRow: {
  981. flexDirection: 'row',
  982. flexWrap: 'wrap',
  983. gap: 8,
  984. },
  985. currencyChip: {
  986. borderRadius: 999,
  987. borderWidth: 1,
  988. borderColor: '#C6C6C6',
  989. paddingHorizontal: 10,
  990. paddingVertical: 4,
  991. },
  992. currencyChipActive: {
  993. borderColor: '#2F7D4F',
  994. backgroundColor: '#E7F3EA',
  995. },
  996. currencyText: {
  997. fontSize: 12,
  998. },
  999. currencyTextActive: {
  1000. fontSize: 12,
  1001. color: '#2F7D4F',
  1002. fontWeight: '600',
  1003. },
  1004. demoRow: {
  1005. flexDirection: 'row',
  1006. flexWrap: 'wrap',
  1007. gap: 12,
  1008. },
  1009. snackbar: {
  1010. position: 'absolute',
  1011. left: 16,
  1012. right: 16,
  1013. bottom: 24,
  1014. backgroundColor: '#2B2B23',
  1015. borderRadius: 14,
  1016. paddingHorizontal: 16,
  1017. paddingVertical: 12,
  1018. flexDirection: 'row',
  1019. alignItems: 'center',
  1020. gap: 12,
  1021. },
  1022. snackbarText: {
  1023. color: '#FFFFFF',
  1024. flex: 1,
  1025. },
  1026. snackbarAction: {
  1027. paddingHorizontal: 10,
  1028. paddingVertical: 6,
  1029. borderRadius: 999,
  1030. borderWidth: 1,
  1031. borderColor: '#FFFFFF',
  1032. },
  1033. snackbarActionText: {
  1034. color: '#FFFFFF',
  1035. fontWeight: '600',
  1036. fontSize: 12,
  1037. },
  1038. input: {
  1039. borderRadius: 10,
  1040. borderWidth: 1,
  1041. borderColor: '#B9B9B9',
  1042. paddingHorizontal: 12,
  1043. paddingVertical: 10,
  1044. fontSize: 16,
  1045. },
  1046. buttonRow: {
  1047. paddingTop: 4,
  1048. },
  1049. saveIndicator: {
  1050. marginTop: 10,
  1051. alignSelf: 'center',
  1052. backgroundColor: '#E7F3EA',
  1053. borderColor: '#2F7D4F',
  1054. borderWidth: 1,
  1055. borderRadius: 999,
  1056. paddingHorizontal: 12,
  1057. paddingVertical: 6,
  1058. fontSize: 12,
  1059. fontWeight: '600',
  1060. color: '#2F7D4F',
  1061. },
  1062. photo: {
  1063. height: 140,
  1064. width: 140,
  1065. borderRadius: 70,
  1066. },
  1067. photoWrap: {
  1068. alignItems: 'center',
  1069. },
  1070. });
  1071. async function fetchDemoBackup(db: Awaited<typeof dbPromise>): Promise<DemoBackup> {
  1072. const user_profile = await db.getAllAsync<DemoBackup['user_profile'][number]>(
  1073. 'SELECT * FROM user_profile;'
  1074. );
  1075. const fields = await db.getAllAsync<DemoBackup['fields'][number]>('SELECT * FROM fields;');
  1076. const crops = await db.getAllAsync<DemoBackup['crops'][number]>('SELECT * FROM crops;');
  1077. const observations = await db.getAllAsync<DemoBackup['observations'][number]>(
  1078. 'SELECT * FROM observations;'
  1079. );
  1080. const images = await db.getAllAsync<DemoBackup['images'][number]>('SELECT * FROM images;');
  1081. const daily_tasks = await db.getAllAsync<DemoBackup['daily_tasks'][number]>(
  1082. 'SELECT * FROM daily_tasks;'
  1083. );
  1084. const daily_task_entries = await db.getAllAsync<DemoBackup['daily_task_entries'][number]>(
  1085. 'SELECT * FROM daily_task_entries;'
  1086. );
  1087. const ml_inferences = await db.getAllAsync<DemoBackup['ml_inferences'][number]>(
  1088. 'SELECT * FROM ml_inferences;'
  1089. );
  1090. const harvests = await db.getAllAsync<DemoBackup['harvests'][number]>(
  1091. 'SELECT * FROM harvests;'
  1092. );
  1093. const sales = await db.getAllAsync<DemoBackup['sales'][number]>(
  1094. 'SELECT * FROM sales;'
  1095. );
  1096. const costs = await db.getAllAsync<DemoBackup['costs'][number]>(
  1097. 'SELECT * FROM costs;'
  1098. );
  1099. return {
  1100. user_profile,
  1101. fields,
  1102. crops,
  1103. observations,
  1104. images,
  1105. daily_tasks,
  1106. daily_task_entries,
  1107. ml_inferences,
  1108. harvests,
  1109. sales,
  1110. costs,
  1111. };
  1112. }
  1113. async function restoreDemoBackup(db: Awaited<typeof dbPromise>, backup: DemoBackup) {
  1114. for (const field of backup.fields) {
  1115. await db.runAsync(
  1116. 'INSERT INTO fields (id, name, area_ha, boundary_geojson, notes, photo_uri, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
  1117. field.id,
  1118. field.name,
  1119. field.area_ha,
  1120. field.boundary_geojson,
  1121. field.notes,
  1122. field.photo_uri,
  1123. field.created_at,
  1124. field.updated_at
  1125. );
  1126. }
  1127. for (const crop of backup.crops) {
  1128. await db.runAsync(
  1129. 'INSERT INTO crops (id, field_id, crop_name, variety, planting_date, expected_harvest_date, photo_uri) VALUES (?, ?, ?, ?, ?, ?, ?);',
  1130. crop.id,
  1131. crop.field_id,
  1132. crop.crop_name,
  1133. crop.variety,
  1134. crop.planting_date,
  1135. crop.expected_harvest_date,
  1136. crop.photo_uri
  1137. );
  1138. }
  1139. for (const observation of backup.observations) {
  1140. await db.runAsync(
  1141. 'INSERT INTO observations (id, field_id, crop_id, obs_type, note, severity, lat, lng, observed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',
  1142. observation.id,
  1143. observation.field_id,
  1144. observation.crop_id,
  1145. observation.obs_type,
  1146. observation.note,
  1147. observation.severity,
  1148. observation.lat,
  1149. observation.lng,
  1150. observation.observed_at
  1151. );
  1152. }
  1153. for (const image of backup.images) {
  1154. await db.runAsync(
  1155. 'INSERT INTO images (id, observation_id, uri, thumbnail_uri, width, height, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);',
  1156. image.id,
  1157. image.observation_id,
  1158. image.uri,
  1159. image.thumbnail_uri,
  1160. image.width,
  1161. image.height,
  1162. image.created_at
  1163. );
  1164. }
  1165. for (const task of backup.daily_tasks) {
  1166. await db.runAsync(
  1167. 'INSERT INTO daily_tasks (id, name, description, default_time, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?);',
  1168. task.id,
  1169. task.name,
  1170. task.description,
  1171. task.default_time,
  1172. task.is_active,
  1173. task.created_at
  1174. );
  1175. }
  1176. for (const entry of backup.daily_task_entries) {
  1177. await db.runAsync(
  1178. 'INSERT INTO daily_task_entries (id, task_id, field_id, notes, status, completed_at, created_at, meta_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
  1179. entry.id,
  1180. entry.task_id,
  1181. entry.field_id,
  1182. entry.notes,
  1183. entry.status,
  1184. entry.completed_at,
  1185. entry.created_at,
  1186. entry.meta_json
  1187. );
  1188. }
  1189. for (const inference of backup.ml_inferences) {
  1190. await db.runAsync(
  1191. 'INSERT INTO ml_inferences (id, image_id, model_name, model_version, top_label, top_score, scores_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
  1192. inference.id,
  1193. inference.image_id,
  1194. inference.model_name,
  1195. inference.model_version,
  1196. inference.top_label,
  1197. inference.top_score,
  1198. inference.scores_json,
  1199. inference.created_at
  1200. );
  1201. }
  1202. for (const harvest of backup.harvests) {
  1203. await db.runAsync(
  1204. 'INSERT INTO harvests (id, field_id, crop_id, harvested_at, quantity, unit, notes, photo_uri, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',
  1205. harvest.id,
  1206. harvest.field_id,
  1207. harvest.crop_id,
  1208. harvest.harvested_at,
  1209. harvest.quantity,
  1210. harvest.unit,
  1211. harvest.notes,
  1212. harvest.photo_uri,
  1213. harvest.created_at
  1214. );
  1215. }
  1216. for (const sale of backup.sales) {
  1217. await db.runAsync(
  1218. 'INSERT INTO sales (id, harvest_id, field_id, crop_id, sold_at, quantity, unit, price, buyer, notes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
  1219. sale.id,
  1220. sale.harvest_id,
  1221. sale.field_id,
  1222. sale.crop_id,
  1223. sale.sold_at,
  1224. sale.quantity,
  1225. sale.unit,
  1226. sale.price,
  1227. sale.buyer,
  1228. sale.notes,
  1229. sale.created_at
  1230. );
  1231. }
  1232. for (const cost of backup.costs) {
  1233. await db.runAsync(
  1234. 'INSERT INTO costs (id, field_id, crop_id, category, amount, currency, vendor, notes, spent_at, photo_uri, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
  1235. cost.id,
  1236. cost.field_id,
  1237. cost.crop_id,
  1238. cost.category,
  1239. cost.amount,
  1240. cost.currency,
  1241. cost.vendor,
  1242. cost.notes,
  1243. cost.spent_at,
  1244. cost.photo_uri,
  1245. cost.created_at
  1246. );
  1247. }
  1248. }
  1249. async function loadDemoImageUris() {
  1250. const modules = [
  1251. require('@/assets/images/fields.jpg'),
  1252. require('@/assets/images/crops.jpg'),
  1253. require('@/assets/images/observations.jpg'),
  1254. ];
  1255. await Asset.loadAsync(modules);
  1256. const assets = modules.map((mod) => Asset.fromModule(mod));
  1257. return assets.map((asset) => asset.localUri ?? asset.uri ?? '');
  1258. }