Skip to content

Commit

Permalink
tabbed ui complete flow (almost)
Browse files Browse the repository at this point in the history
  • Loading branch information
gyfarkas-test committed Nov 15, 2020
1 parent 231afdf commit df17f35
Show file tree
Hide file tree
Showing 7 changed files with 404 additions and 76 deletions.
13 changes: 7 additions & 6 deletions daml/DataManagement/Report.daml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ template Report with
signatory reporter, operator
controller operator can
Check : ContractId Publication do
exerciseByKey @Publication operator AddObserver with obs = reporter
exerciseByKey @Publication (content.species, operator) AddObserver with obs = reporter
Reject : ContractId Publication do
exerciseByKey @Publication operator RemoveObserver with obs = reporter
exerciseByKey @Publication (content.species, operator) RemoveObserver with obs = reporter

data PublicationData = PublicationData with
targetArea : (Coordinates, Decimal)
Expand All @@ -37,14 +37,15 @@ template Publication with
content : PublicationData
where
signatory operator
key (operator): Party
maintainer key
key (content.species, operator): (Text, Party)
maintainer key._2
observer observers
controller operator can
AddObserver: ContractId Publication with obs : Party do
create this with observers = dedup $ obs :: observers
RemoveObserver: ContractId Publication with obs : Party do
create this with observers = observers \\ [obs]
choice RequestQuota: ContractId FishingQuotaRequest with requestor : Party
nonconsuming choice RequestQuota: ContractId FishingQuotaRequest with requestor : Party
controller requestor
do create FishingQuotaRequest with operator; requestor ; species = content.species
do
create FishingQuotaRequest with operator; requestor ; species = content.species
27 changes: 22 additions & 5 deletions daml/Main.daml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import Daml.Script
import DA.Date
import DA.Time

import FishingQuota.FishingQuota()
import DataManagement.Report (Report(..), ReportContent(..), Publication(..), PublicationData(..))
import FishingQuota.FishingQuota(Issue(..))
import DataManagement.Report (RequestQuota(..), Check(..), Report(..), ReportContent(..), Publication(..), PublicationData(..))
import VesselTracking.ShipTrajectory()
import Data.Coordinates

Expand Down Expand Up @@ -54,8 +54,11 @@ template User with
setup: Script ()
setup = do
let microsecondsInDay = 86400000000
-- Create system operator commission
commission <- allocatePartyWithHint "Commission" (PartyIdHint "Commission")
op <- commission `submit` createCmd OperatorOrganisation with operator = commission ; participants = []

-- onboard countries as users
us <- allocatePartyWithHint "USA" (PartyIdHint "USA")
uk <- allocatePartyWithHint "UK" (PartyIdHint "UK")
canada <- allocatePartyWithHint "Canada" (PartyIdHint "Canada")
Expand All @@ -80,15 +83,17 @@ setup = do
spUser <- spain `submit` exerciseCmd inv7 Subscribe
(op8, inv8) <- commission `submit` exerciseCmd op7 $ Onboard with participant = portugal ; userName = "Portugal"
portugal `submit` exerciseCmd inv8 Subscribe

t <- getTime
-- submitting fishing reports
brasil `submit` exerciseCmd brasilUser $ SubmitReport with
content = ReportContent with
species = "ALB"
caughtQty = 0.09
area = ((Coordinates with lat = 30.0; long = -45.0), 10.0)
timestamp = time (date 2020 Mar 15) 0 0 0
duration = convertMicrosecondsToRelTime (14 * microsecondsInDay)
brasil `submit` exerciseCmd brasilUser $ SubmitReport with
brReport <- brasil `submit` exerciseCmd brasilUser $ SubmitReport with
content = ReportContent with
species = "ALB"
caughtQty = 11.95782
Expand All @@ -104,14 +109,16 @@ setup = do
timestamp = time (date 2020 Jun 3) 0 0 0
duration = convertMicrosecondsToRelTime (14 * microsecondsInDay)

spain `submit` exerciseCmd spUser $ SubmitReport with
espReport <- spain `submit` exerciseCmd spUser $ SubmitReport with
content = ReportContent with
species = "ALB"
caughtQty = 10.01248
area = ((Coordinates with lat = 40.0; long = -50.0), 10.0)
timestamp = time (date 2020 Jun 3) 0 0 0
duration = convertMicrosecondsToRelTime (14 * microsecondsInDay)
commission `submit` createCmd $ Publication with

-- commission prepares a ppublication about fishing opportunities
pub <- commission `submit` createCmd $ Publication with
operator = commission
observers = []
content = PublicationData with
Expand All @@ -120,4 +127,14 @@ setup = do
species = "ALB"
timeLimit = time (date 2020 Dec 1) 0 0 0

-- commission accepts report and by that reveals publication for the party
commission `submit` exerciseCmd espReport Check
pub2 <- commission `submit` exerciseCmd brReport Check

-- the parties that see the opportunity request fising quota
qr <- spain `submit` exerciseCmd pub2 RequestQuota with requestor = spain
brasil `submit` exerciseCmd pub2 RequestQuota with requestor = brasil

-- commission issues a quota
commission `submit` exerciseCmd qr Issue
pure ()
223 changes: 170 additions & 53 deletions ui/src/components/MainView.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { DataManagement, Main } from '@daml.js/odyssey';
import { useLedger, useParty } from '@daml/react';
import { FishingQuota, DataManagement, Main } from '@daml.js/odyssey';
import { useLedger, useParty, useQuery } from '@daml/react';
import React, { useMemo, useState, useRef, useEffect } from 'react';
import * as ui from 'semantic-ui-react';
import MapView from './MapView';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import { LatLngExpression } from 'leaflet';
import { ReportView, ReportModel } from './ReportView';
import { ReportView, ReportModel, ReportViewModel } from './ReportView';
import { ReportForm } from './ReportForm';
import { formatDiagnosticsWithColorAndContext } from 'typescript';
import { ContractId } from '@daml/types';
import { Report } from '@daml.js/odyssey/lib/DataManagement/Report';
import { PublicationModel, PublicationView } from './PublicationView';
import { Tab } from 'semantic-ui-react';
import { QuotaView, QuotaRequestModel, QuotaModel } from './QuotaView';

const MainView: React.FC = () => {

Expand All @@ -16,74 +21,186 @@ const MainView: React.FC = () => {

const ledger = useLedger();

let [reports, setReports] = useState<ReportModel[]>([])
let [reports, setReports] = useState<ReportViewModel[]>([]);

let reportModelFromReport = function (r: DataManagement.Report.Report): ReportModel {
let [publications, setPublications] = useState<PublicationModel[]>([]);

let [quotaRequests, setQuotaRequsts] = useState<QuotaRequestModel[]>([]);

let [quotas, setQuotas] = useState<QuotaModel[]>([]);

let quotaRequestModelFromContract = function (
contractId: ContractId<FishingQuota.FishingQuota.FishingQuotaRequest>,
req: FishingQuota.FishingQuota.FishingQuotaRequest
): QuotaRequestModel {
return {
reporter: r.reporter,
caughtQty: Number.parseFloat(r.content.caughtQty),
areaCenterLong: Number.parseFloat(r.content.area._1.long),
areaCenterLat: Number.parseFloat(r.content.area._1.lat),
areaRadius: Number.parseFloat(r.content.area._2),
fish: r.content.species,
}
fish: req.species,
requestor: req.requestor,
contractId: contractId
};
}

let quotaModelFromContract = function (
contractId: ContractId<FishingQuota.FishingQuota.FishingQuota>,
q: FishingQuota.FishingQuota.FishingQuota
): QuotaModel {
return {
qty: Number.parseFloat(q.quantity),
fish: q.species,
owner: q.owner,
issuer: q.issuer,
};
}

let reportModelFromReport = function (
contractId: ContractId<DataManagement.Report.Report>,
r: DataManagement.Report.Report): ReportViewModel {
return {
report: {
reporter: r.reporter,
caughtQty: Number.parseFloat(r.content.caughtQty),
areaCenterLong: Number.parseFloat(r.content.area._1.long),
areaCenterLat: Number.parseFloat(r.content.area._1.lat),
areaRadius: Number.parseFloat(r.content.area._2),
fish: r.content.species,
},
contractId: contractId
};
};

let publicationModelFromContract = function (
contractId: ContractId<DataManagement.Report.Publication>,
p: DataManagement.Report.Publication): PublicationModel {
return {
fish: p.content.species,
allowed: Number.parseFloat(p.content.totalAllowance),
timeLimit: p.content.timeLimit,
areaCenterLat: Number.parseFloat(p.content.targetArea._1.lat),
areaCenterLong: Number.parseFloat(p.content.targetArea._1.long),
areaRadius: Number.parseFloat(p.content.targetArea._2),
contractId: contractId
};
}

let reportsQ = ledger.query(DataManagement.Report.Report)
.then(xs => xs.map(x => reportModelFromReport(x.payload)))
.then(setReports)
let reportQ = useQuery(DataManagement.Report.Report)
let pubQ = useQuery(DataManagement.Report.Publication)
let quotaRequestQ = useQuery(FishingQuota.FishingQuota.FishingQuotaRequest);
let quotaQ = useQuery(FishingQuota.FishingQuota.FishingQuota)
useEffect(() => {
setReports(reportQ.contracts.map(x => reportModelFromReport(x.contractId, x.payload)));
setPublications(pubQ.contracts.map(x => publicationModelFromContract(x.contractId, x.payload)));
setQuotaRequsts(quotaRequestQ.contracts.map(x => quotaRequestModelFromContract(x.contractId, x.payload)));
setQuotas(quotaQ.contracts.map(x => quotaModelFromContract(x.contractId, x.payload)));
console.log("quotas");
console.log(quotas);
}, [ledger, reportQ, pubQ, quotaRequestQ, quotaQ])

let createReport = function (r: ReportModel) {
ledger.fetchByKey(Main.User, username).then(user => {
if (user) {
ledger.exercise(Main.User.SubmitReport, user.contractId,
{
content: {
species: r.fish,
caughtQty: r.caughtQty.toFixed(),
timestamp: (new Date()).toISOString(),
area: {
_1: {
long: r.areaCenterLong.toFixed(),
lat: r.areaCenterLat.toFixed()
try {
ledger.fetchByKey(Main.User, username).then(user => {
if (user) {
ledger.exercise(Main.User.SubmitReport, user.contractId,
{
content: {
species: r.fish,
caughtQty: r.caughtQty.toFixed(),
timestamp: (new Date()).toISOString(),
area: {
_1: {
long: r.areaCenterLong.toFixed(),
lat: r.areaCenterLat.toFixed()
},
_2: r.areaRadius.toFixed()
},
_2: r.areaRadius.toFixed()
},
duration: { microseconds: "0" }
}
})
}
});
duration: { microseconds: "0" }
}
})
}
}).catch(e => console.log(`error report create ${e}`));
} catch {
console.log("error report create");
}
}

let check = function (contractId: ContractId<DataManagement.Report.Report>) {
try {
ledger.exercise(DataManagement.Report.Report.Check, contractId, {})
.catch(e => console.log(`error: reject: ${e} `));
} catch {
console.log("error: check")
}
}

let reject = function (contractId: ContractId<DataManagement.Report.Report>) {
try {
ledger.exercise(DataManagement.Report.Report.Reject, contractId, {})
.catch(e => console.log(`error: reject: ${e} `));
} catch {
console.log("error: reject");
}
}

let requestQuota = function (contractId: ContractId<DataManagement.Report.Publication>) {
try {
ledger.exercise(DataManagement.Report.Publication.RequestQuota, contractId, { requestor: username })
.catch(e => console.log(`error: request: ${e}`));
} catch {
console.log("error: quota request");
}
}

let issueQuota = function(contractId: ContractId<FishingQuota.FishingQuota.FishingQuotaRequest>) {
if(username=="Commission") {
ledger.exercise(FishingQuota.FishingQuota.FishingQuotaRequest.Issue, contractId, {})
.catch(e => console.log(`error quota issue: ${e}`));
} else {

}
}

var view = <ui.Container />
if (username == "Commission") {
view = <ReportView reports={reports}> </ReportView>;
view = <ReportView reports={reports} check={check} reject={reject}> </ReportView>;
}
else {
view = <ReportForm submit={createReport} reporter={username} > </ReportForm>;
}

const mapView = (
<MapContainer id="mapid" center={[32.3104298, -64.7954125]} zoom={5} scrollWheelZoom={false}>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{reports
.map(rvm => rvm.report)
.map(rs => { return { p: ([rs.areaCenterLat, rs.areaCenterLong] as LatLngExpression), r: rs } })
.map(({ p, r }) => {
return (
<Marker position={p}>
<Popup>
{r.fish} fishing activity from {r.reporter}:
<span>qty: {r.caughtQty}</span>
</Popup>
</Marker>)
})}
</MapContainer>);

const panes = [
{ menuItem: 'Map View', pane: (<Tab.Pane key="map"><div>{mapView}</div></Tab.Pane>) },
{ menuItem: 'Reports', pane: <Tab.Pane key="report"><div>{view}</div></Tab.Pane> },
{
menuItem: 'Publications', pane: <Tab.Pane key="pub"><div>
{publications.map(p => <PublicationView publication={p} username={username} request={requestQuota} />)}
</div>
</Tab.Pane>
},
{ menuItem: 'Quotas', pane: <Tab.Pane key="q"><div><QuotaView quotas={quotas} requests={quotaRequests} username={username} issue={issueQuota} /></div></Tab.Pane> },
]

return (
<ui.Container>
<MapContainer id="mapid" center={[32.3104298, -64.7954125]} zoom={5} scrollWheelZoom={true}>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{reports
.map(rs => { return {p : ([rs.areaCenterLat, rs.areaCenterLong] as LatLngExpression), r: rs }})
.map(({p, r}) => {
return (
<Marker position={p}>
<Popup>
{r.fish} fishing activity from {r.reporter}:
<span>qty: {r.caughtQty }</span>
</Popup>
</Marker>)
})}
</MapContainer>
{view}
<Tab panes={panes} renderActiveOnly={false} />
</ui.Container>);
}

Expand Down
Loading

0 comments on commit df17f35

Please sign in to comment.