From a6ed060ea8a867350591808ae8f3b962ccb4fa74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ugor=20Marcilio=20Brand=C3=A3o=20Costa?= Date: Wed, 28 Aug 2024 21:48:29 -0300 Subject: [PATCH 01/20] feat: edit user offiline --- package-lock.json | 24 +++++ src/app/db/index.ts | 4 +- src/app/db/migrations.ts | 36 ++++++- src/app/db/schema.ts | 28 +++-- src/app/model/Idoso.ts | 20 ++++ src/app/model/User.ts | 9 +- .../private/pages/CadastroIdosoExemplo.tsx | 100 ++++++++++++++++++ src/app/private/pages/editarPerfil.tsx | 86 +++++++++++++-- src/app/private/pages/listarIdosos.tsx | 36 +++++-- src/app/public/login.tsx | 53 +++++++--- 10 files changed, 340 insertions(+), 56 deletions(-) create mode 100644 src/app/model/Idoso.ts create mode 100644 src/app/private/pages/CadastroIdosoExemplo.tsx diff --git a/package-lock.json b/package-lock.json index 906fc018..d348f76c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9152,6 +9152,11 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, + "node_modules/base-64": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", + "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==" + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -19378,6 +19383,25 @@ "resolved": "https://registry.npmjs.org/react-native-dropdown-select-list/-/react-native-dropdown-select-list-2.0.5.tgz", "integrity": "sha512-TepbcagQVUMB6nLuIlVU2ghRpQHAECOeZWe8K04ymW6NqbKbxuczZSDFfdCiABiiQ2dFD+8Dz65y4K7/uUEqGg==" }, + "node_modules/react-native-fs": { + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/react-native-fs/-/react-native-fs-2.20.0.tgz", + "integrity": "sha512-VkTBzs7fIDUiy/XajOSNk0XazFE9l+QlMAce7lGuebZcag5CnjszB+u4BdqzwaQOdcYb5wsJIsqq4kxInIRpJQ==", + "license": "MIT", + "dependencies": { + "base-64": "^0.1.0", + "utf8": "^3.0.0" + }, + "peerDependencies": { + "react-native": "*", + "react-native-windows": "*" + }, + "peerDependenciesMeta": { + "react-native-windows": { + "optional": true + } + } + }, "node_modules/react-native-gesture-handler": { "version": "2.16.2", "resolved": "https://registry.npmjs.org/react-native-gesture-handler/-/react-native-gesture-handler-2.16.2.tgz", diff --git a/src/app/db/index.ts b/src/app/db/index.ts index 48e0935d..eac5dd12 100644 --- a/src/app/db/index.ts +++ b/src/app/db/index.ts @@ -5,13 +5,13 @@ import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite' import schema from './schema' import migrations from './migrations' import User from '../model/User' +import Idoso from '../model/Idoso' // import Post from './model/Post' // ⬅️ You'll import your Models here // First, create the adapter to the underlying database: const adapter = new SQLiteAdapter({ schema, // (You might want to comment it out for development purposes -- see Migrations documentation) - migrations, // (optional database name or file system path) // dbName: 'myapp', // (recommended option, should work flawlessly out of the box on iOS. On Android, @@ -28,7 +28,7 @@ const database = new Database({ adapter, modelClasses: [ // Post, // ⬅️ You'll add Models to Watermelon here - User + User, Idoso ], }); diff --git a/src/app/db/migrations.ts b/src/app/db/migrations.ts index edd8b7bb..4228bd1b 100644 --- a/src/app/db/migrations.ts +++ b/src/app/db/migrations.ts @@ -1,7 +1,37 @@ -import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations' +import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations'; +import { tableSchema } from '@nozbe/watermelondb'; +// Define a migração para a versão 2 do banco de dados export default schemaMigrations({ migrations: [ - // We'll add migration definitions here later + { + toVersion: 2, + steps: [ + // Passo para adicionar as colunas à tabela 'users' se elas ainda não existirem + { + type: 'add_columns', + table: 'users', + columns: [ + { name: 'created_at', type: 'number' }, + { name: 'updated_at', type: 'number' }, + ], + }, + // Passo para criar a tabela 'idoso' se ela ainda não existir + { + type: 'create_table', + schema: tableSchema({ + name: 'idoso', + columns: [ + { name: 'nome', type: 'string' }, + { name: 'dataNascimento', type: 'string' }, + { name: 'tipoSanguineo', type: 'string' }, + { name: 'telefoneResponsavel', type: 'string' }, + { name: 'descricao', type: 'string', isOptional: true }, + { name: 'user_id', type: 'string', isIndexed: true }, + ], + }), + }, + ], + }, ], -}) \ No newline at end of file +}); diff --git a/src/app/db/schema.ts b/src/app/db/schema.ts index 3b702c61..23490e1f 100644 --- a/src/app/db/schema.ts +++ b/src/app/db/schema.ts @@ -1,9 +1,8 @@ -import { appSchema, tableSchema } from '@nozbe/watermelondb' +import { appSchema, tableSchema } from '@nozbe/watermelondb'; export default appSchema({ - version: 1, + version: 3, tables: [ - // We'll add tableSchemas here later tableSchema({ name: 'users', columns: [ @@ -11,11 +10,22 @@ export default appSchema({ { name: 'name', type: 'string' }, { name: 'email', type: 'string' }, { name: 'photo', type: 'string' }, - { name: 'admin', type: 'boolean'}, + { name: 'admin', type: 'boolean' }, { name: 'password', type: 'string' }, { name: 'created_at', type: 'number' }, - { name: 'updated_at', type: 'number' } - ] - }) - ] -}) \ No newline at end of file + { name: 'updated_at', type: 'number' }, + ], + }), + tableSchema({ + name: 'idoso', + columns: [ + { name: 'nome', type: 'string' }, + { name: 'dataNascimento', type: 'string' }, + { name: 'tipoSanguineo', type: 'string' }, + { name: 'telefoneResponsavel', type: 'string' }, + { name: 'descricao', type: 'string' }, + { name: 'user_id', type: 'string', isIndexed: true }, + ], + }), + ], +}); diff --git a/src/app/model/Idoso.ts b/src/app/model/Idoso.ts new file mode 100644 index 00000000..d8bc8028 --- /dev/null +++ b/src/app/model/Idoso.ts @@ -0,0 +1,20 @@ +import { Model } from '@nozbe/watermelondb'; +import { text, field, readonly, relation, date } from '@nozbe/watermelondb/decorators'; +import User from './User'; + +export default class Idoso extends Model { + static table = 'idoso'; + + @text('nome') nome!: string; + @text('dataNascimento') dataNascimento!: string; + @field('tipoSanguineo') tipoSanguineo!: string; + @text('telefoneResponsavel') telefoneResponsavel!: string; + @text('descricao') descricao!: string; + + @field('user_id') userId!: string; + + @relation('users', 'user_id') user!: User; + + @readonly @date('created_at') createdAt!: Date; + @readonly @date('updated_at') updatedAt!: Date; +} diff --git a/src/app/model/User.ts b/src/app/model/User.ts index a44c8f80..11945f5c 100644 --- a/src/app/model/User.ts +++ b/src/app/model/User.ts @@ -1,11 +1,10 @@ -// model/Post.js import { Model } from '@nozbe/watermelondb'; -import { text, field, date, readonly } from '@nozbe/watermelondb/decorators'; +import { text, field, date, readonly, children } from '@nozbe/watermelondb/decorators'; +import Idoso from './Idoso'; export default class User extends Model { static table = 'users'; - // ID coming from the API @text('external_id') externalId!: string; @text('name') name!: string; @text('email') email!: string; @@ -14,4 +13,6 @@ export default class User extends Model { @text('password') password!: string; @readonly @date('created_at') createdAt!: Date; @readonly @date('updated_at') updatedAt!: Date; -} \ No newline at end of file + + @children('idoso') idosos!: Idoso[]; +} diff --git a/src/app/private/pages/CadastroIdosoExemplo.tsx b/src/app/private/pages/CadastroIdosoExemplo.tsx new file mode 100644 index 00000000..35f4a959 --- /dev/null +++ b/src/app/private/pages/CadastroIdosoExemplo.tsx @@ -0,0 +1,100 @@ +import AsyncStorage from "@react-native-async-storage/async-storage"; +import React, { useEffect, useState } from "react"; +import { Image, StyleSheet, Text, View, Button, ToastAndroid } from "react-native"; +import { ScrollView } from "react-native"; +import database from "../../db"; +import Idoso from "../../model/Idoso"; +import { ETipoSanguineo } from "../../interfaces/idoso.interface"; +import { Collection } from "@nozbe/watermelondb"; +import { useRouter } from "expo-router"; +import { IUser } from "../../interfaces/user.interface"; + + +export default function InsertIdoso() { + const [idUsuario, setIdUsuario] = useState(null); + const router = useRouter(); + + useEffect(() => { + const getIdUsuario = async () => { + try { + const response = await AsyncStorage.getItem("usuario"); + if (response) { + const usuario = JSON.parse(response) as IUser; + setIdUsuario(usuario.id); + console.log("Usuário logado:", usuario); + } else { + console.log("Usuário não encontrado no AsyncStorage."); + } + } catch (error) { + console.error("Erro ao obter usuário:", error); + } + }; + + getIdUsuario(); + }, []); + + const handleInsertIdoso = async () => { + if (!idUsuario) { + ToastAndroid.show("Usuário não encontrado.", ToastAndroid.SHORT); + return; + } + + try { + await database.write(async () => { + const idosoCollection = database.get('idoso') as Collection; + + await idosoCollection.create((idoso) => { + idoso.nome = 'João da Silva'; + idoso.dataNascimento = new Date('1945-07-15').toISOString(); + idoso.telefoneResponsavel = '987654321'; + idoso.descricao = 'Idoso exemplo para testes.'; + idoso.tipoSanguineo = ETipoSanguineo.O_POSITIVO; + idoso.userId = idUsuario.toString(); + }); + }); + + ToastAndroid.show("Idoso inserido com sucesso!", ToastAndroid.SHORT); + router.push("/private/pages/listarIdosos"); + } catch (error) { + console.error("Erro ao inserir o idoso:", error); + ToastAndroid.show("Erro ao inserir o idoso.", ToastAndroid.SHORT); + } + }; + + return ( + + + + + + Inserir Idoso de Exemplo +