After changing about commission dispatch and adding sharing card7

This commit is contained in:
Your Name 2026-08-02 14:14:54 +02:00
parent 867a8c830d
commit 704bee9bd6
12 changed files with 264 additions and 90 deletions

View File

@ -12,7 +12,7 @@ function sendError(res: Response, e: unknown, fallback: string): void {
export async function getConfig(req: AuthRequest, res: Response): Promise<void> {
try {
const config = await shareCardService.getConfigForUser();
const config = await shareCardService.getConfigForUser(req.user!.userId);
res.json(config);
} catch (e) {
sendError(res, e, 'Failed');

View File

@ -5,6 +5,7 @@
import crypto from 'crypto';
import { config } from '../config';
import { query } from '../db/connection';
import { getPublicWebBaseUrl, buildReferralRegisterLink } from '../utils/publicWebUrl';
import * as shareCardRepository from '../repositories/shareCardRepository';
import * as candlePredictRepository from '../repositories/candlePredictRepository';
@ -25,7 +26,13 @@ export type ShareableWalletOpType =
const STAKE_DECIMALS = 6;
export function mapSettingsForClient(row: ShareCardSettingsRow) {
export function mapSettingsForClient(
row: ShareCardSettingsRow,
extras?: {
referrerMustHaveDeposited?: boolean;
hasDeposited?: boolean;
}
) {
return {
enabled: Boolean(row.enabled),
allowMainWallet: Boolean(row.allow_main_wallet),
@ -38,13 +45,44 @@ export function mapSettingsForClient(row: ShareCardSettingsRow) {
allowDeposit: row.allow_deposit !== false,
allowWithdrawal: row.allow_withdrawal !== false,
allowTransfer: row.allow_transfer !== false,
referrerMustHaveDeposited: extras?.referrerMustHaveDeposited === true,
hasDeposited: extras?.hasDeposited === true,
updatedAt: row.updated_at.toISOString(),
};
}
async function userHasRealDeposit(userId: string): Promise<boolean> {
const rows = await query<Array<{ ok: boolean }>>(
`SELECT (first_deposit_at IS NOT NULL) AS ok
FROM users
WHERE id = $1 AND deleted_at IS NULL`,
[userId]
);
return Boolean(rows[0]?.ok);
}
async function referralShareGate(userId: string): Promise<{
referrerMustHaveDeposited: boolean;
hasDeposited: boolean;
}> {
const [referralSettings, hasDeposited] = await Promise.all([
referralRepository.getSettings(),
userHasRealDeposit(userId),
]);
return {
referrerMustHaveDeposited: Boolean(referralSettings.referrer_must_have_deposited),
hasDeposited,
};
}
export function canSharePredictionResult(
settings: ShareCardSettingsRow,
input: { stakeAccountKind: StakeAccountKind; status: string }
input: {
stakeAccountKind: StakeAccountKind;
status: string;
referrerMustHaveDeposited?: boolean;
hasDeposited?: boolean;
}
): boolean {
if (!settings.enabled) return false;
if (input.status !== 'won' && input.status !== 'lost' && input.status !== 'refunded') {
@ -52,7 +90,11 @@ export function canSharePredictionResult(
}
if (input.stakeAccountKind === 'main' && !settings.allow_main_wallet) return false;
if (input.stakeAccountKind === 'bonus' && !settings.allow_bonus_wallet) return false;
if (input.stakeAccountKind === 'test' && !settings.allow_test_wallet) return false;
if (input.stakeAccountKind === 'test') {
if (!settings.allow_test_wallet) return false;
// Block test-wallet promo when referral requires a real deposit and user has none.
if (input.referrerMustHaveDeposited && !input.hasDeposited) return false;
}
if (input.status === 'won' && !settings.allow_won) return false;
if (input.status === 'lost' && !settings.allow_lost) return false;
if (input.status === 'refunded' && !settings.allow_refunded) return false;
@ -290,9 +332,12 @@ async function buildWalletOpCardPayload(
};
}
export async function getConfigForUser() {
const settings = await shareCardRepository.getSettings();
return mapSettingsForClient(settings);
export async function getConfigForUser(userId: string) {
const [settings, gate] = await Promise.all([
shareCardRepository.getSettings(),
referralShareGate(userId),
]);
return mapSettingsForClient(settings, gate);
}
export async function getSettingsForAdmin() {
@ -332,12 +377,25 @@ export async function getSharePayloadForOwner(userId: string, betId: string) {
if (!bet || bet.user_id !== userId) {
throw new ShareCardError('Prediction not found', 404);
}
const gate = await referralShareGate(userId);
if (
!canSharePredictionResult(settings, {
stakeAccountKind: bet.stake_account_kind,
status: bet.status,
referrerMustHaveDeposited: gate.referrerMustHaveDeposited,
hasDeposited: gate.hasDeposited,
})
) {
if (
bet.stake_account_kind === 'test' &&
gate.referrerMustHaveDeposited &&
!gate.hasDeposited
) {
throw new ShareCardError(
'You must make at least one real-funds deposit before sharing Test Wallet results and using your referral link.',
403
);
}
throw new ShareCardError('Sharing is not available for this prediction', 403);
}
const referralCode = await referralRepository.getUserReferralCode(userId);

View File

@ -70,6 +70,30 @@ describe('share card eligibility', () => {
);
});
test('blocks test wallet when referrer must deposit and has not', () => {
assert.equal(
canSharePredictionResult(settings({ allow_test_wallet: true }), {
stakeAccountKind: 'test',
status: 'won',
referrerMustHaveDeposited: true,
hasDeposited: false,
}),
false
);
});
test('allows test wallet when referrer deposit rule is satisfied', () => {
assert.equal(
canSharePredictionResult(settings({ allow_test_wallet: true }), {
stakeAccountKind: 'test',
status: 'won',
referrerMustHaveDeposited: true,
hasDeposited: true,
}),
true
);
});
test('wallet ops respect global and per-type flags', () => {
assert.equal(canShareWalletOperation(settings(), { type: 'deposit' }), true);
assert.equal(canShareWalletOperation(settings(), { type: 'bonus' }), true);

View File

@ -11,6 +11,8 @@ class ShareCardConfig {
required this.allowDeposit,
required this.allowWithdrawal,
required this.allowTransfer,
required this.referrerMustHaveDeposited,
required this.hasDeposited,
});
final bool enabled;
@ -24,6 +26,8 @@ class ShareCardConfig {
final bool allowDeposit;
final bool allowWithdrawal;
final bool allowTransfer;
final bool referrerMustHaveDeposited;
final bool hasDeposited;
factory ShareCardConfig.fromJson(Map<String, dynamic> json) {
return ShareCardConfig(
@ -38,6 +42,8 @@ class ShareCardConfig {
allowDeposit: json['allowDeposit'] != false,
allowWithdrawal: json['allowWithdrawal'] != false,
allowTransfer: json['allowTransfer'] != false,
referrerMustHaveDeposited: json['referrerMustHaveDeposited'] == true,
hasDeposited: json['hasDeposited'] == true,
);
}
@ -50,7 +56,10 @@ class ShareCardConfig {
final kind = stakeAccountKind ?? 'main';
if (kind == 'main' && !allowMainWallet) return false;
if (kind == 'bonus' && !allowBonusWallet) return false;
if (kind == 'test' && !allowTestWallet) return false;
if (kind == 'test') {
if (!allowTestWallet) return false;
if (referrerMustHaveDeposited && !hasDeposited) return false;
}
if (status == null || status.isEmpty) return !requireStatus;
if (status != 'won' && status != 'lost' && status != 'refunded') return false;
if (status == 'won' && !allowWon) return false;
@ -59,6 +68,13 @@ class ShareCardConfig {
return true;
}
bool isTestWalletBlockedByDeposit(String? stakeAccountKind) {
return stakeAccountKind == 'test' &&
allowTestWallet &&
referrerMustHaveDeposited &&
!hasDeposited;
}
bool isWalletOpEligible(String operationType) {
if (!enabled || !walletOpsEnabled) return false;
switch (operationType) {
@ -92,6 +108,7 @@ class ShareCardPayload {
const ShareCardPayload({
required this.kind,
required this.verifyUrl,
required this.registerUrl,
this.betId,
this.gameName,
this.direction,
@ -116,6 +133,7 @@ class ShareCardPayload {
final String kind; // prediction | wallet
final String verifyUrl;
final String registerUrl;
// Prediction
final String? betId;
@ -149,6 +167,7 @@ class ShareCardPayload {
return ShareCardPayload(
kind: kind,
verifyUrl: (json['verifyUrl'] ?? '').toString(),
registerUrl: (json['registerUrl'] ?? json['verifyUrl'] ?? '').toString(),
betId: json['betId']?.toString(),
gameName: (json['gameName'] ?? 'Candle Predict').toString(),
direction: (json['direction'] ?? 'long').toString(),

View File

@ -106,7 +106,7 @@ class _ShareResultDialogState extends State<_ShareResultDialog> {
await SharePlus.instance.share(
ShareParams(
files: [XFile(file.path)],
text: payload.verifyUrl,
text: payload.registerUrl.isNotEmpty ? payload.registerUrl : payload.verifyUrl,
subject: 'Prediqo',
),
);
@ -471,10 +471,16 @@ class _ShareResultIconButtonState extends State<ShareResultIconButton> {
@override
Widget build(BuildContext context) {
final isWallet = widget.transactionId != null;
final s = context.strings;
final blockedMsg = s.t(
'You must make at least one real-funds deposit before sharing Test Wallet results and using your referral link.',
'Vous devez effectuer au moins un dépôt avec des fonds réels avant de pouvoir partager vos résultats Test Wallet et utiliser votre lien de parrainage.',
);
// While loading wallet-op share, keep the icon visible so the action is discoverable.
if (!_loaded && isWallet) {
return IconButton(
tooltip: context.strings.t('Share result', 'Partager le résultat'),
tooltip: s.t('Share result', 'Partager le résultat'),
icon: const Icon(Icons.ios_share_rounded, color: AppColors.primary),
visualDensity: VisualDensity.compact,
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
@ -487,6 +493,9 @@ class _ShareResultIconButtonState extends State<ShareResultIconButton> {
);
}
if (!_loaded || _config == null) return const SizedBox.shrink();
final blockedByDeposit =
!isWallet && _config!.isTestWalletBlockedByDeposit(widget.stakeAccountKind);
final ok = isWallet
? _config!.isWalletOpEligible(widget.operationType ?? '')
: _config!.isPredictionEligible(
@ -494,18 +503,30 @@ class _ShareResultIconButtonState extends State<ShareResultIconButton> {
stakeAccountKind: widget.stakeAccountKind,
requireStatus: widget.requireStatus,
);
if (!ok) return const SizedBox.shrink();
if (!ok && !blockedByDeposit) return const SizedBox.shrink();
return IconButton(
tooltip: context.strings.t('Share result', 'Partager le résultat'),
icon: const Icon(Icons.ios_share_rounded, color: AppColors.primary),
tooltip: blockedByDeposit
? blockedMsg
: s.t('Share result', 'Partager le résultat'),
icon: Icon(
Icons.ios_share_rounded,
color: blockedByDeposit ? AppColors.textMuted : AppColors.primary,
),
visualDensity: VisualDensity.compact,
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
padding: EdgeInsets.zero,
onPressed: () => openShareResultDialog(
context,
betId: widget.betId,
transactionId: widget.transactionId,
),
onPressed: () {
if (blockedByDeposit) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(blockedMsg)));
return;
}
openShareResultDialog(
context,
betId: widget.betId,
transactionId: widget.transactionId,
);
},
);
}
}

View File

@ -483,13 +483,6 @@ export function RecentPredictionsPanel({
bgcolor: `${statusColor(p.status)}14`,
}}
/>
<Box sx={{ ml: 'auto' }}>
<ShareResultButton
betId={p.id}
status={p.status}
stakeAccountKind={p.stakeAccountKind}
/>
</Box>
</Stack>
<Box sx={{ mb: 1 }}>
@ -511,6 +504,16 @@ export function RecentPredictionsPanel({
payout,
})}
</Typography>
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center', mt: 0.5 }}>
<Typography variant="body2" sx={{ fontWeight: 800 }}>
{typeof payout === 'number' ? `+${payout}` : payout}
</Typography>
<ShareResultButton
betId={p.id}
status={p.status}
stakeAccountKind={p.stakeAccountKind}
/>
</Stack>
{progressDetail && !isMultiPrediction(p) && (
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 600, display: 'block' }}>
{progressDetail}
@ -552,10 +555,9 @@ export function RecentPredictionsPanel({
</TableCell>
<TableCell sx={{ width: 88 }}>{t(`${cols}.account`)}</TableCell>
<TableCell sx={{ minWidth: 110 }}>{t(`${cols}.status`)}</TableCell>
<TableCell align="right" sx={{ width: 72 }}>
<TableCell align="right" sx={{ width: 96 }}>
{t(`${cols}.payout`)}
</TableCell>
<TableCell sx={{ width: 48 }} />
</TableRow>
</TableHead>
<TableBody>
@ -608,14 +610,20 @@ export function RecentPredictionsPanel({
</Stack>
</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap', fontWeight: 600 }}>
{p.payoutDisplay > 0 ? p.payoutDisplay : '—'}
</TableCell>
<TableCell>
<ShareResultButton
betId={p.id}
status={p.status}
stakeAccountKind={p.stakeAccountKind}
/>
<Stack
direction="row"
spacing={0.5}
sx={{ alignItems: 'center', justifyContent: 'flex-end' }}
>
<Box component="span">
{p.payoutDisplay > 0 ? p.payoutDisplay : '—'}
</Box>
<ShareResultButton
betId={p.id}
status={p.status}
stakeAccountKind={p.stakeAccountKind}
/>
</Stack>
</TableCell>
</TableRow>
);

View File

@ -7,7 +7,11 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useShareCardConfig } from './hooks';
import { ShareResultDialog } from './ShareResultDialog';
import { isPredictionShareEligible, isWalletOpShareEligible } from './types';
import {
isPredictionShareEligible,
isTestWalletShareBlockedByDeposit,
isWalletOpShareEligible,
} from './types';
type PredictionProps = {
kind?: 'prediction';
@ -46,34 +50,48 @@ export function ShareResultButton(props: Props) {
requireStatus: props.requireStatus ?? true,
});
if (!eligible) return null;
const blockedByDeposit =
props.kind !== 'wallet' &&
isTestWalletShareBlockedByDeposit(configQ.data, props.stakeAccountKind);
if (!eligible && !blockedByDeposit) return null;
const targetKey =
props.kind === 'wallet' ? props.transactionId : props.betId;
const tooltip = blockedByDeposit
? t('shareCard.testWalletNeedsDeposit')
: t('shareCard.share');
return (
<>
<Tooltip title={t('shareCard.share')}>
<IconButton
size={size}
color="primary"
onClick={(e) => {
e.stopPropagation();
setSession((n) => n + 1);
setOpen(true);
}}
aria-label={t('shareCard.share')}
>
<ShareRoundedIcon fontSize="inherit" />
</IconButton>
<Tooltip title={tooltip}>
<span>
<IconButton
size={size}
color="primary"
disabled={blockedByDeposit}
onClick={(e) => {
e.stopPropagation();
if (blockedByDeposit) return;
setSession((n) => n + 1);
setOpen(true);
}}
aria-label={tooltip}
>
<ShareRoundedIcon fontSize="inherit" />
</IconButton>
</span>
</Tooltip>
<ShareResultDialog
key={`${targetKey}-${session}`}
open={open}
betId={props.kind === 'wallet' ? null : props.betId}
transactionId={props.kind === 'wallet' ? props.transactionId : null}
onClose={() => setOpen(false)}
/>
{!blockedByDeposit ? (
<ShareResultDialog
key={`${targetKey}-${session}`}
open={open}
betId={props.kind === 'wallet' ? null : props.betId}
transactionId={props.kind === 'wallet' ? props.transactionId : null}
onClose={() => setOpen(false)}
/>
) : null}
</>
);
}

View File

@ -73,14 +73,14 @@ function canShareUrlOnly(): boolean {
return typeof nav.share === 'function';
}
function shareCaption(verifyUrl: string): string {
return `Prediqo — ${verifyUrl}`;
function shareCaption(inviteUrl: string): string {
return `Prediqo — ${inviteUrl}`;
}
async function tryNativeShare(opts: {
blob: Blob;
filename: string;
verifyUrl: string;
inviteUrl: string;
}): Promise<'shared' | 'cancelled' | 'unsupported'> {
const nav = navigator as NavShare;
if (typeof nav.share !== 'function') return 'unsupported';
@ -93,15 +93,15 @@ async function tryNativeShare(opts: {
await nav.share({
files: [file],
title: 'Prediqo',
text: shareCaption(opts.verifyUrl),
text: shareCaption(opts.inviteUrl),
});
return 'shared';
}
// Desktop / limited browsers: share link only (no silent download).
// Desktop / limited browsers: share invite link only (no silent download).
await nav.share({
title: 'Prediqo',
text: shareCaption(opts.verifyUrl),
url: opts.verifyUrl,
text: shareCaption(opts.inviteUrl),
url: opts.inviteUrl,
});
return 'shared';
} catch (e) {
@ -233,7 +233,7 @@ export function ShareResultDialog({ open, betId, transactionId, onClose }: Props
const result = await tryNativeShare({
blob: exported.blob,
filename: exported.filename,
verifyUrl: payload.verifyUrl,
inviteUrl: payload.registerUrl,
});
if (result === 'shared') {
setHint(t('shareCard.sharedOrDownloaded'));
@ -257,7 +257,7 @@ export function ShareResultDialog({ open, betId, transactionId, onClose }: Props
const copyLink = async () => {
if (!payload) return;
closeMenu();
const ok = await copyTextToClipboard(payload.verifyUrl);
const ok = await copyTextToClipboard(payload.registerUrl);
setHint(ok ? t('shareCard.linkCopied') : t('shareCard.exportFailed'));
};
@ -266,9 +266,9 @@ export function ShareResultDialog({ open, betId, transactionId, onClose }: Props
window.open(url, '_blank', 'noopener,noreferrer');
};
const verifyUrl = payload?.verifyUrl ?? '';
const encodedUrl = encodeURIComponent(verifyUrl);
const encodedText = encodeURIComponent(shareCaption(verifyUrl));
const inviteUrl = payload?.registerUrl ?? '';
const encodedUrl = encodeURIComponent(inviteUrl);
const encodedText = encodeURIComponent(shareCaption(inviteUrl));
return (
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>

View File

@ -10,6 +10,10 @@ export type ShareCardConfig = {
allowDeposit: boolean;
allowWithdrawal: boolean;
allowTransfer: boolean;
/** From referral program: referrer must have deposited. */
referrerMustHaveDeposited: boolean;
/** Whether the current user has a real-funds first deposit. */
hasDeposited: boolean;
updatedAt?: string;
};
@ -103,7 +107,10 @@ export function isPredictionShareEligible(
const kind = input.stakeAccountKind ?? 'main';
if (kind === 'main' && !c.allowMainWallet) return false;
if (kind === 'bonus' && !c.allowBonusWallet) return false;
if (kind === 'test' && !c.allowTestWallet) return false;
if (kind === 'test') {
if (!c.allowTestWallet) return false;
if (c.referrerMustHaveDeposited && !c.hasDeposited) return false;
}
const status = input.status;
if (!status) {
@ -116,6 +123,16 @@ export function isPredictionShareEligible(
return true;
}
/** True when Test Wallet share is blocked only by the referral deposit rule. */
export function isTestWalletShareBlockedByDeposit(
config: ShareCardConfig | null | undefined,
stakeAccountKind?: string | null
): boolean {
const c = normalizeShareCardConfig(config ?? undefined);
if (!c || stakeAccountKind !== 'test') return false;
return Boolean(c.allowTestWallet && c.referrerMustHaveDeposited && !c.hasDeposited);
}
/** Normalize partial / legacy API payloads so wallet-op flags default to ON. */
export function normalizeShareCardConfig(
raw: Partial<ShareCardConfig> | null | undefined
@ -133,6 +150,8 @@ export function normalizeShareCardConfig(
allowDeposit: raw.allowDeposit !== false,
allowWithdrawal: raw.allowWithdrawal !== false,
allowTransfer: raw.allowTransfer !== false,
referrerMustHaveDeposited: raw.referrerMustHaveDeposited === true,
hasDeposited: raw.hasDeposited === true,
updatedAt: raw.updatedAt,
};
}

View File

@ -201,23 +201,26 @@ export function TransactionList({
</Stack>
</TableCell>
<TableCell>
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center' }}>
<Typography variant="body2">{txLabel(tx)}</Typography>
{/* Beside the label so share stays visible without horizontal scroll */}
{shareButton}
</Stack>
<Typography variant="body2">{txLabel(tx)}</Typography>
</TableCell>
<TableCell align="right">
<Typography
variant="body2"
sx={{
fontWeight: 700,
color: credit ? 'success.main' : 'warning.main',
}}
<Stack
direction="row"
spacing={0.5}
sx={{ alignItems: 'center', justifyContent: 'flex-end' }}
>
{credit ? '+' : '−'}
{human}
</Typography>
<Typography
variant="body2"
sx={{
fontWeight: 700,
color: credit ? 'success.main' : 'warning.main',
}}
>
{credit ? '+' : '−'}
{human}
</Typography>
{shareButton}
</Stack>
</TableCell>
<TableCell>
<Chip

View File

@ -217,15 +217,15 @@ export const en = {
shareCard: {
share: 'Share',
shareVia: 'Share via…',
copyLink: 'Copy verify link',
linkCopied: 'Verify link copied to clipboard.',
copyLink: 'Copy invite link',
linkCopied: 'Invite link copied to clipboard.',
openNativeShare: 'Device share sheet',
shareWhatsApp: 'WhatsApp',
shareTelegram: 'Telegram',
shareX: 'X (Twitter)',
shareFacebook: 'Facebook',
nativeShareUnavailable:
'Your browser cannot share images directly. Copy the verify link or download the card, then post it on social media.',
'Your browser cannot share images directly. Copy the invite link or download the card, then post it on social media.',
cancel: 'Cancel',
download: 'Download',
previewTitle: 'Share card preview',
@ -234,6 +234,8 @@ export const en = {
downloaded: 'Card downloaded.',
sharedOrDownloaded: 'Shared successfully.',
exportFailed: 'Could not export the card image.',
testWalletNeedsDeposit:
'You must make at least one real-funds deposit before sharing Test Wallet results and using your referral link.',
prediction: 'Prediction',
interval: 'Interval',
intervalValue: '{{minutes}} min',

View File

@ -223,15 +223,15 @@ export const fr = {
shareCard: {
share: 'Partager',
shareVia: 'Partager via…',
copyLink: 'Copier le lien de vérification',
linkCopied: 'Lien de vérification copié.',
copyLink: 'Copier le lien d’invitation',
linkCopied: 'Lien d’invitation copié.',
openNativeShare: 'Partage de l’appareil',
shareWhatsApp: 'WhatsApp',
shareTelegram: 'Telegram',
shareX: 'X (Twitter)',
shareFacebook: 'Facebook',
nativeShareUnavailable:
'Votre navigateur ne peut pas partager d’image directement. Copiez le lien de vérification ou téléchargez la carte, puis publiez-la sur les réseaux.',
'Votre navigateur ne peut pas partager d’image directement. Copiez le lien d’invitation ou téléchargez la carte, puis publiez-la sur les réseaux.',
cancel: 'Annuler',
download: 'Télécharger',
previewTitle: 'Aperçu de la carte',
@ -241,6 +241,8 @@ export const fr = {
downloaded: 'Carte téléchargée.',
sharedOrDownloaded: 'Partage réussi.',
exportFailed: 'Impossible d’exporter l’image de la carte.',
testWalletNeedsDeposit:
'Vous devez effectuer au moins un dépôt avec des fonds réels avant de pouvoir partager vos résultats Test Wallet et utiliser votre lien de parrainage.',
prediction: 'Prédiction',
interval: 'Intervalle',
intervalValue: '{{minutes}} min',