| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429 | import React, { Component } from "react";import { Row, Col, Card, CardBody, FormGroup, Input, Button, Progress } from "reactstrap";import { toast } from "react-toastify";import { Formik, Form, Field, ErrorMessage } from "formik";import * as Yup from "yup";import { connect } from "react-redux";import { getOneSanksi, update } from "@/actions/sanksi";import DatePicker from "react-datepicker";import "react-datepicker/dist/react-datepicker.css";import { addDays, addMonths } from 'date-fns';import id from 'date-fns/locale/id';import moment from "moment";import 'moment/min/locales';moment.locale('id');import Router from "next/router";import { getPelanggaranSanksi } from "@/actions/pelanggaran";import Select from "react-select";import { getCsrf } from "../../actions/security";import Swal from "sweetalert2";const selectInstanceId = 1;const checkIfFilesAreTooBig = (files) => {    let valid = true;    if (files) {        files.map((file) => {            if (file.size > 15 * 1024 * 1024) {                valid = false;            }        });    }    return valid;};const checkIfFilesAreCorrectType = (files) => {    let valid = true;    if (files) {        files.map((file) => {            if (!["image/jpeg", "image/png"].includes(file.type)) {                valid = false;            }        });    }    return valid;};const rekomendasiSchema = Yup.object().shape({    no_sanksi: Yup.string().required("Wajib isi Nomor Sanksi"),    keterangan: Yup.string().min(3, "Minimal 3 Huruf").max(200).required("Wajib isi keterangan"),    from_date: Yup.date().required("Wajib diisi"),    to_date: Yup.date().notRequired("Wajib diisi"),    sanksi: Yup.array().required("Wajib isi pelanggaran"),    dokumen: Yup.array().required("Wajib diisi").test("filesize", "Maksimal ukuran dokumen 15mb", checkIfFilesAreTooBig),});let Dropzone = null;const level_sanksi = {    "Sanksi Administratif Ringan": 1,    "Sanksi Administratif Sedang": 2,    "Sanksi Administratif Berat": 3,}class DropzoneWrapper extends Component {    state = {        isClient: false,    };    componentDidMount = () => {        Dropzone = require("react-dropzone").default;        this.setState({ isClient: true });    };    render() {        return Dropzone ? <Dropzone {...this.props}>{this.props.children}</Dropzone> : null;    }}class InputTanggal extends Component {    constructor(props) {        super(props);        const tmt_awal = new Date();        this.state = {            dropdownOpen: false,            splitButtonOpen: false,            files: [],            sanksi: {},            data: {},            from_date: "",            to_date: "",            startDay: tmt_awal,            keteranganLaporan: "",            tmtCheck: false,            listSanksi: "",            selectedFile: {}        };    }    async componentDidMount() {        const { token, query } = this.props;        const { id } = query;        const sanksi = await getOneSanksi(token, id);        const { data: listSanksi } = await getPelanggaranSanksi(token, { down: true })        this.setState({ sanksi, listSanksi })    }    toggleSplit = () => {        this.setState({            splitButtonOpen: !this.state.splitButtonOpen,        });    };    toggleDropDown = () => {        this.setState({            dropdownOpen: !this.state.dropdownOpen,        });    };    onDrop = (selectedFile) => {        this.setState({            selectedFile: selectedFile.map((file) =>                Object.assign(file, {                    preview: URL.createObjectURL(file),                })            ),            stat: "Added " + selectedFile.length + " file(s)",        });        const selectFile = this.state.selectedFile        this.setState(prevState => ({            files: [...prevState.files, ...selectFile]        }))    };    uploadFiles = (e) => {        e.preventDefault();        e.stopPropagation();        this.setState({            stat: this.state.files.length ? "Dropzone ready to upload " + this.state.files.length + " file(s)" : "No files added.",        });    };    clearFiles = (e) => {        e.preventDefault();        e.stopPropagation();        this.setState({            stat: this.state.files.length ? this.state.files.length + " file(s) cleared." : "No files to clear.",        });        this.setState({            files: [],        });    };    static getInitialProps = async ({ query }) => {        return { query };    };    setKeteranganPelaporan = (e) => {        this.setState({ keteranganLaporan: e.target.value });    };    handleTmtCheck = () => {        this.setState({ tmtCheck: !this.state.tmtCheck });    };    handelSimpan = async (data) => {        if (this.props.user.role.id === 2024) {            Swal.fire({                icon: 'error',                title: 'Oops...',                html: 'Maaf anda tidak memiliki akses untuk menyelesaikan<p> proses ini.</p>',                confirmButtonColor: "#3e3a8e",                confirmButtonText: 'Oke'            })        } else {            const getToken = await getCsrf();            const _csrf = getToken.token;            const { token, query } = this.props;            const { id } = query;            const formdata = new FormData();            formdata.append("no_sanksi", data.no_sanksi);            formdata.append("keterangan", data.keterangan);            formdata.append("from_date", data.from_date);            formdata.append("to_date", data.to_date);            formdata.append("sanksi", JSON.stringify(data.sanksi.map((e) => ({ label: e.value.split(";")[0], description: e.value.split(";")[1], level: e.value.split(";")[2] }))));            this.state.files.forEach((e) => {                formdata.append("dokumen", e);            });            const toastid = toast.loading("Please wait...");            const added = await update(token, id, formdata, _csrf);            if (!added) {                toast.update(toastid, { render: "All is not good", type: "error", isLoading: false, autoClose: true, closeButton: true });            } else {                toast.update(toastid, { render: "All is good", type: "success", isLoading: false, autoClose: true, closeButton: true });                Router.push("/app/turun-sanksi");            }        }    };    render() {        const { files } = this.state;        const removeFile = file => () => {            const newFiles = [...files]            newFiles.splice(newFiles.indexOf(file), 1)            this.setState({                files: newFiles,            });        }        const thumbs = files.map((file, index) => (            <p>                <em className="far fa-file" />  {file.name}                <button className="bg-transparent button-transparent border-0 fas fa-trash text-danger float-right" onClick={removeFile(file)} />            </p>        ));        return (            <Card className="card-default">                <CardBody>                    <p className="lead bb">Dokumen Surat Turun Sanksi</p>                    <Formik                        initialValues={{                            no_sanksi: "",                            keterangan: "",                            from_date: "",                            to_date: "",                            sanksi: [],                            dokumen: [],                        }}                        validationSchema={rekomendasiSchema}                        onSubmit={this.handelSimpan}                    >                        {({ isSubmitting }) => (                            <Form className="form-horizontal">                                <FormGroup row>                                    <label className="col-md-2 col-form-label">Nomor Surat</label>                                    <div className="col-md-10">                                        <Field name="no_sanksi">{({ field }) => <Input type="textarea" placeholder="Nomor Surat" {...field} />}</Field>                                        <ErrorMessage name="no_sanksi" component="div" className="form-text text-danger" />                                    </div>                                </FormGroup>                                <FormGroup row>                                    <label className="col-md-2 col-form-label">Keterangan</label>                                    <div className="col-md-10">                                        <Field name="keterangan">{({ field }) => <Input type="textarea" placeholder="Keterangan" {...field} />}</Field>                                        <ErrorMessage name="keterangan" component="div" className="form-text text-danger" />                                    </div>                                </FormGroup>                                <FormGroup row>                                    <label className="col-md-2 col-form-label">Tidak Perlu TMT</label>                                    <div className="col-md-10 mt-2">                                        <div className="checkbox c-checkbox">                                            <label>                                                <Input type="checkbox" onChange={this.handleTmtCheck} defaultChecked={this.state.tmtCheck} />                                                <span className="fa fa-check"></span></label>                                        </div>                                    </div>                                </FormGroup>                                {this.state.tmtCheck && (                                    <FormGroup row className="mt-3">                                        <label className="col-md-2 col-form-label">Tanggal Penetapan Sanksi</label>                                        <span className="col-sm-3 float-left">                                            <Field name="from_date">                                                {({ field, form }) => (                                                    <DatePicker                                                        selected={this.state.from_date}                                                        onChange={(from_date) => {                                                            this.setState({ from_date })                                                            form.setFieldValue(field.name, from_date);                                                        }}                                                        dateFormat="dd/MM/yyyy"                                                        maxDate={this.state.startDay}                                                        placeholderText="Dari Tanggal"                                                        locale={id}                                                        className="form-control bg-white"                                                    />                                                )}                                            </Field>                                            <ErrorMessage name="from_date" component="div" className="form-text text-danger" />                                        </span>                                    </FormGroup>                                )}                                {!this.state.tmtCheck && (                                    <FormGroup row className="mt-3">                                        <label className="col-md-2 col-form-label">Isi TMT :</label>                                        <div className="col-md-6">                                            <Row >                                                <Col>                                                    <FormGroup>                                                        <Field name="from_date">                                                            {({ field, form }) => (                                                                <DatePicker                                                                    selected={this.state.from_date}                                                                    onChange={(from_date) => {                                                                        this.setState({ from_date })                                                                        form.setFieldValue(field.name, from_date);                                                                    }}                                                                    dateFormat="dd/MM/yyyy"                                                                    maxDate={this.state.startDay}                                                                    placeholderText="Dari Tanggal"                                                                    locale={id}                                                                    className="form-control bg-white"                                                                />                                                            )}                                                        </Field>                                                        <ErrorMessage name="from_date" component="div" className="form-text text-danger" />                                                    </FormGroup>                                                </Col>                                                <Col>                                                    <FormGroup>                                                        <Field name="to_date">                                                            {({ field, form }) => (                                                                <DatePicker                                                                    selected={this.state.to_date}                                                                    onChange={(to_date) => {                                                                        this.setState({ to_date })                                                                        form.setFieldValue(field.name, to_date);                                                                    }}                                                                    dateFormat="dd/MM/yyyy"                                                                    minDate={this.state.from_date}                                                                    maxDate={addMonths(new Date(this.state.from_date), 6)}                                                                    placeholderText="Sampai tanggal"                                                                    locale={id}                                                                    className="form-control bg-white"                                                                />                                                            )}                                                        </Field>                                                        <ErrorMessage name="to_date" component="div" className="form-text text-danger" />                                                    </FormGroup>                                                </Col>                                            </Row>                                        </div>                                    </FormGroup>                                )}                                {!this.state.tmtCheck && (                                    <FormGroup row className="mt-1">                                        <label className="col-md-2 col-form-label">TMT berlaku</label>                                        <div className="col-md-10 mt-2">                                            <b>{this.state.from_date ? moment(this.state.from_date).format("DD-MM-YYYY") : "-"}</b> hingga <b>{this.state.to_date ? moment(this.state.to_date).format("DD-MM-YYYY") : "-"}</b>                                        </div>                                    </FormGroup>                                )}                                {!this.state.tmtCheck && (                                    <FormGroup row className="mt-1">                                        <label className="col-md-2 col-form-label">TMT</label>                                        <div className="col-md-10 mt-2">                                            <b>{this.state.to_date ? moment(this.state.to_date).diff(this.state.from_date, 'month') : "-"} bulan</b>                                        </div>                                    </FormGroup>                                )}                                <FormGroup row className="mt-3">                                    <label className="col-md-2 col-form-label">List sanksi </label>                                    <div className="col-md-10">                                        <Field name="sanksi">{({ field, form }) => <Select                                            options={this.props.listSanksi.map(e => ({ value: e, label: `Sanksi Administratif ${e.split(";")[0]} - ${e.split(";")[1]}` }))}                                            isMulti                                            onChange={(e) => {                                                form.setFieldValue(field.name, e);                                            }}                                        />}</Field>                                        <ErrorMessage name="sanksi" component="div" className="form-text text-danger" />                                    </div>                                </FormGroup>                                <FormGroup row className="mt-3">                                    <label className="col-md-2 col-form-label">Dokumen Perubahan sanksi : <span className="text-danger">*</span></label>                                    <div className="col-md-10">                                        <Field name="dokumen">                                            {({ field, form }) => (                                                <DropzoneWrapper                                                    className=""                                                    onDrop={(e) => {                                                        this.onDrop(e);                                                        form.setFieldValue(field.name, e);                                                    }}                                                >                                                    {({ getRootProps, getInputProps, isDragActive }) => {                                                        return (                                                            <div {...getRootProps()} className={"dropzone card" + (isDragActive ? "dropzone-drag-active" : "")}>                                                                <input {...getInputProps()} />                                                                <div className="dropzone-previews flex">                                                                    <div className="dropzone-style-1">                                                                        <div className="center-ver-hor dropzone-previews flex">{this.state.files.length > 0 ?                                                                            <div className="text-center fa-2x icon-cloud-upload mr-2 ">                                                                                <h5 className="text-center dz-default dz-message">Klik untuk tambah file</h5>                                                                            </div> :                                                                            <div className="text-center fa-2x icon-cloud-upload mr-2 ">                                                                                <h5 className="text-center dz-default dz-message">Upload dokumen rekomendasi delegasi</h5>                                                                            </div>                                                                        }                                                                        </div>                                                                    </div>                                                                </div>                                                                <div className="d-flex align-items-center">                                                                    <small className="ml-auto">                                                                        <button                                                                            type="button"                                                                            className="btn btn-link"                                                                            onClick={(e) => {                                                                                this.clearFiles(e);                                                                                form.setFieldValue(field.name, []);                                                                            }}                                                                        >                                                                            Reset dokumen                                                                        </button>                                                                    </small>                                                                </div>                                                            </div>                                                        );                                                    }}                                                </DropzoneWrapper>                                            )}                                        </Field>                                        <div>                                            {thumbs}                                        </div>                                    </div>                                </FormGroup>                                <FormGroup row>                                    <div className="col-xl-10">                                        <Button color className="color-3e3a8e btn-login" type="submit" disabled={isSubmitting}>                                            <span className="font-color-white">Kirim</span>                                        </Button>                                    </div>                                </FormGroup>                            </Form>                        )}                    </Formik>                </CardBody>            </Card>        );    }}const mapStateToProps = (state) => ({ user: state.user, token: state.token });export default connect(mapStateToProps)(InputTanggal);
 |