Skip to content

Commit

Permalink
claim page properly
Browse files Browse the repository at this point in the history
  • Loading branch information
GraemeFulton committed Jun 4, 2024
1 parent 52d807a commit cc692ef
Show file tree
Hide file tree
Showing 4 changed files with 210 additions and 48 deletions.
5 changes: 5 additions & 0 deletions lib/queries/singleToolById.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export default `
title
slug
content
claimedBy{
data{
id
}
}
link
date
legacyFeaturedImage:legacyMedia{
Expand Down
8 changes: 4 additions & 4 deletions pages/api/post/attachImage.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as formidable from 'formidable';
import axios from 'axios'
import FormData from 'form-data';
// import * as formidable from 'formidable';
// import axios from 'axios'
// import FormData from 'form-data';

import fs from 'fs'
// import fs from 'fs'
import fetch from 'node-fetch'
export const config = {
api: {
Expand Down
73 changes: 73 additions & 0 deletions pages/api/post/claimPost.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { userCheck } from "@/lib/account/userCheck";
import { getIronSession } from "iron-session";

import { sessionOptions } from "@/lib/iron-session/session";
const axios = require("axios");

async function handler(req, res) {
// Check for secret to confirm this is a valid request

//only logged in user can claim
const { userId, user } = userCheck({ req, res });

if (!userId) {
return res.status(401).json({ message: "Unauthorized" });
}

const { postId } = req.body;

if (!postId) {
return res.status(400).json({ message: "postId is required" });
}

try {

// fetch post
let postEndpointConfig = {
method: "get",
url: `${process.env.NEXT_PUBLIC_API_URL}/api/posts/${postId}?populate=claimedBy`,
headers: {
Authorization: `Bearer ${process.env.STRAPI_READONLY_TOKEN}`,
},
};

let postResult = await axios(postEndpointConfig);
let post = postResult.data;

let claims = post?.data?.attributes?.claimedBy?.data?.length? post?.data?.attributes?.claimedBy?.data : [];

//push userId to claims array if not already there
if(!claims?.includes(userId)){
claims.push(userId)
}


let postData = {
claimedBy: claims,
};

let claimPostEndpointConfig = {
method: "put",
url: `${process.env.NEXT_PUBLIC_API_URL}/api/posts/${postId}`,
headers: {
Authorization: `Bearer ${process.env.STRAPI_WRITEABLE_TOKEN}`,
},
data: {
data: { ...postData },
},
};


let claimPostResult = await axios(claimPostEndpointConfig);
return res.status(200).json(claimPostResult.data);
} catch (error) {
console.log(error);
return res.status(500).send("Error claiming post");
}
}

export default async function mainHandler(req, res) {
const session = await getIronSession(req, res, sessionOptions);
req.session = session;
return handler(req, res);
}
172 changes: 128 additions & 44 deletions pages/toolbox/post/[id]/claim.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import Layout from "@/components/new-index/layoutForIndex";
import Container from "@/components/container";
import axios from "axios";
import useUser from '@/lib/iron-session/useUser'
import useUser from "@/lib/iron-session/useUser";
import { useLoad } from "@/components/Jobs/jobHooks";
import Button from "@/components/Primitives/Button";
import { useRouter } from "next/router";
Expand All @@ -13,27 +13,56 @@ import LoginForm from "@/components/sign-in/LoginForm";

// const PRODUCT_ID = 2

export default function ClaimToolPage({data}) {
export default function ClaimToolPage({ data }) {
const [post, setPost] = useState();

const [post, setPost] = useState()
const [isSubmitting, setIsSubmitting] = useState(false);
const [claimedByUser, setClaimedByUser] = useState(false);

useEffect(()=>{
setPost(data?.posts?.data[0])
},[data])


const {user, mutateUser} = useUser({
const { user, mutateUser } = useUser({
// redirectTo: '/',
redirectIfFound: false,
})
});

useEffect(() => {
if (!post) {
setPost(data?.posts?.data[0]);
}

if (data?.posts?.data[0]?.attributes?.claimedBy && user?.id) {
//if the user id exists in claimedByUser.data, then setClaimedByUser to true
setClaimedByUser(
data?.posts?.data[0]?.attributes?.claimedBy?.data?.some(
claimUser => user.id == claimUser?.id
)
);
}
}, [data, user]);

const [isSignUp, setSignUp] = useState(true);

const toggleSignIn = () => {
setSignUp(!isSignUp);
};

const claimTool = async () => {
setIsSubmitting(true);
axios
.post(`/api/post/claimPost`, { postId: post?.id })
.then(res => {
if (res.status === 200) {
alert(
"Claim request sent. You will be notified once the claim is approved."
);
setIsSubmitting(false);
setClaimedByUser(true);
}
})
.catch(err => {
setIsSubmitting(false);
console.log(err);
});
};

return (
<Layout
Expand All @@ -47,52 +76,107 @@ export default function ClaimToolPage({data}) {
}}
activeNav={"toolbox"}
>
<Container maxWidth="max-w-[1320px]">
<Container maxWidth="max-w-[1320px]">
<div className="max-w-[650px] mt-6 mx-auto pt-3 mb-3 p-5 border border-black/10 rounded-xl bg-white">
<img className="rounded rounded-lg shadow-sm border border-gray-100" src={post?.attributes?.legacyFeaturedImage?.logoNew} width={60} height={60}/>
<div className="">
<h1 className="text-xl mb-3 font-bold mt-2">Claim "{post?.attributes?.title}"</h1>
<div className="text-gray-800">
{!user?.isLoggedIn?<p className="mb-2">Please sign in to claim this page.</p>:''}
<p className="mb-2">Once approved as owner, you'll be able to edit the description, images, and see the page stats for this tool.</p>
{user?.isLoggedIn?<p className="mb-2">To claim the page, send a message with the tool name and URL, along with your user name.</p>:''}
</div>
</div>
{(user?.isLoggedIn===true)?
<Button
className="mt-6"
onClick={()=>{
// console.log(user)
// pop up chat
// window.$chatwoot?.setUser(user?.id, {
// claimId: post?.id,
// claimName: post?.attributes?.title,
// });
window.$chatwoot?.toggle()
// window.$chatwoot.popoutChatWindow();
<img
className="rounded rounded-lg shadow-sm border border-gray-100"
src={post?.attributes?.legacyFeaturedImage?.logoNew}
width={60}
height={60}
/>
<div className="">
<h1 className="text-xl mb-3 font-bold mt-2">
Claim "{post?.attributes?.title}"
</h1>
{!claimedByUser ? (
<div className="text-gray-800">
{!user?.isLoggedIn ? (
<p className="mb-2">Please sign in to claim this page.</p>
) : (
""
)}
<p className="mb-2">
Once approved as owner, you'll be able to edit the
description, images, and see the page stats for this tool.
</p>
{user?.isLoggedIn ? (
<p className="mb-2">
To claim the page, send a message with the tool name and
URL, along with your user name.
</p>
) : (
""
)}
</div>
) : null}
</div>
{user?.isLoggedIn === true && !claimedByUser ? (
<Button
className="mt-6 rounded-full"
onClick={claimTool}
type="button"
>
{isSubmitting ? <Spinner size="sm" /> : "Claim now"}
</Button>
) : claimedByUser ? (
<>
<p className="text-gray-800 mt-6">
✅ You have claimed this page. You will be notified once the claim
is approved.
</p>
<p className="text-gray-800 mt-1">
💬 Please contact support if you need any more help.
</p>
<Button
className="mt-6 rounded-full"
onClick={() => {
// console.log(user)
// pop up chat
// window.$chatwoot?.setUser(user?.id, {
// claimId: post?.id,
// claimName: post?.attributes?.title,
// });
window.$chatwoot?.toggle();
// window.$chatwoot.popoutChatWindow();

// woot-widget-bubble
}} type="button">Ask support</Button>:''}
// woot-widget-bubble
}}
type="button"
>
Ask support
</Button>
</>
) : (
""
)}
</div>

{!(user?.isLoggedIn===true)?
<div className="w-full relative max-w-4xl mx-auto ">
{!(user?.isLoggedIn === true) ? (
<div className="w-full relative max-w-4xl mx-auto ">
<div
className="w-full bg-white mt-6 border border-gray-300/70 mb-20 pt-20 shadow-sm pb-20 rounded-xl flex justify-center mx-auto"
style={{ maxWidth: 650 }}
>
<LoginForm isSignUp={isSignUp} user={user} toggleSignIn={toggleSignIn} />
<LoginForm
isSignUp={isSignUp}
user={user}
toggleSignIn={toggleSignIn}
/>
</div>
</div>:''}
</div>
) : (
""
)}
</Container>
</Layout>
);
}

export async function getServerSideProps({ params, preview = null, locale }) {

const data = await getToolById(params.id, preview);
return { props: {
data
} };
}
const data = await getToolById(params.id, preview);
return {
props: {
data,
},
};
}

0 comments on commit cc692ef

Please sign in to comment.