TableChcmDocument.js 15.2 KB
Newer Older
Riri Novita's avatar
Riri Novita committed
1
import React, { Component } from 'react';
Riri Novita's avatar
Riri Novita committed
2 3 4 5 6
import api from "../../api";
import Constant from "../../library/Constant";
import Images from "../../assets/Images";
import ReactTooltip from "react-tooltip";
import PropagateLoader from "react-spinners/PropagateLoader";
Riri Novita's avatar
Riri Novita committed
7
import { createMuiTheme, MuiThemeProvider, Snackbar } from "@material-ui/core";
Riri Novita's avatar
Riri Novita committed
8
import MUIDataTable from "mui-datatables";
Riri Novita's avatar
Riri Novita committed
9
import { withStyles } from "@material-ui/core/styles";
Riri Novita's avatar
Riri Novita committed
10
import MuiAlert from "@material-ui/lab/Alert";
Riri Novita's avatar
Riri Novita committed
11 12
import EditDocumentChcm from './EditDocumentChcm';
import PopUpDelete from "./PopUpDelete";
Riri Novita's avatar
Riri Novita committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable());
const options = ct.customOptionsManagementDocument();

const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);


export default class TableChcmDocument extends Component {

    constructor(props) {
        super(props)
        this.state = {
            dataTable: [],
            visibleCreate: false,
            refresh: '',
            alert: false,
Riri Novita's avatar
Riri Novita committed
31 32
            visibleEdit: false,
            popupDel: false,
Riri Novita's avatar
Riri Novita committed
33 34 35 36 37 38 39 40 41
        }
    }

    componentDidMount() {
        this.getData()
    }

    componentWillReceiveProps(props) {
        // console.log(props);
Riri Novita's avatar
Riri Novita committed
42
        const { refresh } = this.props;
Riri Novita's avatar
Riri Novita committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
        if (props.refresh !== refresh) {
            this.getData()
        }
    }

    getData() {
        let payload = {
            "submenu_id": this.props.submenu_id
        }
        this.setState({ loading: true })
        api.create().getChcmDocumentBySubmenu(payload).then(response => {
            // console.log("table document carfm");
            console.log(response)
            // console.log("table document carfm stop")
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let dataTable = []
                        response.data.data.map((item, index) => {
                            let indexId = this.props.userCompActive.findIndex((val) => val == item.company_id)
Riri Novita's avatar
Riri Novita committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
                            if (indexId !== -1) {
                                dataTable.push([
                                    index,
                                    item.document_name,
                                    item.description,
                                    item.company_name,
                                    item.document_month,
                                    item.document_periode,
                                    item.document_type,
                                    String(Number(item.document_size) / 1000 + ' KB'),
                                    item.created_by,
                                    item.created_at,
                                    item.values,
                                    item.document_id,
                                ])
                            }
Riri Novita's avatar
Riri Novita committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
                        })

                        let docPath = response.data.data.map((item) => {
                            return [
                                item.document_filepath
                            ]
                        })

                        let docId = response.data.data.map((item) => {
                            return [
                                item.document_id
                            ]
                        })

                        // console.log(dataTable)
                        this.setState({ dataTable, docPath, docId, loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    console.log("error di table document getcarfm 1");
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
                }
            } else {
                console.log("error di table document getcarfm 2");
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

Riri Novita's avatar
Riri Novita committed
116
    openPopUp = async (index, val, type) => {
Riri Novita's avatar
Riri Novita committed
117
        console.log(index);
Riri Novita's avatar
Riri Novita committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        
        if (type === "download") {
            try {
                let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/document/download_chcm_document?documentName=${this.state.docPath[val]}&&fileType=${index[6]}`;

                console.log("Fetching URL:", url); // Debugging step

                let response = await fetch(url);

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                let blob = await response.blob();

                if (blob.size > 0) {
                    let downloadUrl = window.URL.createObjectURL(blob);
                    let a = document.createElement("a");
                    a.href = downloadUrl;
                    a.download =
                        (String(index[3]).includes(":")
                            ? String(index[3]).replace(":", " (") + ` )`
                            : String(index[3])) +
                        " - " +
                        index[4] +
                        " - " +
                        index[5] +
                        " - " +
Riri Novita's avatar
Riri Novita committed
146
                        index[1] +
Riri Novita's avatar
Riri Novita committed
147 148 149 150 151 152 153 154 155 156
                        "." +
                        index[6];
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                } else {
                    console.error("Downloaded file is empty.");
                }
            } catch (error) {
                console.error("Download error:", error);
Riri Novita's avatar
Riri Novita committed
157 158
            }
        }
Riri Novita's avatar
Riri Novita committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        if (type === 'delete') {
            this.setState({
                id: this.state.docId[val],
                rowData: index,
                popupDel: true
            })
        }
        if (type === 'edit') {
            this.setState({
                id: this.state.docId[val],
                rowData: index,
                visibleEdit: true
            })
        }
    };

    deleteDoc = (payload) => {
        console.log(payload);

        this.setState({ popupDel: false, loading: true })
        api.create().deleteReportChcm(payload).then(response => {
            console.log(response.data)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        this.getData()
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success', loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    updateDocument(payload) {
        console.log(payload);
        this.setState({ visibleEdit: false, loading: true })
        api.create().updateReportChcm(payload).then(response => {
            // console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        this.getData()
                        this.setState({ konfirmasi: false, alert: true, messageAlert: response.data.message, tipeAlert: 'success', visibleEdit: false, loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
Riri Novita's avatar
Riri Novita committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    }

    closeAlert() {
        this.setState({ alert: false })
    }

    render() {
        let columns = [{
            name: "Action",
            options: {
                filter: false,
                sort: false,
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>

                            {this.props.btndownload && <a data-tip={'Download'} data-for="download">
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 15
                                    }}
                                    onClick={() => this.openPopUp(tableMeta.rowData, val, 'download')}
                                >
                                    <img src={Images.download} />
                                </button>
                            </a>}
Riri Novita's avatar
Riri Novita committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
                            {this.props.btnedit && <a data-tip={'Edit'} data-for="download">
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 15
                                    }}
                                    onClick={() => this.openPopUp(tableMeta.rowData, val, 'edit')}
                                >
                                    <img src={Images.editCopy} />
                                </button>
                            </a>}
                            {this.props.btndelete && <a data-tip={'Delete'} data-for="download">
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 15
                                    }}
                                    onClick={() => this.openPopUp(tableMeta.rowData, val, 'delete')}
                                >
                                    <img src={Images.delete} />
                                </button>
                            </a>}
                            <ReactTooltip border={true} id="delete" place="bottom" type="light" effect="solid" />
Riri Novita's avatar
Riri Novita committed
288 289 290 291 292
                        </div >
                    );
                }
            }
        },
Riri Novita's avatar
Riri Novita committed
293 294 295 296 297 298
        {
            name: "File Name",
            options: {
                display: false
            }
        },
Riri Novita's avatar
Riri Novita committed
299 300
            "Description", "Company Name", "Period Month", "Period Year",
            "Type", "File Size", "Created By", "Created Date",
Riri Novita's avatar
Riri Novita committed
301 302 303 304 305 306 307 308 309 310 311 312
        {
            name: "Category",
            options: {
                display: false
            }
        },
        {
            name: "",
            options: {
                display: false
            }
        },
Riri Novita's avatar
Riri Novita committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        ]

        const loadingComponent = (
            <div style={{ position: 'absolute', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)' }}>
                <PropagateLoader
                    // css={override}
                    size={20}
                    color={"#274B80"}
                    loading={this.state.loading}
                />
            </div>
        );

        return (
            <div style={{ width: '100%' }}>
                {this.props.load && (
                    <div style={{ padding: 25 }}>
                        <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                            <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                                {this.state.messageAlert}
                            </Alert>
                        </Snackbar>
                        {this.state.loading && loadingComponent}
                        <MuiThemeProvider theme={getMuiTheme()}>
                            <MUIDataTable
                                // theme={getMuiTheme()}
                                data={this.state.dataTable}
                                columns={columns}
                                options={options}
                            />
                        </MuiThemeProvider>
                    </div>
                )}
Riri Novita's avatar
Riri Novita committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
                {this.state.visibleEdit && (
                    <EditDocumentChcm
                        type={"edit"}
                        onClickClose={() => this.setState({ visibleEdit: false })}
                        data={this.state.rowData}
                        idoc={this.state.id}
                        updateDocument={this.updateDocument.bind(this)}
                        menuName={this.props.menuName}
                        submenu_id={this.props.submenu_id}
                    />
                )}
                {this.state.popupDel && (
                    <PopUpDelete
                        type={"delete"}
                        onClickClose={() => this.setState({ popupDel: false })}
                        data={this.state.rowData}
                        idoc={this.state.id}
                        // getList={() => this.getData.bind(this)}
                        deleteDoc={this.deleteDoc.bind(this)}
                    />
                )}
Riri Novita's avatar
Riri Novita committed
367 368 369 370 371
            </div>
        )
    }
}