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 { useFetchWithAuth } from '../../hooks/useFetchWithAuth'
import { ProductCardList } from '../../components/cardList/ProductCardList';
import { ProductItem } from './ProductItem';
export const ProductList = () => {
@ -64,7 +65,7 @@ export const ProductList = () => {
<View id={item} className='flex-1 items-center'>
<Card>
<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>
</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 { Text } from 'react-native'
import { Background } from '../../components/Background'
import { useContext, useEffect, useState } from 'react'
import { FlatList, Text, View } from 'react-native'
import { Button } from '../../components/Button';
import { Card } from '../../components/Card';
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 { useFetchWithAuth } from '../../hooks/useFetchWithAuth';
import { saveWithAuth } from '../../hooks/saveWithAuth';
import { ManyToOne } from '../../components/ManyToOne';
import { RootStackParams } from './SalesOrderStack';
import OneToMany from '../../components/OneToMany';
import { SalesOrderContext } from './SalesOrderContex';
interface Props extends NativeStackScreenProps<RootStackParams, 'SalesOrderFormScreen'> { };
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: {
id: 0,
numero: '',
cliente: { id: 0 },
detalle: []
cliente: { id: 0 }
}
});
let id: string = "0";
if (route.params?.id != undefined) {
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 () => {
if (!id || id == "0")
return;
@ -40,7 +66,9 @@ export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
setValue("id", data['id'])
setValue("numero", data['numero'])
setValue("cliente", data['cliente'])
setValue("detalle", data['detalle'])
const lines: SalesOrderLine[] = data['detalle'];
console.log("Agregando lineas:")
setLines(lines);
}
} else {
@ -57,8 +85,6 @@ export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
try {
let endpoint = "pedido";
entity['cliente'] = { id: entity['cliente'].id }
console.log("Entidad:")
console.log(entity)
const { data, error } = await saveWithAuth(endpoint, id, entity);
if (error) {
console.log(error);
@ -73,21 +99,30 @@ export const SalesOrderFormScreen = ({ route, navigation }: Props) => {
return (
<>
<Background >
<Card>
<Text className='text-xl text-center my-4'>Registro de Pedido</Text>
<Input name="numero" label='Número' control={control} />
<ManyToOne entity='cliente' columname='cliente' columnvalue="nombre" control={control} />
<Button
title='Agrega produtos'
additionalStyle='mb-4'
onPress={() => navigation.navigate("ProductListScreen" as never)} />
<Button
title='Guardar'
onPress={handleSubmit(onSubmit)}
/>
</Card>
</Background>
<FlatList
data={[""]}
renderItem={({ item }) =>
<>
<Card>
<Text className='text-xl text-center my-4'>Registro de Pedido</Text>
<Input name="numero" label='Número' control={control} />
<ManyToOne entity='cliente' columname='cliente' columnvalue="nombre" control={control} />
<OneToMany />
<Button
title='Agrega produtos'
additionalStyle='mb-4'
onPress={() => navigation.navigate("ProductList" as never)} />
<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 getInitData = async () => {
const { data, error } = await useFetchWithAuth(endpoints);
if (!error) {
setEntities(data);
} else {
console.log(error)
}
const { data, error } = await useFetchWithAuth(endpoints);
if (!error) {
setEntities(data);
} else {
console.log(error)
}
}
useEffect(() => {
getInitData();
getInitData();
}, [refreshing])
const onRefresh = () => {
setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
}, 1000);
setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
}, 1000);
};
return (
<View className='bg-sky-100'>
<Button
title=' + '
additionalStyle='z-10 absolute bottom-2 right-0'
onPress={() => navigation.navigate("SalesOrderFormScreen" as never)} />
<FlatList
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
<View className='bg-sky-100'>
<Button
title=' + '
additionalStyle='z-10 absolute bottom-2 right-0'
onPress={() => navigation.navigate("SalesOrderFormScreen" as never)} />
<FlatList
refreshControl={
<RefreshControl
refreshing={refreshing}
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}
/>
}
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>
</View>
)
}

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