-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathsubscribe-profile-modal.tsx
More file actions
306 lines (277 loc) · 10 KB
/
Copy pathsubscribe-profile-modal.tsx
File metadata and controls
306 lines (277 loc) · 10 KB
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
// REACT IMPORTS
import React, { useEffect, useState } from 'react';
// REDUX IMPORTS
import { useDispatch } from 'react-redux';
// MUI IMPORTS
import Box from '@mui/material/Box';
import LoadingButton from '@mui/lab/LoadingButton';
import LinearProgress from '@mui/material/LinearProgress';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Divider,
Paper,
Stack,
TextField,
Typography,
} from '@mui/material';
// VIEM IMPORTS
import { Address, formatUnits, parseUnits } from 'viem';
// LOCAL IMPORTS
import NeonPaper from '@src/sections/publication/components/neon-paper-container.tsx';
import { useSubscribe } from '@src/hooks/protocol/use-subscribe.ts';
import { useGetPolicyTerms } from '@src/hooks/protocol/use-get-policy-terms.ts';
import { setBalance } from '@redux/auth';
import { useGetBalance } from '@src/hooks/protocol/use-get-balance.ts';
import { useNotifications } from '@src/hooks/use-notifications.ts';
import { useNotificationPayload } from '@src/hooks/use-notification-payload.ts';
import { notifyError, notifySuccess } from '@src/libs/notifications/internal-notifications.ts';
import { useAuth } from '@src/hooks/use-auth.ts';
import { GLOBAL_CONSTANTS } from '@src/config-global.ts';
import { SUCCESS } from '@src/libs/notifications/success.ts';
import { ERRORS } from '@src/libs/notifications/errors.ts';
import { User } from '@src/graphql/generated/graphql.ts';
import { resolveSrc } from '@src/utils/image.ts';
// ----------------------------------------------------------------------
interface SubscribeProfileModalProps {
isOpen: boolean;
onClose: () => void;
onSubscribe: () => void;
profile: User;
}
// ----------------------------------------------------------------------
export const SubscribeProfileModal = ({
isOpen,
onClose,
profile,
onSubscribe,
}: SubscribeProfileModalProps) => {
const [selectedDuration, setSelectedDuration] = useState('7');
const [customDuration, setCustomDuration] = useState('');
const dispatch = useDispatch();
const { session: sessionData, balance: balanceFromRedux } = useAuth();
const { balance: balanceFromContract, refetch } = useGetBalance();
const { data, error, loading, subscribe } = useSubscribe();
const { sendNotification } = useNotifications();
const { generatePayload } = useNotificationPayload(sessionData);
const { terms, loading: loadingTerms } = useGetPolicyTerms(
GLOBAL_CONSTANTS.SUBSCRIPTION_POLICY_ADDRESS as Address,
profile?.address as Address
);
useEffect(() => {
if (balanceFromContract) {
dispatch(setBalance({ balance: balanceFromContract }));
}
}, [balanceFromContract]);
// Options for predefined durations
const durationOptions = [
{ value: '7', title: '1 week' },
{ value: '15', title: '15 days' },
{ value: '30', title: '1 month' },
];
// Calculate total cost and check if the balance is sufficient
const duration = customDuration || selectedDuration || '0';
const durationDays = parseInt(duration);
const minDays = 7;
const isCustomDurationInvalid = customDuration && (isNaN(durationDays) || durationDays < minDays);
let totalCostWei = BigInt(0);
let totalCostMMC = '0.00';
if (!isCustomDurationInvalid && durationDays >= minDays && terms?.amount) {
totalCostWei = terms.amount * BigInt(durationDays);
totalCostMMC = formatUnits(totalCostWei, 18); // Convert Wei to MMC
}
const balanceWei = balanceFromRedux
? parseUnits(balanceFromRedux.toString(), 18)
: BigInt(0);
const isBalanceSufficient = balanceWei && totalCostWei && balanceWei >= totalCostWei;
// Determine if the subscribe button should be disabled
const isButtonDisabled =
loading ||
(!selectedDuration && !customDuration) ||
isCustomDurationInvalid ||
!isBalanceSufficient;
// Effect to handle subscription errors
useEffect(() => {
if (error) {
notifyError(error as ERRORS);
}
}, [error]);
// Effect to handle successful subscription
useEffect(() => {
if (data?.receipt) {
notifySuccess(SUCCESS.PROFILE_JOINED_SUCCESSFULLY);
onSubscribe?.();
refetch?.();
onClose?.();
}
}, [data]);
// Handler for changing the selected duration
const handleDurationChange = (value: string) => {
setSelectedDuration(value);
setCustomDuration('');
};
// Handler for changing the custom duration
const handleCustomDurationChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSelectedDuration('');
setCustomDuration(event.target.value);
};
// Handler for the subscribe action
const handleSubscribe = async () => {
if (!duration) {
return;
}
if (isCustomDurationInvalid) {
notifyError(ERRORS.SUBSCRIBE_MINIMUN_DAYS_ERROR);
return;
}
if (!isBalanceSufficient) {
notifyError(ERRORS.INSUFICIENT_BALANCE_ERROR);
return;
}
try {
// Proceed with the subscription using the calculated amount
await subscribe({
holderAddress: profile?.address as Address,
amount: totalCostMMC,
}).then(async () => {
// Send notification to the profile owner
const notificationPayload = generatePayload(
'JOIN',
{
id: profile.address,
displayName: profile?.displayName ?? 'no name',
avatar: resolveSrc(profile?.profilePicture || profile?.address, 'profile')
},
{
durationDays: `${durationDays}`,
totalCostMMC,
rawDescription: `${sessionData?.user?.displayName} has joined to your content`,
}
);
await sendNotification(profile.address, sessionData?.user?.address ?? '', notificationPayload);
});
} catch (err) {
console.error(err);
notifyError(ERRORS.FAILED_JOIN_PROFILE_ERROR);
}
};
const RainbowEffect = loading ? NeonPaper : Box;
return (
<>
<Dialog open={isOpen} onClose={onClose} fullWidth maxWidth="xs">
<DialogTitle sx={{ pb: 2 }}>Access {profile?.displayName}'s content</DialogTitle>
<Divider sx={{ mb: 2, borderStyle: 'dashed' }} />
<DialogContent>
{loadingTerms ? (
<LinearProgress
color="inherit"
sx={{ width: 1, maxWidth: 360, marginTop: '16px', alignSelf: 'center' }}
/>
) : (
<>
<Typography variant="body2" color="textSecondary" sx={{ mb: 3 }}>
Select how many days you'd like to join.
</Typography>
<Stack spacing={2}>
<Stack spacing={2} direction="row">
{durationOptions.map((option) => (
<Paper
key={option.value}
onClick={() => handleDurationChange(option.value)}
sx={{
p: 1.5,
cursor: 'pointer',
width: '33%',
backgroundColor: 'transparent',
opacity: selectedDuration === option.value ? 1 : 0.4,
border:
selectedDuration === option.value
? '2px solid rgba(255,255,255,0.3)'
: '1px solid rgba(255,255,255,0.3)',
'&:hover': { opacity: 1 },
}}
>
<Typography align="center" variant="body1" fontWeight="bold">
{option.title}
</Typography>
</Paper>
))}
</Stack>
<TextField
type="number"
placeholder="Enter custom days (min 7 days)"
fullWidth
value={customDuration}
onChange={handleCustomDurationChange}
InputProps={{
inputProps: { min: 7 },
}}
/>
</Stack>
<Divider sx={{ my: 2, borderStyle: 'dashed' }} />
<Stack spacing={1}>
<Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
Total Cost:
</Typography>
{!isCustomDurationInvalid && durationDays >= minDays ? (
<Stack
spacing={0}
sx={{
p: 1,
backgroundColor: 'rgba(255,255,255,0.05)',
borderRadius: 1,
flexGrow: 1,
textAlign: 'center',
}}
>
<Typography variant="h6" color={isBalanceSufficient ? 'text.primary' : 'error'}>
{totalCostMMC} MMC
</Typography>
<Typography variant="body2" color="textSecondary">
for {durationDays} days
</Typography>
</Stack>
) : (
<Typography variant="body2" color="error" sx={{ mt: 1 }}>
Please enter a valid number of days (minimum {minDays} days).
</Typography>
)}
</Stack>
</>
)}
</DialogContent>
{!loadingTerms && (
<>
<Divider sx={{ mt: 3, borderStyle: 'dashed' }} />
<DialogActions>
<Button variant="text" onClick={onClose}>
Cancel
</Button>
<RainbowEffect
{...(loading && {
borderRadius: '10px',
animationSpeed: '3s',
padding: '0',
width: 'auto',
})}
>
<LoadingButton
variant="contained"
sx={{ backgroundColor: '#fff' }}
onClick={handleSubscribe}
disabled={isButtonDisabled}
loading={loading}
>
Join
</LoadingButton>
</RainbowEffect>
</DialogActions>
</>
)}
</Dialog>
</>
);
};