Added redemptions & redeemable actions. Fixed a few bugs.

This commit is contained in:
Tom
2024-06-24 22:16:55 +00:00
parent 68df045c54
commit 6548ce33e0
35 changed files with 1787 additions and 471 deletions

View File

@ -0,0 +1,316 @@
import axios from "axios";
import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Label } from "../ui/label";
import { Maximize2, Minimize2, Trash2Icon } from "lucide-react";
import { ActionType } from "@prisma/client";
const actionTypes = [
{
"name": "Overwrite local file content",
"value": ActionType.WRITE_TO_FILE
},
{
"name": "Append to local file",
"value": ActionType.APPEND_TO_FILE
},
{
"name": "Cause a transformation on OBS scene item",
"value": ActionType.OBS_TRANSFORM
},
{
"name": "Play an audio file locally",
"value": ActionType.AUDIO_FILE
},
]
interface RedeemableAction {
name: string
type: string | undefined
data: { [key: string]: string }
edit?: boolean
showEdit?: boolean
isNew: boolean
obsTransformations: { label: string, placeholder: string, description: string }[]
adder: (name: string, type: ActionType, data: { [key: string]: string }) => void
remover: (action: { name: string, type: string, data: any }) => void
}
const RedemptionAction = ({
name,
type,
data,
edit,
showEdit = true,
isNew = false,
obsTransformations = [],
adder,
remover
}: RedeemableAction) => {
const [open, setOpen] = useState(false)
const [actionName, setActionName] = useState(name)
const [actionType, setActionType] = useState<{ name: string, value: ActionType } | undefined>(actionTypes.find(a => a.value == type?.toUpperCase()))
const [actionData, setActionData] = useState<{ [key: string]: string }>(data)
const [isEditable, setIsEditable] = useState(edit)
const [isMinimized, setIsMinimized] = useState(!isNew)
const [oldData, setOldData] = useState<{ n: string, t: ActionType | undefined, d: { [k: string]: string } } | undefined>(undefined)
function Save(name: string, type: ActionType | undefined, data: { [key: string]: string }, isNew: boolean) {
// TODO: validation
if (!name) {
return
}
if (!type) {
return
}
if (!data) {
return
}
let info: any = {
name,
type
}
info = { ...info, ...data }
if (isNew) {
axios.post("/api/settings/redemptions/actions", info)
.then(d => {
adder(name, type, data)
setActionName("")
setActionType(undefined)
setActionData({})
})
} else {
axios.put("/api/settings/redemptions/actions", info)
.then(d => {
setIsEditable(false)
})
}
}
function Cancel(data: { n: string, t: ActionType | undefined, d: { [k: string]: string } } | undefined) {
if (!data)
return
setActionName(data.n)
setActionType(actionTypes.find(a => a.value == data.t))
setActionData(data.d)
setIsEditable(false)
setOldData(undefined)
}
function Delete() {
axios.delete("/api/settings/redemptions/actions?action_name=" + name)
.then(d => {
remover(d.data)
})
}
return (
<div
className="bg-orange-300 p-3 border-2 border-orange-400 rounded-lg w-[830px]">
{isMinimized &&
<div
className="flex">
<Label
className="mr-2 grow text-lg align-middle"
htmlFor="name">
{actionName}
</Label>
<Button
className="flex inline-block self-end"
onClick={e => setIsMinimized(!isMinimized)}>
{isMinimized ? <Maximize2 /> : <Minimize2 />}
</Button>
</div>
|| !isMinimized &&
<div>
<div
className="pb-3">
<Label
className="mr-2"
htmlFor="name">
Action name
</Label>
<Input
className="inline-block w-[300px]"
id="name"
placeholder="Enter a name for this action"
onChange={e => setActionName(e.target.value)}
value={actionName}
readOnly={!isNew} />
<Label
className="ml-10 mr-2"
htmlFor="type">
Action type
</Label>
{!isEditable &&
<Input
className="inline-block w-[300px] justify-between"
name="type"
value={actionType?.name}
readOnly />
|| isEditable &&
<Popover
open={open}
onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-[300px] justify-between"
>{!actionType ? "Select one..." : actionType.name}</Button>
</PopoverTrigger>
<PopoverContent>
<Command>
<CommandInput
placeholder="Filter actions..."
autoFocus={true} />
<CommandList>
<CommandEmpty>No action found.</CommandEmpty>
<CommandGroup>
{actionTypes.map((action) => (
<CommandItem
value={action.name}
key={action.value}
onSelect={(value) => {
setActionType(actionTypes.find(v => v.name.toLowerCase() == value.toLowerCase()))
setOpen(false)
}}>
{action.name}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
}
</div>
<div>
{actionType && (actionType.value == ActionType.WRITE_TO_FILE || actionType.value == ActionType.APPEND_TO_FILE) &&
<div>
<Label
className="mr-2"
htmlFor="file_path">
File path
</Label>
<Input
className="w-[300px] justify-between inline-block"
name="file_path"
placeholder={actionType.value == ActionType.WRITE_TO_FILE ? "Enter the local file path to the file to overwrite" : "Enter the local file path to the file to append to"}
value={actionData["file_path"]}
onChange={e => setActionData({ ...actionData, "file_path": e.target.value })}
readOnly={!isEditable} />
<Label
className="ml-10 mr-2"
htmlFor="file_content">
File content
</Label>
<Input
className="w-[300px] justify-between inline-block"
name="file_content"
placeholder="Enter the content that should be written"
value={actionData["file_content"]}
onChange={e => setActionData({ ...actionData, "file_content": e.target.value })}
readOnly={!isEditable} />
</div>
}
{actionType && actionType.value == ActionType.OBS_TRANSFORM &&
<div>
{obsTransformations.map(t =>
<div
className="mt-3">
<Label
className="mr-2"
htmlFor={t.label.toLowerCase()}>
{t.label.split("_").map(w => w.substring(0, 1).toUpperCase() + w.substring(1).toLowerCase()).join(" ")}
</Label>
<Input
className="w-[300px] justify-between inline-block"
name={t.label.toLowerCase()}
placeholder={t.placeholder}
value={actionData[t.label]}
onChange={e => {
let c = { ...actionData }
c[t.label] = e.target.value
setActionData(c)
}}
readOnly={!isEditable} />
</div>
)}
</div>
}
{actionType && actionType.value == ActionType.AUDIO_FILE &&
<div>
<Label
className="mr-2"
htmlFor="file_path">
File path
</Label>
<Input
className="w-[300px] justify-between inline-block"
name="file_path"
placeholder={"Enter the local file path where the audio file is at"}
value={actionData["file_path"]}
onChange={e => setActionData({ ...actionData, "file_path": e.target.value })}
readOnly={!isEditable} />
</div>
}
</div>
<div>
{isEditable &&
<Button
className="m-3"
onClick={() => Save(actionName, actionType?.value, actionData, isNew)}>
{isNew ? "Add" : "Save"}
</Button>
}
{isEditable && !isNew &&
<Button
className="m-3"
onClick={() => Cancel(oldData)}>
Cancel
</Button>
}
{showEdit && !isEditable &&
<Button
className="m-3"
onClick={() => {
setOldData({ n: actionName, t: actionType?.value, d: actionData })
setIsEditable(true)
}}>
Edit
</Button>
}
{!isEditable &&
<Button
className="m-3 bg-red-500 hover:bg-red-600 align-bottom"
onClick={() => Delete()}>
<Trash2Icon />
</Button>
}
{!isNew &&
<Button
className="m-3 align-middle"
onClick={e => setIsMinimized(!isMinimized)}>
{isMinimized ? <Maximize2 /> : <Minimize2 />}
</Button>
}
</div>
</div>
}
</div>
);
}
export default RedemptionAction;

View File

@ -0,0 +1,274 @@
import axios from "axios";
import { useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Label } from "../ui/label";
import { HelpCircleIcon, Trash2Icon } from "lucide-react";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "../ui/tooltip"
interface Redemption {
id: string | undefined
redemptionId: string | undefined
actionName: string
edit: boolean
showEdit: boolean
isNew: boolean
actions: string[]
twitchRedemptions: { id: string, title: string }[]
adder: (id: string, actionName: string, redemptionId: string, order: number) => void
remover: (redemption: { id: string, redemptionId: string, actionName: string, order: number }) => void
}
const OBSRedemption = ({
id,
redemptionId,
actionName,
edit,
showEdit,
isNew,
actions,
twitchRedemptions,
adder,
remover
}: Redemption) => {
const [actionOpen, setActionOpen] = useState(false)
const [redemptionOpen, setRedemptionOpen] = useState(false)
const [twitchRedemption, setTwitchRedemption] = useState<{ id: string, title: string } | undefined>(undefined)
const [action, setAction] = useState<string | undefined>(actionName)
const [order, setOrder] = useState<number>(0)
const [isEditable, setIsEditable] = useState(edit)
const [oldData, setOldData] = useState<{ r: { id: string, title: string } | undefined, a: string | undefined, o: number } | undefined>(undefined)
useEffect(() => {
console.log("TR:", twitchRedemptions, redemptionId, twitchRedemptions.find(r => r.id == redemptionId))
setTwitchRedemption(twitchRedemptions.find(r => r.id == redemptionId))
}, [])
function Save() {
// TODO: validation
if (!isNew && !id)
return
if (!action || !twitchRedemption)
return
if (isNew) {
axios.post("/api/settings/redemptions", {
actionName: action,
redemptionId: twitchRedemption?.id,
order: order,
state: true
}).then(d => {
adder(d.data.id, action, twitchRedemption.id, 0)
setAction(undefined)
setTwitchRedemption(undefined)
setOrder(0)
})
} else {
axios.put("/api/settings/redemptions", {
id: id,
actionName: action,
redemptionId: twitchRedemption?.id,
order: order,
state: true
}).then(d => {
setIsEditable(false)
})
}
}
function Cancel() {
if (!oldData)
return
setAction(oldData.a)
setTwitchRedemption(oldData.r)
setOrder(oldData.o)
setIsEditable(false)
setOldData(undefined)
}
function Delete() {
axios.delete("/api/settings/redemptions?id=" + id)
.then(d => {
remover(d.data)
})
}
return (
<div
className="bg-orange-300 p-5 border-2 border-orange-400 rounded-lg w-[830px]">
<div
className="pb-4">
<Label
className="mr-2"
htmlFor="redemption">
Twitch Redemption
</Label>
{!isEditable &&
<Input
className="inline-block w-[290px] justify-between"
name="redemption"
value={twitchRedemption?.title}
readOnly />
|| isEditable &&
<Popover
open={redemptionOpen}
onOpenChange={setRedemptionOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={actionOpen}
className="w-[290px] justify-between"
>{!twitchRedemption ? "Select one..." : twitchRedemption.title}</Button>
</PopoverTrigger>
<PopoverContent>
<Command>
<CommandInput
placeholder="Filter redemptions..."
autoFocus={true} />
<CommandList>
<CommandEmpty>No redemption found.</CommandEmpty>
<CommandGroup>
{twitchRedemptions.map((redemption) => (
<CommandItem
value={redemption.title}
key={redemption.id}
onSelect={(value) => {
setTwitchRedemption(twitchRedemptions.find(v => v.title.toLowerCase() == value.toLowerCase()))
setRedemptionOpen(false)
}}>
{redemption.title}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
}
<Label
className="ml-10 mr-2"
htmlFor="action">
Action
</Label>
{!isEditable &&
<Input
className="inline-block w-[290px] justify-between"
name="action"
value={action}
readOnly />
|| isEditable &&
<Popover
open={actionOpen}
onOpenChange={setActionOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={actionOpen}
className="w-[290px] justify-between">
{!action ? "Select one..." : action}
</Button>
</PopoverTrigger>
<PopoverContent>
<Command>
<CommandInput
placeholder="Filter actions..."
autoFocus={true} />
<CommandList>
<CommandEmpty>No action found.</CommandEmpty>
<CommandGroup>
{actions.map((action) => (
<CommandItem
value={action}
key={action}
onSelect={(value) => {
let a = actions.find(v => v == action)
if (a)
setAction(a)
setActionOpen(false)
}}>
{action}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
}
</div>
<div
className="pb-4">
<Label
className="mr-2"
htmlFor="order">
Order
</Label>
<Input
className="inline-block w-[300px]"
id="name"
placeholder="Enter an order number for this action"
onChange={e => setOrder(e.target.value.length == 0 ? 0 : parseInt(e.target.value))}
value={order}
readOnly={!isEditable} />
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<HelpCircleIcon
className="inline-block ml-3"/>
</TooltipTrigger>
<TooltipContent>
<p>This decides when this action will be done relative to other actions for this Twitch redemption.<br/>
Action start from lowest to highest order number.<br/>
Equal order numbers cannot be guaranteed proper order.</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<div>
{isEditable &&
<Button
className="m-3"
onClick={() => Save()}>
{isNew ? "Add" : "Save"}
</Button>
}
{isEditable && !isNew &&
<Button
className="m-3"
onClick={() => Cancel()}>
Cancel
</Button>
}
{showEdit && !isEditable &&
<Button
className="m-3"
onClick={() => {
setOldData({ a: actionName, r: twitchRedemption, o: order })
setIsEditable(true)
}}>
Edit
</Button>
}
{!isEditable &&
<Button
className="m-3 bg-red-500 hover:bg-red-600 align-bottom"
onClick={() => Delete()}>
<Trash2Icon />
</Button>
}
</div>
</div>
);
}
export default OBSRedemption;

View File

@ -13,110 +13,104 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "
const AdminProfile = () => {
const session = useSession();
const [impersonation, setImpersonation] = useState<string | null>(null)
const [open, setOpen] = useState(false)
const session = useSession();
const [impersonation, setImpersonation] = useState<string | null>(null)
const [open, setOpen] = useState(false)
const [users, setUsers] = useState<User[]>([])
const [users, setUsers] = useState<User[]>([])
useEffect(() => {
const fetch = async (userId: string | undefined) => {
if (!userId) return
useEffect(() => {
const fetch = async (userId: string | undefined) => {
if (!userId) return
await axios.get("/api/users?id=" + userId)
.then(u => setImpersonation(u.data?.name))
}
await axios.get<User>("/api/users?id=" + userId)
.then(u => {
setImpersonation(u.data?.name)
})
const fetchUsers = async () => {
await axios.get<User[]>("/api/users")
.then((u) => {
setUsers(u.data.filter(x => x.id != session.data?.user.id))
})
}
fetch(session?.data?.user?.impersonation?.id)
fetchUsers()
}, [])
const onImpersonationChange = async (userId: string, name: string) => {
console.log("IMPERSONATION", impersonation)
if (impersonation) {
if (impersonation == name) {
await axios.delete("/api/account/impersonate")
.then(() => {
setImpersonation(null)
window.location.reload()
})
} else {
await axios.put("/api/account/impersonate", { targetId: userId })
.then(() => {
setImpersonation(name)
window.location.reload()
})
}
} else {
await axios.post("/api/account/impersonate", { targetId: userId })
.then(() => {
setImpersonation(name)
window.location.reload()
})
}
}
console.log(session)
fetch(session?.data?.user?.impersonation?.id)
}, [])
useEffect(() => {
const fetchUsers = async () => {
await axios.get<User[]>("/api/users")
.then((u) => {
setUsers(u.data.filter(x => x.id != session.data?.user.id))
})
}
fetchUsers()
}, [])
const onImpersonationChange = async (userId: string, name: string) => {
if (impersonation) {
if (impersonation == session.data?.user.impersonation?.name) {
await axios.delete("/api/account/impersonate")
.then(() => {
setImpersonation(null)
window.location.reload()
})
} else {
await axios.put("/api/account/impersonate", { targetId: userId })
.then(() => {
setImpersonation(name)
window.location.reload()
})
}
} else {
await axios.post("/api/account/impersonate", { targetId: userId })
.then(() => {
setImpersonation(name)
window.location.reload()
})
}
}
return (
<div className={"px-5 py-3 rounded-md bg-red-300 overflow-hidden wrap my-[10px] flex flex-grow flex-col gap-y-3"}>
<div>
<p className="text-xs text-gray-200">Role:</p>
<p>{session?.data?.user?.role}</p>
</div>
<div>
<p className="text-xs text-gray-200">Impersonation:</p>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="flex flex-grow justify-between text-xs">
{impersonation ? impersonation : "Select a user"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<Command>
<CommandInput placeholder="Search users by name" />
<CommandEmpty>No voices found.</CommandEmpty>
<CommandGroup>
{users.map((user) => (
<CommandItem
key={user.id}
value={user.name ?? undefined}
onSelect={(currentValue) => {
onImpersonationChange(user.id, user.name ?? "")
setOpen(false)
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
user.name == impersonation ? "opacity-100" : "opacity-0"
)}
/>
{user.name}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
</div>
</div>
);
return (
<div className={"px-5 py-3 rounded-md bg-red-300 overflow-hidden wrap my-[10px] flex flex-grow flex-col gap-y-3"}>
<div>
<p className="text-xs text-gray-200">Role:</p>
<p>{session?.data?.user?.role}</p>
</div>
<div>
<p className="text-xs text-gray-200">Impersonation:</p>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="flex flex-grow justify-between text-xs">
{impersonation ? impersonation : "Select a user"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<Command>
<CommandInput placeholder="Search users by name" />
<CommandEmpty>No voices found.</CommandEmpty>
<CommandGroup>
{users.map((user) => (
<CommandItem
key={user.id}
value={user.name ?? undefined}
onSelect={(currentValue) => {
onImpersonationChange(user.id, user.name ?? "")
setOpen(false)
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
user.name == impersonation ? "opacity-100" : "opacity-0"
)}
/>
{user.name}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
</div>
</div>
);
}
export default AdminProfile;

View File

@ -47,6 +47,17 @@ const SettingsNavigation = async () => {
</Link>
</li>
<li className="text-xs text-gray-200">
Twitch
</li>
<li className="">
<Link href={"/settings/redemptions"}>
<Button variant="ghost" className="w-full text-lg">
Channel Redemptions
</Button>
</Link>
</li>
<li className="text-xs text-gray-200">
API
</li>

View File

@ -22,7 +22,7 @@ const UserProfile = () => {
const fetchData = async () => {
if (user) return
var userData = (await axios.get("/api/account")).data
let userData = (await axios.get("/api/account")).data
setUser(userData)
}

30
components/ui/tooltip.tsx Normal file
View File

@ -0,0 +1,30 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }