import React, { useEffect, useState } from 'react'; import { View, Text, TouchableOpacity, ScrollView, Image, Modal, Platform, StyleSheet, Alert } from 'react-native'; import { useRoute, useNavigation } from '@react-navigation/native'; import { post } from '../../../api/ApiService'; import IMAGES from '../../../constants/Images'; import { GlobalTheme } from '../../../theme'; import Loader from '../../../constants/Loader'; import { SafeAreaView } from 'react-native-safe-area-context'; import { toastError } from '../../../constants/Toast'; const Details = () => { const route = useRoute(); const navigation = useNavigation(); const { selectedDetails = [], storeData, year, month, mainTabIndex } = route.params || {}; const [modalGraphData, setModalGraphData] = useState({}); const [activePromoTab, setActivePromoTab] = useState('Executed'); const [allCatData, setAllCatData] = useState([]) const [selectedCategoryData, setSelectedCategoryData] = useState([]); const [categoryModalVisible, setCategoryModalVisible] = useState(false); useEffect(() => { if (selectedDetails.length > 0) { fetchDetailGraphs(selectedDetails); } }, [selectedDetails]); useEffect(() => { getAllCatData(); }, []) const getAllCatData = () => { let data = { parameters: { projectid: 41654, year: year, monthno: month, storeid: storeData?.StoreId }, } const apiUrl = mainTabIndex === 0 ? 'https://dax.parinaam.in/execute/dabur/detmtd/oos_sku_list_for_all_visits_mtd' : 'https://dax.parinaam.in/execute/dabur/detlsv/oos_sku_list_on_lsv'; post(apiUrl, data) .then(res => { setAllCatData(res?.data); }) .catch(err => { console.log('Error =>', err); }); } const fetchDetailGraphs = async (detailPages) => { try { const resultMap = {}; for (let item of detailPages) { const response = await post(item.GraphUrl, { parameters: { projectid: 41654, year: year, monthno: month, storeid: storeData?.StoreId }, }); resultMap[item.GraphUrl] = response?.data || []; } setModalGraphData(resultMap); } catch (error) { console.log("❌ Error fetching detail graphs:", error); } }; const showCategoryDetails = (data) => { setCategoryModalVisible(!categoryModalVisible) // Filter SKUs from allCatData where the category name matches const filteredCategory = allCatData.filter(item => item.Product_CategoryCategory_Name === data.Product_CategoryCategory_Name ); // Save for display setSelectedCategoryData(filteredCategory); } const isOSATab = selectedDetails.some(item => item.GraphTitle === "OSA - Category"); console.log('isOSATab----',isOSATab); return ( {/* Header */} navigation.goBack()} style={{ padding: 5 }}> Details {selectedDetails && selectedDetails.length > 0 ? selectedDetails.map((detail, index) => { const values = modalGraphData[detail.GraphUrl] || []; if (!modalGraphData[detail.GraphUrl]) { return ( ); } switch (detail.GraphType) { case 'Table': // Check if it's the Promotion table const isPromotionTable = values.length > 0 && values[0].hasOwnProperty('Product_CategoryCategory_Name') && values[0].hasOwnProperty('Promotion_MasterPromotion_Definition'); if (isPromotionTable) { // Filter data based on active tab const filteredValues = values.filter(row => activePromoTab === 'Executed' ? row.Executed?.toLowerCase() === 'yes' : row.Executed?.toLowerCase() === 'no' ); // Group data by Product_CategoryCategory_Name const groupedData = filteredValues.reduce((acc, curr) => { const category = curr.Product_CategoryCategory_Name || 'Unknown'; if (!acc[category]) acc[category] = []; acc[category].push(curr); return acc; }, {}); return ( {/* Horizontal Tabs - show once at top */} {index === 0 && ( // ensures only first promotion table renders the toggle {['Executed', 'Not Executed'].map(tab => { const isSelected = activePromoTab === tab; return ( setActivePromoTab(tab)} style={{ flex: 1, paddingVertical: 10, backgroundColor: isSelected ? '#113F8C' : '#E3EBF8', borderRadius: 8, marginHorizontal: 5, alignItems: 'center', }} > {tab} ); })} )} {/* No data message */} {filteredValues.length === 0 ? ( ) : ( Object.keys(groupedData).map((categoryName, catIdx) => ( {/* Category Header */} {String(categoryName)} {/* Table Header */} Definition Executed {/* Table Rows */} {groupedData[categoryName].map((row, rowIdx) => ( {String(row.Promotion_MasterPromotion_Definition) || '-'} {row.Executed || '-'} ))} )) )} ); } let displayKey = null; let presentKey = null; if (values.length > 0) { const presentKeys = Object.keys(values[0]).filter(k => (typeof values[0][k] === 'string' && ['Yes', 'No'].includes(values[0][k])) || typeof values[0][k] === 'boolean' || typeof values[0][k] === 'number' ); presentKey = presentKeys.length > 0 ? presentKeys[0] : null; const displayKeys = Object.keys(values[0]).filter(k => k !== presentKey && typeof values[0][k] === 'string'); displayKey = displayKeys.length > 0 ? displayKeys[0] : null; } return ( {detail.GraphTitle} {displayKey ? displayKey.replace(/_/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2') : ''} {presentKey ? presentKey.replace(/_/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2') : ''} {values.map((row, idx) => { const presentKeys = Object.keys(row).filter(k => (typeof row[k] === 'string' && ['Yes', 'No'].includes(row[k])) || typeof row[k] === 'boolean' || typeof row[k] === 'number' ); const presentKey = presentKeys.length > 0 ? presentKeys[0] : null; const displayKeys = Object.keys(row).filter(k => k !== presentKey && typeof row[k] === 'string'); const displayKey = displayKeys.length > 0 ? displayKeys[0] : null; return ( {row[displayKey] || '--'} { if (row[presentKey] == 100 || row[presentKey] == '100') { toastError('Alert', 'No Data Available') } else { showCategoryDetails(row) } }} style={{ width: '20%', }}> {presentKey ? ( typeof row[presentKey] === 'string' && ['Yes', 'No'].includes(row[presentKey]) ? row[presentKey] : typeof row[presentKey] === 'boolean' ? (row[presentKey] ? 'Yes' : 'No') : typeof row[presentKey] === 'number' ? row[presentKey].toFixed(2) : row[presentKey] || '-' ) : '-'} { isOSATab && row[presentKey] != 100 || isOSATab && row[presentKey] != '100'? :null} ); })} ); default: return ( Unsupported GraphType: {detail.GraphType} ); } }) : } setCategoryModalVisible(false)} > {/* Header */} {selectedCategoryData[0]?.Product_CategoryCategory_Name || 'Category'} setCategoryModalVisible(false)} style={{ width: '7%', alignItems: 'center' }}> {'Out of Stock SKUs:'} {/* SKU List */} {/* OOS SKU details */} {selectedCategoryData.map((item, idx) => ( {idx + 1}. {item.Product_MasterProduct_Name} {/* {item['#_of_OOS_SKU_for_all_visits']} */} ))} ); }; const styled = StyleSheet.create({ header: { width: '100%', backgroundColor: '#113F8C', padding: 10, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }, categoryHeader: { flexDirection: 'row', justifyContent: 'space-between', backgroundColor: '#EDEDED', paddingVertical: 8, paddingHorizontal: 10, borderTopLeftRadius: 8, borderTopRightRadius: 8, }, itemContainer: { backgroundColor: '#fff', paddingHorizontal: 10, borderBottomLeftRadius: 8, borderBottomRightRadius: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.1, shadowRadius: 2, elevation: 2 } }) export default Details;