<filename>src/Components/Billing.component.js<gh_stars>1-10
import axios from "axios";
import React, {Component, useEffect} from "react";
import "../css/billing.component.css";
import Cookies from "js-cookie";
import jsPDF from "jspdf";
import "jspdf-autotable";
import Plan from "./Plan.component";
import Dialog from "./DialoguePlans";
import {useDispatch, useSelector} from 'react-redux';
import {open , close} from '../redux/actions/feedback'
import Snackbar from './snackbar.component'
import jwt from "jsonwebtoken"
export default function Billing(props) {
	const dispatch = useDispatch();
	const [bills, setBills] = React.useState([])
	const [show, setShow] = React.useState(false)
	const [plan, setPlan] = React.useState(-1)
	const [open, setOpen] = React.useState(false);
	const [openSnack, setOpenSnack] = React.useState(false);
	const [msg, setMsg] = React.useState("");
	const [sever, setSever] = React.useState("");
	const [amountToPay, setAmount] = React.useState(0);
	const [cantPay, setPay] = React.useState(true); 
	const [token, setToken] = React.useState("")
	const role = jwt.decode(Cookies.get("jwtoken")).role;

	const closeSnack=()=>{
		setOpenSnack(false)
	}
	const openSnackbar = (message, severity)=>{
		setMsg(message);
		setSever(severity);
		setOpenSnack(true)
	}
	useEffect(()=>{
		getBills();
		getInfo();
	}, []) 
	const changePlan = (tier)=> {
		axios
			.put("http://localhost:5000/billing", {
				tier: tier,
				jwt: Cookies.get("jwtoken")
			})
			.then((res) => {
				if(res.status == 200){
					Close();
					getInfo();
				}else if(res.status == 201){

				}
				
			});
	}
	const Close=()=> {
		setOpen(false)
	}
	const OpenPlan=()=> {
		setOpen(true)
	}
	const pay = (bool, Amount)=>{
		console.log(bool);
		console.log(amountToPay == 0)
		console.log(cantPay)
		if(!bool && amountToPay == 0 && cantPay){
			axios.post("https://sandbox.paymee.tn/api/v1/payments/create", 
		{
		 "vendor": 1822,
		 "amount": Amount,
		 "note" : "projectID: "+Cookies.getJSON("projectID")
	   },  {headers: {Authorization: "Token <PASSWORD>"}
	 }).then(res=>{
		 setToken(res.data.data.token)
		 setAmount(res.data.data.amount)
		 setPay(false);
	   }).catch(err=>console.log(err))
		}
	}
	const generatePDF=(amount, tiers) =>{
		const doc = new jsPDF();
		const head = [["plan", "number of days", "amount"]];
		const body = [];
		if (tiers.basic != 0) {
			body.push([
				"basic",
				tiers.basic,
				parseFloat(((80 / 30) * tiers.basic).toFixed(2)),
			]);
		}
		if (tiers.developer != 0) {
			body.push([
				"developer",
				tiers.developer,
				parseFloat(((100 / 30) * tiers.developer).toFixed(2)),
			]);
		}
		if (tiers.pro != 0) {
			body.push([
				"pro",
				tiers.pro,
				parseFloat(((150 / 30) * tiers.pro).toFixed(2)),
			]);
		}
		const head2 = [["total"]];
		const body2 = [[amount]];
		doc.autoTable({
			head: head,
			body: body,
		});
		doc.autoTable({
			head: head2,
			body: body2,
			margin: {left: 170},
			columnStyles: {
				0: {cellWidth: 25},
			},
		});
		doc.save("creometry-facture");
	}
	const getBills=()=> {
		axios
			.get(
				"http://localhost:5000/billing?projectID=&jwt="+Cookies.get("jwtoken")
			)
			.then((res) => {
				if(res.status == 200){
					setBills(res.data);
					setShow(true)

				}else if(res.status == 201){
					
				}
					
			});
	}
	const getInfo=()=> {
		axios
			.get(
				"http://localhost:5000/project?projectID=&jwt="+Cookies.get("jwtoken")
			)
			.then((res) => {
				if(res.status == 200){
					setPlan(res.data.plan[res.data.plan.length - 1].plan)

				}else if(res.status == 201){
					
				}
			});
	}

	
		return (
			<div>
								<Snackbar open={openSnack} message={msg} severity={sever} close={closeSnack} />
				<Dialog
					current={plan}
					open={open}
					close={Close}
					upgrade={changePlan}
				/>
				<div className="row clearfix">
					<div className="col-lg-5 col-md-8">
						<div className="card product-report">
							<div className="header">
								<h2>Current Plan </h2>
							</div>
							<div className="body">
								{plan === -1 ? (
									<div></div>
								) : (
									<div>
										{role == "Editor" || role=="Admin" || role=="Owner"?<Plan
										plan={plan}
										onClick={OpenPlan}
										button="Upgrade"
									/> :<Plan
									plan={plan}
									onClick={OpenPlan}
								/> }
										
									</div>
									
								)}
							</div>
						</div>
					</div>

					<div className="col-lg-7 col-md-4">
						<div className="card product-report">
							<div className="header">
								<h2>Purchase history</h2>
							</div>
							<div className="body">
								<div className="body table-responsive">
									{show ? (
										<table className="table ">
											<thead>
												<tr>
													<th>From</th>
													<th>To</th>
													<th>Amount</th>
													<th>Status</th>
													<th>Export</th>
												</tr>
											</thead>
											<tbody>
												{bills.map((bill, index) => (
													<tr key={index}>
														<td>{bill.first.substring(0, 10)}</td>
														<td>{bill.end.substring(0, 10)}</td>
														<td>{bill.amount}</td>
														<td>{bill.paid ? "paid" : "unpaid"}</td>
															{
															pay(bill.paid,bill.amount)
															}
														<td>
															<i
																className="material-icons icon-blue"
																onClick={() =>
																	generatePDF(bill.amount, bill.tiers)
																}
															>
																file_download
															</i>
														</td>
													</tr>
												))}
											</tbody>
										</table>
									) : (
										<div></div>
									)}
								</div>
								{role == "Editor" || role=="Admin" || role=="Owner"? 
								<div className="row">
								<div className="col-lg-5"></div>
								<form method="post" action="https://sandbox.paymee.tn/gateway/">
										<input type="hidden" name="payment_token" value={token} />
										<input type="hidden" name="url_ok" value="http://localhost:3000/factureOK" />
										<input type="hidden" name="url_ko" value="http://localhost:3000/billing" />
										<button className="button-simple" disabled={cantPay}>
									Pay
								</button>
									</form>
								
								<div className="col-lg-4"></div>
							</div>: <div></div> }
								
							</div>
						</div>
					</div>
				</div>
			</div>
		);
	
}
