forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollaboration.service.ts
More file actions
364 lines (327 loc) · 12.9 KB
/
Copy pathcollaboration.service.ts
File metadata and controls
364 lines (327 loc) · 12.9 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import {
Injectable,
NotFoundException,
BadRequestException,
ForbiddenException,
ConflictException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource, Not, IsNull } from "typeorm";
import {
Collaboration,
CollaborationStatus,
} from "./entities/collaboration.entity";
import { Artist } from "../artists/entities/artist.entity";
import { CreateCollaborationDto } from "./dto/create-collaboration.dto";
import { RespondToCollaborationDto } from "./dto/update-collaboration.dto";
import { CollaborationNotificationService } from "./services/notification.service";
@Injectable()
export class CollaborationService {
constructor(
@InjectRepository(Collaboration)
private readonly collaborationRepository: Repository<Collaboration>,
@InjectRepository(Artist)
private readonly artistRepository: Repository<Artist>,
private readonly dataSource: DataSource,
private readonly notificationService: CollaborationNotificationService,
) {}
async createCollaboration(
inviterWallet: string,
createDto: CreateCollaborationDto,
): Promise<Collaboration> {
return await this.dataSource.transaction(async (manager) => {
// Check if artist exists
const artist = await manager.findOne(Artist, {
where: { walletAddress: createDto.artistWalletAddress },
});
if (!artist) {
throw new NotFoundException("Artist not found");
}
// Check for duplicate invitation
const existingCollaboration = await manager.findOne(Collaboration, {
where: {
trackId: createDto.trackId,
artistId: artist.id,
status: CollaborationStatus.INVITED,
},
});
if (existingCollaboration) {
throw new ConflictException(
"Collaboration invitation already exists",
);
}
// Validate split percentage if provided
if (createDto.splitPercentage !== undefined) {
await this.validateSplitPercentage(
manager,
createDto.trackId,
createDto.splitPercentage,
);
}
// Create collaboration
const collaboration = manager.create(Collaboration, {
...createDto,
artistId: artist.id,
invitedBy: inviterWallet,
status: CollaborationStatus.INVITED,
auditLog: [
{
action: "invited",
performedBy: inviterWallet,
performedAt: new Date(),
details: {
role: createDto.role,
type: createDto.type,
splitPercentage: createDto.splitPercentage,
},
},
],
});
const savedCollaboration = await manager.save(collaboration);
// Send notification to artist
await this.notificationService.sendCollaborationInvitation(
artist.walletAddress,
{
collaborationId: savedCollaboration.id,
trackTitle: createDto.trackTitle,
inviterWallet,
role: createDto.role,
message: createDto.message,
},
);
return savedCollaboration;
});
}
async respondToCollaboration(
collaborationId: string,
artistWallet: string,
responseDto: RespondToCollaborationDto,
): Promise<Collaboration> {
return await this.dataSource.transaction(async (manager) => {
const collaboration = await manager.findOne(Collaboration, {
where: { id: collaborationId },
relations: ["artist"],
});
if (!collaboration) {
throw new NotFoundException("Collaboration not found");
}
// Verify the responding artist
if (collaboration.artist.walletAddress !== artistWallet) {
throw new ForbiddenException(
"You can only respond to your own invitations",
);
}
// Check if invitation is still pending
if (collaboration.status !== CollaborationStatus.INVITED) {
throw new BadRequestException(
"This invitation is no longer pending",
);
}
// Update collaboration
const updatedCollaboration = await manager.save(Collaboration, {
...collaboration,
status: responseDto.status,
respondedAt: new Date(),
respondedBy: artistWallet,
responseMessage: responseDto.responseMessage,
auditLog: [
...(collaboration.auditLog || []),
{
action:
responseDto.status === CollaborationStatus.ACTIVE
? "accepted"
: "rejected",
performedBy: artistWallet,
performedAt: new Date(),
details: {
responseMessage: responseDto.responseMessage,
},
},
],
});
// Send notification to inviter
await this.notificationService.sendCollaborationResponse(
collaboration.invitedBy,
{
collaborationId: collaboration.id,
artistName: collaboration.artist.displayName,
artistWallet: artistWallet,
status: responseDto.status,
responseMessage: responseDto.responseMessage,
},
);
return updatedCollaboration;
});
}
async removeCollaboration(
collaborationId: string,
removerWallet: string,
removalReason: string,
): Promise<Collaboration> {
return await this.dataSource.transaction(async (manager) => {
const collaboration = await manager.findOne(Collaboration, {
where: { id: collaborationId },
relations: ["artist"],
});
if (!collaboration) {
throw new NotFoundException("Collaboration not found");
}
// Verify remover is either the inviter or the artist
if (
collaboration.invitedBy !== removerWallet &&
collaboration.artist.walletAddress !== removerWallet
) {
throw new ForbiddenException(
"You can only remove collaborations you are involved in",
);
}
// Update collaboration
const updatedCollaboration = await manager.save(Collaboration, {
...collaboration,
status: CollaborationStatus.REMOVED,
removedAt: new Date(),
removedBy: removerWallet,
removalReason,
auditLog: [
...(collaboration.auditLog || []),
{
action: "removed",
performedBy: removerWallet,
performedAt: new Date(),
details: { removalReason },
},
],
});
// Send notification to the other party
const notifiedParty =
collaboration.invitedBy === removerWallet
? collaboration.artist.walletAddress
: collaboration.invitedBy;
await this.notificationService.sendCollaborationRemoval(
notifiedParty,
{
collaborationId: collaboration.id,
removerWallet,
removalReason,
},
);
return updatedCollaboration;
});
}
async getCollaborationsForUser(
userWallet: string,
status?: CollaborationStatus,
page = 1,
limit = 10,
): Promise<{ collaborations: Collaboration[]; total: number }> {
const queryBuilder = this.collaborationRepository
.createQueryBuilder("collaboration")
.leftJoinAndSelect("collaboration.artist", "artist")
.where(
"(collaboration.invitedBy = :userWallet OR collaboration.artist.walletAddress = :userWallet)",
{ userWallet },
);
if (status) {
queryBuilder.andWhere("collaboration.status = :status", { status });
}
const [collaborations, total] = await queryBuilder
.orderBy("collaboration.createdAt", "DESC")
.skip((page - 1) * limit)
.take(limit)
.getManyAndCount();
return { collaborations, total };
}
async getCollaborationById(
collaborationId: string,
userWallet: string,
): Promise<Collaboration> {
const collaboration = await this.collaborationRepository.findOne({
where: { id: collaborationId },
relations: ["artist"],
});
if (!collaboration) {
throw new NotFoundException("Collaboration not found");
}
// Verify user is involved in this collaboration
if (
collaboration.invitedBy !== userWallet &&
collaboration.artist.walletAddress !== userWallet
) {
throw new ForbiddenException(
"You can only view collaborations you are involved in",
);
}
return collaboration;
}
private async validateSplitPercentage(
manager: any,
trackId: string,
newSplitPercentage: number,
): Promise<void> {
// Get all active collaborations for this track
const activeCollaborations = await manager.find(Collaboration, {
where: {
trackId,
status: CollaborationStatus.ACTIVE,
splitPercentage: Not(IsNull()),
},
});
const totalCurrentPercentage = activeCollaborations.reduce(
(sum: number, collab: Collaboration) => sum + (collab.splitPercentage || 0),
0,
);
if (totalCurrentPercentage + newSplitPercentage > 100) {
throw new BadRequestException(
`Total split percentage cannot exceed 100%. Current: ${totalCurrentPercentage}%, Adding: ${newSplitPercentage}%`,
);
}
}
async getCollaborationStats(userWallet: string): Promise<any> {
const stats = await this.collaborationRepository
.createQueryBuilder("collaboration")
.select(
"COUNT(CASE WHEN collaboration.status = :invited THEN 1 END)",
"totalInvites",
)
.addSelect(
"COUNT(CASE WHEN collaboration.status = :active THEN 1 END)",
"activeCollaborations",
)
.addSelect(
"COUNT(CASE WHEN collaboration.status = :invited THEN 1 END)",
"pendingResponses",
)
.addSelect(
"COUNT(CASE WHEN collaboration.status = :rejected THEN 1 END)",
"rejectedInvites",
)
.addSelect(
"COUNT(CASE WHEN collaboration.status = :completed THEN 1 END)",
"completedCollaborations",
)
.addSelect(
"AVG(EXTRACT(EPOCH FROM (collaboration.respondedAt - collaboration.createdAt)) / 3600)",
"averageResponseTime",
)
.where(
"(collaboration.invitedBy = :userWallet OR collaboration.artist.walletAddress = :userWallet)",
{ userWallet },
)
.setParameter("invited", CollaborationStatus.INVITED)
.setParameter("active", CollaborationStatus.ACTIVE)
.setParameter("rejected", CollaborationStatus.REJECTED)
.setParameter("completed", CollaborationStatus.COMPLETED)
.getRawOne();
return {
totalInvites: parseInt(stats.totalInvites) || 0,
activeCollaborations: parseInt(stats.activeCollaborations) || 0,
pendingResponses: parseInt(stats.pendingResponses) || 0,
rejectedInvites: parseInt(stats.rejectedInvites) || 0,
completedCollaborations:
parseInt(stats.completedCollaborations) || 0,
averageResponseTime: stats.averageResponseTime
? parseFloat(stats.averageResponseTime)
: undefined,
};
}
}