Skip to content

Commit

Permalink
feat: edit
Browse files Browse the repository at this point in the history
  • Loading branch information
HuberTRoy committed Nov 29, 2023
1 parent 50cc9a9 commit 90e3739
Show file tree
Hide file tree
Showing 7 changed files with 200 additions and 66 deletions.
24 changes: 18 additions & 6 deletions src/hooks/useConsumerHostServices.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const useConsumerHostServices = (
getAuthReqHeader(localStorage.getItem(`consumer-host-services-token-${account}`) || ''),
);
const [hasLogin, setHasLogin] = useState(false);
const [loading, setLoading] = useState(true);

const requestConsumerHostToken = async (account: string) => {
try {
Expand Down Expand Up @@ -147,13 +148,18 @@ export const useConsumerHostServices = (
};

const checkIfHasLogin = async () => {
// this api do not need argements. so use it to check if need login.
const res = await getUserApiKeysApi();
if (isConsumerHostError(res.data) && `${res.data.code}` === '403') {
setHasLogin(false);
return;
// this api do not need arguements. so use it to check if need login.
try {
setLoading(true);
const res = await getUserApiKeysApi();
if (isConsumerHostError(res.data) && `${res.data.code}` === '403') {
setHasLogin(false);
return;
}
setHasLogin(true);
} finally {
setLoading(false);
}
setHasLogin(true);
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -279,6 +285,7 @@ export const useConsumerHostServices = (
<Button
shape="round"
type="primary"
style={{ background: 'var(--sq-blue600)', borderColor: 'var(--sq-blue600)' }}
onClick={async () => {
const res = await loginConsumerHost(true);
if (!res.status) {
Expand Down Expand Up @@ -317,6 +324,7 @@ export const useConsumerHostServices = (
loginConsumerHost,
requestTokenLayout,
hasLogin,
loading,
};
};

Expand Down Expand Up @@ -349,6 +357,10 @@ export interface IGetHostingPlans {
version: string;
deployment_id: number;
};
project: {
metadata: string;
id: number;
};
channels: string;
maximum: number;
price: BigNumberish;
Expand Down
10 changes: 5 additions & 5 deletions src/pages/consumer/MyFlexPlans/MyFlexPlanTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export const MyFlexPlanTable: React.FC<MyFlexPlanTableProps> = ({ queryFn }) =>
width: 30,
title: <TableTitle title={i18next.t('flexPlans.channelStatus')} />,
render: (status: ChannelStatus, plan) => {
if (path === ONGOING_PLANS_NAV) {
if (status === ChannelStatus.OPEN && +new Date(plan.expiredAt) > +new Date()) {
return <Tag color="green">{i18next.t('general.active')}</Tag>;
} else if (status === ChannelStatus.FINALIZED) {
return <Tag color="blue">{i18next.t('general.completed')}</Tag>;
Expand All @@ -120,13 +120,13 @@ export const MyFlexPlanTable: React.FC<MyFlexPlanTableProps> = ({ queryFn }) =>
title: <TableTitle title={i18next.t('general.action')} />,
dataIndex: 'deploymentId',
fixed: 'right',
width: path === CLOSED_PLANS_NAV ? 20 : 40,
width: 40,
render: (_, plan) => {
if (path === CLOSED_PLANS_NAV) {
return <ClaimFlexPlan flexPlan={plan} onSuccess={onSuccess} />;
if (plan.status === ChannelStatus.OPEN && +new Date(plan.expiredAt) > +new Date()) {
return <OngoingFlexPlanActions flexPlan={plan} onSuccess={onSuccess} />;
}

return <OngoingFlexPlanActions flexPlan={plan} onSuccess={onSuccess} />;
return <ClaimFlexPlan flexPlan={plan} onSuccess={onSuccess} />;
},
},
];
Expand Down
73 changes: 64 additions & 9 deletions src/pages/consumer/MyFlexPlans/MyFlexPlans.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@

import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { Navigate, Route, Routes } from 'react-router';
import { Navigate, Route, Routes, useMatch, useNavigate, useParams } from 'react-router';
import { useRouteQuery } from '@hooks';
import { useIsLogin } from '@hooks/useIsLogin';
import { useGetConsumerOngoingFlexPlansLazyQuery } from '@subql/react-hooks';
import { Typography } from '@subql/components';
import { useGetConsumerClosedFlexPlansLazyQuery, useGetConsumerOngoingFlexPlansLazyQuery } from '@subql/react-hooks';
import { Breadcrumb } from 'antd';
import i18next from 'i18next';

import { AppPageHeader, Card, TabButtons, WalletRoute } from '../../../components';
Expand Down Expand Up @@ -53,16 +56,64 @@ const BalanceCards = () => {
const Header = () => {
const { t } = useTranslation();
const isLogin = useIsLogin();
const match = useMatch(`/consumer/flex-plans/${ONGOING_PLANS}/details/:id/*`);
const navigate = useNavigate();
const query = useRouteQuery();

return (
<>
<AppPageHeader title={t('plans.category.myFlexPlans')} desc={t('myFlexPlans.description')} />
{isLogin && (
{!match ? (
<>
<BalanceCards />
<div className={styles.tabs}>
<TabButtons tabs={buttonLinks} whiteTab />
</div>
<AppPageHeader title={t('plans.category.myFlexPlans')} desc={t('myFlexPlans.description')} />
{isLogin && (
<>
<BalanceCards />
<div className={styles.tabs}>
<TabButtons tabs={buttonLinks} whiteTab />
</div>
</>
)}
</>
) : (
<div style={{ marginTop: 14 }}>
<Breadcrumb
style={{ marginBottom: 50 }}
items={[
{
key: 'My Flex Plans',
title: (
<Typography variant="medium" type="secondary" style={{ cursor: 'pointer' }}>
Explorer
</Typography>
),
onClick: () => {
navigate('/consumer/flex-plans/ongoing');
},
},
{
key: 'current',
title: query.get('projectName'),
},
]}
></Breadcrumb>
<TabButtons
tabs={[
{
label: i18next.t('myFlexPlans.ongoing'),
link: `ongoing/details/${query.get('id')}/ongoing?id=${query.get('id')}&deploymentId=${query.get(
'deploymentId',
)}`,
},
{
label: i18next.t('myFlexPlans.closed'),
link: `ongoing/details/${query.get('id')}/closed?id=${query.get('id')}&deploymentId=${query.get(
'deploymentId',
)}`,
},
]}
whiteTab
/>
</div>
)}
</>
);
Expand All @@ -78,9 +129,13 @@ export const MyFlexPlans: React.FC = () => {
<Routes>
<Route path={ONGOING_PLANS} element={<MyHostedPlan></MyHostedPlan>} />
<Route
path={`${ONGOING_PLANS}/details/:id`}
path={`${ONGOING_PLANS}/details/:id/ongoing`}
element={<MyFlexPlanTable queryFn={useGetConsumerOngoingFlexPlansLazyQuery} />}
></Route>
<Route
path={`${ONGOING_PLANS}/details/:id/closed`}
element={<MyFlexPlanTable queryFn={useGetConsumerClosedFlexPlansLazyQuery} />}
></Route>
<Route path={API_KEY} element={<ApiKeys />} />
<Route path={'/'} element={<Navigate replace to={ONGOING_PLANS} />} />
</Routes>
Expand Down
71 changes: 55 additions & 16 deletions src/pages/consumer/MyFlexPlans/MyHostedPlan/MyHostedPlan.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,24 @@ import styles from './MyHostedPlan.module.less';

const MyHostedPlan: FC = (props) => {
const navigate = useNavigate();
const { updateHostingPlanApi, getHostingPlanApi, hasLogin } = useConsumerHostServices({
const {
updateHostingPlanApi,
getHostingPlanApi,
hasLogin,
loading: consumerHostLoading,
requestTokenLayout,
} = useConsumerHostServices({
alert: true,
autoLogin: false,
});

const [loading, setLoading] = useState(false);
const [createdHostingPlan, setCreatedHostingPlan] = useState<IGetHostingPlans[]>([]);
const [createdHostingPlan, setCreatedHostingPlan] = useState<(IGetHostingPlans & { projectName: string | number })[]>(
[],
);
const [currentEditInfo, setCurrentEditInfo] = useState<IGetHostingPlans>();
const { getMetadataFromCid } = useProjectMetadata();
const ref = useRef<CreateHostingFlexPlanRef>(null);
// const { getMetadataFromCid } = useProjectMetadata()
const init = async () => {
try {
setLoading(true);
Expand All @@ -36,7 +44,21 @@ const MyHostedPlan: FC = (props) => {
}

const res = await getHostingPlanApi();
setCreatedHostingPlan(res.data);
const allMetadata = await Promise.allSettled(
res.data.map((i) => {
return getMetadataFromCid(i.project.metadata);
}),
);
setCreatedHostingPlan(
res.data.map((raw, index) => {
const result = allMetadata[index];
const name = result.status === 'fulfilled' ? result.value.name : raw.id;
return {
...raw,
projectName: name,
};
}),
);
} finally {
setLoading(false);
}
Expand All @@ -46,15 +68,19 @@ const MyHostedPlan: FC = (props) => {
init();
}, [hasLogin]);

if (!hasLogin && !consumerHostLoading) return requestTokenLayout('Hosting Plan');

return (
<div className={styles.myHostedPlan}>
<Table
rowKey={(record) => record.id}
style={{ marginTop: 40 }}
loading={loading}
loading={loading || consumerHostLoading}
dataSource={createdHostingPlan}
columns={[
{
title: 'Project',
dataIndex: 'projectName',
},
{
title: 'Maximum Price',
Expand Down Expand Up @@ -95,7 +121,9 @@ const MyHostedPlan: FC = (props) => {
<Typography
style={{ color: 'var(--sq-blue600)', padding: '6px 10px' }}
onClick={() => {
navigate(`/consumer/flex-plans/ongoing/details/1`);
navigate(
`/consumer/flex-plans/ongoing/details/${record.id}/ongoing?id=${record.id}&projectName=${record.projectName}&deploymentId=${record.deployment.deployment}`,
);
}}
>
View Details
Expand All @@ -107,19 +135,30 @@ const MyHostedPlan: FC = (props) => {
ref.current?.showModal();
}}
>
Edit
{record.price === '0' ? 'Restart' : 'Edit'}
</Typography>

<Typography
style={{ color: 'var(--sq-error)', padding: '6px 10px', marginLeft: 16 }}
onClick={() => {
updateHostingPlanApi({
id: record.id,
deploymentId: record.deployment.deployment,
price: '0',
maximum: 2,
expiration: 0,
});
style={{
color: record.price === '0' ? 'var(--sq-gray400)' : 'var(--sq-error)',
padding: '6px 10px',
marginLeft: 16,
}}
onClick={async () => {
if (record.price === '0') return;
try {
setLoading(true);
await updateHostingPlanApi({
id: record.id,
deploymentId: record.deployment.deployment,
price: '0',
maximum: 2,
expiration: 0,
});
init();
} finally {
setLoading(false);
}
}}
>
Stop
Expand Down
44 changes: 32 additions & 12 deletions src/pages/consumer/MyFlexPlans/apiKeys.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import React, { ChangeEvent, FC, useEffect, useRef, useState } from 'react';
import PasswordField from '@components/PasswordField';
import { GetUserApiKeys, isConsumerHostError, useConsumerHostServices } from '@hooks/useConsumerHostServices';
import { Modal, openNotification, TextInput, Typography } from '@subql/components';
import { Modal, openNotification, Spinner, TextInput, Typography } from '@subql/components';
import { Table } from 'antd';
import moment from 'moment';

Expand All @@ -29,31 +29,51 @@ const EmptyApiKeys: FC<{ children: React.ReactNode }> = ({ children }) => {
};

const ApiKeysFC: FC = () => {
const { getUserApiKeysApi, createNewApiKey, deleteNewApiKey, requestTokenLayout, hasLogin } = useConsumerHostServices(
{
alert: true,
autoLogin: false,
},
);
const {
getUserApiKeysApi,
createNewApiKey,
deleteNewApiKey,
requestTokenLayout,
hasLogin,
loading: consumerHostLoading,
} = useConsumerHostServices({
alert: true,
autoLogin: false,
});

const [openCreateNew, setOpenCreateNew] = useState(false);
const [openDeleteConfirm, setOpenDeleteConfirm] = useState(false);
const [loading, setLoading] = useState(false);
const currentApiKey = useRef<number>();
const [newApiKeyName, setNewApiKeyName] = useState('');
const [apiKeys, setApiKeys] = useState<GetUserApiKeys[]>([]);

const init = async () => {
if (!hasLogin) return;
const res = await getUserApiKeysApi();
if (!isConsumerHostError(res.data)) {
setApiKeys(res.data);
try {
setLoading(true);
if (!hasLogin) return;
const res = await getUserApiKeysApi();
if (!isConsumerHostError(res.data)) {
setApiKeys(res.data);
}
} finally {
setLoading(false);
}
};

useEffect(() => {
init();
if (hasLogin) {
init();
}
}, [hasLogin]);

if (consumerHostLoading || loading)
return (
<div className={styles.apiKeys}>
<Spinner></Spinner>
</div>
);

return (
<div className={styles.apiKeys}>
{apiKeys.length ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ const CreateHostingFlexPlan = forwardRef<

React.useEffect(() => {
getHostingPlans();
}, [account]);
}, [account, hasLogin]);

useEffect(() => {
if (props.editInformation) {
Expand Down
Loading

0 comments on commit 90e3739

Please sign in to comment.