Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- FlatList,
- SafeAreaView,
- StyleSheet,
- Text,
- View,
- TouchableOpacity,
- RefreshControl,
- } from 'react-native';
- import React, {useState, useEffect, useMemo} from 'react';
- import {AccordionItem, Button, Gap, Header, Input} from '../../components';
- import {colors, fonts, getData, useForm} from '../../utils';
- import {IcNotFound} from '../../assets';
- import axios from 'axios';
- import base64 from 'react-native-base64';
- import {Dropdown} from 'react-native-element-dropdown';
- import {API_HOST} from '../../config';
- import Modal from 'react-native-modal';
- import {ScrollView} from 'react-native-gesture-handler';
- import {useDispatch, useSelector} from 'react-redux';
- import {store} from '../../redux/store';
- import {editHistory} from '../../redux/reducer/history';
- import {showMessage} from 'react-native-flash-message';
- // import { TouchableOpacity } from 'react-native-gesture-handler'
- const DetailHistorySps = ({navigation, route}) => {
- const [kodeDepo, setKodeDepo] = useState('001');
- const [depoData, setDepoData] = useState([]);
- const [dataDepo, setDataDepo] = useState(null);
- const [isFocus, setIsFocus] = useState(false);
- const [selectedDepo, setSelectedDepo] = useState(null);
- const [userProfile, setUserProfile] = useState({});
- const [historyData, setHistoryData] = useState([])
- const [loading, setLoading] = useState(false)
- const getDepo = () => {
- let username = 'admin';
- let adminPassword = 'Databa53';
- const authHeader = 'Basic ' + base64.encode(`${username}:${adminPassword}`);
- axios
- .get(`${API_HOST.url_staging}/depo`, {
- headers: {
- Authorization: authHeader,
- },
- })
- .then(res => {
- let count = Object.keys(res.data).length;
- let depoArray = [];
- for (let i = 0; i < count; i++) {
- depoArray.push({
- id: res.data[i].kode_depo,
- label: res.data[i].depo,
- });
- }
- setDepoData(depoArray);
- setKodeDepo(res.data[0].id);
- setSelectedDepo(depoArray[0].id);
- })
- .catch(err => {
- console.log('gagal', err);
- });
- }; // mengambil data listing depo
- useEffect(() => {
- getData('userProfile').then(res => {
- setUserProfile(res);
- });
- getDepo();
- }, [historyData]);
- const getEdit = id_stock => {
- //get data edit ketika tombol edit history di click
- setIsModalVisible(true);
- let username = 'admin';
- let adminPassword = 'Databa53';
- const authHeader = 'Basic ' + base64.encode(`${username}:${adminPassword}`);
- axios
- .get(`${API_HOST.url_staging}/stock_sps/data_stock/` + id_stock, {
- headers: {
- Authorization: authHeader,
- },
- params: {
- id_stock,
- },
- })
- .then(res => {
- console.log('successs gan": ', res.data.data[0]);
- dispatch({
- type: 'SET_EDIT_HISTORY',
- value: {
- id_stock: res.data.data[0].id_stock,
- id_line: res.data.data[0].id_line,
- titik_pallet: res.data.data[0].titik_pallet,
- total_qty_titik: res.data.data[0].total_qty_titik,
- total_qty_line: res.data.data[0].total_qty_line,
- qty_add: res.data.data[0].qty_add,
- tidak_layak: res.data.data[0].tidak_layak,
- rusak_karton: res.data.data[0].rusak_karton,
- total_stock: res.data.data[0].total_stock,
- },
- });
- })
- .catch(err => console.log(err));
- };
- const [isModalVisible, setIsModalVisible] = useState(false);
- // const [historyData, setHistoryData] = useState(
- // route.params.historyData || [],
- // );
- const dispatch = useDispatch();
- const historyEdit = useSelector(state => state.historyEditReducer);
- console.log('returned', historyEdit);
- //trigger button edit value history
- const changeText = (key, value) => {
- if (key === 'qty_add' || key === 'total_qty_titik') {
- const qtyAdd = parseFloat(value);
- const titikPallet = parseFloat(historyEdit.titik_pallet);
- const totalQtyLine = parseFloat(historyEdit.total_qty_line);
- const totalPallet = parseFloat(historyEdit.total_qty_titik);
- const totalLine =
- !isNaN(totalQtyLine) && !isNaN(titikPallet)
- ? totalQtyLine * titikPallet
- : 0;
- const newTotalQtyTitik = !isNaN(totalPallet) ? totalLine : 0;
- const tidakLayak = parseFloat(historyEdit.tidak_layak) || 0;
- const rusakKarton = parseFloat(historyEdit.rusak_karton) || 0;
- const newTotalStock =
- newTotalQtyTitik + tidakLayak + rusakKarton + qtyAdd;
- dispatch({
- type: 'SET_EDIT_HISTORY',
- value: {
- ...historyEdit,
- [key]: value,
- total_qty_titik: newTotalQtyTitik.toString(),
- total_stock: newTotalStock.toString(),
- },
- });
- } else {
- dispatch({
- type: 'SET_EDIT_HISTORY',
- value: {
- ...historyEdit,
- [key]: value,
- },
- });
- }
- }; //trigger button edit value history
- //action button batal
- const cancelBtn = () => {
- return setIsModalVisible(!isModalVisible);
- };
- // simpan hasil edit
- let editCount = 0;
- let itemHasBeenEdited = false;
- const saveEdit = id_stock => {
- if (itemHasBeenEdited) {
- showMessage({
- message: 'This item has already been edited twice. Further edits are not allowed.',
- type: 'danger',
- hideStatusBar: true,
- floating: true,
- });
- return;
- }
- let username = 'admin';
- let adminPassword = 'Databa53';
- const authHeader = 'Basic ' + base64.encode(`${username}:${adminPassword}`);
- const requestData = {
- id_stock: historyEdit.id_stock || '',
- total_qty_line: historyEdit.total_qty_line || 0,
- titik_pallet: historyEdit.titik_pallet || '',
- qty_add: historyEdit.qty_add || 0,
- total_qty_titik: historyEdit.total_qty_titik || 0,
- total_stock: historyEdit.total_stock || 0,
- user_insert: userProfile.user_nama || '',
- };
- axios
- .put(
- `${API_HOST.url_staging}/stock_sps/${historyEdit.id_stock}`,
- requestData,
- {
- headers: {
- Authorization: authHeader,
- 'Content-Type': 'application/json',
- },
- params: {
- id_stock,
- },
- },
- )
- .then(res => {
- setIsModalVisible(!isModalVisible);
- console.log('berhasil edit: ', res.data);
- editCount++;
- if (editCount > 1) {
- itemHasBeenEdited = true; // Menandakan bahwa item telah diedit maksimal 2 kali
- }
- if (itemHasBeenEdited) {
- const updatedData = historyData.map(item => {
- if (item.id_stock === historyEdit.id_stock) {
- return {
- ...item,
- titik_pallet: historyEdit.titik_pallet,
- total_stock: historyEdit.total_stock,
- rusak_karton: historyEdit.rusak_karton,
- qty_add: historyEdit.qty_add,
- };
- }
- return item;
- });
- setHistoryData(updatedData);
- }
- if(res.data.alert) {
- showMessage({
- message: res.data.alert.message,
- type: 'info',
- hideStatusBar: true,
- floating: true,
- });
- } else {
- showMessage({
- message: res.data.message,
- type: 'danger',
- hideStatusBar: true,
- floating: true,
- });
- }
- })
- .catch(err => {
- showMessage({
- message: res.data.alert.message,
- type: 'danger',
- backgroundColor: colors.error,
- hideStatusBar: true,
- floating: true,
- });
- console.log('gagal edit: ', err);
- });
- }; // simpan hasil edit
- console.log('historyGan: ', historyData);
- useEffect(() => {
- refreshItem()
- }, [depoSelect])
- const depoSelect = useSelector(state => state.selectReducer);
- const refreshItem = () => {
- let username = 'admin'
- let passwordAdmin = 'Databa53'
- const authHeader = 'Basic ' + base64.encode(`${username}:${passwordAdmin}`);
- const today = new Date().toISOString().slice(0, 10);
- dispatch({type: "SET_LOADING", value: true})
- axios.get(`${API_HOST.url_staging}/stock_sps/data_history`, {
- headers: {
- Authorization: authHeader,
- 'Content-Type': 'application/json',
- },
- params: {
- type_stock: userProfile.type_user,
- id_depo:userProfile.lokasi_id ? userProfile.lokasi_id : kodeDepo, // tadinya depoSelect diganti dengan userProfile dari state
- tanggal: today,
- },
- }).then(res => {
- console.log('refresh sukses: ', res.data.data)
- const newData = res.data.data || []; // Extract data from the response
- setHistoryData(newData);
- // setHistoryData(res.data.data)
- dispatch({type: 'SET_LOADING', value: false})
- setLoading(false)
- }).catch(err => {
- console.log('refresh error: ', err)
- dispatch({type: 'SET_LOADING', value: false})
- setLoading(false)
- })
- } // get Data hasil terbaru dengan reresh controll
- return (
- <>
- <Header
- title="Detail History SPS"
- onPress={() => navigation.goBack()}
- />
- <View
- style={{
- flex: 1,
- top: 10,
- paddingHorizontal: 12,
- backgroundColor: '#FFFFFF',
- }}>
- <View style={{flex: 1}}>
- <>
- <FlatList
- data={historyData}
- renderItem={({ item, index }) => {
- <AccordionItem
- key={index}
- id_line={item.line}
- title={item.line}
- depo={item.depo}
- tanggal={item.tanggal}
- sku={item.nama_produk}
- qty_pallet={item.titik_pallet}
- qty_add={item.qty_add}
- total={item.total_stock}
- rusak_karton={item.rusak_karton}
- afkir={item.afkir}
- button={
- <TouchableOpacity
- style={styles.btnEdit}
- activeOpacity={0.8}
- onPress={() => getEdit(item.id_stock)}>
- <Text style={styles.textEdit}>Edit History</Text>
- </TouchableOpacity>
- }
- />
- }}
- onRefresh={() => refreshItem()}
- refreshing={loading}
- keyExtractor={(item, index) => index.toString()}
- ListEmptyComponent={() => (
- <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
- <IcNotFound />
- <Text style={{ fontFamily: fonts.primary[300], fontSize: 18, color: colors.secondary }}>OPPS BELUM ADA HISTORY YANG ANDA PILIH</Text>
- </View>
- )}
- />
- {/* <Dropdown
- style={styles.dropdownCover}
- placeholderStyle={styles.placeholderStyle}
- selectedTextStyle={styles.selectedTextStyle}
- inputSearchStyle={styles.inputSearchStyle}
- search
- labelField="label"
- valueField="value"
- data={depoData}
- maxHeight={300}
- value={dataDepo}
- placeholder={!isFocus ? 'Pilih Depo' : '....'}
- searchPlaceholder="Search..."
- onChange={item => {
- setSelectedDepo(item.id);
- // setKodeDepo(item.id);
- console.log('select depo: ', item);
- dispatch({
- type: 'SET_DEPO',
- value: {
- id_depo: item.id,
- },
- });
- }}
- itemTextStyle={{
- color: colors.secondary,
- fontSize: 13,
- fontFamily: fonts.primary[200],
- }}
- />
- {historyData.length ? (
- historyData.map((item, index) => (
- <AccordionItem
- key={index}
- id_line={item.line}
- title={item.line}
- depo={item.depo}
- tanggal={item.tanggal}
- sku={item.nama_produk}
- qty_pallet={item.titik_pallet}
- qty_add={item.qty_add}
- total={item.total_stock}
- rusak_karton={item.rusak_karton}
- afkir={item.afkir}
- button={
- <TouchableOpacity
- style={styles.btnEdit}
- activeOpacity={0.8}
- onPress={() => getEdit(item.id_stock)}>
- <Text style={styles.textEdit}>Edit History</Text>
- </TouchableOpacity>
- }
- />
- ))
- ) : (
- <>
- <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
- <IcNotFound />
- <Text style={{ fontFamily: fonts.primary[300], fontSize: 18, color: colors.secondary }}>OPPS BELUM ADA HISTORY YANG ANDA PILIH</Text>
- </View>
- </>
- )} */}
- </>
- {/* {historyData.length && (<Text>OPPS BELUM ADA HISTORY</Text>)} */}
- </View>
- <View>
- <Modal
- isVisible={isModalVisible}
- backdropColor="black"
- animationIn={'slideInDown'}
- animationInTiming={250}
- animationOutTiming={200}
- animationOut={'slideOutUp'}
- backdropOpacity={0.5}
- deviceHeight={850}>
- <ScrollView showsVerticalScrollIndicator={false} style={{flex: 1}}>
- <View
- style={{flex: 1, borderRadius: 5, backgroundColor: '#FFFF'}}>
- <Text
- style={{
- fontFamily: fonts.primary[300],
- fontSize: 18,
- color: colors.secondary,
- left: 20,
- top: 16,
- }}>
- Edit History Anda
- </Text>
- <Gap height={20} />
- <View
- style={{paddingHorizontal: 16, marginBottom: 25, flex: 1}}>
- <Input
- label="Line"
- value={historyEdit.id_line}
- onChangeText={value => changeText('id_line', value)}
- disable
- />
- <Gap height={20} />
- <Input
- label="Id_Stock"
- value={historyEdit.id_stock}
- onChangeText={value => changeText('id_stock', value)}
- disable
- />
- <Gap height={15} />
- <Input
- label="Titik Pallet"
- value={historyEdit.titik_pallet}
- onChangeText={value => changeText('titik_pallet', value)}
- keyboardType="numeric"
- />
- <Gap height={15} />
- <Input
- label="Total Qty Line"
- value={historyEdit.total_qty_line}
- onChangeText={value => changeText('total_qty_line', value)}
- disable
- />
- <Gap height={15} />
- <Input
- label="Quantity Pallet"
- value={historyEdit.total_qty_titik}
- disable
- />
- <Gap height={15} />
- <Input
- label="Quantity Add"
- value={historyEdit.qty_add}
- onChangeText={value => changeText('qty_add', value)}
- keyboardType="numeric"
- />
- <Gap height={15} />
- <Input
- label="Tidak Layak"
- value={historyEdit.tidak_layak}
- onChangeText={value => changeText('tidak_layak', value)}
- disable
- />
- <Gap height={15} />
- <Input
- label="Rusak Karton"
- value={historyEdit.rusak_karton}
- onChangeText={value => changeText('rusak_karton', value)}
- disable
- />
- <Gap height={15} />
- <Input
- label="Total Semua"
- value={historyEdit.total_stock}
- onChangeText={value => changeText('total-stock', value)}
- // value={total.toString()}
- disable
- />
- <View
- style={{
- flexDirection: 'row',
- top: 25,
- marginBottom: 25,
- justifyContent: 'center',
- }}>
- <TouchableOpacity
- style={styles.btnCancel}
- activeOpacity={0.7}
- onPress={cancelBtn}>
- <Text style={styles.textCancel}>Batal</Text>
- </TouchableOpacity>
- <TouchableOpacity
- style={styles.btnSimpanEdit}
- onPress={saveEdit}>
- <Text style={styles.textCancel}>Simpan</Text>
- </TouchableOpacity>
- </View>
- </View>
- </View>
- </ScrollView>
- </Modal>
- </View>
- </View>
- </>
- );
- };
- export default DetailHistorySps;
- const styles = StyleSheet.create({
- dropdownCover: {
- height: 50,
- backgroundColor: '#FFFFFF',
- borderRadius: 8,
- padding: 12,
- shadowColor: '#000',
- shadowOffset: {
- width: 0,
- height: 1,
- },
- borderWidth: 0.4,
- shadowOpacity: 0.2,
- shadowRadius: 1.41,
- elevation: 2,
- },
- selectedTextStyle: {
- fontSize: 16,
- color: 'blue',
- },
- inputSearchStyle: {
- height: 50,
- fontSize: 15,
- fontFamily: fonts.primary[200],
- color: colors.secondary,
- borderColor: colors.secondary,
- borderRadius: 4,
- },
- selectedTextStyle: {
- fontFamily: fonts.primary[200],
- fontSize: 14,
- color: colors.primary,
- },
- btnEdit: {
- backgroundColor: colors.secondary,
- justifyContent: 'center',
- padding: 12,
- width: 120,
- borderRadius: 5,
- marginLeft: 38,
- },
- textEdit: {
- fontSize: 14,
- color: '#FFFFFF',
- textAlign: 'center',
- fontFamily: fonts.primary[300],
- },
- btnCancel: {
- padding: 16,
- width: '45%',
- borderRadius: 5,
- backgroundColor: '#F74D4D',
- alignItems: 'center',
- },
- textCancel: {
- fontSize: 16,
- color: '#FFF',
- fontFamily: fonts.primary[300],
- },
- btnSimpanEdit: {
- padding: 16,
- width: '45%',
- borderRadius: 5,
- backgroundColor: '#39C822',
- alignItems: 'center',
- marginLeft: 15,
- },
- });
Add Comment
Please, Sign In to add comment