avances con listado

master
Freddy Heredia 2 years ago
parent d220d4b2fd
commit 477d589aac

@ -0,0 +1,37 @@
import { FC, useContext } from 'react'
import { FlatList, ScrollView, Text, View } from 'react-native'
import { SalesOrderContext } from '../screens/salesorder/SalesOrderContex';
interface Props {
//control: any,
//fields: any
}
const OneToMany: FC<Props> = ({}) => {
const { lines } = useContext(SalesOrderContext);
console.log("Lineas: "+JSON.stringify(lines))
return (
<ScrollView style={{flex: 1}}>
<FlatList
style={{flex: 1}}
contentContainerStyle={{ paddingBottom: 20 }}
data={lines}
extraData={lines}
renderItem={({ item }) =>
<View className='flex-1 items-center bg-red-200'>
<>
<Text className='text-xl text-center my-4'>{item.producto.nombre}</Text>
</>
</View>
}
keyExtractor={(item: SalesOrderLine) => String(item.producto.id)}
/>
{lines.map((line: SalesOrderLine) =>(<Text key={line.producto.id}>{line.producto.id}</Text>))}
</ScrollView>
)
}
export default OneToMany

@ -0,0 +1,4 @@
interface Product {
id: number;
nombre: string;
}

@ -0,0 +1,69 @@
import React, { FC, useContext, useEffect, useState } from 'react'
import { FlatList, RefreshControl, Text, TouchableOpacity, View } from 'react-native'
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { Avatar, Layout } from '@ui-kitten/components';
import { CardItem } from '../../components/CardItem';
import { SalesOrderContext } from './SalesOrderContex';
interface Props {
entities: [],
screenName: string,
columnDisplay: string
}
export const ProductItem: FC<Props> = ({ entities, screenName, columnDisplay }) => {
const navigation = useNavigation<NativeStackNavigationProp<any>>();
const {lines, setLines, add} = useContext(SalesOrderContext);
return (
<>
<FlatList
data={entities}
renderItem={({ item }) =>
<TouchableOpacity
onPress={() => {
// Pass and merge params back to home screen
const newLine: SalesOrderLine = {
producto: { id: item['id'], nombre: item["nombre"] },
cantidad: 1,
precio: 0
}
add(newLine)
navigation.navigate(
{
name: screenName,
params: { productId: item['id'] },
merge: true,
} as never
);
}}
>
<CardItem>
<View className='flex-row'>
<Avatar
size='giant'
source={{ uri: 'https://images.philips.com/is/image/PhilipsConsumer/271V8_69-IMS-en_HK?$jpglarge$&wid=1250' }}
/>
<Text className='mx-4'>
{item[columnDisplay]}
</Text>
</View>
</CardItem>
</TouchableOpacity>
}
keyExtractor={item => item["id"]}
/>
</>
)
}

@ -6,6 +6,7 @@ import { CardList } from '../../components/cardList/CardList'
import { Button } from '../../components/Button' import { Button } from '../../components/Button'
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth' import { useFetchWithAuth } from '../../hooks/useFetchWithAuth'
import { ProductCardList } from '../../components/cardList/ProductCardList'; import { ProductCardList } from '../../components/cardList/ProductCardList';
import { ProductItem } from './ProductItem';
export const ProductList = () => { export const ProductList = () => {
@ -64,7 +65,7 @@ export const ProductList = () => {
<View id={item} className='flex-1 items-center'> <View id={item} className='flex-1 items-center'>
<Card> <Card>
<Text className='text-xl text-center my-4'>Listado de Produtos</Text> <Text className='text-xl text-center my-4'>Listado de Produtos</Text>
<ProductCardList screenName="ProductFormScreen" columnDisplay="nombre" entities={entities} /> <ProductItem screenName="SalesOrderFormScreen" columnDisplay="nombre" entities={entities} />
</Card> </Card>
</View> </View>
} }

@ -0,0 +1,8 @@
interface SalesOrder {
id: number;
numero: string;
cliente: {
id: number;
};
detalle: SalesOrderLine[];
}

@ -0,0 +1,37 @@
import React, { createContext, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
type SalesOrderContextProps = {
lines: SalesOrderLine[],
add: (newLine:SalesOrderLine)=>void,
remove: (productId: number)=>void,
setLines: (lines: SalesOrderLine[])=>void
}
export const SalesOrderContext = createContext({} as SalesOrderContextProps);
export const SalesOrderProvider = ({ children }: {children: JSX.Element | JSX.Element[]})=> {
const [lines, setLines] = useState<SalesOrderLine[]>([]);
const add = (newLine:SalesOrderLine) => {
setLines([...lines,newLine]);
}
const remove = (productId:number) => {
setLines(lines.filter(line => line.producto.id === productId));
}
return (
<SalesOrderContext.Provider value={{
lines,
add,
remove,
setLines
}}>
{ children }
</SalesOrderContext.Provider>
)
}

@ -1,34 +1,60 @@
import { useEffect } from 'react' import { useContext, useEffect, useState } from 'react'
import { Text } from 'react-native' import { FlatList, Text, View } from 'react-native'
import { Background } from '../../components/Background'
import { Button } from '../../components/Button'; import { Button } from '../../components/Button';
import { Card } from '../../components/Card'; import { Card } from '../../components/Card';
import { Input } from '../../components/Input'; import { Input } from '../../components/Input';
import { useForm } from 'react-hook-form'; import { useForm, useFieldArray } from 'react-hook-form';
import { NativeStackScreenProps } from '@react-navigation/native-stack'; import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth'; import { useFetchWithAuth } from '../../hooks/useFetchWithAuth';
import { saveWithAuth } from '../../hooks/saveWithAuth'; import { saveWithAuth } from '../../hooks/saveWithAuth';
import { ManyToOne } from '../../components/ManyToOne'; import { ManyToOne } from '../../components/ManyToOne';
import { RootStackParams } from './SalesOrderStack'; import { RootStackParams } from './SalesOrderStack';
import OneToMany from '../../components/OneToMany';
import { SalesOrderContext } from './SalesOrderContex';
interface Props extends NativeStackScreenProps<RootStackParams, 'SalesOrderFormScreen'> { }; interface Props extends NativeStackScreenProps<RootStackParams, 'SalesOrderFormScreen'> { };
export const SalesOrderFormScreen = ({ route, navigation }: Props) => { export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
console.log("Apertura de screem :" + route.params?.productId)
const {lines, setLines, add} = useContext(SalesOrderContext);
const { control, handleSubmit, setValue, formState: { errors } } = useForm({ const { control, handleSubmit, setValue, getValues, formState: { errors } } = useForm({
defaultValues: { defaultValues: {
id: 0, id: 0,
numero: '', numero: '',
cliente: { id: 0 }, cliente: { id: 0 }
detalle: []
} }
}); });
let id: string = "0"; let id: string = "0";
if (route.params?.id != undefined) { if (route.params?.id != undefined) {
id = String(route.params.id); id = String(route.params.id);
} }
useEffect(() => {
if (route.params?.productId != undefined && route.params?.productId > 0) {
const newId = route.params?.productId;
const exits = lines.filter(line => line.producto.id == newId)
if (exits.length == 0) {
const newLine: SalesOrderLine = {
producto: { id: newId, nombre: "test" },
cantidad: 1,
precio: 0
}
console.log("Nueva linea :" + route.params?.productId)
//append(newLine);
add(newLine);
//setValue("detalle", lines);
//console.table(fields)
}else{
console.log("Linea repetida");
console.log(exits)
}
}
}, [route.params?.productId]);
const getInitData = async () => { const getInitData = async () => {
if (!id || id == "0") if (!id || id == "0")
return; return;
@ -40,7 +66,9 @@ export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
setValue("id", data['id']) setValue("id", data['id'])
setValue("numero", data['numero']) setValue("numero", data['numero'])
setValue("cliente", data['cliente']) setValue("cliente", data['cliente'])
setValue("detalle", data['detalle']) const lines: SalesOrderLine[] = data['detalle'];
console.log("Agregando lineas:")
setLines(lines);
} }
} else { } else {
@ -57,8 +85,6 @@ export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
try { try {
let endpoint = "pedido"; let endpoint = "pedido";
entity['cliente'] = { id: entity['cliente'].id } entity['cliente'] = { id: entity['cliente'].id }
console.log("Entidad:")
console.log(entity)
const { data, error } = await saveWithAuth(endpoint, id, entity); const { data, error } = await saveWithAuth(endpoint, id, entity);
if (error) { if (error) {
console.log(error); console.log(error);
@ -73,21 +99,30 @@ export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
return ( return (
<> <>
<Background > <FlatList
<Card>
<Text className='text-xl text-center my-4'>Registro de Pedido</Text> data={[""]}
<Input name="numero" label='Número' control={control} /> renderItem={({ item }) =>
<ManyToOne entity='cliente' columname='cliente' columnvalue="nombre" control={control} /> <>
<Button <Card>
title='Agrega produtos' <Text className='text-xl text-center my-4'>Registro de Pedido</Text>
additionalStyle='mb-4' <Input name="numero" label='Número' control={control} />
onPress={() => navigation.navigate("ProductListScreen" as never)} /> <ManyToOne entity='cliente' columname='cliente' columnvalue="nombre" control={control} />
<Button <OneToMany />
title='Guardar' <Button
onPress={handleSubmit(onSubmit)} title='Agrega produtos'
/> additionalStyle='mb-4'
</Card> onPress={() => navigation.navigate("ProductList" as never)} />
</Background> <Button
title='Guardar'
onPress={handleSubmit(onSubmit)}
/>
</Card>
</>
}
keyExtractor={item2 => item2}
/>
</> </>
) )
} }

@ -0,0 +1,6 @@
interface SalesOrderLine {
id?: number
producto: Product,
cantidad: number,
precio: number
}

@ -15,49 +15,49 @@ export const SalesOrderListScreen = () => {
const [entities, setEntities] = useState(defaultData); const [entities, setEntities] = useState(defaultData);
const getInitData = async () => { const getInitData = async () => {
const { data, error } = await useFetchWithAuth(endpoints); const { data, error } = await useFetchWithAuth(endpoints);
if (!error) { if (!error) {
setEntities(data); setEntities(data);
} else { } else {
console.log(error) console.log(error)
} }
} }
useEffect(() => { useEffect(() => {
getInitData(); getInitData();
}, [refreshing]) }, [refreshing])
const onRefresh = () => { const onRefresh = () => {
setRefreshing(true); setRefreshing(true);
setTimeout(() => { setTimeout(() => {
setRefreshing(false); setRefreshing(false);
}, 1000); }, 1000);
}; };
return ( return (
<View className='bg-sky-100'> <View className='bg-sky-100'>
<Button <Button
title=' + ' title=' + '
additionalStyle='z-10 absolute bottom-2 right-0' additionalStyle='z-10 absolute bottom-2 right-0'
onPress={() => navigation.navigate("SalesOrderFormScreen" as never)} /> onPress={() => navigation.navigate("SalesOrderFormScreen" as never)} />
<FlatList <FlatList
refreshControl={ refreshControl={
<RefreshControl <RefreshControl
refreshing={refreshing} refreshing={refreshing}
onRefresh={onRefresh} onRefresh={onRefresh}
/>
}
data={[""]}
renderItem={({ item }) =>
<View id={item} className='flex-1 items-center'>
<Card>
<Text className='text-xl text-center my-4'>Listado de pedidos</Text>
<CardList screenName="SalesOrderFormScreen" columnDisplay="numero" entities={entities} />
</Card>
</View>
}
keyExtractor={item => item}
/> />
} </View>
data={[""]}
renderItem={({ item }) =>
<View id={item} className='flex-1 items-center'>
<Card>
<Text className='text-xl text-center my-4'>Listado de pedidos</Text>
<CardList screenName="SalesOrderFormScreen" columnDisplay="numero" entities={entities} />
</Card>
</View>
}
keyExtractor={item => item}
/>
</View>
) )
} }

@ -4,10 +4,11 @@ import { AuthContext } from '../login/AuthContext';
import { SalesOrderFormScreen } from './SalesOrderFormScreen'; import { SalesOrderFormScreen } from './SalesOrderFormScreen';
import { SalesOrderListScreen } from './SalesOrderListScreen'; import { SalesOrderListScreen } from './SalesOrderListScreen';
import { ProductList } from './ProductList'; import { ProductList } from './ProductList';
import { SalesOrderProvider } from './SalesOrderContex';
export type RootStackParams = { export type RootStackParams = {
SalesOrderListScreen: undefined, SalesOrderListScreen: undefined,
SalesOrderFormScreen: { id: number }, SalesOrderFormScreen: { id: number, productId: number },
ProductList: undefined ProductList: undefined
} }
const Stack = createNativeStackNavigator<RootStackParams>(); const Stack = createNativeStackNavigator<RootStackParams>();
@ -16,18 +17,21 @@ export const SalesOrderStack = () => {
const { isAuthenticated } = useContext(AuthContext) const { isAuthenticated } = useContext(AuthContext)
return ( return (
<Stack.Navigator <SalesOrderProvider>
screenOptions={{ <Stack.Navigator
headerShown: true, screenOptions={{
}} headerShown: true,
> }}
{isAuthenticated && ( >
<> {isAuthenticated && (
<Stack.Screen name="SalesOrderListScreen" component={SalesOrderListScreen} /> <>
<Stack.Screen name="SalesOrderFormScreen" component={SalesOrderFormScreen} /> <Stack.Screen name="SalesOrderListScreen" component={SalesOrderListScreen} />
<Stack.Screen name="ProductList" component={ProductList} /> <Stack.Screen name="SalesOrderFormScreen" component={SalesOrderFormScreen} />
</> <Stack.Screen name="ProductList" component={ProductList} />
)} </>
</Stack.Navigator> )}
</Stack.Navigator>
</SalesOrderProvider>
) )
} }
Loading…
Cancel
Save