1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-06-25 02:36:48 +02:00
market/src/components/organisms/AssetActions/Edit/index.tsx

218 lines
6.2 KiB
TypeScript
Raw Normal View History

import { Formik } from 'formik'
import React, { ReactElement, useState } from 'react'
import { MetadataEditForm } from '../../../../@types/MetaData'
import {
validationSchema,
getInitialValues
} from '../../../../models/FormEditMetadata'
import { useAsset } from '../../../../providers/Asset'
import { useUserPreferences } from '../../../../providers/UserPreferences'
2021-02-16 10:27:02 +01:00
import { MetadataPreview } from '../../../molecules/MetadataPreview'
Edit compute dataset (#417) * WIP * created form for editing compute privacy * used editComputePrivacy method * select and update trusted algorithm * display and select multiple trusted algorithms * fixed update when trusted algorithm list not changed * code refactoring * moved separator inside condition * moved functions and interface from EditComputeDataset component * moved algorithmOptions to parent component * used AssetSelection to display algorithms * use AssetSelection to select trusted algorithms * getAlgorithmsOptions function review * review fixes * removed unused imports * merge fixes * AssetSelection style & usability tweaks * use custom radio & checkbox styles * add simple search for name & DID * spacing adjustments * copy updates, remove raw algo input, hardcode allowRawAlgorithm * copy * AssetSelection usability tweaks * make rows clickable * tweak layout, style and markup * use formik set function to update values * sorted algorithm list, added checked field * sort assetSelection list on user select * fix getAlgorithmsForAssetSelection breaking on empty responses * form debug output * another empty publisherTrustedAlgorithms fix * created separate algorithms state for the form, sort list on edit * refactor * use Formik functionality wherever possible * unify transforming form data to final data * fix form debug transformation * fix form submit, fix defaultChecked * refactor * use Formik functionality wherever possible * unify transforming form data to final data * fix form debug transformation * fix form submit, fix defaultChecked * disable assetSelection when allowAllAlgorithms is true * added loader to AssetSelection * changed allowAllAlgorithms to allowAllPublishedAlgorithms * fixed lint error * updated transformComputeFormToServiceComputePrivacy * lint fix * modify publish defaults Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
2021-03-25 08:34:07 +01:00
import Debug from './DebugEditMetadata'
import Web3Feedback from '../../../molecules/Web3Feedback'
import FormEditMetadata from './FormEditMetadata'
import { mapTimeoutStringToSeconds } from '../../../../utils/metadata'
import styles from './index.module.css'
import { Logger } from '@oceanprotocol/lib'
import MetadataFeedback from '../../../molecules/MetadataFeedback'
import { graphql, useStaticQuery } from 'gatsby'
import { useWeb3 } from '../../../../providers/Web3'
import { useOcean } from '../../../../providers/Ocean'
import {
setMinterToDispenser,
setMinterToPublisher
} from '../../../../utils/freePrice'
const contentQuery = graphql`
query EditMetadataQuery {
content: allFile(filter: { relativePath: { eq: "pages/edit.json" } }) {
edges {
node {
childPagesJson {
description
form {
success
successAction
error
data {
name
placeholder
label
help
type
min
required
sortOptions
options
rows
}
}
}
}
}
}
}
`
export default function Edit({
setShowEdit
}: {
setShowEdit: (show: boolean) => void
}): ReactElement {
const data = useStaticQuery(contentQuery)
const content = data.content.edges[0].node.childPagesJson
const { debug } = useUserPreferences()
const { accountId } = useWeb3()
const { ocean } = useOcean()
const { metadata, ddo, refreshDdo, price } = useAsset()
const [success, setSuccess] = useState<string>()
const [error, setError] = useState<string>()
const [timeoutStringValue, setTimeoutStringValue] = useState<string>()
Edit compute dataset (#417) * WIP * created form for editing compute privacy * used editComputePrivacy method * select and update trusted algorithm * display and select multiple trusted algorithms * fixed update when trusted algorithm list not changed * code refactoring * moved separator inside condition * moved functions and interface from EditComputeDataset component * moved algorithmOptions to parent component * used AssetSelection to display algorithms * use AssetSelection to select trusted algorithms * getAlgorithmsOptions function review * review fixes * removed unused imports * merge fixes * AssetSelection style & usability tweaks * use custom radio & checkbox styles * add simple search for name & DID * spacing adjustments * copy updates, remove raw algo input, hardcode allowRawAlgorithm * copy * AssetSelection usability tweaks * make rows clickable * tweak layout, style and markup * use formik set function to update values * sorted algorithm list, added checked field * sort assetSelection list on user select * fix getAlgorithmsForAssetSelection breaking on empty responses * form debug output * another empty publisherTrustedAlgorithms fix * created separate algorithms state for the form, sort list on edit * refactor * use Formik functionality wherever possible * unify transforming form data to final data * fix form debug transformation * fix form submit, fix defaultChecked * refactor * use Formik functionality wherever possible * unify transforming form data to final data * fix form debug transformation * fix form submit, fix defaultChecked * disable assetSelection when allowAllAlgorithms is true * added loader to AssetSelection * changed allowAllAlgorithms to allowAllPublishedAlgorithms * fixed lint error * updated transformComputeFormToServiceComputePrivacy * lint fix * modify publish defaults Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
2021-03-25 08:34:07 +01:00
const timeout = ddo.findServiceByType('access')
? ddo.findServiceByType('access').attributes.main.timeout
: ddo.findServiceByType('compute').attributes.main.timeout
const hasFeedback = error || success
async function updateFixedPrice(newPrice: number) {
const setPriceResp = await ocean.fixedRateExchange.setRate(
price.address,
newPrice,
accountId
)
if (!setPriceResp) {
setError(content.form.error)
Logger.error(content.form.error)
}
}
async function handleSubmit(
values: Partial<MetadataEditForm>,
resetForm: () => void
) {
try {
if (price.type === 'free') {
const tx = await setMinterToPublisher(
ocean,
ddo.dataToken,
accountId,
setError
)
if (!tx) return
}
// Construct new DDO with new values
const ddoEditedMetdata = await ocean.assets.editMetadata(ddo, {
title: values.name,
description: values.description,
links: typeof values.links !== 'string' ? values.links : []
})
price.type === 'exchange' &&
values.price !== price.value &&
(await updateFixedPrice(values.price))
if (!ddoEditedMetdata) {
setError(content.form.error)
Logger.error(content.form.error)
return
}
let ddoEditedTimeout = ddoEditedMetdata
if (timeoutStringValue !== values.timeout) {
Start compute job (#439) * Wip start compute job * Wip select algorithm design * Asset selection form component, for start compute job (#442) * prototype AssetSelection * assetselection styling * typing "fix" * put back file info icon * AssetSelection styling in context * update start job method, fixed algo select, and fixed option typing * compute logic update * add has previous orders for algo asset * fixed search algorithm assets in start compute form * fixed lint errors * updated previous order for algo logic and compute flow * update use price hook and added buy DT for algo * display only alg of type exchange and sort by value * display only trusted algo for asset if field is set * added logic for allow all published algorithms or no algorithms allowed * asset selection style & spacing tweaks * refactor get algorithms for compute and edit compute * fixed form options and more refactoring * new ButtonBuy component * shared component between consume/compute * dealing with various states: loading, previous orders, help text output * effect dependencies * move error output into toast * formik data flow refactor * ditch custom field change handler * fix initialValues * typed form data & validation * fixes multiple form validation issues along the way * isInitialValid → validateOnMount * metadata display tweaks * error feedback tweaks * oler assets checks, confeti on succes job, market fee on order, removed algo compute logic * more startJob logging * feedback & messaging changes * metadata display * return all algos, fixed & dynamic priced ones * fix DOM nesting * messaging updates * copy tweaks * check algorithm previous history for both acces and compute sercive types * handle start compute error * extra checks on start compute response * styling tweaks, fix toast UI errors * AssetSelection: empty screen, tweak min/max height * fix FRE issues on start compute * check is ordarable before start compute job * logging tweaks * disable eslint no-unused-vars rule for some Apollo code blocks * fix metadata editing for compute assets * consider dataset timeout for compute too Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
2021-04-01 17:21:08 +02:00
const service =
ddoEditedMetdata.findServiceByType('access') ||
ddoEditedMetdata.findServiceByType('compute')
const timeout = mapTimeoutStringToSeconds(values.timeout)
ddoEditedTimeout = await ocean.assets.editServiceTimeout(
ddoEditedMetdata,
service.index,
timeout
)
}
if (!ddoEditedTimeout) {
setError(content.form.error)
Logger.error(content.form.error)
return
}
const storedddo = await ocean.assets.updateMetadata(
ddoEditedTimeout,
accountId
)
if (!storedddo) {
setError(content.form.error)
Logger.error(content.form.error)
return
} else {
if (price.type === 'free') {
const tx = await setMinterToDispenser(
ocean,
ddo.dataToken,
accountId,
setError
)
if (!tx) return
}
// Edit succeeded
setSuccess(content.form.success)
resetForm()
}
} catch (error) {
Logger.error(error.message)
setError(error.message)
}
}
return (
<Formik
2021-04-22 13:18:23 +02:00
initialValues={getInitialValues(metadata, timeout, price.value)}
validationSchema={validationSchema}
onSubmit={async (values, { resetForm }) => {
// move user's focus to top of screen
window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
// kick off editing
await handleSubmit(values, resetForm)
}}
>
{({ isSubmitting, values, initialValues }) =>
isSubmitting || hasFeedback ? (
<MetadataFeedback
title="Updating Data Set"
error={error}
success={success}
setError={setError}
successAction={{
name: content.form.successAction,
onClick: async () => {
await refreshDdo()
setShowEdit(false)
}
}}
/>
) : (
<>
<p className={styles.description}>{content.description}</p>
<article className={styles.grid}>
<FormEditMetadata
data={content.form.data}
setShowEdit={setShowEdit}
setTimeoutStringValue={setTimeoutStringValue}
values={initialValues}
showPrice={price.type === 'exchange'}
/>
<aside>
<MetadataPreview values={values} />
<Web3Feedback />
</aside>
{debug === true && <Debug values={values} ddo={ddo} />}
</article>
</>
)
}
</Formik>
)
}