All files / publisher/pages/Members Members.tsx

40.45% Statements 53/131
48.8% Branches 41/84
35.71% Functions 15/42
39.37% Lines 50/127

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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532                                                                                        16x 16x         16x         16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x     16x   16x   16x                                                                                                                   16x                         16x 8x   16x 4x 4x 4x 8x   4x 4x             16x 8x 4x       16x 4x     16x 8x 8x       16x 16x 8x   8x       16x 16x   8x 8x           16x                                                       2x 2x     4x                                                                                                                                                                                                                                                                       64x                                                                                                                                                                                                                                                                                                                                                      
import { ChangeEvent, useEffect, useState } from "react";
import { useParams, Navigate } from "react-router-dom";
import { useRecoilValue } from "recoil";
import {
  Spinner,
  Accordion,
  Row,
  Col,
  Button,
  SearchBox,
  Input,
  Notification,
} from "@canonical/react-components";
 
import ROLES from "./memberRoles";
 
import MembersTable from "./MembersTable";
import InvitesTable from "./InvitesTable";
import StoreNotFound from "../StoreNotFound";
import Navigation from "../../components/Navigation";
 
import { brandStoresState } from "../../state/brandStoreState";
import { useMembers, useInvites } from "../../hooks";
 
import { setPageTitle } from "../../utils";
 
type Members = {
  members: {
    members: Array<Member>;
    loading: boolean;
    notFound: boolean;
  };
};
 
type Member = {
  displayname: string;
  email: string;
  id: string;
  roles: string[];
  username: string;
  current_user: boolean;
};
 
function Members(): React.JSX.Element {
  const brandStoresList = useRecoilValue(brandStoresState);
  const { id } = useParams();
  const {
    data: members,
    isLoading: membersLoading,
    refetch: refetchMembers,
  } = useMembers(id || "");
  const {
    data: invites,
    isLoading: invitesLoading,
    refetch: refetchInvites,
  } = useInvites(id || "");
  const [filteredMembers, setFilteredMembers] = useState<Member[]>([]);
  const [sidePanelOpen, setSidePanelOpen] = useState(false);
  const [newMemberEmail, setNewMemberEmail] = useState("");
  const [newMemberRoles, setNewMemberRoles] = useState<string[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [showSuccessNotification, setShowSuccessNotification] = useState(false);
  const [showErrorNotification, setShowErrorNotification] = useState(false);
  const [showInviteForm, setShowInviteForm] = useState(false);
  const [storeName, setStoreName] = useState<string | undefined>("");
  const [memberButtonDisabled, setMemberButtonDisabled] = useState(false);
  const [changedMembers, setChangedMembers] = useState<Member[]>([]);
  const [notificationText, setNotificationText] = useState(
    "Changes have been saved",
  );
  const [currentMember, setCurrentMember] = useState<Member | undefined>();
 
  setPageTitle(`Members in ${storeName}`);
 
  const handleInvite = (action: string) => {
    setIsSaving(true);
 
    const memberData = new FormData();
    const member = [
      {
        email: newMemberEmail,
        roles: newMemberRoles,
      },
    ];
    memberData.set("csrf_token", window.CSRF_TOKEN);
    memberData.set("members", JSON.stringify(member));
 
    fetch(`/api/store/${id}/${action}`, {
      method: "POST",
      body: memberData,
    })
      .then((response) => {
        if (response.status === 200) {
          return response.json();
        } else {
          throw Error();
        }
      })
      .then((data) => {
        // Add timeout so that the user has time to notice the save action
        // in the event of it happening very fast
        setTimeout(() => {
          setIsSaving(false);
 
          if (data.msg === "invite") {
            setShowInviteForm(true);
          } else {
            setSidePanelOpen(false);
            setNewMemberEmail("");
            setNewMemberRoles([]);
            refetchMembers();
            refetchInvites();
            setShowSuccessNotification(true);
            setNotificationText("Member has been added to the store");
            setShowInviteForm(false);
 
            setTimeout(() => {
              setShowSuccessNotification(false);
            }, 5000);
          }
        }, 1500);
      })
      .catch(() => {
        setIsSaving(false);
        setShowErrorNotification(true);
 
        setTimeout(() => {
          setShowErrorNotification(false);
        }, 5000);
      });
  };
 
  const handleRoleChange = (e: ChangeEvent) => {
    const role = e.target.id;
    let roles: Array<string> = newMemberRoles;
 
    if (!roles.includes(role)) {
      roles = [...roles, role];
    } else {
      roles = roles.filter((item) => item !== role);
    }
 
    setNewMemberRoles(roles);
  };
 
  const isOnlyViewer = () =>
    currentMember?.roles.length === 1 && currentMember?.roles.includes("view");
 
  useEffect(() => {
    refetchMembers();
    refetchInvites();
    setStoreName((): string | undefined => {
      const store = brandStoresList.find((item) => item.id === id);
 
      if (store) {
        return store.name;
      } else E{
        return id;
      }
    });
  }, [id]);
 
  useEffect(() => {
    if (members) {
      setFilteredMembers(members);
    }
  }, [members]);
 
  useEffect(() => {
    setMemberButtonDisabled(!newMemberEmail || newMemberRoles.length === 0);
  }, [newMemberEmail, newMemberRoles]);
 
  useEffect(() => {
    if (members) {
      setCurrentMember(members.find((member: Member) => member.current_user));
    }
  }, [members, membersLoading, invitesLoading]);
 
  const getSectionName = () => {
    if (members && invites) {
      return "members";
    } else {
      return null;
    }
  };
 
  const getStoreName = (storeId: string) => {
    const store = brandStoresList.find((item) => item.id === storeId);
 
    if (store) {
      return store.name;
    } else E{
      return storeId;
    }
  };
 
  return (
    <div className="l-application" role="presentation">
      <Navigation sectionName={getSectionName()} />
      <main className="l-main">
        <div className="p-panel">
          <div className="p-panel__content">
            {membersLoading && invitesLoading ? (
              <div className="u-fixed-width">
                <Spinner text="Loading&hellip;" />
              </div>
            ) : (!members && !membersLoading) ||
              (!invites && !invitesLoading) ? (
              <StoreNotFound />
            ) : isOnlyViewer() ? (
              <Navigate to={`/admin/${id}/snaps`} />
            ) : (
              <div>
                <div className="u-fixed-width">
                  <h1 className="p-heading--4">
                    {getStoreName(id || "")} / Members
                  </h1>
                </div>
                <Row>
                  <Col size={6}>
                    <SearchBox
                      placeholder="Search and filter"
                      autocomplete="off"
                      onChange={(query) => {
                        if (query) {
                          setFilteredMembers(
                            members.filter(
                              (member: Member) =>
                                member.displayname.includes(query) ||
                                member.email.includes(query),
                            ),
                          );
                        } else E{
                          setFilteredMembers(members);
                        }
                      }}
                    />
                  </Col>
                  <Col size={6} className="u-align--right">
                    <Button
                      onClick={() => {
                        setSidePanelOpen(true);
                      }}
                    >
                      Add new member
                    </Button>
                  </Col>
                </Row>
                <div className="u-fixed-width app-accordion">
                  <Accordion
                    expanded="members-table"
                    sections={[
                      {
                        key: "members-table",
                        title: `${filteredMembers.length} members`,
                        content: (
                          <MembersTable
                            filteredMembers={filteredMembers}
                            changedMembers={changedMembers}
                            setChangedMembers={setChangedMembers}
                          />
                        ),
                      },
                      {
                        key: "invites-table",
                        title: `${invites ? invites.length : 0} invites`,
                        content: (
                          <InvitesTable
                            invites={invites}
                            refetchInvites={refetchInvites}
                            setNotificationText={setNotificationText}
                            setShowSuccessNotification={
                              setShowSuccessNotification
                            }
                            setShowErrorNotification={setShowErrorNotification}
                          />
                        ),
                      },
                    ]}
                  />
                </div>
              </div>
            )}
          </div>
        </div>
      </main>
      <div
        className={`l-aside__overlay ${sidePanelOpen ? "" : "u-hide"}`}
        onClick={() => {
          setSidePanelOpen(false);
          setShowInviteForm(false);
          setNewMemberEmail("");
          setNewMemberRoles([]);
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            setSidePanelOpen(false);
            setShowInviteForm(false);
            setNewMemberEmail("");
            setNewMemberRoles([]);
          }
        }}
        role="button"
        tabIndex={0}
        aria-label="Close the side panel"
      ></div>
      <aside
        className={`l-aside ${sidePanelOpen ? "" : "is-collapsed"}`}
        id="aside-panel"
      >
        <div className="p-panel is-flex-column">
          <div className="p-panel__header">
            <h4 className="p-panel__title">
              {showInviteForm
                ? "Send invitation to join this store"
                : "Add new member"}
            </h4>
          </div>
          <div className="p-panel__content u-no-padding--top">
            {showInviteForm && (
              <div className="u-fixed-width">
                <p>
                  We couldn&rsquo;t find an existing user for the email{" "}
                  <strong>{newMemberEmail}</strong>
                </p>
                <p>
                  Would you like to send an email inviting them to join{" "}
                  <strong>{storeName}</strong>?
                </p>
                <p>
                  When they accept they will be granted the following
                  permissions:
                </p>
                <ul>
                  {newMemberRoles.map((role: string) => (
                    <li key={role}>
                      <div>{ROLES[role].name}</div>
                      <small className="u-text-muted">
                        {ROLES[role].description}
                      </small>
                    </li>
                  ))}
                </ul>
              </div>
            )}
            {!showInviteForm && (
              <div className="u-fixed-width">
                <Input
                  id="new-member-email"
                  type="email"
                  label="Email"
                  placeholder="yourname@example.com"
                  help="The primary email for the Ubuntu One account"
                  value={newMemberEmail}
                  onChange={(e) => {
                    setNewMemberEmail(e.target.value);
                  }}
                />
                <h4>Roles</h4>
                {Object.keys(ROLES).map((role) => (
                  <Input
                    key={ROLES[role].name}
                    type="checkbox"
                    id={role}
                    label={ROLES[role].name}
                    help={ROLES[role].description}
                    onChange={handleRoleChange}
                    checked={newMemberRoles.includes(role)}
                  />
                ))}
              </div>
            )}
          </div>
          <div className="p-panel__footer u-align--right">
            <div className="u-fixed-width">
              <Button
                className="u-no-margin--bottom"
                onClick={() => {
                  setSidePanelOpen(false);
                  setNewMemberEmail("");
                  setNewMemberRoles([]);
                  setShowInviteForm(false);
                }}
              >
                Cancel
              </Button>
 
              {!showInviteForm && (
                <Button
                  appearance="positive"
                  className={`u-no-margin--bottom u-no-margin--right ${
                    isSaving ? "has-icon is-dark" : ""
                  }`}
                  disabled={memberButtonDisabled}
                  onClick={() => {
                    handleInvite("members");
                  }}
                >
                  {isSaving ? (
                    <>
                      <i className="p-icon--spinner u-animation--spin is-light"></i>
                      <span>Saving...</span>
                    </>
                  ) : (
                    "Add member"
                  )}
                </Button>
              )}
 
              {showInviteForm && (
                <Button
                  appearance="positive"
                  className={`u-no-margin--bottom u-no-margin--right ${
                    isSaving ? "has-icon is-dark" : ""
                  }`}
                  onClick={() => {
                    handleInvite("invite");
                  }}
                >
                  {isSaving ? (
                    <>
                      <i className="p-icon--spinner u-animation--spin is-light"></i>
                      <span>Saving...</span>
                    </>
                  ) : (
                    "Send invite"
                  )}
                </Button>
              )}
            </div>
          </div>
        </div>
      </aside>
 
      {changedMembers.length ? (
        <aside className="l-status">
          <div className="u-fixed-width u-align--right">
            <Button
              className={`u-no-margin--bottom ${
                isSaving ? "has-icon is-dark" : ""
              }`}
              appearance="positive"
              onClick={() => {
                setIsSaving(true);
 
                const memberData = new FormData();
                const members = changedMembers.map((m: Member) => {
                  return {
                    email: m.email,
                    roles: m.roles,
                  };
                });
 
                memberData.set("csrf_token", window.CSRF_TOKEN);
                memberData.set("members", JSON.stringify(members));
 
                fetch(`/api/store/${id}/members`, {
                  method: "POST",
                  body: memberData,
                })
                  .then((response) => {
                    if (response.status === 200) {
                      return response.json();
                    } else {
                      throw Error();
                    }
                  })
                  .then(() => {
                    // Add timeout so that the user has time to notice the save action
                    // in the event of it happening very fast
                    setTimeout(() => {
                      setChangedMembers([]);
                      setIsSaving(false);
                      setShowSuccessNotification(true);
                      setNotificationText("Member roles have been changed");
 
                      setTimeout(() => {
                        setShowSuccessNotification(false);
                      }, 5000);
                    }, 1500);
                  })
                  .catch(() => {
                    setIsSaving(false);
                    setShowErrorNotification(true);
 
                    setTimeout(() => {
                      setShowErrorNotification(false);
                    }, 5000);
                  });
              }}
            >
              {isSaving ? (
                <>
                  <i className="p-icon--spinner u-animation--spin is-light"></i>
                  <span>Saving...</span>
                </>
              ) : (
                "Save changes"
              )}
            </Button>
          </div>
        </aside>
      ) : null}
 
      <div className="p-notification-center">
        {showSuccessNotification && (
          <Notification
            severity="positive"
            onDismiss={() => setShowSuccessNotification(false)}
          >
            {notificationText}
          </Notification>
        )}
 
        {showErrorNotification && (
          <Notification
            severity="negative"
            onDismiss={() => setShowErrorNotification(false)}
          >
            Something went wrong.{" "}
            <a href="https://github.com/canonical-web-and-design/snapcraft.io/issues/new">
              Report a bug
            </a>
          </Notification>
        )}
      </div>
    </div>
  );
}
 
export default Members;