All files / src/pages/flowsheet-page/menuBar ShareFlowsheet.tsx

70.64% Statements 77/109
71.73% Branches 33/46
42.85% Functions 6/14
77.64% Lines 66/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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 116 117 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 146 147 148 149 150 151 152 153 154 155 156 157 158 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 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280                                                                103x                                   2352x 2352x 2352x     2352x 2352x   2352x 2552x 200x 2352x   2552x   2352x 2352x   2352x 2352x 2558x   2352x   104x               4704x     2352x 5x 5x                         1x           1x         1x         3x             3x 3x 3x 3x           4487x   2352x             1x           1x 1x       2952x   2352x             1x             1x 1x       2952x       104x                   2352x               2352x   112x       2352x     2464x     104x 2352x     104x         2352x 104x     2352x 2456x 305x   2657x 3267x             2463x 297x 7x                             1x                                 1x             3243x 2946x 2962x 2970x      
import { defineCommand, useRegisterCommand } from "just-search-it";
import { Share2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/ahuora-design-system/ui/dialog";
import { Input } from "@/ahuora-design-system/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import { Separator } from "@/ahuora-design-system/ui/separator";
import {
  useCoreProjectsRemoveUserCreateMutation,
  useCoreProjectsShareCreateMutation,
  useCoreProjectsSharedUsersRetrieveQuery,
  useCoreProjectsUpdateSharedUserAccessCreateMutation,
} from "@/api/apiStore.gen";
import { useCurrentProject } from "@/hooks/project";
import { normalizeSharedUsers } from "@/lib/flowsheetAccess";
import { ToolTipCover } from "../../../ahuora-design-system/ui/tooltip";
 
const ShareProjectCommand = defineCommand<[], void>("shareProject");
 
function getApiErrorMessage(error: unknown, fallback: string) {
  if (
    typeof error === "object" &&
    error !== null &&
    "data" in error &&
    typeof error.data === "object" &&
    error.data !== null &&
    "error" in error.data &&
    typeof error.data.error === "string"
  ) {
    return error.data.error;
  }
 
  return fallback;
}
 
export default function ShareFlowsheet() {
  const [email, setEmail] = useState("");
  const [shareAccess, setShareAccess] = useState<"read_only" | "editable">(
    "read_only",
  );
  const { data: project } = useCurrentProject();
  const projectId = project?.id ? String(project.id) : "";
  const { data: emailList, refetch: refetchSharedUsers } =
    useCoreProjectsSharedUsersRetrieveQuery(
      { id: projectId },
      {
        skip: !projectId,
        refetchOnMountOrArgChange: true,
      },
    );
  const [shareProject] = useCoreProjectsShareCreateMutation();
  const [clearProjectShares] = useCoreProjectsRemoveUserCreateMutation();
  const [updateSharedUserAccess] =
    useCoreProjectsUpdateSharedUserAccessCreateMutation();
  const [open, setOpen] = useState(false);
  const sharedUsers = normalizeSharedUsers(emailList?.users);
 
  useRegisterCommand(
    ShareProjectCommand,
    {
      name: "Share Project",
      description: "Share your project with other users",
      group: "Sharing",
      icon: <Share2 className="icon-ls" />,
    },
    () => {
      setOpen(true);
    },
  );
 
  async function share() {
    const trimmedEmail = email.trim();
    const normalizedEmail = trimmedEmail.toLowerCase();
 
    if (!trimmedEmail) {
      toast.error("Enter an email address to share this project.");
      return;
    }
 
    if (!projectId) {
      toast.error("Project is still loading. Please try again in a moment.");
      return;
    }
 
    if (project?.owner.email?.toLowerCase() === normalizedEmail) {
      toast.error("You cannot share a project with yourself.");
      return;
    }
 
    if (
      sharedUsers.some(
        (sharedUser) => sharedUser.email.toLowerCase() === normalizedEmail,
      )
    ) {
      // Keep duplicate-share feedback local to the dialog so the owner gets a
      // fast explanation instead of waiting for a round trip to the backend.
      toast.error("This user already has access to the project.");
      return;
    }
 
    try {
      await shareProject({
        id: projectId,
        projectSharing: {
          user_email: trimmedEmail,
          read_only: shareAccess === "read_only",
        },
      }).unwrap();
      toast.success("Project shared successfully.");
      setEmail("");
      setShareAccess("read_only");
      await refetchSharedUsers();
    } catch (error: unknown) {
      toast.error(
        getApiErrorMessage(error, "Unable to share this project right now."),
      );
    }
  }
 
  async function handleRemove(userEmail: string) {
    if (!projectId) {
      toast.error("Project is still loading. Please try again in a moment.");
      return;
    }
 
    try {
      await clearProjectShares({
        id: projectId,
        removeSharedProjectUser: {
          user_email: userEmail,
        },
      }).unwrap();
      toast.success("Access removed.");
      await refetchSharedUsers();
    } catch (error: unknown) {
      toast.error(getApiErrorMessage(error, "Unable to remove access."));
    }
  }
 
  async function handleAccessChange(userEmail: string, readOnly: boolean) {
    if (!projectId) {
      toast.error("Project is still loading. Please try again in a moment.");
      return;
    }
 
    try {
      await updateSharedUserAccess({
        id: projectId,
        updateSharedProjectUserAccess: {
          user_email: userEmail,
          read_only: readOnly,
        },
      }).unwrap();
      toast.success("Access updated.");
      await refetchSharedUsers();
    } catch (error: unknown) {
      toast.error(getApiErrorMessage(error, "Unable to update access."));
    }
  }
 
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <ToolTipCover asChild content="Share your project with other users">
        <DialogTrigger asChild>
          <Button
            size="sm"
            variant="secondary"
            aria-label="share-project-dialog"
          >
            <Share2 size={18} /> Share
          </Button>
        </DialogTrigger>
      </ToolTipCover>
      <DialogContent className="flex flex-col gap-5 sm:max-w-[520px]">
        <DialogHeader className="flex flex-col gap-2">
          <DialogTitle>Share Your Project</DialogTitle>
          <DialogDescription>
            Share your project with other users by entering an email address in
            the box below.
          </DialogDescription>
        </DialogHeader>
        <div className="flex flex-col gap-2 sm:flex-row">
          <Input
            id="email"
            placeholder="Enter email"
            className="flex min-w-0 rounded-md border h-9"
            onChange={(e) => setEmail(e.target.value)}
            value={email}
            aria-label="share-project-email-input"
          />
          <Select
            value={shareAccess}
            onValueChange={(value: "read_only" | "editable") =>
              setShareAccess(value)
            }
          >
            <SelectTrigger
              className="w-full sm:w-[250px]"
              aria-label="share-project-access-select"
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="read_only">Can view</SelectItem>
              <SelectItem value="editable">Can edit</SelectItem>
            </SelectContent>
          </Select>
          <Button className="shrink-0" onClick={share}>
            Share
          </Button>
        </div>
        <div className="flex flex-col gap-2">
          {sharedUsers.length !== 0 && (
            <div className="flex flex-col gap-3" aria-label="shared-users">
              <Separator />
              <h3>Shared with</h3>
            </div>
          )}
          {sharedUsers.map((sharedUser) => (
            <div
              className="flex justify-between items-center"
              key={sharedUser.email}
              aria-label={`shared-user-${sharedUser.email}`}
            >
              <div className="flex flex-col">
                <p>{sharedUser.email}</p>
              </div>
              <div className="flex items-center gap-2">
                <Select
                  value={sharedUser.read_only ? "read_only" : "editable"}
                  onValueChange={(value: "read_only" | "editable") =>
                    // The dropdown mirrors the add-user permission selector so
                    // owners can switch a share between view-only and editable
                    // without removing and re-adding the user.
                    handleAccessChange(sharedUser.email, value === "read_only")
                  }
                >
                  <SelectTrigger
                    className="w-[140px]"
                    aria-label={`shared-user-access-${sharedUser.email}`}
                  >
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="read_only">Can view</SelectItem>
                    <SelectItem value="editable">Can edit</SelectItem>
                  </SelectContent>
                </Select>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => handleRemove(sharedUser.email)}
                  aria-label={`remove-user-${sharedUser.email}`}
                >
                  Remove
                </Button>
              </div>
            </div>
          ))}
        </div>
      </DialogContent>
    </Dialog>
  );
}