diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/__tests__/navigation-test.tsx | 32 | ||||
| -rw-r--r-- | src/app/GuardarPersona.tsx | 34 | ||||
| -rw-r--r-- | src/app/GuardarProducto.tsx | 61 | ||||
| -rw-r--r-- | src/app/_layout.tsx | 58 | ||||
| -rw-r--r-- | src/app/index.tsx | 39 | ||||
| -rw-r--r-- | src/context/AppContextProvider.tsx | 39 | ||||
| -rw-r--r-- | src/db/schema.ts | 43 | ||||
| -rw-r--r-- | src/images/android-icon-background.png | bin | 0 -> 17549 bytes | |||
| -rw-r--r-- | src/images/android-icon-foreground.png | bin | 0 -> 78796 bytes | |||
| -rw-r--r-- | src/images/android-icon-monochrome.png | bin | 0 -> 4140 bytes | |||
| -rw-r--r-- | src/images/favicon.png | bin | 0 -> 1129 bytes | |||
| -rw-r--r-- | src/images/icon.png | bin | 0 -> 393493 bytes | |||
| -rw-r--r-- | src/images/partial-react-logo.png | bin | 0 -> 5075 bytes | |||
| -rw-r--r-- | src/images/react-logo.png | bin | 0 -> 6341 bytes | |||
| -rw-r--r-- | src/images/react-logo@2x.png | bin | 0 -> 14225 bytes | |||
| -rw-r--r-- | src/images/react-logo@3x.png | bin | 0 -> 21252 bytes | |||
| -rw-r--r-- | src/images/splash-icon.png | bin | 0 -> 17547 bytes |
17 files changed, 306 insertions, 0 deletions
diff --git a/src/__tests__/navigation-test.tsx b/src/__tests__/navigation-test.tsx new file mode 100644 index 0000000..4123ab7 --- /dev/null +++ b/src/__tests__/navigation-test.tsx @@ -0,0 +1,32 @@ +import { renderRouter, screen, fireEvent } from 'expo-router/testing-library'; +import React from "react"; +import { Text } from "react-native"; + +/** + * Mock mínimo de las rutas reales + * No renderiza toda la app, solo lo necesario + */ +describe("Navegación index → crearUsuario", () => { + it("navega a la pantalla Crear Usuario al pulsar el botón", async () => { + renderRouter( + { + index: require("../app/index").default, + crearUsuario: require("../app/crearUsuario").default, + }, + { + initialUrl: "/", + } + ); + + // Estamos en index + expect(screen.getByText("crear usuario")).toBeTruthy(); + + // Pulsamos el botón + fireEvent.press(screen.getByTestId("btn-crear-usuario")); + + // Ahora debe renderizarse crearUsuario + expect( + await screen.findByText("Crear Usuario") + ).toBeTruthy(); + }); +}); diff --git a/src/app/GuardarPersona.tsx b/src/app/GuardarPersona.tsx new file mode 100644 index 0000000..58b1d2d --- /dev/null +++ b/src/app/GuardarPersona.tsx @@ -0,0 +1,34 @@ +import { StyleSheet, Text, View, Button} from 'react-native' +import React from 'react' +import { useSQLiteContext } from 'expo-sqlite'; +import { drizzle, useLiveQuery } from 'drizzle-orm/expo-sqlite'; +import { personas } from '../db/schema'; +import { SafeAreaView } from 'react-native-safe-area-context'; + + +const GuardarPersona = () => { + const db = useSQLiteContext(); + const drizzleDb = drizzle(db, { schema: { personas } }); + const { data: lista } = useLiveQuery(drizzleDb.select().from(personas)); + async function almacenarPersona(){ + let edadAleatoria = Math.trunc(Math.random()*100); + let nombreAleatorio = "persona_"+Math.trunc(Math.random()*10000); + await drizzleDb.insert(personas).values({ nombre: nombreAleatorio, edad: edadAleatoria }); + } + + return ( + <SafeAreaView style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}> + <Text style={{fontSize: 24, fontWeight: 'bold', marginBottom: 20 }}>Guardar Persona</Text> + <Button title='Guardar Persona' onPress={almacenarPersona} /> + <View style={{marginTop:20, flex: 1}}> + <Text>Lista de personas guardadas:</Text> + {lista?.map((p)=><Text key={p.id}>{p.id} - {p.nombre} - {p.edad} años</Text>)} + </View> + + </SafeAreaView> + ) +} + +export default GuardarPersona + +const styles = StyleSheet.create({})
\ No newline at end of file diff --git a/src/app/GuardarProducto.tsx b/src/app/GuardarProducto.tsx new file mode 100644 index 0000000..abdd8c1 --- /dev/null +++ b/src/app/GuardarProducto.tsx @@ -0,0 +1,61 @@ +import { StyleSheet, Text, View, Button, Alert} from 'react-native' +import React from 'react' +import { useSQLiteContext } from 'expo-sqlite'; +import { drizzle, useLiveQuery } from 'drizzle-orm/expo-sqlite'; +//import { personas, categorias, productos } from '../db/schema'; +import { SafeAreaView } from 'react-native-safe-area-context'; + + +const GuardarProducto = () => { + const db = useSQLiteContext(); + + /* + const drizzleDb = drizzle(db, { schema: { personas } }); + const { data: listaCategorias } = useLiveQuery(drizzleDb.select().from(categorias)); + const { data: listaProductos } = useLiveQuery(drizzleDb.select().from(productos)); + + async function almacenarCategoria(){ + let edadAleatoria = Math.trunc(Math.random()*100); + let nombreAleatorio = "categoria_"+Math.trunc(Math.random()*10000); + await drizzleDb.insert(categorias).values({ nombre: nombreAleatorio }); + } + + async function almacenarProducto(){ + let edadAleatoria = Math.trunc(Math.random()*100); + let nombreAleatorio = "producto_"+Math.trunc(Math.random()*10000); + let precioAleatorio = (Math.trunc(Math.random()*10000) ) / 100 + if( listaCategorias.length <= 0 ){ + Alert.alert("No hay categorías aún. No se guarda producto"); + return; + } + let posCategoria = Math.trunc(Math.random()*listaCategorias.length); + let idCategoria = listaCategorias[posCategoria].id; + + await drizzleDb.insert(productos).values({ nombre: nombreAleatorio, precio: precioAleatorio, categoriaId: idCategoria }); + } + */ + return ( + <SafeAreaView style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}> + + + + {/* + <Text style={{fontSize: 24, fontWeight: 'bold', marginBottom: 20 }}>Guardar Categoría</Text> + <Button title='Guardar Categoria' onPress={almacenarCategoria} /> + <View style={{marginTop:20, flex: 1}}> + <Text>Lista de categorias guardadas:</Text> + {listaCategorias?.map((p)=><Text key={p.id}>{JSON.stringify(p)} </Text>)} + </View> + <Button title='Guardar Producto' onPress={almacenarProducto} /> + <View style={{marginTop:20, flex: 1}}> + <Text>Lista de productos guardadas:</Text> + {listaProductos?.map((p)=><Text key={p.id}>{JSON.stringify(p)}</Text>)} + </View> + */} + </SafeAreaView> + ) +} + +export default GuardarProducto + +const styles = StyleSheet.create({})
\ No newline at end of file diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx new file mode 100644 index 0000000..e2eb936 --- /dev/null +++ b/src/app/_layout.tsx @@ -0,0 +1,58 @@ +import { Slot, Stack } from "expo-router"; +import React, { Suspense } from 'react' +import AppContextProvider from "../context/AppContextProvider"; +import { ActivityIndicator, Text, View } from "react-native"; +import { openDatabaseSync, SQLiteProvider } from "expo-sqlite"; +import { drizzle } from "drizzle-orm/expo-sqlite"; +import { sql } from 'drizzle-orm'; +import { migrate, useMigrations } from "drizzle-orm/expo-sqlite/migrator"; +import migrations from "../../drizzle/migrations"; +type Props = {} +export const DATABASE_NAME = 'prueba3Drizzle'; +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +function LoadingScreen() { + return ( + <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> + <ActivityIndicator size="large" color="#0000ff" /> + <Text >Cargando la app...</Text> + </View> + ); +} +const RootLayout = (props: Props) => { + return ( + <AppContextProvider> + <Suspense fallback={<LoadingScreen />}> + <SQLiteProvider + databaseName={DATABASE_NAME} + options={{ enableChangeListener: true }} + useSuspense + onInit={async (database) => { + try { + console.log("Simulando carga lenta..."); + await sleep(2000); // 2 segundos retraso + const db = drizzle(database); + await migrate(db, migrations); + console.log("Migration success"); + + // Activa FK aquí (después de migraciones) + await db.run(sql`PRAGMA foreign_keys = ON`); + console.log("Foreign keys enabled"); + + } catch (error) { + console.error("Migration error", error); + } + }} + > + <Stack + screenOptions={{ headerShown: false }} + + /> + + </SQLiteProvider> + </Suspense> + </AppContextProvider> + + ) +} + +export default RootLayout;
\ No newline at end of file diff --git a/src/app/index.tsx b/src/app/index.tsx new file mode 100644 index 0000000..cf5f7c1 --- /dev/null +++ b/src/app/index.tsx @@ -0,0 +1,39 @@ +import { router } from "expo-router"; +import { Button, Text, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + +export default function Index() { + + + function navegarGuardarPersona(){ + console.log("ir a pantalla") + router.push({ + pathname: "/GuardarPersona", + //params: + }) + } + + + function navegarGuardarProducto(){ + console.log("ir a pantalla") + router.push({ + pathname: "/GuardarProducto", + //params: + }) + } + return ( + <SafeAreaView + style={{ + flex: 1, + justifyContent: "center", + alignItems: "center", + }} + > + + <Button title="crear usuario " testID="btn-crear-usuario" color={"green"} onPress={()=> navegarGuardarPersona()} /> + {/* + <Button title="crear categorias y productos " testID="btn-crear-categoria-producto" color={"blue"} onPress={()=> navegarGuardarProducto()} /> + */} + </SafeAreaView> + ); +} diff --git a/src/context/AppContextProvider.tsx b/src/context/AppContextProvider.tsx new file mode 100644 index 0000000..75ece38 --- /dev/null +++ b/src/context/AppContextProvider.tsx @@ -0,0 +1,39 @@ +import React, { Dispatch, SetStateAction, createContext, useContext, useState } from 'react'; + +export type Usuario={ + id: string, + nick: string, + rol?: string +} + +export interface AppContextType{ + + listaUsuarios: Usuario[], + + setListaUsuarios: Dispatch<SetStateAction<Usuario[]>> +} + +export const AppContext = createContext<AppContextType>({} as AppContextType); + +const AppContextProvider = (props: any) => { + const [listaUsuarios, setListaUsuarios] = useState<Usuario[]>([]); + + + const contextValues: AppContextType = { + + listaUsuarios: listaUsuarios, + + setListaUsuarios: setListaUsuarios + } + return ( + <AppContext.Provider value={contextValues}> + {props.children} + </AppContext.Provider> + ) +} + +export const useAppContext = () =>{ + return useContext(AppContext); +} + +export default AppContextProvider
\ No newline at end of file diff --git a/src/db/schema.ts b/src/db/schema.ts new file mode 100644 index 0000000..322d78d --- /dev/null +++ b/src/db/schema.ts @@ -0,0 +1,43 @@ +; +import { relations } from 'drizzle-orm'; +import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core'; +export const personas = sqliteTable('personas', { + id: integer('id').primaryKey({ autoIncrement: true }), + nombre: text('nombre').notNull(), + edad: integer('edad'), +}); + + + + +/* +export const categorias = sqliteTable('categorias', { + id: integer('id').primaryKey({ autoIncrement: true }), + nombre: text('nombre').unique().notNull(), + + +}); + + +export const productos = sqliteTable('productos', { + id: integer('id').primaryKey({ autoIncrement: true }), + nombre: text('nombre').unique().notNull(), + stock: integer('stock'), + precio: real('precio'), + categoriaId: integer('categoria_id').references(() => categorias.id), +}); + + + +export const categoriasRelations = relations(categorias, ({ many }) => ({ + productos: many(productos), +})); + +export const productosRelations = relations(productos, ({ one }) => ({ + pais: one(categorias, { + fields: [productos.categoriaId], + references: [categorias.id], + }), +})); + +*/
\ No newline at end of file diff --git a/src/images/android-icon-background.png b/src/images/android-icon-background.png Binary files differnew file mode 100644 index 0000000..5ffefc5 --- /dev/null +++ b/src/images/android-icon-background.png diff --git a/src/images/android-icon-foreground.png b/src/images/android-icon-foreground.png Binary files differnew file mode 100644 index 0000000..3a9e501 --- /dev/null +++ b/src/images/android-icon-foreground.png diff --git a/src/images/android-icon-monochrome.png b/src/images/android-icon-monochrome.png Binary files differnew file mode 100644 index 0000000..77484eb --- /dev/null +++ b/src/images/android-icon-monochrome.png diff --git a/src/images/favicon.png b/src/images/favicon.png Binary files differnew file mode 100644 index 0000000..408bd74 --- /dev/null +++ b/src/images/favicon.png diff --git a/src/images/icon.png b/src/images/icon.png Binary files differnew file mode 100644 index 0000000..7165a53 --- /dev/null +++ b/src/images/icon.png diff --git a/src/images/partial-react-logo.png b/src/images/partial-react-logo.png Binary files differnew file mode 100644 index 0000000..66fd957 --- /dev/null +++ b/src/images/partial-react-logo.png diff --git a/src/images/react-logo.png b/src/images/react-logo.png Binary files differnew file mode 100644 index 0000000..9d72a9f --- /dev/null +++ b/src/images/react-logo.png diff --git a/src/images/react-logo@2x.png b/src/images/react-logo@2x.png Binary files differnew file mode 100644 index 0000000..2229b13 --- /dev/null +++ b/src/images/react-logo@2x.png diff --git a/src/images/react-logo@3x.png b/src/images/react-logo@3x.png Binary files differnew file mode 100644 index 0000000..a99b203 --- /dev/null +++ b/src/images/react-logo@3x.png diff --git a/src/images/splash-icon.png b/src/images/splash-icon.png Binary files differnew file mode 100644 index 0000000..03d6f6b --- /dev/null +++ b/src/images/splash-icon.png |