Compare commits

...

3 Commits

Author SHA1 Message Date
c02b61163d Update from master 2025-11-07 17:56:13 +07:00
Tran Anh Tuan
53bf2d18e6 thêm modal thêm mới/cập nhật NKĐT 2025-11-07 16:50:47 +07:00
Tran Anh Tuan
f7b05f1e08 tadd select component 2025-11-07 15:28:55 +07:00
13 changed files with 808 additions and 182 deletions

View File

@@ -1,56 +1,21 @@
import AlarmList from "@/components/AlarmList";
import { Link } from "expo-router";
import {
Platform,
StyleSheet,
Text,
TouchableOpacity,
View,
} from "react-native";
import CreateOrUpdateHaulModal from "@/components/tripInfo/modal/CreateOrUpdateHaulModal";
import { useState } from "react";
import { Button, Platform, StyleSheet, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
const alarmExample = {
alarms: [
{
name: "Ngập nước có cảnh báo",
t: 1762226488,
level: 1,
id: "0:8:1",
},
{
name: "Tầu cảnh báo sos",
t: 1762226596,
level: 3,
id: "50:15",
},
{
name: "Khói có cảnh báo",
t: 1762226589,
level: 1,
id: "0:1:1",
},
{
name: "Cửa có cảnh báo",
t: 1762226547,
level: 1,
id: "0:7:1",
},
],
level: 3,
};
export default function Warning() {
const [isShowModal, setIsShowModal] = useState(false);
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={styles.titleText}>Nhật Chuyến Đi</Text>
<Link href="/modal" asChild>
<TouchableOpacity style={styles.button}>
<Text style={styles.buttonText}>Mở Modal</Text>
</TouchableOpacity>
</Link>
<AlarmList alarmsData={alarmExample.alarms} />
<CreateOrUpdateHaulModal
haulData={null}
isVisible={isShowModal}
onClose={function (): void {
setIsShowModal(false);
}}
/>
<Button title="Thêm thu hoạch" onPress={() => setIsShowModal(true)} />
</View>
</SafeAreaView>
);
@@ -88,3 +53,106 @@ const styles = StyleSheet.create({
fontWeight: "600",
},
});
const fishingInfoDatas: Model.FishingLogInfo[] = [
{
fish_species_id: 10,
fish_name: "Cá quỷ biển (Barracuda)",
catch_number: 820,
catch_unit: "kg",
fish_size: 29,
fish_rarity: 1,
fish_condition: "Bị thương",
gear_usage: "",
},
{
fish_species_id: 1,
fish_name: "Cá thu",
catch_number: 1293,
catch_unit: "kg",
fish_size: 37,
fish_rarity: 1,
fish_condition: "Bị thương",
gear_usage: "",
},
{
fish_species_id: 13,
fish_name: "Cá song đỏ",
catch_number: 1738,
catch_unit: "kg",
fish_size: 28,
fish_rarity: 2,
fish_condition: "Còn sống",
gear_usage: "",
},
{
fish_species_id: 17,
fish_name: "Cá nược",
catch_number: 690,
catch_unit: "kg",
fish_size: 63,
fish_rarity: 1,
fish_condition: "Chết",
gear_usage: "",
},
{
fish_species_id: 19,
fish_name: "Cá hổ Thái Lan",
catch_number: 825,
catch_unit: "kg",
fish_size: 55,
fish_rarity: 4,
fish_condition: "Chết",
gear_usage: "Câu tay",
},
{
fish_species_id: 8,
fish_name: "Cá hồng phớn",
catch_number: 1409,
catch_unit: "kg",
fish_size: 172,
fish_rarity: 3,
fish_condition: "Chết",
gear_usage: "Bẫy lưới",
},
{
fish_species_id: 16,
fish_name: "Cá rồng biển",
catch_number: 1426,
catch_unit: "kg",
fish_size: 105,
fish_rarity: 3,
fish_condition: "Chết",
gear_usage: "Lưới rê",
},
{
fish_species_id: 3,
fish_name: "Cá chim trắng",
catch_number: 176,
catch_unit: "kg",
fish_size: 83,
fish_rarity: 2,
fish_condition: "Chết",
gear_usage: "",
},
{
fish_species_id: 14,
fish_name: "Cá mú cườm",
catch_number: 724,
catch_unit: "kg",
fish_size: 36,
fish_rarity: 2,
fish_condition: "Chết",
gear_usage: "",
},
{
fish_species_id: 18,
fish_name: "Cá đuối quạt",
catch_number: 1712,
catch_unit: "kg",
fish_size: 105,
fish_rarity: 4,
fish_condition: "Còn sống",
gear_usage: "Câu vàng",
},
];

View File

@@ -4,27 +4,10 @@ import { PolygonWithLabel } from "@/components/map/PolygonWithLabel";
import type { PolylineWithLabelProps } from "@/components/map/PolylineWithLabel";
import { PolylineWithLabel } from "@/components/map/PolylineWithLabel";
import SosButton from "@/components/map/SosButton";
import {
ENTITY,
EVENT_ALARM_DATA,
EVENT_BANZONE_DATA,
EVENT_ENTITY_DATA,
EVENT_GPS_DATA,
EVENT_TRACK_POINTS_DATA,
IOS_PLATFORM,
LIGHT_THEME,
} from "@/constants";
import { ENTITY, IOS_PLATFORM, LIGHT_THEME } from "@/constants";
import { useColorScheme } from "@/hooks/use-color-scheme.web";
import { usePlatform } from "@/hooks/use-platform";
import {
getAlarmEventBus,
getBanzonesEventBus,
getEntitiesEventBus,
getGpsEventBus,
getTrackPointsEventBus,
} from "@/services/device_events";
import { getShipIcon } from "@/services/map_service";
import eventBus from "@/utils/eventBus";
import {
convertWKTLineStringToLatLngArray,
convertWKTtoLatLngString,
@@ -61,69 +44,70 @@ export default function HomeScreen() {
// const [number, setNumber] = useState(0);
useEffect(() => {
getGpsEventBus();
getAlarmEventBus();
getEntitiesEventBus();
getBanzonesEventBus();
getTrackPointsEventBus();
const queryGpsData = (gpsData: Model.GPSResponse) => {
if (gpsData) {
// console.log("GPS Data: ", gpsData);
setGpsData(gpsData);
} else {
setGpsData(null);
setPolygonCoordinates([]);
setPolylineCoordinates(null);
}
};
const queryAlarmData = (alarmData: Model.AlarmResponse) => {
// console.log("Alarm Data: ", alarmData.alarms.length);
setAlarmData(alarmData);
};
const queryEntityData = (entityData: Model.TransformedEntity[]) => {
// console.log("Entities Length Data: ", entityData.length);
setEntityData(entityData);
};
const queryBanzonesData = (banzoneData: Model.Zone[]) => {
// console.log("Banzone Data: ", banzoneData.length);
// useEffect(() => {
// getGpsEventBus();
// getAlarmEventBus();
// getEntitiesEventBus();
// getBanzonesEventBus();
// getTrackPointsEventBus();
// const queryGpsData = (gpsData: Model.GPSResponse) => {
// if (gpsData) {
// // console.log("GPS Data: ", gpsData);
// setGpsData(gpsData);
// } else {
// setGpsData(null);
// setPolygonCoordinates([]);
// setPolylineCoordinates(null);
// }
// };
// const queryAlarmData = (alarmData: Model.AlarmResponse) => {
// // console.log("Alarm Data: ", alarmData.alarms.length);
// setAlarmData(alarmData);
// };
// const queryEntityData = (entityData: Model.TransformedEntity[]) => {
// // console.log("Entities Length Data: ", entityData.length);
// setEntityData(entityData);
// };
// const queryBanzonesData = (banzoneData: Model.Zone[]) => {
// // console.log("Banzone Data: ", banzoneData.length);
setBanzoneData(banzoneData);
};
const queryTrackPointsData = (TrackPointsData: Model.ShipTrackPoint[]) => {
// console.log("TrackPoints Data: ", TrackPointsData.length);
if (TrackPointsData && TrackPointsData.length > 0) {
setTrackPointsData(TrackPointsData);
} else {
setTrackPointsData(null);
}
};
// setBanzoneData(banzoneData);
// };
// const queryTrackPointsData = (TrackPointsData: Model.ShipTrackPoint[]) => {
// // console.log("TrackPoints Data: ", TrackPointsData.length);
// if (TrackPointsData && TrackPointsData.length > 0) {
// setTrackPointsData(TrackPointsData);
// } else {
// setTrackPointsData(null);
// }
// };
eventBus.on(EVENT_GPS_DATA, queryGpsData);
// console.log("Registering event handlers in HomeScreen");
eventBus.on(EVENT_GPS_DATA, queryGpsData);
// console.log("Subscribed to EVENT_GPS_DATA");
eventBus.on(EVENT_ALARM_DATA, queryAlarmData);
// console.log("Subscribed to EVENT_ALARM_DATA");
eventBus.on(EVENT_ENTITY_DATA, queryEntityData);
// console.log("Subscribed to EVENT_ENTITY_DATA");
eventBus.on(EVENT_TRACK_POINTS_DATA, queryTrackPointsData);
// console.log("Subscribed to EVENT_TRACK_POINTS_DATA");
eventBus.once(EVENT_BANZONE_DATA, queryBanzonesData);
// console.log("Subscribed once to EVENT_BANZONE_DATA");
// eventBus.on(EVENT_GPS_DATA, queryGpsData);
// // console.log("Registering event handlers in HomeScreen");
// eventBus.on(EVENT_GPS_DATA, queryGpsData);
// // console.log("Subscribed to EVENT_GPS_DATA");
// eventBus.on(EVENT_ALARM_DATA, queryAlarmData);
// // console.log("Subscribed to EVENT_ALARM_DATA");
// eventBus.on(EVENT_ENTITY_DATA, queryEntityData);
// // console.log("Subscribed to EVENT_ENTITY_DATA");
// eventBus.on(EVENT_TRACK_POINTS_DATA, queryTrackPointsData);
// // console.log("Subscribed to EVENT_TRACK_POINTS_DATA");
// eventBus.once(EVENT_BANZONE_DATA, queryBanzonesData);
// // console.log("Subscribed once to EVENT_BANZONE_DATA");
// return () => {
// // console.log("Unregistering event handlers in HomeScreen");
// eventBus.off(EVENT_GPS_DATA, queryGpsData);
// // console.log("Unsubscribed EVENT_GPS_DATA");
// eventBus.off(EVENT_ALARM_DATA, queryAlarmData);
// // console.log("Unsubscribed EVENT_ALARM_DATA");
// eventBus.off(EVENT_ENTITY_DATA, queryEntityData);
// // console.log("Unsubscribed EVENT_ENTITY_DATA");
// eventBus.off(EVENT_TRACK_POINTS_DATA, queryTrackPointsData);
// // console.log("Unsubscribed EVENT_TRACK_POINTS_DATA");
// };
// }, []);
return () => {
// console.log("Unregistering event handlers in HomeScreen");
eventBus.off(EVENT_GPS_DATA, queryGpsData);
// console.log("Unsubscribed EVENT_GPS_DATA");
eventBus.off(EVENT_ALARM_DATA, queryAlarmData);
// console.log("Unsubscribed EVENT_ALARM_DATA");
eventBus.off(EVENT_ENTITY_DATA, queryEntityData);
// console.log("Unsubscribed EVENT_ENTITY_DATA");
eventBus.off(EVENT_TRACK_POINTS_DATA, queryTrackPointsData);
// console.log("Unsubscribed EVENT_TRACK_POINTS_DATA");
};
}, []);
useEffect(() => {
setPolylineCoordinates(null);
setPolygonCoordinates([]);

View File

@@ -1,4 +1,5 @@
import ScanQRCode from "@/components/ScanQRCode";
import Select from "@/components/Select";
import { useState } from "react";
import {
Platform,
@@ -21,13 +22,32 @@ export default function Sensor() {
const handleScanPress = () => {
setScanModalVisible(true);
};
const [selectedValue, setSelectedValue] = useState<
string | number | undefined
>(undefined);
const options = [
{ label: "Apple", value: "apple" },
{ label: "Banana", value: "banana" },
{ label: "Cherry", value: "cherry", disabled: true },
];
return (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView contentContainerStyle={styles.scrollContent}>
<View style={styles.container}>
<Text style={styles.titleText}>Cảm biến trên tàu</Text>
<Select
style={{ width: "80%", marginBottom: 20 }}
options={options}
value={selectedValue}
onChange={(val) => {
setSelectedValue(val);
console.log("Value: ", val);
}}
placeholder="Select a fruit"
allowClear
/>
<Pressable style={styles.scanButton} onPress={handleScanPress}>
<Text style={styles.scanButtonText}>📱 Scan QR Code</Text>
</Pressable>

View File

@@ -1,8 +1,8 @@
import { ThemedText } from "@/components/themed-text";
import { ThemedView } from "@/components/themed-view";
import { showToastError } from "@/config";
import { TOKEN } from "@/constants";
import { login } from "@/controller/AuthController";
import { showErrorToast } from "@/services/toast_service";
import {
getStorageItem,
removeStorageItem,
@@ -57,7 +57,7 @@ export default function LoginScreen() {
const handleLogin = async () => {
// Validate input
if (!username.trim() || !password.trim()) {
showToastError("Lỗi", "Vui lòng nhập tài khoản và mật khẩu");
showErrorToast("Vui lòng nhập tài khoản và mật khẩu");
return;
}
@@ -81,8 +81,7 @@ export default function LoginScreen() {
router.replace("/(tabs)");
}
} catch (error) {
showToastError(
"Lỗi",
showErrorToast(
error instanceof Error ? error.message : "Đăng nhập thất bại"
);
} finally {

View File

@@ -20,6 +20,12 @@ interface StartButtonProps {
onPress?: () => void;
}
interface a {
fishingLogs?: Model.FishingLogInfo[] | null;
onCallback?: (fishingLogs: Model.FishingLogInfo[]) => void;
isEditing?: boolean;
}
const ButtonCreateNewHaulOrTrip: React.FC<StartButtonProps> = ({
gpsData,
onPress,
@@ -167,6 +173,7 @@ const ButtonCreateNewHaulOrTrip: React.FC<StartButtonProps> = ({
</IconButton>
)}
<CreateOrUpdateHaulModal
haulData={null}
isVisible={isFinishHaulModalOpen}
onClose={function (): void {
setIsFinishHaulModalOpen(false);

272
components/Select.tsx Normal file
View File

@@ -0,0 +1,272 @@
import { AntDesign } from "@expo/vector-icons";
import React, { useEffect, useState } from "react";
import {
ActivityIndicator,
ScrollView,
StyleProp,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
ViewStyle,
} from "react-native";
export interface SelectOption {
label: string;
value: string | number;
disabled?: boolean;
}
export interface SelectProps {
value?: string | number;
defaultValue?: string | number;
options: SelectOption[];
onChange?: (value: string | number | undefined) => void;
placeholder?: string;
disabled?: boolean;
loading?: boolean;
allowClear?: boolean;
showSearch?: boolean;
mode?: "single" | "multiple"; // multiple not implemented yet
style?: StyleProp<ViewStyle>;
size?: "small" | "middle" | "large";
}
/**
* Select
* A Select component inspired by Ant Design, adapted for React Native.
* Supports single selection, search, clear, loading, disabled states.
*/
const Select: React.FC<SelectProps> = ({
value,
defaultValue,
options,
onChange,
placeholder = "Select an option",
disabled = false,
loading = false,
allowClear = false,
showSearch = false,
mode = "single",
style,
size = "middle",
}) => {
const [selectedValue, setSelectedValue] = useState<
string | number | undefined
>(value ?? defaultValue);
const [isOpen, setIsOpen] = useState(false);
const [searchText, setSearchText] = useState("");
const [containerHeight, setContainerHeight] = useState(0);
useEffect(() => {
setSelectedValue(value);
}, [value]);
const filteredOptions = showSearch
? options.filter((opt) =>
opt.label.toLowerCase().includes(searchText.toLowerCase())
)
: options;
const selectedOption = options.find((opt) => opt.value === selectedValue);
const handleSelect = (val: string | number) => {
setSelectedValue(val);
onChange?.(val);
setIsOpen(false);
setSearchText("");
};
const handleClear = () => {
setSelectedValue(undefined);
onChange?.(undefined);
};
const sizeMap = {
small: { height: 32, fontSize: 14, paddingHorizontal: 10 },
middle: { height: 40, fontSize: 16, paddingHorizontal: 14 },
large: { height: 48, fontSize: 18, paddingHorizontal: 18 },
};
const sz = sizeMap[size];
return (
<View style={styles.wrapper}>
<TouchableOpacity
style={[
styles.container,
{
height: sz.height,
paddingHorizontal: sz.paddingHorizontal,
opacity: disabled ? 0.6 : 1,
},
style,
]}
onPress={() => !disabled && !loading && setIsOpen(!isOpen)}
disabled={disabled || loading}
activeOpacity={0.8}
onLayout={(e) => setContainerHeight(e.nativeEvent.layout.height)}
>
<View style={styles.content}>
{loading ? (
<ActivityIndicator size="small" color="#4ecdc4" />
) : (
<Text
style={[
styles.text,
{
fontSize: sz.fontSize,
color: selectedValue ? "#111" : "#999",
},
]}
numberOfLines={1}
>
{selectedOption?.label || placeholder}
</Text>
)}
</View>
<View style={styles.suffix}>
{allowClear && selectedValue && !loading ? (
<TouchableOpacity onPress={handleClear} style={styles.icon}>
<AntDesign name="close" size={16} color="#999" />
</TouchableOpacity>
) : null}
<AntDesign
name={isOpen ? "up" : "down"}
size={14}
color="#999"
style={styles.arrow}
/>
</View>
</TouchableOpacity>
{isOpen && (
<View style={[styles.dropdown, { top: containerHeight }]}>
{showSearch && (
<TextInput
style={styles.searchInput}
placeholder="Search..."
value={searchText}
onChangeText={setSearchText}
autoFocus
/>
)}
<ScrollView style={styles.list}>
{filteredOptions.map((item) => (
<TouchableOpacity
key={item.value}
style={[
styles.option,
item.disabled && styles.optionDisabled,
selectedValue === item.value && styles.optionSelected,
]}
onPress={() => !item.disabled && handleSelect(item.value)}
disabled={item.disabled}
>
<Text
style={[
styles.optionText,
item.disabled && styles.optionTextDisabled,
selectedValue === item.value && styles.optionTextSelected,
]}
>
{item.label}
</Text>
{selectedValue === item.value && (
<AntDesign name="check" size={16} color="#4ecdc4" />
)}
</TouchableOpacity>
))}
</ScrollView>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
wrapper: {
position: "relative",
},
container: {
borderWidth: 1,
borderColor: "#e6e6e6",
borderRadius: 8,
backgroundColor: "#fff",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
},
content: {
flex: 1,
},
text: {
color: "#111",
},
suffix: {
flexDirection: "row",
alignItems: "center",
},
icon: {
marginRight: 8,
},
arrow: {
marginLeft: 4,
},
dropdown: {
position: "absolute",
left: 0,
right: 0,
backgroundColor: "#fff",
borderWidth: 1,
borderColor: "#e6e6e6",
borderTopWidth: 0,
borderRadius: 10,
borderBottomLeftRadius: 8,
borderBottomRightRadius: 8,
shadowColor: "#000",
shadowOpacity: 0.1,
shadowRadius: 4,
shadowOffset: { width: 0, height: 2 },
elevation: 5,
zIndex: 1000,
},
searchInput: {
borderWidth: 1,
borderColor: "#e6e6e6",
borderRadius: 4,
padding: 8,
margin: 8,
},
list: {
maxHeight: 200,
},
option: {
padding: 12,
borderBottomWidth: 1,
borderBottomColor: "#f0f0f0",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
},
optionDisabled: {
opacity: 0.5,
},
optionSelected: {
backgroundColor: "#f6ffed",
},
optionText: {
fontSize: 16,
color: "#111",
},
optionTextDisabled: {
color: "#999",
},
optionTextSelected: {
color: "#4ecdc4",
fontWeight: "600",
},
});
export default Select;

View File

@@ -1,18 +1,251 @@
import Select from "@/components/Select";
import { useFishes } from "@/state/use-fish";
import { zodResolver } from "@hookform/resolvers/zod";
import React from "react";
import { Modal, Text } from "react-native";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { Button, FlatList, Modal, Text, TextInput, View } from "react-native";
import { z } from "zod";
interface CreateOrUpdateHaulModalProps {
isVisible: boolean;
onClose: () => void;
haulData?: Model.FishingLog | null;
haulData?: Model.FishingLogInfo[] | null;
}
const UNITS = ["con", "kg", "tấn"] as const;
type Unit = (typeof UNITS)[number];
const UNITS_OPTIONS = UNITS.map((unit) => ({
label: unit,
value: unit.toString(),
}));
// Zod schema cho 1 dòng cá
const fishItemSchema = z.object({
id: z.number().min(1, "Chọn loài cá"),
quantity: z
.number({ invalid_type_error: "Số lượng phải là số" })
.positive("Số lượng > 0"),
unit: z.enum(UNITS, { required_error: "Chọn đơn vị" }),
size: z
.number({ invalid_type_error: "Kích thước phải là số" })
.positive("Kích thước > 0")
.optional(),
});
// Schema tổng: mảng các item
const formSchema = z.object({
fish: z.array(fishItemSchema).min(1, "Thêm ít nhất 1 loài cá"),
});
type FormValues = z.infer<typeof formSchema>;
const defaultItem = (): FormValues["fish"][number] => ({
id: -1,
quantity: 1,
unit: "con",
size: undefined,
});
const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
isVisible,
onClose,
haulData,
}) => {
const [isCreateMode, setIsCreateMode] = React.useState(!haulData);
const { control, handleSubmit, formState, watch, reset } =
useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
fish: [defaultItem()],
},
mode: "onSubmit",
});
const { fishSpecies, getFishSpecies } = useFishes();
const { errors } = formState;
if (!fishSpecies) {
getFishSpecies();
}
const { fields, append, remove } = useFieldArray({
control,
name: "fish",
keyName: "_id", // tránh đụng key
});
const onSubmit = (values: FormValues) => {
// Map form values to the FishingLogInfo-like shape the user requested
const mapped = values.fish.map((f) => {
const meta = fishSpecies!.find((x) => x.id === f.id);
return {
fish_species_id: f.id,
fish_name: meta?.name,
catch_number: f.quantity,
catch_unit: f.unit,
fish_size: f.size,
fish_rarity: meta?.rarity_level,
fish_condition: "",
gear_usage: "",
} as unknown; // inferred shape — keep as unknown to avoid relying on global types here
});
console.log("SUBMIT (FishingLogInfo[]): ", JSON.stringify(mapped, null, 2));
// close modal after submit (you can change this to pass the payload to a parent via prop)
onClose();
};
// Initialize / reset form when modal visibility or haulData changes
React.useEffect(() => {
if (!isVisible) {
// when modal closed, clear form to default
reset({ fish: [defaultItem()] });
setIsCreateMode(true);
return;
}
// when modal opened, populate based on haulData
if (haulData === null) {
// explicit null -> start with a single default item
reset({ fish: [defaultItem()] });
setIsCreateMode(true);
} else if (Array.isArray(haulData) && haulData.length > 0) {
// map FishingLogInfo -> form rows
const mapped = haulData.map((h) => ({
id: h.fish_species_id ?? -1,
quantity: (h.catch_number as number) ?? 1,
unit: (h.catch_unit as Unit) ?? (defaultItem().unit as Unit),
size: (h.fish_size as number) ?? undefined,
}));
reset({ fish: mapped as any });
setIsCreateMode(false);
} else {
// undefined or empty array -> default
reset({ fish: [defaultItem()] });
setIsCreateMode(true);
}
}, [isVisible, haulData, reset]);
const renderRow = ({ item, index }: { item: any; index: number }) => {
return (
<View
style={{
marginBottom: 12,
padding: 12,
borderWidth: 1,
borderRadius: 8,
}}
>
<Text style={{ fontWeight: "600", marginBottom: 8 }}>
Loài #{index + 1}
</Text>
{/* Species dropdown */}
<Controller
control={control}
name={`fish.${index}.id`}
render={({ field: { value, onChange } }) => (
<View style={{ marginBottom: 8 }}>
<Text style={{ marginBottom: 4 }}>Tên </Text>
<Select
options={fishSpecies!.map((fish) => ({
label: fish.name,
value: fish.id,
}))}
value={value}
onChange={onChange}
placeholder="Chọn loài cá"
/>
{errors.fish?.[index]?.id && (
<Text style={{ color: "red" }}>
{errors.fish[index]?.id?.message as string}
</Text>
)}
</View>
)}
/>
{/* Quantity */}
<Controller
control={control}
name={`fish.${index}.quantity`}
render={({ field: { value, onChange, onBlur } }) => (
<View style={{ marginBottom: 8 }}>
<Text style={{ marginBottom: 4 }}>Số lượng</Text>
<TextInput
keyboardType="numeric"
value={String(value ?? "")}
onBlur={onBlur}
onChangeText={(t) =>
onChange(Number(t.replace(/,/g, ".")) || 0)
}
style={{ padding: 10, borderWidth: 1, borderRadius: 6 }}
/>
{errors.fish?.[index]?.quantity && (
<Text style={{ color: "red" }}>
{errors.fish[index]?.quantity?.message as string}
</Text>
)}
</View>
)}
/>
{/* Unit dropdown */}
<Controller
control={control}
name={`fish.${index}.unit`}
render={({ field: { value, onChange } }) => (
<View style={{ marginBottom: 8 }}>
<Text style={{ marginBottom: 4 }}>Đơn vị</Text>
<Select
options={UNITS_OPTIONS.map((unit) => ({
label: unit.label,
value: unit.value,
}))}
value={value}
onChange={onChange}
placeholder="Chọn đơn vị"
/>
{errors.fish?.[index]?.unit && (
<Text style={{ color: "red" }}>
{errors.fish[index]?.unit?.message as string}
</Text>
)}
</View>
)}
/>
{/* Size (optional) */}
<Controller
control={control}
name={`fish.${index}.size`}
render={({ field: { value, onChange, onBlur } }) => (
<View style={{ marginBottom: 8 }}>
<Text style={{ marginBottom: 4 }}>
Kích thước (cm) tùy chọn
</Text>
<TextInput
keyboardType="numeric"
value={value ? String(value) : ""}
onBlur={onBlur}
onChangeText={(t) =>
onChange(t ? Number(t.replace(/,/g, ".")) : undefined)
}
style={{ padding: 10, borderWidth: 1, borderRadius: 6 }}
/>
{errors.fish?.[index]?.size && (
<Text style={{ color: "red" }}>
{errors.fish[index]?.size?.message as string}
</Text>
)}
</View>
)}
/>
{/* Remove row */}
<View style={{ flexDirection: "row", justifyContent: "flex-end" }}>
<Button title="Xóa loài này" onPress={() => remove(index)} />
</View>
</View>
);
};
return (
<Modal
@@ -22,6 +255,29 @@ const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
onRequestClose={onClose}
>
<Text>{isCreateMode ? "Create Haul" : "Update Haul"}</Text>
<FlatList
data={fields}
keyExtractor={(it) => it._id}
renderItem={renderRow}
ListFooterComponent={
<View style={{ marginTop: 8 }}>
<Button
title="Thêm loài cá"
onPress={() => append(defaultItem())}
/>
</View>
}
/>
{errors.fish && (
<Text style={{ color: "red", marginTop: 8 }}>
{(errors.fish as any)?.message}
</Text>
)}
<View style={{ marginTop: 16 }}>
<Button title="Lưu thu hoạch" onPress={handleSubmit(onSubmit)} />
</View>
</Modal>
);
};

View File

@@ -45,16 +45,6 @@ export const FishCardForm: React.FC<FishCardFormProps> = ({
onUpdateCatchItem,
}) => {
const { fishSpecies } = useFishes();
const [fishNameOptions, setFishNameOptions] = React.useState<string[]>([]);
React.useEffect(() => {
console.log("Length: ", fishSpecies?.length);
if (Array.isArray(fishSpecies)) {
const names = fishSpecies.map((item) => item.name).filter(Boolean);
setFishNameOptions(names);
}
}, [fishSpecies]);
return (
<>
@@ -66,15 +56,14 @@ export const FishCardForm: React.FC<FishCardFormProps> = ({
{isEditing ? (
<FishSelectDropdown
options={fishSpecies || []}
selectedValue={null}
selectedFishId={selectedFishIndex}
isOpen={selectedFishIndex === index}
onToggle={() =>
setSelectedFishIndex(selectedFishIndex === index ? null : index)
}
onSelect={(value: Model.FishSpeciesResponse) => {
onUpdateCatchItem(index, "fish_name", value.name);
// setSelectedFishIndex(null);
setSelectedFishIndex(value.id);
console.log("Fish Selected: ", fish);
}}
zIndex={1000 - index}

View File

@@ -5,7 +5,7 @@ import styles from "../../style/NetDetailModal.styles";
interface FishSelectDropdownProps {
options: Model.FishSpeciesResponse[];
selectedValue: Model.FishSpeciesResponse | null;
selectedFishId: number | null;
isOpen: boolean;
onToggle: () => void;
onSelect: (value: Model.FishSpeciesResponse) => void;
@@ -15,7 +15,7 @@ interface FishSelectDropdownProps {
export const FishSelectDropdown: React.FC<FishSelectDropdownProps> = ({
options,
selectedValue,
selectedFishId,
isOpen,
onToggle,
onSelect,
@@ -23,12 +23,17 @@ export const FishSelectDropdown: React.FC<FishSelectDropdownProps> = ({
styleOverride,
}) => {
const dropdownStyle = styleOverride || styles.optionsList;
const findFishNameById = (id: number | null) => {
const fish = options.find((item) => item.id === id);
return fish?.name || "Chọn cá";
};
const [selectedFish, setSelectedFish] =
React.useState<Model.FishSpeciesResponse | null>(null);
return (
<View style={{ zIndex }}>
<TouchableOpacity style={styles.selectButton} onPress={onToggle}>
<Text style={styles.selectButtonText}>
{selectedValue ? selectedValue.name : "Chọn cá"}
{findFishNameById(selectedFishId)}
</Text>
<IconSymbol
name={isOpen ? "chevron.up" : "chevron.down"}
@@ -44,7 +49,9 @@ export const FishSelectDropdown: React.FC<FishSelectDropdownProps> = ({
style={styles.optionItem}
onPress={() => onSelect(option)}
>
<Text style={styles.optionText}>{option.name}</Text>
<Text style={styles.optionText}>
{findFishNameById(option.id)}
</Text>
</TouchableOpacity>
))}
</ScrollView>

View File

@@ -2,20 +2,6 @@ import React from "react";
import { Text, View } from "react-native";
import styles from "../../style/NetDetailModal.styles";
interface NetDetail {
id: string;
stt: string;
trangThai: string;
thoiGianBatDau?: string;
thoiGianKetThuc?: string;
viTriHaThu?: string;
viTriThuLuoi?: string;
doSauHaThu?: string;
doSauThuLuoi?: string;
catchList?: any[];
ghiChu?: string;
}
interface InfoSectionProps {
netData?: Model.FishingLog;
isCompleted: boolean;
@@ -49,22 +35,22 @@ export const InfoSection: React.FC<InfoSectionProps> = ({
? new Date(netData.end_at).toLocaleString()
: "Chưa cập nhật",
},
{
label: "Vị trí hạ thu",
value: netData.viTriHaThu || "Chưa cập nhật",
},
{
label: "Vị trí thu lưới",
value: netData.viTriThuLuoi || "Chưa cập nhật",
},
{
label: "Độ sâu hạ thu",
value: netData.doSauHaThu || "Chưa cập nhật",
},
{
label: "Độ sâu thu lưới",
value: netData.doSauThuLuoi || "Chưa cập nhật",
},
// {
// label: "Vị trí hạ thu",
// value: netData.viTriHaThu || "Chưa cập nhật",
// },
// {
// label: "Vị trí thu lưới",
// value: netData.viTriThuLuoi || "Chưa cập nhật",
// },
// {
// label: "Độ sâu hạ thu",
// value: netData.doSauHaThu || "Chưa cập nhật",
// },
// {
// label: "Độ sâu thu lưới",
// value: netData.doSauThuLuoi || "Chưa cập nhật",
// },
];
return (

36
package-lock.json generated
View File

@@ -12,6 +12,7 @@
"@expo/vector-icons": "^15.0.3",
"@gluestack-ui/core": "^3.0.12",
"@gluestack-ui/utils": "^3.0.11",
"@hookform/resolvers": "^5.2.2",
"@legendapp/motion": "^2.5.3",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-navigation/bottom-tabs": "^7.4.0",
@@ -38,6 +39,7 @@
"react": "19.1.0",
"react-aria": "^3.44.0",
"react-dom": "19.1.0",
"react-hook-form": "^7.66.0",
"react-native": "0.81.5",
"react-native-gesture-handler": "~2.28.0",
"react-native-keyboard-aware-scroll-view": "^0.9.5",
@@ -2389,6 +2391,18 @@
"tailwindcss": ">=3.0.0"
}
},
"node_modules/@hookform/resolvers": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
"license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": {
"react-hook-form": "^7.55.0"
}
},
"node_modules/@humanfs/core": {
"version": "0.19.1",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",
@@ -5101,6 +5115,12 @@
"@sinonjs/commons": "^3.0.0"
}
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
"version": "0.5.17",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.17.tgz",
@@ -13244,6 +13264,22 @@
"react": ">=17.0.0"
}
},
"node_modules/react-hook-form": {
"version": "7.66.0",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.66.0.tgz",
"integrity": "sha512-xXBqsWGKrY46ZqaHDo+ZUYiMUgi8suYu5kdrS20EG8KiL7VRQitEbNjm+UcrDYrNi1YLyfpmAeGjCZYXLT9YBw==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/react-hook-form"
},
"peerDependencies": {
"react": "^16.8.0 || ^17 || ^18 || ^19"
}
},
"node_modules/react-is": {
"version": "19.2.0",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.0.tgz",

View File

@@ -15,6 +15,7 @@
"@expo/vector-icons": "^15.0.3",
"@gluestack-ui/core": "^3.0.12",
"@gluestack-ui/utils": "^3.0.11",
"@hookform/resolvers": "^5.2.2",
"@legendapp/motion": "^2.5.3",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-navigation/bottom-tabs": "^7.4.0",
@@ -41,6 +42,7 @@
"react": "19.1.0",
"react-aria": "^3.44.0",
"react-dom": "19.1.0",
"react-hook-form": "^7.66.0",
"react-native": "0.81.5",
"react-native-gesture-handler": "~2.28.0",
"react-native-keyboard-aware-scroll-view": "^0.9.5",

View File

@@ -2,7 +2,7 @@ import { queryFish } from "@/controller/FishController";
import { create } from "zustand";
type Fish = {
fishSpecies: Model.FishSpeciesResponse | null;
fishSpecies: Model.FishSpeciesResponse[] | null;
getFishSpecies: () => Promise<void>;
error: string | null;
loading?: boolean;
@@ -13,7 +13,7 @@ export const useFishes = create<Fish>((set) => ({
getFishSpecies: async () => {
try {
const response = await queryFish();
console.log("Fish fetching API");
console.log("Fish fetching API: ", response.data.length);
set({ fishSpecies: response.data, loading: false });
} catch (error) {