Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added view budget histories component #717

Merged
merged 2 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,12 @@ func (db database) GetOrganizationBudget(org_uuid string) BountyBudget {
return ms
}

func (db database) GetOrganizationBudgetHistory(org_uuid string) []BudgetHistoryData {
budgetHistory := []BudgetHistoryData{}
db.db.Raw(`SELECT budget.id, budget.org_uuid, budget.amount, budget.created, budget.updated, budget.payment_type, budget.status, budget.sender_pub_key, sender.unique_name AS sender_name FROM public.budget_histories AS budget LEFT OUTER JOIN public.people AS sender ON budget.sender_pub_key = sender.owner_pub_key WHERE budget.org_uuid = '` + org_uuid + `' ORDER BY budget.created DESC`).Find(&budgetHistory)
return budgetHistory
}

func (db database) AddAndUpdateBudget(budget BudgetStoreData) BudgetHistory {
created := budget.Created
org_uuid := budget.OrgUuid
Expand Down
36 changes: 25 additions & 11 deletions db/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -445,10 +445,11 @@ type BountyBudget struct {
}

type BudgetInvoiceRequest struct {
Amount uint `json:"amount"`
SenderPubKey string `json:"sender_pubkey"`
OrgUuid string `json:"org_uuid"`
Websocket_token string `json:"websocket_token,omitempty"`
Amount uint `json:"amount"`
SenderPubKey string `json:"sender_pubkey"`
OrgUuid string `json:"org_uuid"`
PaymentType BudgetPaymentType `json:"payment_type,omitempty"`
Websocket_token string `json:"websocket_token,omitempty"`
}

type BudgetStoreData struct {
Expand All @@ -460,14 +461,27 @@ type BudgetStoreData struct {
Created *time.Time `json:"created"`
}

type BudgetPaymentType string

const (
Add BudgetPaymentType = "add"
Deposit BudgetPaymentType = "deposit"
)

type BudgetHistory struct {
ID uint `json:"id"`
OrgUuid string `json:"org_uuid"`
Amount uint `json:"amount"`
SenderPubKey string `json:"sender_pubkey"`
Created *time.Time `json:"created"`
Updated *time.Time `json:"updated"`
Status bool `json:"status"`
ID uint `json:"id"`
OrgUuid string `json:"org_uuid"`
Amount uint `json:"amount"`
SenderPubKey string `json:"sender_pubkey"`
Created *time.Time `json:"created"`
Updated *time.Time `json:"updated"`
Status bool `json:"status"`
PaymentType BudgetPaymentType `json:"payment_type"`
}

type BudgetHistoryData struct {
BudgetHistory
SenderName string `json:"sender_name"`
kevkevinpal marked this conversation as resolved.
Show resolved Hide resolved
}

type PaymentHistory struct {
Expand Down
11 changes: 11 additions & 0 deletions frontend/app/src/components/form/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ export const Wrap = styled.div<WrapProps>`
min-width: 230px;
`;

export const OrgWrap = styled.div<WrapProps>`
padding: ${(p: any) => (p?.newDesign ? '28px 0px' : '30px 20px')};
margin-bottom: ${(p: any) => !p?.newDesign && '100px'};
display: flex;
height: inherit;
flex-direction: column;
align-content: center;
min-width: 500px;
max-width: auto;
`;

interface bottomButtonProps {
assigneeName?: string;
color?: any;
Expand Down
2 changes: 2 additions & 0 deletions frontend/app/src/helpers/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ export const userHasRole = (bountyRoles: any[], userRoles: any[], role: Roles):
};

export const toCapitalize = (word: string): string => {
if(!word.length) return word;

const wordString = word.split(' ');
const capitalizeStrings = wordString.map((w: string) => w[0].toUpperCase() + w.slice(1));

Expand Down
87 changes: 78 additions & 9 deletions frontend/app/src/people/widgetViews/OrganizationDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { useStores } from 'store';
import { Wrap } from 'components/form/style';
import { OrgWrap, Wrap } from 'components/form/style';
import { EuiGlobalToastList } from '@elastic/eui';
import { InvoiceForm, InvoiceInput, InvoiceLabel } from 'people/utils/style';
import moment from 'moment';
Expand All @@ -10,7 +10,7 @@ import { Button, IconButton } from 'components/common';
import { useIsMobile } from 'hooks/uiHooks';
import { Formik } from 'formik';
import { FormField, validator } from 'components/form/utils';
import { BountyRoles, Organization, PaymentHistory, Person } from 'store/main';
import { BountyRoles, BudgetHistory, Organization, PaymentHistory, Person } from 'store/main';
import MaterialIcon from '@material/react-material-icon';
import { userHasRole } from 'helpers';
import { Modal } from '../../components/common';
Expand Down Expand Up @@ -153,9 +153,11 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
const [isOpenRoles, setIsOpenRoles] = useState<boolean>(false);
const [isOpenBudget, setIsOpenBudget] = useState<boolean>(false);
const [isOpenHistory, setIsOpenHistory] = useState<boolean>(false);
const [isOpenBudgetHistory, setIsOpenBudgetHistory] = useState<boolean>(false);
const [usersCount, setUsersCount] = useState<number>(0);
const [orgBudget, setOrgBudget] = useState<number>(0);
const [paymentsHistory, setPaymentsHistory] = useState<PaymentHistory[]>([]);
const [budgetsHistory, setBudgetsHistory] = useState<BudgetHistory[]>([]);
const [disableFormButtons, setDisableFormButtons] = useState(false);
const [users, setUsers] = useState<Person[]>([]);
const [user, setUser] = useState<Person>();
Expand Down Expand Up @@ -260,14 +262,20 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
setPaymentsHistory(paymentHistories);
}, [main]);

const getBudgetHistory = useCallback(async () => {
const budgetHistories = await main.getBudgettHistories(uuid);
setBudgetsHistory(budgetHistories);
}, [main]);

const generateInvoice = async () => {
const token = ui.meInfo?.websocketToken;
if (token) {
const data = await main.getBudgetInvoice({
amount: amount,
sender_pubkey: ui.meInfo?.owner_pubkey ?? '',
org_uuid: uuid,
websocket_token: token
websocket_token: token,
payment_type: 'deposit'
});

setLnInvoice(data.response.invoice);
Expand Down Expand Up @@ -296,6 +304,10 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
setIsOpenHistory(false);
};

const closeBudgetHistoryHandler = () => {
setIsOpenBudgetHistory(false);
};

const onSubmit = async (body: any) => {
setIsLoading(true);

Expand Down Expand Up @@ -359,6 +371,7 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und

// get new organization budget
getOrganizationBudget();
getBudgetHistory();
closeBudgetHandler();
}
};
Expand All @@ -369,12 +382,14 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
getBountyRoles();
getOrganizationBudget();
getPaymentsHistory();
getBudgetHistory();
}, [
getOrganizationUsers,
getOrganizationUsersCount,
getBountyRoles,
getOrganizationBudget,
getPaymentsHistory
getPaymentsHistory,
getBudgetHistory
]);

useEffect(() => {
Expand Down Expand Up @@ -429,7 +444,10 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
/>
)}
{(isOrganizationAdmin || userHasRole(bountyRoles, userRoles, 'VIEW REPORT')) && (
<ViewHistoryText onClick={() => setIsOpenHistory(true)}>View history</ViewHistoryText>
<>
<ViewHistoryText onClick={() => setIsOpenBudgetHistory(true)}>Budget history</ViewHistoryText>
<ViewHistoryText onClick={() => setIsOpenHistory(true)}>Payment history</ViewHistoryText>
</>
)}
</DataCount>
</OrgInfoWrap>
Expand Down Expand Up @@ -545,8 +563,8 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
style={
item.name === 'github_description' && !values.ticket_url
? {
display: 'none'
}
display: 'none'
}
: undefined
}
/>
Expand Down Expand Up @@ -710,7 +728,7 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
borderRadius: '50%'
}}
>
<Wrap style={{ width: '300px' }}>
<OrgWrap style={{ width: '300px' }}>
<ModalTitle>Payment history</ModalTitle>
<table>
<thead>
Expand All @@ -730,7 +748,58 @@ const OrganizationDetails = (props: { close: () => void; org: Organization | und
))}
</tbody>
</table>
</Wrap>
</OrgWrap>
</Modal>
)}
{isOpenBudgetHistory && (
<Modal
visible={isOpenBudgetHistory}
style={{
height: '100%',
flexDirection: 'column',
}}
envStyle={{
marginTop: isMobile ? 64 : 0,
background: color.pureWhite,
zIndex: 20,
...(config?.modalStyle ?? {}),
maxHeight: '100%',
borderRadius: '10px'
}}
overlayClick={closeBudgetHistoryHandler}
bigCloseImage={closeBudgetHistoryHandler}
bigCloseImageStyle={{
top: '-18px',
right: '-18px',
background: '#000',
borderRadius: '50%'
}}
>
<OrgWrap>
<ModalTitle>Budget history</ModalTitle>
<table>
<thead>
<tr>
<th>Sender</th>
<th>Amount</th>
<th>Type</th>
<th>Status</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{budgetsHistory.map((b: BudgetHistory, i: number) => (
<tr key={i}>
<td className="ellipsis">{b.sender_name}</td>
<td>{b.amount} sats</td>
<td>{b.payment_type}</td>
<td>{b.status ? 'settled' : 'peending'}</td>
<td>{moment(b.created).fromNow()}</td>
</tr>
))}
</tbody>
</table>
</OrgWrap>
</Modal>
)}
</DetailsWrap>
Expand Down
6 changes: 3 additions & 3 deletions frontend/app/src/people/widgetViews/OrganizationView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const Organizations = (props: { person: Person }) => {
const isMobile = useIsMobile();
const config = widgetConfigs['organizations'];
const formRef = useRef(null);
const isMyProfile = ui?.meInfo?.pubkey == props.person.owner_pubkey;
const isMyProfile = ui?.meInfo?.pubkey == props?.person?.owner_pubkey;

const schema = [...config.schema];

Expand Down Expand Up @@ -247,8 +247,8 @@ const Organizations = (props: { person: Person }) => {
style={
item.name === 'github_description' && !values.ticket_url
? {
display: 'none'
}
display: 'none'
}
: undefined
}
/>
Expand Down
39 changes: 38 additions & 1 deletion frontend/app/src/store/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,18 @@ export interface PaymentHistory {
created: string;
}

export interface BudgetHistory {
id: number;
amount: number;
org_uuid: string;
payment_type: string;
created: string;
updated: string;
sender_pub_key: string;
sender_name: string;
status: boolean;
}

export interface PersonOffer {
person: PersonFlex;
title: string;
Expand Down Expand Up @@ -1541,6 +1553,7 @@ export class MainStore {
org_uuid: string;
sender_pubkey: string;
websocket_token: string;
payment_type: string;
}): Promise<LnInvoice> {
try {
const data = await api.post(
Expand All @@ -1549,7 +1562,8 @@ export class MainStore {
amount: body.amount,
org_uuid: body.org_uuid,
sender_pubkey: body.sender_pubkey,
websocket_token: body.websocket_token
websocket_token: body.websocket_token,
payment_type: body.payment_type
},
{
'Content-Type': 'application/json'
Expand Down Expand Up @@ -1815,6 +1829,7 @@ export class MainStore {

return r.json();
} catch (e) {
console.log('Error getOrganizationBudget', e);
return false;
}
}
Expand All @@ -1839,6 +1854,7 @@ export class MainStore {

return r;
} catch (e) {
console.log('Error makeBountyPayment', e);
return false;
}
}
Expand All @@ -1858,6 +1874,27 @@ export class MainStore {

return r.json();
} catch (e) {
console.log('Error getPaymentHistories', e);
return [];
}
}

async getBudgettHistories(uuid: string): Promise<BudgetHistory[]> {
try {
if (!uiStore.meInfo) return [];
const info = uiStore.meInfo;
const r: any = await fetch(`${TribesURL}/organizations/budget/history/${uuid}`, {
method: 'GET',
mode: 'cors',
headers: {
'x-jwt': info.tribe_jwt,
'Content-Type': 'application/json'
}
});

return r.json();
} catch (e) {
console.log('Error gettHistories', e);
return [];
}
}
Expand Down
9 changes: 9 additions & 0 deletions handlers/organizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,15 @@ func GetOrganizationBudget(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(organizationBudget)
}

func GetOrganizationBudgetHistory(w http.ResponseWriter, r *http.Request) {
uuid := chi.URLParam(r, "uuid")
// get the organization budget
organizationBudget := db.DB.GetOrganizationBudgetHistory(uuid)

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(organizationBudget)
}

func GetPaymentHistory(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string)
Expand Down
1 change: 1 addition & 0 deletions handlers/tribes.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ func GenerateBudgetInvoice(w http.ResponseWriter, r *http.Request) {
var budgetHistoryData = db.BudgetHistory{
Amount: invoice.Amount,
OrgUuid: invoice.OrgUuid,
PaymentType: invoice.PaymentType,
SenderPubKey: invoice.SenderPubKey,
Created: &now,
Updated: &now,
Expand Down
Loading