Arga_Fauzianto

DetailHistorySps

Dec 5th, 2023
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.37 KB | None | 0 0
  1. import {
  2. FlatList,
  3. SafeAreaView,
  4. StyleSheet,
  5. Text,
  6. View,
  7. TouchableOpacity,
  8. RefreshControl,
  9. } from 'react-native';
  10. import React, {useState, useEffect, useMemo} from 'react';
  11. import {AccordionItem, Button, Gap, Header, Input} from '../../components';
  12. import {colors, fonts, getData, useForm} from '../../utils';
  13. import {IcNotFound} from '../../assets';
  14. import axios from 'axios';
  15. import base64 from 'react-native-base64';
  16. import {Dropdown} from 'react-native-element-dropdown';
  17. import {API_HOST} from '../../config';
  18. import Modal from 'react-native-modal';
  19. import {ScrollView} from 'react-native-gesture-handler';
  20. import {useDispatch, useSelector} from 'react-redux';
  21. import {store} from '../../redux/store';
  22. import {editHistory} from '../../redux/reducer/history';
  23. import {showMessage} from 'react-native-flash-message';
  24.  
  25. // import { TouchableOpacity } from 'react-native-gesture-handler'
  26.  
  27. const DetailHistorySps = ({navigation, route}) => {
  28. const [kodeDepo, setKodeDepo] = useState('001');
  29. const [depoData, setDepoData] = useState([]);
  30. const [dataDepo, setDataDepo] = useState(null);
  31. const [isFocus, setIsFocus] = useState(false);
  32. const [selectedDepo, setSelectedDepo] = useState(null);
  33. const [userProfile, setUserProfile] = useState({});
  34. const [historyData, setHistoryData] = useState([])
  35. const [loading, setLoading] = useState(false)
  36.  
  37. const getDepo = () => {
  38. let username = 'admin';
  39. let adminPassword = 'Databa53';
  40. const authHeader = 'Basic ' + base64.encode(`${username}:${adminPassword}`);
  41. axios
  42. .get(`${API_HOST.url_staging}/depo`, {
  43. headers: {
  44. Authorization: authHeader,
  45. },
  46. })
  47. .then(res => {
  48.  
  49. let count = Object.keys(res.data).length;
  50. let depoArray = [];
  51. for (let i = 0; i < count; i++) {
  52. depoArray.push({
  53. id: res.data[i].kode_depo,
  54. label: res.data[i].depo,
  55.  
  56. });
  57. }
  58. setDepoData(depoArray);
  59. setKodeDepo(res.data[0].id);
  60. setSelectedDepo(depoArray[0].id);
  61. })
  62. .catch(err => {
  63. console.log('gagal', err);
  64. });
  65. }; // mengambil data listing depo
  66.  
  67. useEffect(() => {
  68. getData('userProfile').then(res => {
  69. setUserProfile(res);
  70. });
  71. getDepo();
  72. }, [historyData]);
  73.  
  74. const getEdit = id_stock => {
  75.  
  76. //get data edit ketika tombol edit history di click
  77.  
  78. setIsModalVisible(true);
  79. let username = 'admin';
  80. let adminPassword = 'Databa53';
  81. const authHeader = 'Basic ' + base64.encode(`${username}:${adminPassword}`);
  82.  
  83. axios
  84. .get(`${API_HOST.url_staging}/stock_sps/data_stock/` + id_stock, {
  85. headers: {
  86. Authorization: authHeader,
  87. },
  88. params: {
  89. id_stock,
  90. },
  91. })
  92. .then(res => {
  93. console.log('successs gan": ', res.data.data[0]);
  94. dispatch({
  95. type: 'SET_EDIT_HISTORY',
  96. value: {
  97. id_stock: res.data.data[0].id_stock,
  98. id_line: res.data.data[0].id_line,
  99. titik_pallet: res.data.data[0].titik_pallet,
  100. total_qty_titik: res.data.data[0].total_qty_titik,
  101. total_qty_line: res.data.data[0].total_qty_line,
  102. qty_add: res.data.data[0].qty_add,
  103. tidak_layak: res.data.data[0].tidak_layak,
  104. rusak_karton: res.data.data[0].rusak_karton,
  105. total_stock: res.data.data[0].total_stock,
  106. },
  107. });
  108. })
  109. .catch(err => console.log(err));
  110. };
  111. const [isModalVisible, setIsModalVisible] = useState(false);
  112.  
  113. // const [historyData, setHistoryData] = useState(
  114. // route.params.historyData || [],
  115. // );
  116.  
  117. const dispatch = useDispatch();
  118.  
  119. const historyEdit = useSelector(state => state.historyEditReducer);
  120.  
  121. console.log('returned', historyEdit);
  122.  
  123. //trigger button edit value history
  124. const changeText = (key, value) => {
  125. if (key === 'qty_add' || key === 'total_qty_titik') {
  126. const qtyAdd = parseFloat(value);
  127. const titikPallet = parseFloat(historyEdit.titik_pallet);
  128. const totalQtyLine = parseFloat(historyEdit.total_qty_line);
  129. const totalPallet = parseFloat(historyEdit.total_qty_titik);
  130.  
  131. const totalLine =
  132. !isNaN(totalQtyLine) && !isNaN(titikPallet)
  133. ? totalQtyLine * titikPallet
  134. : 0;
  135.  
  136. const newTotalQtyTitik = !isNaN(totalPallet) ? totalLine : 0;
  137.  
  138. const tidakLayak = parseFloat(historyEdit.tidak_layak) || 0;
  139. const rusakKarton = parseFloat(historyEdit.rusak_karton) || 0;
  140.  
  141. const newTotalStock =
  142. newTotalQtyTitik + tidakLayak + rusakKarton + qtyAdd;
  143.  
  144. dispatch({
  145. type: 'SET_EDIT_HISTORY',
  146. value: {
  147. ...historyEdit,
  148. [key]: value,
  149. total_qty_titik: newTotalQtyTitik.toString(),
  150. total_stock: newTotalStock.toString(),
  151. },
  152. });
  153. } else {
  154. dispatch({
  155. type: 'SET_EDIT_HISTORY',
  156. value: {
  157. ...historyEdit,
  158. [key]: value,
  159. },
  160. });
  161. }
  162. }; //trigger button edit value history
  163.  
  164. //action button batal
  165. const cancelBtn = () => {
  166. return setIsModalVisible(!isModalVisible);
  167. };
  168.  
  169. // simpan hasil edit
  170.  
  171.  
  172. let editCount = 0;
  173. let itemHasBeenEdited = false;
  174.  
  175. const saveEdit = id_stock => {
  176. if (itemHasBeenEdited) {
  177. showMessage({
  178. message: 'This item has already been edited twice. Further edits are not allowed.',
  179. type: 'danger',
  180. hideStatusBar: true,
  181. floating: true,
  182. });
  183. return;
  184. }
  185.  
  186. let username = 'admin';
  187. let adminPassword = 'Databa53';
  188. const authHeader = 'Basic ' + base64.encode(`${username}:${adminPassword}`);
  189.  
  190. const requestData = {
  191. id_stock: historyEdit.id_stock || '',
  192. total_qty_line: historyEdit.total_qty_line || 0,
  193. titik_pallet: historyEdit.titik_pallet || '',
  194. qty_add: historyEdit.qty_add || 0,
  195. total_qty_titik: historyEdit.total_qty_titik || 0,
  196. total_stock: historyEdit.total_stock || 0,
  197. user_insert: userProfile.user_nama || '',
  198. };
  199.  
  200. axios
  201. .put(
  202. `${API_HOST.url_staging}/stock_sps/${historyEdit.id_stock}`,
  203. requestData,
  204. {
  205. headers: {
  206. Authorization: authHeader,
  207. 'Content-Type': 'application/json',
  208. },
  209. params: {
  210. id_stock,
  211. },
  212. },
  213. )
  214. .then(res => {
  215. setIsModalVisible(!isModalVisible);
  216. console.log('berhasil edit: ', res.data);
  217.  
  218. editCount++;
  219.  
  220. if (editCount > 1) {
  221. itemHasBeenEdited = true; // Menandakan bahwa item telah diedit maksimal 2 kali
  222. }
  223.  
  224. if (itemHasBeenEdited) {
  225. const updatedData = historyData.map(item => {
  226. if (item.id_stock === historyEdit.id_stock) {
  227. return {
  228. ...item,
  229. titik_pallet: historyEdit.titik_pallet,
  230. total_stock: historyEdit.total_stock,
  231. rusak_karton: historyEdit.rusak_karton,
  232. qty_add: historyEdit.qty_add,
  233. };
  234. }
  235. return item;
  236. });
  237. setHistoryData(updatedData);
  238. }
  239.  
  240. if(res.data.alert) {
  241. showMessage({
  242. message: res.data.alert.message,
  243. type: 'info',
  244. hideStatusBar: true,
  245. floating: true,
  246. });
  247. } else {
  248. showMessage({
  249. message: res.data.message,
  250. type: 'danger',
  251. hideStatusBar: true,
  252. floating: true,
  253. });
  254. }
  255. })
  256. .catch(err => {
  257. showMessage({
  258. message: res.data.alert.message,
  259. type: 'danger',
  260. backgroundColor: colors.error,
  261. hideStatusBar: true,
  262. floating: true,
  263. });
  264. console.log('gagal edit: ', err);
  265. });
  266. }; // simpan hasil edit
  267.  
  268.  
  269. console.log('historyGan: ', historyData);
  270.  
  271. useEffect(() => {
  272. refreshItem()
  273. }, [depoSelect])
  274.  
  275. const depoSelect = useSelector(state => state.selectReducer);
  276.  
  277. const refreshItem = () => {
  278. let username = 'admin'
  279. let passwordAdmin = 'Databa53'
  280.  
  281. const authHeader = 'Basic ' + base64.encode(`${username}:${passwordAdmin}`);
  282. const today = new Date().toISOString().slice(0, 10);
  283.  
  284. dispatch({type: "SET_LOADING", value: true})
  285.  
  286. axios.get(`${API_HOST.url_staging}/stock_sps/data_history`, {
  287. headers: {
  288. Authorization: authHeader,
  289. 'Content-Type': 'application/json',
  290. },
  291. params: {
  292. type_stock: userProfile.type_user,
  293. id_depo:userProfile.lokasi_id ? userProfile.lokasi_id : kodeDepo, // tadinya depoSelect diganti dengan userProfile dari state
  294. tanggal: today,
  295. },
  296. }).then(res => {
  297. console.log('refresh sukses: ', res.data.data)
  298. const newData = res.data.data || []; // Extract data from the response
  299. setHistoryData(newData);
  300. // setHistoryData(res.data.data)
  301. dispatch({type: 'SET_LOADING', value: false})
  302. setLoading(false)
  303. }).catch(err => {
  304. console.log('refresh error: ', err)
  305. dispatch({type: 'SET_LOADING', value: false})
  306. setLoading(false)
  307. })
  308.  
  309. } // get Data hasil terbaru dengan reresh controll
  310.  
  311. return (
  312. <>
  313. <Header
  314. title="Detail History SPS"
  315. onPress={() => navigation.goBack()}
  316. />
  317. <View
  318. style={{
  319. flex: 1,
  320. top: 10,
  321. paddingHorizontal: 12,
  322. backgroundColor: '#FFFFFF',
  323. }}>
  324. <View style={{flex: 1}}>
  325.  
  326. <>
  327.  
  328. <FlatList
  329. data={historyData}
  330. renderItem={({ item, index }) => {
  331. <AccordionItem
  332. key={index}
  333. id_line={item.line}
  334. title={item.line}
  335. depo={item.depo}
  336. tanggal={item.tanggal}
  337. sku={item.nama_produk}
  338. qty_pallet={item.titik_pallet}
  339. qty_add={item.qty_add}
  340. total={item.total_stock}
  341. rusak_karton={item.rusak_karton}
  342. afkir={item.afkir}
  343. button={
  344. <TouchableOpacity
  345. style={styles.btnEdit}
  346. activeOpacity={0.8}
  347. onPress={() => getEdit(item.id_stock)}>
  348. <Text style={styles.textEdit}>Edit History</Text>
  349. </TouchableOpacity>
  350. }
  351. />
  352. }}
  353. onRefresh={() => refreshItem()}
  354. refreshing={loading}
  355. keyExtractor={(item, index) => index.toString()}
  356. ListEmptyComponent={() => (
  357. <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
  358. <IcNotFound />
  359. <Text style={{ fontFamily: fonts.primary[300], fontSize: 18, color: colors.secondary }}>OPPS BELUM ADA HISTORY YANG ANDA PILIH</Text>
  360. </View>
  361. )}
  362.  
  363. />
  364. {/* <Dropdown
  365. style={styles.dropdownCover}
  366. placeholderStyle={styles.placeholderStyle}
  367. selectedTextStyle={styles.selectedTextStyle}
  368. inputSearchStyle={styles.inputSearchStyle}
  369. search
  370. labelField="label"
  371. valueField="value"
  372. data={depoData}
  373. maxHeight={300}
  374. value={dataDepo}
  375. placeholder={!isFocus ? 'Pilih Depo' : '....'}
  376. searchPlaceholder="Search..."
  377. onChange={item => {
  378. setSelectedDepo(item.id);
  379. // setKodeDepo(item.id);
  380. console.log('select depo: ', item);
  381. dispatch({
  382. type: 'SET_DEPO',
  383. value: {
  384. id_depo: item.id,
  385. },
  386. });
  387. }}
  388. itemTextStyle={{
  389. color: colors.secondary,
  390. fontSize: 13,
  391. fontFamily: fonts.primary[200],
  392. }}
  393. />
  394.  
  395. {historyData.length ? (
  396. historyData.map((item, index) => (
  397. <AccordionItem
  398. key={index}
  399. id_line={item.line}
  400. title={item.line}
  401. depo={item.depo}
  402. tanggal={item.tanggal}
  403. sku={item.nama_produk}
  404. qty_pallet={item.titik_pallet}
  405. qty_add={item.qty_add}
  406. total={item.total_stock}
  407. rusak_karton={item.rusak_karton}
  408. afkir={item.afkir}
  409. button={
  410. <TouchableOpacity
  411. style={styles.btnEdit}
  412. activeOpacity={0.8}
  413. onPress={() => getEdit(item.id_stock)}>
  414. <Text style={styles.textEdit}>Edit History</Text>
  415. </TouchableOpacity>
  416. }
  417. />
  418. ))
  419. ) : (
  420. <>
  421. <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
  422. <IcNotFound />
  423. <Text style={{ fontFamily: fonts.primary[300], fontSize: 18, color: colors.secondary }}>OPPS BELUM ADA HISTORY YANG ANDA PILIH</Text>
  424. </View>
  425. </>
  426. )} */}
  427. </>
  428.  
  429. {/* {historyData.length && (<Text>OPPS BELUM ADA HISTORY</Text>)} */}
  430. </View>
  431.  
  432. <View>
  433. <Modal
  434. isVisible={isModalVisible}
  435. backdropColor="black"
  436. animationIn={'slideInDown'}
  437. animationInTiming={250}
  438. animationOutTiming={200}
  439. animationOut={'slideOutUp'}
  440. backdropOpacity={0.5}
  441. deviceHeight={850}>
  442. <ScrollView showsVerticalScrollIndicator={false} style={{flex: 1}}>
  443. <View
  444. style={{flex: 1, borderRadius: 5, backgroundColor: '#FFFF'}}>
  445. <Text
  446. style={{
  447. fontFamily: fonts.primary[300],
  448. fontSize: 18,
  449. color: colors.secondary,
  450. left: 20,
  451. top: 16,
  452. }}>
  453. Edit History Anda
  454. </Text>
  455. <Gap height={20} />
  456. <View
  457. style={{paddingHorizontal: 16, marginBottom: 25, flex: 1}}>
  458. <Input
  459. label="Line"
  460. value={historyEdit.id_line}
  461. onChangeText={value => changeText('id_line', value)}
  462. disable
  463. />
  464.  
  465. <Gap height={20} />
  466. <Input
  467. label="Id_Stock"
  468. value={historyEdit.id_stock}
  469. onChangeText={value => changeText('id_stock', value)}
  470. disable
  471. />
  472.  
  473. <Gap height={15} />
  474. <Input
  475. label="Titik Pallet"
  476. value={historyEdit.titik_pallet}
  477. onChangeText={value => changeText('titik_pallet', value)}
  478. keyboardType="numeric"
  479. />
  480.  
  481. <Gap height={15} />
  482. <Input
  483. label="Total Qty Line"
  484. value={historyEdit.total_qty_line}
  485. onChangeText={value => changeText('total_qty_line', value)}
  486. disable
  487. />
  488. <Gap height={15} />
  489. <Input
  490. label="Quantity Pallet"
  491. value={historyEdit.total_qty_titik}
  492. disable
  493. />
  494. <Gap height={15} />
  495. <Input
  496. label="Quantity Add"
  497. value={historyEdit.qty_add}
  498. onChangeText={value => changeText('qty_add', value)}
  499. keyboardType="numeric"
  500. />
  501.  
  502. <Gap height={15} />
  503. <Input
  504. label="Tidak Layak"
  505. value={historyEdit.tidak_layak}
  506. onChangeText={value => changeText('tidak_layak', value)}
  507. disable
  508. />
  509.  
  510. <Gap height={15} />
  511. <Input
  512. label="Rusak Karton"
  513. value={historyEdit.rusak_karton}
  514. onChangeText={value => changeText('rusak_karton', value)}
  515. disable
  516. />
  517. <Gap height={15} />
  518. <Input
  519. label="Total Semua"
  520. value={historyEdit.total_stock}
  521. onChangeText={value => changeText('total-stock', value)}
  522. // value={total.toString()}
  523. disable
  524. />
  525. <View
  526. style={{
  527. flexDirection: 'row',
  528. top: 25,
  529. marginBottom: 25,
  530. justifyContent: 'center',
  531. }}>
  532. <TouchableOpacity
  533. style={styles.btnCancel}
  534. activeOpacity={0.7}
  535. onPress={cancelBtn}>
  536. <Text style={styles.textCancel}>Batal</Text>
  537. </TouchableOpacity>
  538. <TouchableOpacity
  539. style={styles.btnSimpanEdit}
  540. onPress={saveEdit}>
  541. <Text style={styles.textCancel}>Simpan</Text>
  542. </TouchableOpacity>
  543. </View>
  544. </View>
  545. </View>
  546. </ScrollView>
  547. </Modal>
  548. </View>
  549. </View>
  550. </>
  551. );
  552. };
  553.  
  554. export default DetailHistorySps;
  555.  
  556. const styles = StyleSheet.create({
  557. dropdownCover: {
  558. height: 50,
  559. backgroundColor: '#FFFFFF',
  560. borderRadius: 8,
  561. padding: 12,
  562. shadowColor: '#000',
  563. shadowOffset: {
  564. width: 0,
  565. height: 1,
  566. },
  567. borderWidth: 0.4,
  568. shadowOpacity: 0.2,
  569. shadowRadius: 1.41,
  570. elevation: 2,
  571. },
  572.  
  573. selectedTextStyle: {
  574. fontSize: 16,
  575. color: 'blue',
  576. },
  577.  
  578. inputSearchStyle: {
  579. height: 50,
  580. fontSize: 15,
  581. fontFamily: fonts.primary[200],
  582. color: colors.secondary,
  583. borderColor: colors.secondary,
  584. borderRadius: 4,
  585. },
  586.  
  587. selectedTextStyle: {
  588. fontFamily: fonts.primary[200],
  589. fontSize: 14,
  590. color: colors.primary,
  591. },
  592.  
  593. btnEdit: {
  594. backgroundColor: colors.secondary,
  595. justifyContent: 'center',
  596. padding: 12,
  597. width: 120,
  598. borderRadius: 5,
  599. marginLeft: 38,
  600. },
  601.  
  602. textEdit: {
  603. fontSize: 14,
  604. color: '#FFFFFF',
  605. textAlign: 'center',
  606. fontFamily: fonts.primary[300],
  607. },
  608.  
  609. btnCancel: {
  610. padding: 16,
  611. width: '45%',
  612. borderRadius: 5,
  613. backgroundColor: '#F74D4D',
  614. alignItems: 'center',
  615. },
  616. textCancel: {
  617. fontSize: 16,
  618. color: '#FFF',
  619. fontFamily: fonts.primary[300],
  620. },
  621.  
  622. btnSimpanEdit: {
  623. padding: 16,
  624. width: '45%',
  625. borderRadius: 5,
  626. backgroundColor: '#39C822',
  627. alignItems: 'center',
  628. marginLeft: 15,
  629. },
  630. });
  631.  
Add Comment
Please, Sign In to add comment