Spaces:
Running

axeronis commited on
Commit
cb7ca84
·
1 Parent(s): 750b2de

Mobile chat improvements + Aurora palette consistency

Browse files
backend/alembic/versions/2025_12_21_fix_partner_columns.py CHANGED
@@ -17,10 +17,13 @@ depends_on = None
17
 
18
  def upgrade():
19
  # Add referrals_count if missing (was omitted from previous migration)
20
- try:
 
 
 
 
 
21
  op.add_column('partners', sa.Column('referrals_count', sa.Integer(), server_default='0', nullable=True))
22
- except:
23
- pass # Column may already exist
24
 
25
 
26
  def downgrade():
 
17
 
18
  def upgrade():
19
  # Add referrals_count if missing (was omitted from previous migration)
20
+ # Use inspector to avoid triggering a PostgreSQL error that aborts the transaction
21
+ bind = op.get_bind()
22
+ inspector = sa.inspect(bind)
23
+ columns = [c['name'] for c in inspector.get_columns('partners')]
24
+
25
+ if 'referrals_count' not in columns:
26
  op.add_column('partners', sa.Column('referrals_count', sa.Integer(), server_default='0', nullable=True))
 
 
27
 
28
 
29
  def downgrade():
backend/app/api/crm.py DELETED
@@ -1,613 +0,0 @@
1
- """
2
- CRM Integration API
3
-
4
- Endpoints for managing CRM integrations and synchronization.
5
- """
6
-
7
- from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
8
- from sqlalchemy.ext.asyncio import AsyncSession
9
- from sqlmodel import select, func
10
- from typing import List, Optional, Dict, Any
11
- from uuid import UUID
12
- from pydantic import BaseModel
13
- from datetime import datetime
14
-
15
- from app.core.database import get_session
16
- from app.models.crm_integration import (
17
- CRMIntegration, CRMSyncLog, CRMFieldMapping, LeadCRMLink,
18
- CRMType, SyncDirection, SyncStatus
19
- )
20
- from app.models.lead import Lead
21
- from app.services.crm_sync import get_crm_sync_service
22
-
23
- router = APIRouter(prefix="/crm", tags=["CRM Integration"])
24
-
25
-
26
- # ===== Request/Response Schemas =====
27
-
28
- class IntegrationCreate(BaseModel):
29
- """Create CRM integration."""
30
- crm_type: str
31
- integration_name: str
32
- api_url: Optional[str] = None
33
- api_key: Optional[str] = None
34
- api_secret: Optional[str] = None
35
- access_token: Optional[str] = None
36
- refresh_token: Optional[str] = None
37
- webhook_url: Optional[str] = None
38
- webhook_secret: Optional[str] = None
39
- webhook_headers: Optional[Dict[str, str]] = None
40
- sync_direction: str = "to_crm"
41
- auto_sync: bool = True
42
- sync_interval_minutes: int = 15
43
- field_mapping: Dict[str, Any] = {}
44
- sync_only_hot_leads: bool = False
45
- sync_statuses: Optional[List[str]] = None
46
-
47
-
48
- class IntegrationUpdate(BaseModel):
49
- """Update CRM integration."""
50
- integration_name: Optional[str] = None
51
- api_key: Optional[str] = None
52
- api_secret: Optional[str] = None
53
- access_token: Optional[str] = None
54
- refresh_token: Optional[str] = None
55
- webhook_url: Optional[str] = None
56
- auto_sync: Optional[bool] = None
57
- sync_interval_minutes: Optional[int] = None
58
- field_mapping: Optional[Dict[str, Any]] = None
59
- sync_only_hot_leads: Optional[bool] = None
60
- sync_statuses: Optional[List[str]] = None
61
- status: Optional[str] = None
62
- is_active: Optional[bool] = None
63
-
64
-
65
- class IntegrationResponse(BaseModel):
66
- """CRM integration response."""
67
- id: str
68
- tenant_id: str
69
- crm_type: str
70
- integration_name: str
71
- sync_direction: str
72
- auto_sync: bool
73
- sync_interval_minutes: int
74
- sync_only_hot_leads: bool
75
- status: str
76
- is_active: bool
77
- last_sync_at: Optional[datetime]
78
- last_successful_sync_at: Optional[datetime]
79
- total_synced_leads: int
80
- failed_sync_count: int
81
- last_error: Optional[str]
82
- created_at: datetime
83
- # Security: Don't expose sensitive fields like api_key, tokens
84
-
85
-
86
- class SyncRequest(BaseModel):
87
- """Manual sync request."""
88
- lead_ids: Optional[List[str]] = None # If None, sync all
89
- force: bool = False # Force sync even if not changed
90
-
91
-
92
- class SyncStatsResponse(BaseModel):
93
- """Sync statistics."""
94
- total: int
95
- success: int
96
- failed: int
97
- skipped: int
98
- errors: List[Dict[str, str]]
99
-
100
-
101
- class FieldMappingResponse(BaseModel):
102
- """Field mapping template."""
103
- id: str
104
- crm_type: str
105
- template_name: str
106
- description: Optional[str]
107
- mapping_config: Dict[str, Any]
108
- is_default: bool
109
-
110
-
111
- # ===== Endpoints =====
112
-
113
- @router.post("/{tenant_id}/integrations", response_model=IntegrationResponse)
114
- async def create_integration(
115
- tenant_id: UUID,
116
- request: IntegrationCreate,
117
- session: AsyncSession = Depends(get_session)
118
- ):
119
- """
120
- Create new CRM integration.
121
-
122
- Supported CRM types:
123
- - amocrm
124
- - bitrix24
125
- - hubspot
126
- - pipedrive
127
- - custom_webhook
128
- """
129
-
130
- # Validate CRM type
131
- try:
132
- crm_type = CRMType(request.crm_type)
133
- except ValueError:
134
- raise HTTPException(status_code=400, detail=f"Invalid CRM type: {request.crm_type}")
135
-
136
- # Create integration
137
- integration = CRMIntegration(
138
- tenant_id=tenant_id,
139
- crm_type=crm_type,
140
- integration_name=request.integration_name,
141
- api_url=request.api_url,
142
- api_key=request.api_key,
143
- api_secret=request.api_secret,
144
- access_token=request.access_token,
145
- refresh_token=request.refresh_token,
146
- webhook_url=request.webhook_url,
147
- webhook_secret=request.webhook_secret,
148
- webhook_headers=request.webhook_headers,
149
- sync_direction=SyncDirection(request.sync_direction),
150
- auto_sync=request.auto_sync,
151
- sync_interval_minutes=request.sync_interval_minutes,
152
- field_mapping=request.field_mapping,
153
- sync_only_hot_leads=request.sync_only_hot_leads,
154
- sync_statuses=request.sync_statuses,
155
- status=SyncStatus.ACTIVE,
156
- is_active=True
157
- )
158
-
159
- session.add(integration)
160
- await session.commit()
161
- await session.refresh(integration)
162
-
163
- return IntegrationResponse(
164
- id=str(integration.id),
165
- tenant_id=str(integration.tenant_id),
166
- crm_type=integration.crm_type.value,
167
- integration_name=integration.integration_name,
168
- sync_direction=integration.sync_direction.value,
169
- auto_sync=integration.auto_sync,
170
- sync_interval_minutes=integration.sync_interval_minutes,
171
- sync_only_hot_leads=integration.sync_only_hot_leads,
172
- status=integration.status.value,
173
- is_active=integration.is_active,
174
- last_sync_at=integration.last_sync_at,
175
- last_successful_sync_at=integration.last_successful_sync_at,
176
- total_synced_leads=integration.total_synced_leads,
177
- failed_sync_count=integration.failed_sync_count,
178
- last_error=integration.last_error,
179
- created_at=integration.created_at
180
- )
181
-
182
-
183
- @router.get("/{tenant_id}/integrations", response_model=List[IntegrationResponse])
184
- async def list_integrations(
185
- tenant_id: UUID,
186
- session: AsyncSession = Depends(get_session)
187
- ):
188
- """List all CRM integrations for tenant."""
189
-
190
- stmt = select(CRMIntegration).where(
191
- CRMIntegration.tenant_id == tenant_id
192
- ).order_by(CRMIntegration.created_at.desc())
193
-
194
- result = await session.execute(stmt)
195
- integrations = list(result.scalars().all())
196
-
197
- return [
198
- IntegrationResponse(
199
- id=str(i.id),
200
- tenant_id=str(i.tenant_id),
201
- crm_type=i.crm_type.value,
202
- integration_name=i.integration_name,
203
- sync_direction=i.sync_direction.value,
204
- auto_sync=i.auto_sync,
205
- sync_interval_minutes=i.sync_interval_minutes,
206
- sync_only_hot_leads=i.sync_only_hot_leads,
207
- status=i.status.value,
208
- is_active=i.is_active,
209
- last_sync_at=i.last_sync_at,
210
- last_successful_sync_at=i.last_successful_sync_at,
211
- total_synced_leads=i.total_synced_leads,
212
- failed_sync_count=i.failed_sync_count,
213
- last_error=i.last_error,
214
- created_at=i.created_at
215
- )
216
- for i in integrations
217
- ]
218
-
219
-
220
- @router.get("/{tenant_id}/integrations/{integration_id}", response_model=IntegrationResponse)
221
- async def get_integration(
222
- tenant_id: UUID,
223
- integration_id: UUID,
224
- session: AsyncSession = Depends(get_session)
225
- ):
226
- """Get specific CRM integration."""
227
-
228
- integration = await session.get(CRMIntegration, integration_id)
229
-
230
- if not integration or integration.tenant_id != tenant_id:
231
- raise HTTPException(status_code=404, detail="Integration not found")
232
-
233
- return IntegrationResponse(
234
- id=str(integration.id),
235
- tenant_id=str(integration.tenant_id),
236
- crm_type=integration.crm_type.value,
237
- integration_name=integration.integration_name,
238
- sync_direction=integration.sync_direction.value,
239
- auto_sync=integration.auto_sync,
240
- sync_interval_minutes=integration.sync_interval_minutes,
241
- sync_only_hot_leads=integration.sync_only_hot_leads,
242
- status=integration.status.value,
243
- is_active=integration.is_active,
244
- last_sync_at=integration.last_sync_at,
245
- last_successful_sync_at=integration.last_successful_sync_at,
246
- total_synced_leads=integration.total_synced_leads,
247
- failed_sync_count=integration.failed_sync_count,
248
- last_error=integration.last_error,
249
- created_at=integration.created_at
250
- )
251
-
252
-
253
- @router.patch("/{tenant_id}/integrations/{integration_id}", response_model=IntegrationResponse)
254
- async def update_integration(
255
- tenant_id: UUID,
256
- integration_id: UUID,
257
- request: IntegrationUpdate,
258
- session: AsyncSession = Depends(get_session)
259
- ):
260
- """Update CRM integration settings."""
261
-
262
- integration = await session.get(CRMIntegration, integration_id)
263
-
264
- if not integration or integration.tenant_id != tenant_id:
265
- raise HTTPException(status_code=404, detail="Integration not found")
266
-
267
- # Update fields
268
- if request.integration_name is not None:
269
- integration.integration_name = request.integration_name
270
- if request.api_key is not None:
271
- integration.api_key = request.api_key
272
- if request.api_secret is not None:
273
- integration.api_secret = request.api_secret
274
- if request.access_token is not None:
275
- integration.access_token = request.access_token
276
- if request.refresh_token is not None:
277
- integration.refresh_token = request.refresh_token
278
- if request.webhook_url is not None:
279
- integration.webhook_url = request.webhook_url
280
- if request.auto_sync is not None:
281
- integration.auto_sync = request.auto_sync
282
- if request.sync_interval_minutes is not None:
283
- integration.sync_interval_minutes = request.sync_interval_minutes
284
- if request.field_mapping is not None:
285
- integration.field_mapping = request.field_mapping
286
- if request.sync_only_hot_leads is not None:
287
- integration.sync_only_hot_leads = request.sync_only_hot_leads
288
- if request.sync_statuses is not None:
289
- integration.sync_statuses = request.sync_statuses
290
- if request.status is not None:
291
- integration.status = SyncStatus(request.status)
292
- if request.is_active is not None:
293
- integration.is_active = request.is_active
294
-
295
- integration.updated_at = datetime.utcnow()
296
-
297
- session.add(integration)
298
- await session.commit()
299
- await session.refresh(integration)
300
-
301
- return IntegrationResponse(
302
- id=str(integration.id),
303
- tenant_id=str(integration.tenant_id),
304
- crm_type=integration.crm_type.value,
305
- integration_name=integration.integration_name,
306
- sync_direction=integration.sync_direction.value,
307
- auto_sync=integration.auto_sync,
308
- sync_interval_minutes=integration.sync_interval_minutes,
309
- sync_only_hot_leads=integration.sync_only_hot_leads,
310
- status=integration.status.value,
311
- is_active=integration.is_active,
312
- last_sync_at=integration.last_sync_at,
313
- last_successful_sync_at=integration.last_successful_sync_at,
314
- total_synced_leads=integration.total_synced_leads,
315
- failed_sync_count=integration.failed_sync_count,
316
- last_error=integration.last_error,
317
- created_at=integration.created_at
318
- )
319
-
320
-
321
- @router.delete("/{tenant_id}/integrations/{integration_id}")
322
- async def delete_integration(
323
- tenant_id: UUID,
324
- integration_id: UUID,
325
- session: AsyncSession = Depends(get_session)
326
- ):
327
- """Delete CRM integration (and all associated sync logs)."""
328
-
329
- integration = await session.get(CRMIntegration, integration_id)
330
-
331
- if not integration or integration.tenant_id != tenant_id:
332
- raise HTTPException(status_code=404, detail="Integration not found")
333
-
334
- await session.delete(integration)
335
- await session.commit()
336
-
337
- return {"ok": True, "message": "Integration deleted"}
338
-
339
-
340
- @router.post("/{tenant_id}/integrations/{integration_id}/sync", response_model=SyncStatsResponse)
341
- async def manual_sync(
342
- tenant_id: UUID,
343
- integration_id: UUID,
344
- request: SyncRequest,
345
- background_tasks: BackgroundTasks,
346
- session: AsyncSession = Depends(get_session)
347
- ):
348
- """
349
- Manually trigger CRM synchronization.
350
-
351
- If lead_ids is provided, only sync those leads.
352
- Otherwise, sync all leads matching filters.
353
- """
354
-
355
- integration = await session.get(CRMIntegration, integration_id)
356
-
357
- if not integration or integration.tenant_id != tenant_id:
358
- raise HTTPException(status_code=404, detail="Integration not found")
359
-
360
- crm_service = get_crm_sync_service()
361
-
362
- if request.lead_ids:
363
- # Sync specific leads
364
- stats = {
365
- "total": len(request.lead_ids),
366
- "success": 0,
367
- "failed": 0,
368
- "skipped": 0,
369
- "errors": []
370
- }
371
-
372
- for lead_id_str in request.lead_ids:
373
- lead = await session.get(Lead, UUID(lead_id_str))
374
-
375
- if not lead or lead.tenant_id != tenant_id:
376
- stats["failed"] += 1
377
- stats["errors"].append({
378
- "lead_id": lead_id_str,
379
- "error": "Lead not found"
380
- })
381
- continue
382
-
383
- result = await crm_service.sync_lead_to_crm(
384
- session, lead, integration, force=request.force
385
- )
386
-
387
- if result.get("success"):
388
- stats["success"] += 1
389
- elif result.get("skipped"):
390
- stats["skipped"] += 1
391
- else:
392
- stats["failed"] += 1
393
- stats["errors"].append({
394
- "lead_id": lead_id_str,
395
- "error": result.get("error", "Unknown error")
396
- })
397
-
398
- return SyncStatsResponse(**stats)
399
-
400
- else:
401
- # Batch sync all leads
402
- stats = await crm_service.sync_tenant_leads(
403
- session, tenant_id, integration_id, limit=1000
404
- )
405
-
406
- return SyncStatsResponse(**stats)
407
-
408
-
409
- @router.get("/{tenant_id}/integrations/{integration_id}/logs")
410
- async def get_sync_logs(
411
- tenant_id: UUID,
412
- integration_id: UUID,
413
- limit: int = 50,
414
- session: AsyncSession = Depends(get_session)
415
- ):
416
- """Get recent sync logs for an integration."""
417
-
418
- # Verify integration belongs to tenant
419
- integration = await session.get(CRMIntegration, integration_id)
420
- if not integration or integration.tenant_id != tenant_id:
421
- raise HTTPException(status_code=404, detail="Integration not found")
422
-
423
- stmt = select(CRMSyncLog).where(
424
- CRMSyncLog.integration_id == integration_id
425
- ).order_by(CRMSyncLog.created_at.desc()).limit(limit)
426
-
427
- result = await session.execute(stmt)
428
- logs = list(result.scalars().all())
429
-
430
- return [
431
- {
432
- "id": str(log.id),
433
- "lead_id": str(log.lead_id) if log.lead_id else None,
434
- "sync_direction": log.sync_direction,
435
- "operation": log.operation,
436
- "success": log.success,
437
- "error_message": log.error_message,
438
- "crm_lead_id": log.crm_lead_id,
439
- "crm_contact_id": log.crm_contact_id,
440
- "duration_ms": log.duration_ms,
441
- "created_at": log.created_at
442
- }
443
- for log in logs
444
- ]
445
-
446
-
447
- @router.get("/{tenant_id}/integrations/{integration_id}/stats")
448
- async def get_integration_stats(
449
- tenant_id: UUID,
450
- integration_id: UUID,
451
- session: AsyncSession = Depends(get_session)
452
- ):
453
- """Get statistics for CRM integration."""
454
-
455
- integration = await session.get(CRMIntegration, integration_id)
456
- if not integration or integration.tenant_id != tenant_id:
457
- raise HTTPException(status_code=404, detail="Integration not found")
458
-
459
- # Count total links
460
- links_stmt = select(func.count()).select_from(LeadCRMLink).where(
461
- LeadCRMLink.integration_id == integration_id
462
- )
463
- links_result = await session.execute(links_stmt)
464
- total_links = links_result.scalar()
465
-
466
- # Count successful syncs (last 24h)
467
- from datetime import timedelta
468
- since = datetime.utcnow() - timedelta(hours=24)
469
-
470
- success_stmt = select(func.count()).select_from(CRMSyncLog).where(
471
- CRMSyncLog.integration_id == integration_id,
472
- CRMSyncLog.success == True,
473
- CRMSyncLog.created_at >= since
474
- )
475
- success_result = await session.execute(success_stmt)
476
- recent_success = success_result.scalar()
477
-
478
- # Count failed syncs (last 24h)
479
- failed_stmt = select(func.count()).select_from(CRMSyncLog).where(
480
- CRMSyncLog.integration_id == integration_id,
481
- CRMSyncLog.success == False,
482
- CRMSyncLog.created_at >= since
483
- )
484
- failed_result = await session.execute(failed_stmt)
485
- recent_failed = failed_result.scalar()
486
-
487
- return {
488
- "integration_id": str(integration_id),
489
- "total_synced_leads": integration.total_synced_leads,
490
- "total_linked_leads": total_links,
491
- "last_sync_at": integration.last_sync_at,
492
- "last_successful_sync_at": integration.last_successful_sync_at,
493
- "recent_success_count_24h": recent_success,
494
- "recent_failed_count_24h": recent_failed,
495
- "failed_sync_count": integration.failed_sync_count,
496
- "status": integration.status.value,
497
- "last_error": integration.last_error
498
- }
499
-
500
-
501
- @router.get("/field-mappings/{crm_type}", response_model=List[FieldMappingResponse])
502
- async def get_field_mapping_templates(
503
- crm_type: str,
504
- session: AsyncSession = Depends(get_session)
505
- ):
506
- """
507
- Get field mapping templates for a CRM type.
508
-
509
- These templates help users quickly configure field mappings.
510
- """
511
-
512
- try:
513
- crm_type_enum = CRMType(crm_type)
514
- except ValueError:
515
- raise HTTPException(status_code=400, detail=f"Invalid CRM type: {crm_type}")
516
-
517
- stmt = select(CRMFieldMapping).where(
518
- CRMFieldMapping.crm_type == crm_type_enum,
519
- CRMFieldMapping.is_public == True
520
- ).order_by(CRMFieldMapping.is_default.desc())
521
-
522
- result = await session.execute(stmt)
523
- templates = list(result.scalars().all())
524
-
525
- return [
526
- FieldMappingResponse(
527
- id=str(t.id),
528
- crm_type=t.crm_type.value,
529
- template_name=t.template_name,
530
- description=t.description,
531
- mapping_config=t.mapping_config,
532
- is_default=t.is_default
533
- )
534
- for t in templates
535
- ]
536
-
537
-
538
- @router.post("/{tenant_id}/leads/{lead_id}/sync-to-crm")
539
- async def sync_single_lead(
540
- tenant_id: UUID,
541
- lead_id: UUID,
542
- integration_id: str,
543
- force: bool = False,
544
- session: AsyncSession = Depends(get_session)
545
- ):
546
- """
547
- Sync a single lead to CRM immediately.
548
-
549
- Used for manual sync or webhook-triggered sync.
550
- """
551
-
552
- # Get lead
553
- lead = await session.get(Lead, lead_id)
554
- if not lead or lead.tenant_id != tenant_id:
555
- raise HTTPException(status_code=404, detail="Lead not found")
556
-
557
- # Get integration
558
- integration = await session.get(CRMIntegration, UUID(integration_id))
559
- if not integration or integration.tenant_id != tenant_id:
560
- raise HTTPException(status_code=404, detail="Integration not found")
561
-
562
- # Sync
563
- crm_service = get_crm_sync_service()
564
- result = await crm_service.sync_lead_to_crm(session, lead, integration, force=force)
565
-
566
- if result.get("success"):
567
- return {
568
- "ok": True,
569
- "message": "Lead synced successfully",
570
- "crm_contact_id": result.get("contact_id"),
571
- "crm_lead_id": result.get("lead_id"),
572
- "crm_url": result.get("url")
573
- }
574
- else:
575
- raise HTTPException(
576
- status_code=500,
577
- detail=result.get("error", "Sync failed")
578
- )
579
-
580
-
581
- @router.get("/{tenant_id}/leads/{lead_id}/crm-links")
582
- async def get_lead_crm_links(
583
- tenant_id: UUID,
584
- lead_id: UUID,
585
- session: AsyncSession = Depends(get_session)
586
- ):
587
- """Get all CRM links for a lead."""
588
-
589
- stmt = select(LeadCRMLink).where(
590
- LeadCRMLink.lead_id == lead_id,
591
- LeadCRMLink.tenant_id == tenant_id
592
- )
593
-
594
- result = await session.execute(stmt)
595
- links = list(result.scalars().all())
596
-
597
- # Get integration details for each link
598
- response = []
599
- for link in links:
600
- integration = await session.get(CRMIntegration, link.integration_id)
601
- response.append({
602
- "link_id": str(link.id),
603
- "integration_id": str(link.integration_id),
604
- "integration_name": integration.integration_name if integration else "Unknown",
605
- "crm_type": integration.crm_type.value if integration else "unknown",
606
- "crm_contact_id": link.crm_contact_id,
607
- "crm_lead_id": link.crm_lead_id,
608
- "crm_url": link.crm_url,
609
- "last_synced_at": link.last_synced_at,
610
- "created_at": link.created_at
611
- })
612
-
613
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/app/main.py CHANGED
@@ -7,7 +7,7 @@ from app.core.config import settings
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
- from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings, upload, demo
11
 
12
  # ... (omitted lines)
13
 
@@ -180,7 +180,6 @@ app.include_router(chats.router, prefix="/api/v1")
180
  app.include_router(playbook.router, prefix="/api/v1")
181
  app.include_router(billing.router, prefix="/api/v1") # Billing & Franchise
182
  app.include_router(ai_training.router, prefix="/api/v1") # AI Training & Learning
183
- app.include_router(crm.router, prefix="/api/v1") # CRM Integration
184
  app.include_router(admin.router, prefix="/api/v1") # Admin Panel (superuser only)
185
  app.include_router(partners.router, prefix="/api/v1") # Partner Dashboard
186
  app.include_router(team.router, prefix="/api/v1") # Team Management (owner only)
 
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
+ from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings, upload, demo
11
 
12
  # ... (omitted lines)
13
 
 
180
  app.include_router(playbook.router, prefix="/api/v1")
181
  app.include_router(billing.router, prefix="/api/v1") # Billing & Franchise
182
  app.include_router(ai_training.router, prefix="/api/v1") # AI Training & Learning
 
183
  app.include_router(admin.router, prefix="/api/v1") # Admin Panel (superuser only)
184
  app.include_router(partners.router, prefix="/api/v1") # Partner Dashboard
185
  app.include_router(team.router, prefix="/api/v1") # Team Management (owner only)
backend/app/models/crm_integration.py DELETED
@@ -1,214 +0,0 @@
1
- from sqlmodel import SQLModel, Field, Relationship, Column
2
- from sqlalchemy import TEXT, JSON
3
- from typing import Optional, Dict, Any, List
4
- from datetime import datetime
5
- from uuid import UUID, uuid4
6
- from enum import Enum
7
-
8
-
9
- class CRMType(str, Enum):
10
- """Supported CRM systems."""
11
- AMOCRM = "amocrm"
12
- BITRIX24 = "bitrix24"
13
- HUBSPOT = "hubspot"
14
- PIPEDRIVE = "pipedrive"
15
- SALESFORCE = "salesforce"
16
- ZOHO = "zoho"
17
- CUSTOM_WEBHOOK = "custom_webhook"
18
-
19
-
20
- class SyncDirection(str, Enum):
21
- """Data synchronization direction."""
22
- BIDIRECTIONAL = "bidirectional" # Both ways
23
- TO_CRM = "to_crm" # Only MicroFunnel → CRM
24
- FROM_CRM = "from_crm" # Only CRM → MicroFunnel
25
-
26
-
27
- class SyncStatus(str, Enum):
28
- """Synchronization status."""
29
- ACTIVE = "active"
30
- PAUSED = "paused"
31
- ERROR = "error"
32
- DISABLED = "disabled"
33
-
34
-
35
- class CRMIntegration(SQLModel, table=True):
36
- """CRM integration configuration for each tenant."""
37
- __tablename__ = "crm_integrations"
38
-
39
- id: UUID = Field(default_factory=uuid4, primary_key=True)
40
-
41
- # Multi-tenancy
42
- tenant_id: UUID = Field(foreign_key="tenants.id", index=True)
43
-
44
- # CRM Configuration
45
- crm_type: CRMType
46
- integration_name: str # User-friendly name like "Main amoCRM"
47
-
48
- # Authentication
49
- api_url: Optional[str] = None # For self-hosted or custom endpoints
50
- api_key: Optional[str] = Field(default=None, sa_column=Column(TEXT))
51
- api_secret: Optional[str] = Field(default=None, sa_column=Column(TEXT))
52
- access_token: Optional[str] = Field(default=None, sa_column=Column(TEXT))
53
- refresh_token: Optional[str] = Field(default=None, sa_column=Column(TEXT))
54
- token_expires_at: Optional[datetime] = None
55
-
56
- # OAuth credentials (for OAuth-based CRMs)
57
- oauth_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
58
-
59
- # Sync Configuration
60
- sync_direction: SyncDirection = Field(default=SyncDirection.TO_CRM)
61
- auto_sync: bool = Field(default=True) # Auto-sync on lead update
62
- sync_interval_minutes: int = Field(default=15) # For periodic sync
63
-
64
- # Field Mapping (MicroFunnel field → CRM field)
65
- field_mapping: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
66
- """
67
- Example:
68
- {
69
- "name": "contact_name",
70
- "phone": "phone_number",
71
- "email": "email_address",
72
- "budget": "custom_field_budget",
73
- "heat_score": "lead_score",
74
- "psychotype": "personality_type",
75
- "ai_summary_json.intent": "purchase_intent",
76
- "ai_summary_json.pain_points": "customer_pain_points"
77
- }
78
- """
79
-
80
- # Filters
81
- sync_only_hot_leads: bool = Field(default=False) # Only sync hot leads (score >= 70)
82
- sync_statuses: Optional[List[str]] = Field(default=None, sa_column=Column(JSON)) # Which statuses to sync
83
-
84
- # Webhook Configuration
85
- webhook_url: Optional[str] = None # For custom webhooks
86
- webhook_secret: Optional[str] = None
87
- webhook_headers: Optional[Dict[str, str]] = Field(default=None, sa_column=Column(JSON))
88
-
89
- # Status
90
- status: SyncStatus = Field(default=SyncStatus.ACTIVE)
91
- is_active: bool = Field(default=True)
92
-
93
- # Statistics
94
- last_sync_at: Optional[datetime] = None
95
- last_successful_sync_at: Optional[datetime] = None
96
- total_synced_leads: int = Field(default=0)
97
- failed_sync_count: int = Field(default=0)
98
- last_error: Optional[str] = Field(default=None, sa_column=Column(TEXT))
99
-
100
- # Timestamps
101
- created_at: datetime = Field(default_factory=datetime.utcnow)
102
- updated_at: datetime = Field(default_factory=datetime.utcnow)
103
- created_by_user_id: Optional[UUID] = Field(default=None, foreign_key="users.id")
104
-
105
-
106
- class CRMSyncLog(SQLModel, table=True):
107
- """Log of CRM synchronization operations."""
108
- __tablename__ = "crm_sync_logs"
109
-
110
- id: UUID = Field(default_factory=uuid4, primary_key=True)
111
-
112
- # References
113
- tenant_id: UUID = Field(foreign_key="tenants.id", index=True)
114
- integration_id: UUID = Field(foreign_key="crm_integrations.id", index=True)
115
- lead_id: Optional[UUID] = Field(default=None, foreign_key="leads.id")
116
-
117
- # Sync details
118
- sync_direction: str # "to_crm", "from_crm"
119
- operation: str # "create", "update", "delete"
120
-
121
- # Status
122
- success: bool = Field(default=False)
123
- error_message: Optional[str] = Field(default=None, sa_column=Column(TEXT))
124
-
125
- # Request/Response data
126
- request_payload: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
127
- response_data: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
128
-
129
- # CRM identifiers
130
- crm_lead_id: Optional[str] = None # ID in external CRM
131
- crm_contact_id: Optional[str] = None
132
- crm_deal_id: Optional[str] = None
133
-
134
- # Performance
135
- duration_ms: Optional[int] = None # How long the sync took
136
-
137
- # Timestamps
138
- created_at: datetime = Field(default_factory=datetime.utcnow)
139
-
140
-
141
- class CRMFieldMapping(SQLModel, table=True):
142
- """Detailed field mapping templates for different CRM systems."""
143
- __tablename__ = "crm_field_mappings"
144
-
145
- id: UUID = Field(default_factory=uuid4, primary_key=True)
146
-
147
- # Configuration
148
- crm_type: CRMType
149
- template_name: str # "Default", "Sales-focused", "Support-focused"
150
- description: Optional[str] = Field(default=None, sa_column=Column(TEXT))
151
-
152
- # Mapping configuration
153
- mapping_config: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
154
- """
155
- Example for amoCRM:
156
- {
157
- "contact_fields": {
158
- "name": {"crm_field": "name", "required": true},
159
- "phone": {"crm_field": "phone", "required": false},
160
- "email": {"crm_field": "email", "required": false}
161
- },
162
- "lead_fields": {
163
- "budget": {"crm_field": "custom_field_123456", "type": "number"},
164
- "heat_score": {"crm_field": "custom_field_789012", "type": "number"},
165
- "psychotype": {"crm_field": "custom_field_345678", "type": "select"}
166
- },
167
- "custom_transformations": {
168
- "heat_level": {
169
- "hot": "Горячий",
170
- "warm": "Теплый",
171
- "cold": "Холодный",
172
- "junk": "Мусор"
173
- }
174
- }
175
- }
176
- """
177
-
178
- # Metadata
179
- is_default: bool = Field(default=False)
180
- is_public: bool = Field(default=True) # Available to all tenants
181
- created_by_tenant_id: Optional[UUID] = Field(default=None, foreign_key="tenants.id")
182
-
183
- # Timestamps
184
- created_at: datetime = Field(default_factory=datetime.utcnow)
185
- updated_at: datetime = Field(default_factory=datetime.utcnow)
186
-
187
-
188
- class LeadCRMLink(SQLModel, table=True):
189
- """Links between MicroFunnel leads and CRM records."""
190
- __tablename__ = "lead_crm_links"
191
-
192
- id: UUID = Field(default_factory=uuid4, primary_key=True)
193
-
194
- # References
195
- tenant_id: UUID = Field(foreign_key="tenants.id", index=True)
196
- lead_id: UUID = Field(foreign_key="leads.id", index=True)
197
- integration_id: UUID = Field(foreign_key="crm_integrations.id", index=True)
198
-
199
- # CRM identifiers
200
- crm_contact_id: Optional[str] = Field(default=None, index=True) # Contact/Person ID
201
- crm_lead_id: Optional[str] = Field(default=None, index=True) # Lead/Deal ID
202
- crm_company_id: Optional[str] = None # Company/Organization ID
203
-
204
- # Additional metadata
205
- crm_url: Optional[str] = None # Direct link to CRM record
206
- crm_data: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
207
-
208
- # Sync tracking
209
- last_synced_at: datetime = Field(default_factory=datetime.utcnow)
210
- sync_hash: Optional[str] = None # To detect changes
211
-
212
- # Timestamps
213
- created_at: datetime = Field(default_factory=datetime.utcnow)
214
- updated_at: datetime = Field(default_factory=datetime.utcnow)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/app/services/crm_sync.py DELETED
@@ -1,636 +0,0 @@
1
- """
2
- CRM Synchronization Service
3
-
4
- Handles automatic synchronization with external CRM systems:
5
- - amoCRM
6
- - Bitrix24
7
- - HubSpot
8
- - Pipedrive
9
- - Custom webhooks
10
- """
11
-
12
- import httpx
13
- import hashlib
14
- import json
15
- from typing import Dict, Any, Optional, List
16
- from datetime import datetime, timedelta
17
- from uuid import UUID
18
- from sqlalchemy.ext.asyncio import AsyncSession
19
- from sqlmodel import select
20
-
21
- from app.models.crm_integration import (
22
- CRMIntegration, CRMSyncLog, LeadCRMLink, CRMType, SyncStatus
23
- )
24
- from app.models.lead import Lead
25
-
26
-
27
- class CRMSyncService:
28
- """Service for synchronizing leads with CRM systems."""
29
-
30
- def __init__(self):
31
- self.timeout = 30.0
32
-
33
- async def sync_lead_to_crm(
34
- self,
35
- session: AsyncSession,
36
- lead: Lead,
37
- integration: CRMIntegration,
38
- force: bool = False
39
- ) -> Dict[str, Any]:
40
- """
41
- Sync a single lead to CRM.
42
-
43
- Args:
44
- lead: Lead to sync
45
- integration: CRM integration configuration
46
- force: Force sync even if not changed
47
-
48
- Returns:
49
- Dict with sync result and CRM IDs
50
- """
51
- start_time = datetime.utcnow()
52
-
53
- try:
54
- # Check if integration is active
55
- if integration.status != SyncStatus.ACTIVE or not integration.is_active:
56
- return {
57
- "success": False,
58
- "error": "Integration is not active"
59
- }
60
-
61
- # Check filters
62
- if not self._should_sync_lead(lead, integration):
63
- return {
64
- "success": False,
65
- "error": "Lead doesn't match sync filters"
66
- }
67
-
68
- # Get existing link
69
- link_stmt = select(LeadCRMLink).where(
70
- LeadCRMLink.lead_id == lead.id,
71
- LeadCRMLink.integration_id == integration.id
72
- )
73
- link_result = await session.execute(link_stmt)
74
- existing_link = link_result.scalar_one_or_none()
75
-
76
- # Calculate hash to detect changes
77
- lead_hash = self._calculate_lead_hash(lead, integration.field_mapping)
78
-
79
- # Skip if not changed (unless force)
80
- if not force and existing_link and existing_link.sync_hash == lead_hash:
81
- return {
82
- "success": True,
83
- "skipped": True,
84
- "reason": "No changes detected"
85
- }
86
-
87
- # Transform lead data based on field mapping
88
- crm_payload = self._transform_lead_to_crm(lead, integration)
89
-
90
- # Sync based on CRM type
91
- if integration.crm_type == CRMType.AMOCRM:
92
- result = await self._sync_to_amocrm(integration, crm_payload, existing_link)
93
- elif integration.crm_type == CRMType.BITRIX24:
94
- result = await self._sync_to_bitrix24(integration, crm_payload, existing_link)
95
- elif integration.crm_type == CRMType.HUBSPOT:
96
- result = await self._sync_to_hubspot(integration, crm_payload, existing_link)
97
- elif integration.crm_type == CRMType.CUSTOM_WEBHOOK:
98
- result = await self._sync_to_webhook(integration, crm_payload, existing_link)
99
- else:
100
- result = {
101
- "success": False,
102
- "error": f"CRM type {integration.crm_type} not implemented yet"
103
- }
104
-
105
- # Calculate duration
106
- duration_ms = int((datetime.utcnow() - start_time).total_seconds() * 1000)
107
-
108
- # Update or create link
109
- if result["success"]:
110
- if existing_link:
111
- existing_link.crm_contact_id = result.get("contact_id")
112
- existing_link.crm_lead_id = result.get("lead_id")
113
- existing_link.crm_url = result.get("url")
114
- existing_link.sync_hash = lead_hash
115
- existing_link.last_synced_at = datetime.utcnow()
116
- existing_link.updated_at = datetime.utcnow()
117
- session.add(existing_link)
118
- else:
119
- new_link = LeadCRMLink(
120
- tenant_id=lead.tenant_id,
121
- lead_id=lead.id,
122
- integration_id=integration.id,
123
- crm_contact_id=result.get("contact_id"),
124
- crm_lead_id=result.get("lead_id"),
125
- crm_url=result.get("url"),
126
- sync_hash=lead_hash,
127
- last_synced_at=datetime.utcnow()
128
- )
129
- session.add(new_link)
130
-
131
- # Update integration stats
132
- integration.last_successful_sync_at = datetime.utcnow()
133
- integration.total_synced_leads = (integration.total_synced_leads or 0) + 1
134
- else:
135
- integration.failed_sync_count = (integration.failed_sync_count or 0) + 1
136
- integration.last_error = result.get("error", "Unknown error")[:500]
137
- if integration.failed_sync_count >= 10:
138
- integration.status = SyncStatus.ERROR
139
-
140
- integration.last_sync_at = datetime.utcnow()
141
- session.add(integration)
142
-
143
- # Log sync operation
144
- log = CRMSyncLog(
145
- tenant_id=lead.tenant_id,
146
- integration_id=integration.id,
147
- lead_id=lead.id,
148
- sync_direction="to_crm",
149
- operation="update" if existing_link else "create",
150
- success=result["success"],
151
- error_message=result.get("error"),
152
- request_payload=crm_payload,
153
- response_data=result.get("response"),
154
- crm_contact_id=result.get("contact_id"),
155
- crm_lead_id=result.get("lead_id"),
156
- duration_ms=duration_ms
157
- )
158
- session.add(log)
159
-
160
- await session.commit()
161
-
162
- return result
163
-
164
- except Exception as e:
165
- print(f"❌ CRM sync error: {e}")
166
- return {
167
- "success": False,
168
- "error": str(e)
169
- }
170
-
171
- def _should_sync_lead(self, lead: Lead, integration: CRMIntegration) -> bool:
172
- """Check if lead matches sync filters."""
173
-
174
- # Check hot leads filter
175
- if integration.sync_only_hot_leads and lead.heat_score < 70:
176
- return False
177
-
178
- # Check status filter
179
- if integration.sync_statuses:
180
- if lead.status.value not in integration.sync_statuses:
181
- return False
182
-
183
- return True
184
-
185
- def _calculate_lead_hash(self, lead: Lead, field_mapping: Dict) -> str:
186
- """Calculate MD5 hash of lead data to detect changes."""
187
-
188
- # Extract relevant fields based on mapping
189
- data_to_hash = {
190
- "name": lead.name,
191
- "phone": lead.phone,
192
- "email": lead.email,
193
- "status": lead.status.value,
194
- "heat_score": lead.heat_score,
195
- "psychotype": lead.psychotype.value,
196
- "budget": lead.budget,
197
- "authority": lead.authority,
198
- "need": lead.need,
199
- "timeline": lead.timeline,
200
- "ai_summary": lead.ai_summary_json
201
- }
202
-
203
- # Sort and stringify
204
- data_str = json.dumps(data_to_hash, sort_keys=True, default=str)
205
- return hashlib.md5(data_str.encode()).hexdigest()
206
-
207
- def _transform_lead_to_crm(
208
- self,
209
- lead: Lead,
210
- integration: CRMIntegration
211
- ) -> Dict[str, Any]:
212
- """Transform MicroFunnel lead to CRM format based on field mapping."""
213
-
214
- mapping = integration.field_mapping or {}
215
- transformed = {}
216
-
217
- # Map fields
218
- for mf_field, crm_field in mapping.items():
219
- # Handle nested fields (e.g., "ai_summary_json.intent")
220
- if "." in mf_field:
221
- parts = mf_field.split(".")
222
- value = getattr(lead, parts[0], {})
223
- if isinstance(value, dict):
224
- value = value.get(parts[1])
225
- else:
226
- value = getattr(lead, mf_field, None)
227
-
228
- # Skip None values
229
- if value is not None:
230
- if isinstance(crm_field, dict):
231
- # Complex mapping with transformations
232
- crm_field_name = crm_field.get("crm_field")
233
- transformed[crm_field_name] = value
234
- else:
235
- # Simple string mapping
236
- transformed[crm_field] = value
237
-
238
- return transformed
239
-
240
- async def _sync_to_amocrm(
241
- self,
242
- integration: CRMIntegration,
243
- payload: Dict[str, Any],
244
- existing_link: Optional[LeadCRMLink]
245
- ) -> Dict[str, Any]:
246
- """Sync to amoCRM."""
247
-
248
- try:
249
- base_url = integration.api_url or "https://api.amocrm.ru"
250
- headers = {
251
- "Authorization": f"Bearer {integration.access_token}",
252
- "Content-Type": "application/json"
253
- }
254
-
255
- async with httpx.AsyncClient(timeout=self.timeout) as client:
256
- # Create or update contact
257
- contact_data = {
258
- "name": payload.get("name", "Unknown"),
259
- "custom_fields_values": []
260
- }
261
-
262
- # Add phone if exists
263
- if payload.get("phone"):
264
- contact_data["custom_fields_values"].append({
265
- "field_code": "PHONE",
266
- "values": [{"value": payload["phone"], "enum_code": "WORK"}]
267
- })
268
-
269
- # Add email if exists
270
- if payload.get("email"):
271
- contact_data["custom_fields_values"].append({
272
- "field_code": "EMAIL",
273
- "values": [{"value": payload["email"], "enum_code": "WORK"}]
274
- })
275
-
276
- if existing_link and existing_link.crm_contact_id:
277
- # Update existing contact
278
- contact_id = existing_link.crm_contact_id
279
- response = await client.patch(
280
- f"{base_url}/api/v4/contacts/{contact_id}",
281
- json=contact_data,
282
- headers=headers
283
- )
284
- else:
285
- # Create new contact
286
- response = await client.post(
287
- f"{base_url}/api/v4/contacts",
288
- json=[contact_data],
289
- headers=headers
290
- )
291
- response.raise_for_status()
292
- result = response.json()
293
- contact_id = result["_embedded"]["contacts"][0]["id"]
294
-
295
- # Create or update lead/deal
296
- lead_data = {
297
- "name": f"Лид: {payload.get('name', 'Unknown')}",
298
- "price": payload.get("budget", 0) if isinstance(payload.get("budget"), int) else 0,
299
- "_embedded": {
300
- "contacts": [{"id": contact_id}]
301
- }
302
- }
303
-
304
- if existing_link and existing_link.crm_lead_id:
305
- # Update existing lead
306
- lead_id = existing_link.crm_lead_id
307
- await client.patch(
308
- f"{base_url}/api/v4/leads/{lead_id}",
309
- json=lead_data,
310
- headers=headers
311
- )
312
- else:
313
- # Create new lead
314
- response = await client.post(
315
- f"{base_url}/api/v4/leads",
316
- json=[lead_data],
317
- headers=headers
318
- )
319
- response.raise_for_status()
320
- result = response.json()
321
- lead_id = result["_embedded"]["leads"][0]["id"]
322
-
323
- # Build URL
324
- subdomain = base_url.split("//")[1].split(".")[0] if "." in base_url else "unknown"
325
- crm_url = f"https://{subdomain}.amocrm.ru/leads/detail/{lead_id}"
326
-
327
- return {
328
- "success": True,
329
- "contact_id": str(contact_id),
330
- "lead_id": str(lead_id),
331
- "url": crm_url,
332
- "response": {"contact_id": contact_id, "lead_id": lead_id}
333
- }
334
-
335
- except httpx.HTTPStatusError as e:
336
- return {
337
- "success": False,
338
- "error": f"amoCRM HTTP error: {e.response.status_code} - {e.response.text}"
339
- }
340
- except Exception as e:
341
- return {
342
- "success": False,
343
- "error": f"amoCRM sync error: {str(e)}"
344
- }
345
-
346
- async def _sync_to_bitrix24(
347
- self,
348
- integration: CRMIntegration,
349
- payload: Dict[str, Any],
350
- existing_link: Optional[LeadCRMLink]
351
- ) -> Dict[str, Any]:
352
- """Sync to Bitrix24."""
353
-
354
- try:
355
- # Bitrix24 uses webhook URLs with access token
356
- webhook_url = integration.webhook_url
357
- if not webhook_url:
358
- return {"success": False, "error": "Webhook URL not configured"}
359
-
360
- async with httpx.AsyncClient(timeout=self.timeout) as client:
361
- # Create or update contact
362
- contact_data = {
363
- "fields": {
364
- "NAME": payload.get("name", "Unknown"),
365
- "PHONE": [{"VALUE": payload.get("phone"), "VALUE_TYPE": "WORK"}] if payload.get("phone") else [],
366
- "EMAIL": [{"VALUE": payload.get("email"), "VALUE_TYPE": "WORK"}] if payload.get("email") else []
367
- }
368
- }
369
-
370
- if existing_link and existing_link.crm_contact_id:
371
- # Update contact
372
- contact_id = existing_link.crm_contact_id
373
- await client.post(
374
- f"{webhook_url}/crm.contact.update",
375
- json={"id": contact_id, **contact_data}
376
- )
377
- else:
378
- # Create contact
379
- response = await client.post(
380
- f"{webhook_url}/crm.contact.add",
381
- json=contact_data
382
- )
383
- response.raise_for_status()
384
- result = response.json()
385
- contact_id = str(result.get("result"))
386
-
387
- # Create or update deal
388
- deal_data = {
389
- "fields": {
390
- "TITLE": f"Лид: {payload.get('name', 'Unknown')}",
391
- "OPPORTUNITY": payload.get("budget", 0) if isinstance(payload.get("budget"), int) else 0,
392
- "CONTACT_ID": contact_id
393
- }
394
- }
395
-
396
- if existing_link and existing_link.crm_lead_id:
397
- # Update deal
398
- deal_id = existing_link.crm_lead_id
399
- await client.post(
400
- f"{webhook_url}/crm.deal.update",
401
- json={"id": deal_id, **deal_data}
402
- )
403
- else:
404
- # Create deal
405
- response = await client.post(
406
- f"{webhook_url}/crm.deal.add",
407
- json=deal_data
408
- )
409
- response.raise_for_status()
410
- result = response.json()
411
- deal_id = str(result.get("result"))
412
-
413
- # Extract portal URL from webhook
414
- portal_url = webhook_url.split("/rest/")[0] if "/rest/" in webhook_url else webhook_url
415
- crm_url = f"{portal_url}/crm/deal/details/{deal_id}/"
416
-
417
- return {
418
- "success": True,
419
- "contact_id": contact_id,
420
- "lead_id": deal_id,
421
- "url": crm_url,
422
- "response": {"contact_id": contact_id, "deal_id": deal_id}
423
- }
424
-
425
- except Exception as e:
426
- return {
427
- "success": False,
428
- "error": f"Bitrix24 sync error: {str(e)}"
429
- }
430
-
431
- async def _sync_to_hubspot(
432
- self,
433
- integration: CRMIntegration,
434
- payload: Dict[str, Any],
435
- existing_link: Optional[LeadCRMLink]
436
- ) -> Dict[str, Any]:
437
- """Sync to HubSpot."""
438
-
439
- try:
440
- base_url = "https://api.hubapi.com"
441
- headers = {
442
- "Authorization": f"Bearer {integration.access_token}",
443
- "Content-Type": "application/json"
444
- }
445
-
446
- async with httpx.AsyncClient(timeout=self.timeout) as client:
447
- # Create or update contact
448
- contact_properties = {
449
- "email": payload.get("email", ""),
450
- "firstname": payload.get("name", "").split()[0] if payload.get("name") else "Unknown",
451
- "phone": payload.get("phone", "")
452
- }
453
-
454
- contact_data = {"properties": contact_properties}
455
-
456
- if existing_link and existing_link.crm_contact_id:
457
- # Update contact
458
- contact_id = existing_link.crm_contact_id
459
- await client.patch(
460
- f"{base_url}/crm/v3/objects/contacts/{contact_id}",
461
- json=contact_data,
462
- headers=headers
463
- )
464
- else:
465
- # Create contact
466
- response = await client.post(
467
- f"{base_url}/crm/v3/objects/contacts",
468
- json=contact_data,
469
- headers=headers
470
- )
471
- response.raise_for_status()
472
- result = response.json()
473
- contact_id = result["id"]
474
-
475
- # Create or update deal
476
- deal_properties = {
477
- "dealname": f"Лид: {payload.get('name', 'Unknown')}",
478
- "amount": payload.get("budget", 0) if isinstance(payload.get("budget"), int) else 0,
479
- "dealstage": "appointmentscheduled"
480
- }
481
-
482
- deal_data = {"properties": deal_properties}
483
-
484
- if existing_link and existing_link.crm_lead_id:
485
- # Update deal
486
- deal_id = existing_link.crm_lead_id
487
- await client.patch(
488
- f"{base_url}/crm/v3/objects/deals/{deal_id}",
489
- json=deal_data,
490
- headers=headers
491
- )
492
- else:
493
- # Create deal and associate with contact
494
- response = await client.post(
495
- f"{base_url}/crm/v3/objects/deals",
496
- json=deal_data,
497
- headers=headers
498
- )
499
- response.raise_for_status()
500
- result = response.json()
501
- deal_id = result["id"]
502
-
503
- # Associate deal with contact
504
- await client.put(
505
- f"{base_url}/crm/v3/objects/deals/{deal_id}/associations/contacts/{contact_id}/3",
506
- headers=headers
507
- )
508
-
509
- crm_url = f"https://app.hubspot.com/contacts/portal/deal/{deal_id}"
510
-
511
- return {
512
- "success": True,
513
- "contact_id": str(contact_id),
514
- "lead_id": str(deal_id),
515
- "url": crm_url,
516
- "response": {"contact_id": contact_id, "deal_id": deal_id}
517
- }
518
-
519
- except Exception as e:
520
- return {
521
- "success": False,
522
- "error": f"HubSpot sync error: {str(e)}"
523
- }
524
-
525
- async def _sync_to_webhook(
526
- self,
527
- integration: CRMIntegration,
528
- payload: Dict[str, Any],
529
- existing_link: Optional[LeadCRMLink]
530
- ) -> Dict[str, Any]:
531
- """Sync to custom webhook."""
532
-
533
- try:
534
- if not integration.webhook_url:
535
- return {"success": False, "error": "Webhook URL not configured"}
536
-
537
- headers = integration.webhook_headers or {}
538
- if integration.webhook_secret:
539
- headers["X-Webhook-Secret"] = integration.webhook_secret
540
-
541
- # Add operation type
542
- webhook_payload = {
543
- "operation": "update" if existing_link else "create",
544
- "lead": payload,
545
- "crm_link": {
546
- "contact_id": existing_link.crm_contact_id if existing_link else None,
547
- "lead_id": existing_link.crm_lead_id if existing_link else None
548
- } if existing_link else None
549
- }
550
-
551
- async with httpx.AsyncClient(timeout=self.timeout) as client:
552
- response = await client.post(
553
- integration.webhook_url,
554
- json=webhook_payload,
555
- headers=headers
556
- )
557
- response.raise_for_status()
558
-
559
- result = response.json()
560
-
561
- return {
562
- "success": True,
563
- "contact_id": result.get("contact_id"),
564
- "lead_id": result.get("lead_id") or result.get("deal_id"),
565
- "url": result.get("url"),
566
- "response": result
567
- }
568
-
569
- except Exception as e:
570
- return {
571
- "success": False,
572
- "error": f"Webhook sync error: {str(e)}"
573
- }
574
-
575
- async def sync_tenant_leads(
576
- self,
577
- session: AsyncSession,
578
- tenant_id: UUID,
579
- integration_id: UUID,
580
- limit: int = 100
581
- ) -> Dict[str, Any]:
582
- """
583
- Batch sync leads for a tenant.
584
-
585
- Returns:
586
- Stats about sync operation
587
- """
588
-
589
- # Get integration
590
- integration = await session.get(CRMIntegration, integration_id)
591
- if not integration or integration.tenant_id != tenant_id:
592
- return {"error": "Integration not found"}
593
-
594
- # Get leads to sync
595
- stmt = select(Lead).where(
596
- Lead.tenant_id == tenant_id
597
- ).limit(limit)
598
-
599
- result = await session.execute(stmt)
600
- leads = list(result.scalars().all())
601
-
602
- stats = {
603
- "total": len(leads),
604
- "success": 0,
605
- "failed": 0,
606
- "skipped": 0,
607
- "errors": []
608
- }
609
-
610
- for lead in leads:
611
- result = await self.sync_lead_to_crm(session, lead, integration)
612
-
613
- if result.get("success"):
614
- stats["success"] += 1
615
- elif result.get("skipped"):
616
- stats["skipped"] += 1
617
- else:
618
- stats["failed"] += 1
619
- stats["errors"].append({
620
- "lead_id": str(lead.id),
621
- "error": result.get("error")
622
- })
623
-
624
- return stats
625
-
626
-
627
- # Singleton instance
628
- _crm_sync_service: Optional[CRMSyncService] = None
629
-
630
-
631
- def get_crm_sync_service() -> CRMSyncService:
632
- """Get CRM sync service singleton."""
633
- global _crm_sync_service
634
- if _crm_sync_service is None:
635
- _crm_sync_service = CRMSyncService()
636
- return _crm_sync_service
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/apply_crm_migration.py DELETED
@@ -1,81 +0,0 @@
1
- """
2
- Apply CRM Integration Migration
3
-
4
- Creates tables for CRM integration functionality.
5
- """
6
-
7
- import asyncio
8
- import sys
9
- from pathlib import Path
10
-
11
- # Fix for Windows async
12
- if sys.platform == 'win32':
13
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
14
-
15
- from sqlalchemy.ext.asyncio import create_async_engine
16
- from app.core.config import settings
17
-
18
-
19
- async def apply_migration():
20
- """Apply CRM integration migration."""
21
-
22
- print("🚀 Applying CRM Integration migration...")
23
-
24
- # Create async engine
25
- # Convert psycopg2 URL to asyncpg for async operations
26
- db_url = settings.DATABASE_URL.replace("postgresql://", "postgresql+psycopg://")
27
-
28
- engine = create_async_engine(
29
- db_url,
30
- echo=False
31
- )
32
-
33
- # Read SQL file
34
- migration_file = Path(__file__).parent / "migrations" / "create_crm_integration_tables.sql"
35
-
36
- if not migration_file.exists():
37
- print(f"❌ Migration file not found: {migration_file}")
38
- return
39
-
40
- sql_content = migration_file.read_text(encoding='utf-8')
41
-
42
- print(f"📄 Executing migration from: {migration_file.name}")
43
-
44
- try:
45
- # Execute migration
46
- async with engine.begin() as conn:
47
- # Execute SQL statements
48
- await conn.execute(text(sql_content))
49
-
50
- print("✅ CRM Integration tables migration applied successfully!")
51
-
52
- # Verify tables created
53
- async with engine.begin() as conn:
54
- result = await conn.execute(text("""
55
- SELECT table_name
56
- FROM information_schema.tables
57
- WHERE table_schema = 'public'
58
- AND table_name IN ('crm_integrations', 'crm_sync_logs', 'crm_field_mappings', 'lead_crm_links')
59
- ORDER BY table_name;
60
- """))
61
- tables = [row[0] for row in result.fetchall()]
62
-
63
- print(f"✅ Verified {len(tables)} tables created:")
64
- for table in tables:
65
- print(f" - {table}")
66
-
67
- print("\n🎉 CRM Integration ready to use!")
68
- print("📚 New endpoints available at: /api/v1/crm/")
69
-
70
- except Exception as e:
71
- print(f"❌ Migration failed: {e}")
72
- import traceback
73
- traceback.print_exc()
74
-
75
- finally:
76
- await engine.dispose()
77
-
78
-
79
- if __name__ == "__main__":
80
- from sqlalchemy import text
81
- asyncio.run(apply_migration())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/app/chats/page.tsx CHANGED
@@ -220,7 +220,7 @@ function ChatsContent() {
220
 
221
 
222
  return (
223
- <div className="flex bg-background h-full overflow-hidden relative">
224
  {/* Left Column: Leads List */}
225
  <div className={cn(
226
  "h-full border-r border-white/10 flex flex-col transition-all duration-300 z-10 bg-background",
 
220
 
221
 
222
  return (
223
+ <div className="chat-container flex bg-background overflow-hidden relative">
224
  {/* Left Column: Leads List */}
225
  <div className={cn(
226
  "h-full border-r border-white/10 flex flex-col transition-all duration-300 z-10 bg-background",
frontend/app/globals.css CHANGED
@@ -695,4 +695,109 @@ nav,
695
  aside,
696
  .sidebar {
697
  touch-action: pan-y;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698
  }
 
695
  aside,
696
  .sidebar {
697
  touch-action: pan-y;
698
+ }
699
+
700
+ /* === MOBILE CHAT IMPROVEMENTS === */
701
+
702
+ /* Chat page uses full viewport height */
703
+ .chat-container {
704
+ height: 100vh;
705
+ height: 100dvh;
706
+ /* Dynamic viewport for mobile keyboards */
707
+ }
708
+
709
+ /* Mobile chat list improvements */
710
+ @media screen and (max-width: 767px) {
711
+
712
+ /* Compact sidebar on mobile */
713
+ .sidebar {
714
+ width: 100% !important;
715
+ max-width: none !important;
716
+ }
717
+
718
+ /* Chat header more compact */
719
+ .chat-header {
720
+ padding: 12px 16px !important;
721
+ }
722
+
723
+ /* Leads list items - larger touch targets */
724
+ .lead-item {
725
+ min-height: 64px;
726
+ padding: 12px 16px;
727
+ }
728
+
729
+ /* Message input area - fixed at bottom */
730
+ .message-input-container {
731
+ position: sticky;
732
+ bottom: 0;
733
+ background: var(--surface);
734
+ padding-bottom: env(safe-area-inset-bottom, 12px);
735
+ border-top: 1px solid var(--border);
736
+ }
737
+
738
+ /* AI summary drawer - full width on small screens */
739
+ .ai-summary-drawer {
740
+ width: 100% !important;
741
+ max-width: 100vw !important;
742
+ border-radius: 24px 24px 0 0 !important;
743
+ }
744
+ }
745
+
746
+ /* Aurora palette improvements for better contrast */
747
+ .text-slate-400 {
748
+ color: var(--text-secondary) !important;
749
+ }
750
+
751
+ .text-slate-500 {
752
+ color: var(--text-muted) !important;
753
+ }
754
+
755
+ .text-slate-600 {
756
+ color: var(--text-dim) !important;
757
+ }
758
+
759
+ .bg-slate-800 {
760
+ background-color: var(--surface-elevated) !important;
761
+ }
762
+
763
+ .bg-slate-900 {
764
+ background-color: var(--surface) !important;
765
+ }
766
+
767
+ /* Gradient accents matching landing page */
768
+ .aurora-gradient-text {
769
+ background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 50%, var(--accent) 100%);
770
+ -webkit-background-clip: text;
771
+ background-clip: text;
772
+ -webkit-text-fill-color: transparent;
773
+ }
774
+
775
+ .aurora-gradient-bg {
776
+ background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 50%, var(--accent) 100%);
777
+ }
778
+
779
+ /* Custom scrollbar matching Aurora theme */
780
+ .custom-scrollbar::-webkit-scrollbar {
781
+ width: 4px;
782
+ }
783
+
784
+ .custom-scrollbar::-webkit-scrollbar-track {
785
+ background: transparent;
786
+ }
787
+
788
+ .custom-scrollbar::-webkit-scrollbar-thumb {
789
+ background: var(--primary);
790
+ border-radius: 2px;
791
+ opacity: 0.5;
792
+ }
793
+
794
+ /* Touch-friendly interactive elements */
795
+ @media (hover: none) and (pointer: coarse) {
796
+
797
+ button,
798
+ a,
799
+ .clickable {
800
+ min-height: 44px;
801
+ min-width: 44px;
802
+ }
803
  }
frontend/app/settings/crm/page.tsx DELETED
@@ -1,496 +0,0 @@
1
- 'use client'
2
-
3
- import { useState } from 'react'
4
- import { useQuery, useQueryClient } from '@tanstack/react-query'
5
- import { useAuth } from '@/contexts/AuthContext'
6
- import { api } from '@/lib/api'
7
- import { Plus, Settings, X, Loader2, CheckCircle2, AlertCircle, Eye, EyeOff, Zap, Trash2 } from 'lucide-react'
8
- import Image from 'next/image'
9
- import { useTranslation } from '@/lib/i18n'
10
-
11
- interface CRMIntegration {
12
- id: string
13
- crm_type: string
14
- integration_name: string
15
- sync_direction: string
16
- auto_sync: boolean
17
- sync_interval_minutes: number
18
- sync_only_hot_leads: boolean
19
- sync_statuses: string[] | null
20
- status: string
21
- is_active: boolean
22
- last_sync_at: string | null
23
- total_synced_leads: number
24
- failed_sync_count: number
25
- }
26
-
27
- // CRM configurations with branding and real logos (SVG)
28
- const CRM_CONFIGS = {
29
- amocrm: {
30
- name: 'AmoCRM',
31
- gradient: 'from-blue-500 via-cyan-500 to-teal-400',
32
- logoUrl: '/crm/amocrm-logo-dark.svg',
33
- placeholder_url: 'https://yourcompany.amocrm.ru'
34
- },
35
- bitrix24: {
36
- name: 'Bitrix24',
37
- gradient: 'from-blue-600 via-blue-500 to-cyan-400',
38
- logoUrl: '/crm/bitrix24-logo-eng.svg',
39
- placeholder_url: 'https://yourcompany.bitrix24.ru/rest/...'
40
- },
41
- salesforce: {
42
- name: 'Salesforce',
43
- gradient: 'from-sky-500 to-blue-600',
44
- logoUrl: '/crm/salesforce.svg',
45
- placeholder_url: 'https://yourinstance.salesforce.com'
46
- },
47
- hubspot: {
48
- name: 'HubSpot',
49
- gradient: 'from-orange-500 to-red-500',
50
- logoUrl: '/crm/hubspot.svg',
51
- placeholder_url: 'https://api.hubapi.com'
52
- },
53
- zoho: {
54
- name: 'Zoho',
55
- gradient: 'from-yellow-400 via-red-500 to-pink-500',
56
- logoUrl: '/crm/zoho.svg',
57
- placeholder_url: 'https://www.zohoapis.com'
58
- }
59
- }
60
-
61
- const AVAILABLE_CRMS = ['salesforce', 'hubspot', 'zoho'] as const
62
-
63
- export default function CRMSettingsPage() {
64
- const { user } = useAuth()
65
- const queryClient = useQueryClient()
66
- const [saving, setSaving] = useState(false)
67
- const [showModal, setShowModal] = useState(false)
68
- const [modalMode, setModalMode] = useState<'add' | 'configure'>('add')
69
- const [selectedCRM, setSelectedCRM] = useState<string | null>(null)
70
- const [successMessage, setSuccessMessage] = useState('')
71
- const [errorMessage, setErrorMessage] = useState('')
72
- const [showToken, setShowToken] = useState(false)
73
- const { t } = useTranslation()
74
-
75
- // Form state
76
- const [formData, setFormData] = useState({
77
- integration_name: '',
78
- api_url: '',
79
- access_token: '',
80
- webhook_url: '',
81
- auto_sync: true,
82
- sync_interval_minutes: 15,
83
- sync_only_hot_leads: true
84
- })
85
-
86
- // React Query for CRM integrations - cached!
87
- const { data: integrations = [], isLoading: loading } = useQuery<CRMIntegration[]>({
88
- queryKey: ['crm-integrations', user?.tenant_id],
89
- queryFn: async () => {
90
- const response = await api.get(`/api/v1/crm/${user!.tenant_id}/integrations`)
91
- return response.data
92
- },
93
- enabled: !!user?.tenant_id,
94
- })
95
-
96
- const openConfigureModal = (crmType: string) => {
97
- setSelectedCRM(crmType)
98
- setModalMode('configure')
99
- setFormData({
100
- integration_name: CRM_CONFIGS[crmType as keyof typeof CRM_CONFIGS]?.name || crmType,
101
- api_url: '',
102
- access_token: '',
103
- webhook_url: '',
104
- auto_sync: true,
105
- sync_interval_minutes: 15,
106
- sync_only_hot_leads: true
107
- })
108
- setShowModal(true)
109
- }
110
-
111
- const handleConnect = async (crmType: string) => {
112
- openConfigureModal(crmType)
113
- }
114
-
115
- const handleSaveIntegration = async () => {
116
- if (!selectedCRM || !user?.tenant_id) return
117
-
118
- setSaving(true)
119
- setErrorMessage('')
120
-
121
- try {
122
- await api.post(`/api/v1/crm/${user.tenant_id}/integrations`, {
123
- crm_type: selectedCRM,
124
- ...formData
125
- })
126
- setSuccessMessage(t('crm.integrationConnected'))
127
- setShowModal(false)
128
- queryClient.invalidateQueries({ queryKey: ['crm-integrations'] })
129
- setTimeout(() => setSuccessMessage(''), 3000)
130
- } catch (error: any) {
131
- setErrorMessage(error.response?.data?.detail || t('crm.connectionError'))
132
- } finally {
133
- setSaving(false)
134
- }
135
- }
136
-
137
- const handleDeleteIntegration = async (id: string) => {
138
- if (!confirm(t('crm.deleteConfirmation'))) return
139
- if (!user?.tenant_id) return
140
-
141
- try {
142
- await api.delete(`/api/v1/crm/${user.tenant_id}/integrations/${id}`)
143
- setSuccessMessage(t('crm.integrationDeleted'))
144
- queryClient.invalidateQueries({ queryKey: ['crm-integrations'] })
145
- setTimeout(() => setSuccessMessage(''), 3000)
146
- } catch (error) {
147
- console.error('Failed to delete:', error)
148
- }
149
- }
150
-
151
- const getActiveIntegration = (crmType: string) => {
152
- return integrations.find(i => i.crm_type === crmType && i.is_active)
153
- }
154
-
155
- if (loading) {
156
- return (
157
- <div className="flex items-center justify-center min-h-screen bg-background">
158
- <div className="w-8 h-8 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin"></div>
159
- </div>
160
- )
161
- }
162
-
163
- return (
164
- <div className="min-h-screen p-8 font-['Inter']">
165
- <div className="max-w-5xl mx-auto">
166
- {/* Header */}
167
- <div className="flex items-center justify-between mb-8">
168
- <div>
169
- <h1 className="text-2xl font-black text-white tracking-wider">CRM</h1>
170
- </div>
171
- </div>
172
-
173
- {/* Success/Error Messages */}
174
- {successMessage && (
175
- <div className="mb-6 p-4 bg-emerald-500/10 border border-emerald-500/30 rounded-xl flex items-center gap-3">
176
- <CheckCircle2 className="w-5 h-5 text-emerald-400" />
177
- <p className="text-emerald-300">{successMessage}</p>
178
- </div>
179
- )}
180
- {errorMessage && (
181
- <div className="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-xl flex items-center gap-3">
182
- <AlertCircle className="w-5 h-5 text-red-400" />
183
- <p className="text-red-300">{errorMessage}</p>
184
- </div>
185
- )}
186
-
187
- {/* CRM Integrations Section */}
188
- <div className="mb-10">
189
- <div className="mb-6">
190
- <h2 className="text-xl font-bold text-white">{t('crm.integrations')}</h2>
191
- </div>
192
-
193
- {/* Active Integrations Cards */}
194
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
195
- {/* AmoCRM Card */}
196
- {(() => {
197
- const active = getActiveIntegration('amocrm')
198
- return (
199
- <div className={`relative rounded-2xl overflow-hidden transition-all duration-300 ${active ? 'saturate-150 brightness-110' : 'saturate-50 brightness-75 hover:saturate-75 hover:brightness-90'}`}>
200
- <div className={`absolute inset-0 bg-gradient-to-br ${CRM_CONFIGS.amocrm.gradient}`}></div>
201
- <div className="relative p-6">
202
- {active && (
203
- <div className="absolute top-4 right-4">
204
- <span className="px-2.5 py-1 bg-emerald-500 text-white text-xs font-bold rounded-full">
205
- {t('crm.active')}
206
- </span>
207
- </div>
208
- )}
209
- <div className="flex items-center gap-3 mb-4">
210
- <div className="w-24 h-16 flex items-center justify-center">
211
- <img src={CRM_CONFIGS.amocrm.logoUrl} alt="AmoCRM" className="w-full h-full object-contain" />
212
- </div>
213
- </div>
214
- <h3 className="text-2xl font-bold text-white mb-2">AmoCRM</h3>
215
- {active ? (
216
- <p className="text-white/70 text-sm mb-6">
217
- Последняя синхронизация<br />
218
- {active.last_sync_at
219
- ? `от ${new Date(active.last_sync_at).toLocaleDateString('ru-RU')} в ${new Date(active.last_sync_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}`
220
- : 'Еще не было'
221
- }
222
- </p>
223
- ) : (
224
- <p className="text-white/70 text-sm mb-6">{t('crm.notConnected')}</p>
225
- )}
226
- <button
227
- onClick={() => active ? openConfigureModal('amocrm') : handleConnect('amocrm')}
228
- className="w-full py-2.5 bg-white/20 hover:bg-white/30 text-white font-medium rounded-lg transition-colors"
229
- >
230
- {active ? t('crm.configure') : t('crm.connect')}
231
- </button>
232
- </div>
233
- </div>
234
- )
235
- })()}
236
-
237
- {/* Bitrix24 Card */}
238
- {(() => {
239
- const active = getActiveIntegration('bitrix24')
240
- return (
241
- <div className={`relative rounded-2xl overflow-hidden transition-all duration-300 ${active ? 'saturate-150 brightness-110' : 'saturate-50 brightness-75 hover:saturate-75 hover:brightness-90'}`}>
242
- <div className={`absolute inset-0 bg-gradient-to-br ${CRM_CONFIGS.bitrix24.gradient}`}></div>
243
- <div className="relative p-6">
244
- {active && (
245
- <div className="absolute top-4 right-4">
246
- <span className="px-2.5 py-1 bg-emerald-500 text-white text-xs font-bold rounded-full">
247
- Активно
248
- </span>
249
- </div>
250
- )}
251
- <div className="flex items-center gap-3 mb-4">
252
- <div className="w-28 h-12 flex items-center justify-center">
253
- <img src={CRM_CONFIGS.bitrix24.logoUrl} alt="Bitrix24" className="w-full h-full object-contain" />
254
- </div>
255
- </div>
256
- <h3 className="text-2xl font-bold text-white mb-2">Bitrix24</h3>
257
- {active ? (
258
- <p className="text-white/70 text-sm mb-6">
259
- Последняя синхронизация<br />
260
- {active.last_sync_at
261
- ? `от ${new Date(active.last_sync_at).toLocaleDateString('ru-RU')} в ${new Date(active.last_sync_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}`
262
- : 'Еще не было'
263
- }
264
- </p>
265
- ) : (
266
- <p className="text-white/70 text-sm mb-6">Не подключено</p>
267
- )}
268
- <button
269
- onClick={() => active ? openConfigureModal('bitrix24') : handleConnect('bitrix24')}
270
- className="w-full py-2.5 bg-white/20 hover:bg-white/30 text-white font-medium rounded-lg transition-colors"
271
- >
272
- {active ? 'Настроить' : 'Подключить'}
273
- </button>
274
- </div>
275
- </div>
276
- )
277
- })()}
278
- </div>
279
- </div>
280
-
281
- {/* Available Integrations Section */}
282
- <div>
283
- <h2 className="text-xl font-bold text-white mb-6">{t('crm.availableIntegrations')}</h2>
284
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
285
- {/* Salesforce */}
286
- {(() => {
287
- const active = getActiveIntegration('salesforce')
288
- return (
289
- <div className={`bg-slate-900/50 backdrop-blur-sm border border-white/10 rounded-2xl p-6 flex flex-col items-center text-center transition-all duration-300 ${active ? 'border-sky-500/50 bg-slate-800/70' : 'grayscale-[30%] opacity-80 hover:opacity-100 hover:grayscale-0'}`}>
290
- <div className="w-16 h-16 bg-white rounded-xl p-2 flex items-center justify-center mb-4">
291
- <img src={CRM_CONFIGS.salesforce.logoUrl} alt="Salesforce" className="w-full h-full object-contain" />
292
- </div>
293
- <h3 className="text-lg font-bold text-white mb-4">Salesforce</h3>
294
- <button
295
- onClick={() => active ? openConfigureModal('salesforce') : handleConnect('salesforce')}
296
- className={`w-full py-2.5 font-medium rounded-lg transition-colors ${active ? 'bg-sky-600 hover:bg-sky-500 text-white' : 'bg-slate-800 hover:bg-slate-700 border border-white/10 text-white'}`}
297
- >
298
- {active ? 'Настроить' : 'Подключить'}
299
- </button>
300
- </div>
301
- )
302
- })()}
303
-
304
- {/* HubSpot */}
305
- {(() => {
306
- const active = getActiveIntegration('hubspot')
307
- return (
308
- <div className={`bg-slate-900/50 backdrop-blur-sm border border-white/10 rounded-2xl p-6 flex flex-col items-center text-center transition-all duration-300 ${active ? 'border-orange-500/50 bg-slate-800/70' : 'grayscale-[30%] opacity-80 hover:opacity-100 hover:grayscale-0'}`}>
309
- <div className="w-16 h-16 bg-white rounded-xl p-2 flex items-center justify-center mb-4">
310
- <img src={CRM_CONFIGS.hubspot.logoUrl} alt="HubSpot" className="w-full h-full object-contain" />
311
- </div>
312
- <h3 className="text-lg font-bold text-white mb-4">HubSpot</h3>
313
- <button
314
- onClick={() => active ? openConfigureModal('hubspot') : handleConnect('hubspot')}
315
- className={`w-full py-2.5 font-medium rounded-lg transition-colors ${active ? 'bg-orange-600 hover:bg-orange-500 text-white' : 'bg-slate-800 hover:bg-slate-700 border border-white/10 text-white'}`}
316
- >
317
- {active ? 'Настроить' : 'Подключить'}
318
- </button>
319
- </div>
320
- )
321
- })()}
322
-
323
- {/* Zoho */}
324
- {(() => {
325
- const active = getActiveIntegration('zoho')
326
- return (
327
- <div className={`bg-slate-900/50 backdrop-blur-sm border border-white/10 rounded-2xl p-6 flex flex-col items-center text-center transition-all duration-300 ${active ? 'border-yellow-500/50 bg-slate-800/70' : 'grayscale-[30%] opacity-80 hover:opacity-100 hover:grayscale-0'}`}>
328
- <div className="w-16 h-16 bg-white rounded-xl p-2 flex items-center justify-center mb-4">
329
- <img src={CRM_CONFIGS.zoho.logoUrl} alt="Zoho" className="w-full h-full object-contain" />
330
- </div>
331
- <h3 className="text-lg font-bold text-white mb-4">Zoho</h3>
332
- <button
333
- onClick={() => active ? openConfigureModal('zoho') : handleConnect('zoho')}
334
- className={`w-full py-2.5 font-medium rounded-lg transition-colors ${active ? 'bg-yellow-600 hover:bg-yellow-500 text-white' : 'bg-slate-800 hover:bg-slate-700 border border-white/10 text-white'}`}
335
- >
336
- {active ? 'Настроить' : 'Подключить'}
337
- </button>
338
- </div>
339
- )
340
- })()}
341
- </div>
342
- </div>
343
-
344
- {/* Configure Modal */}
345
- {showModal && (
346
- <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
347
- <div className="bg-slate-900 border border-white/10 rounded-2xl w-full max-w-lg shadow-2xl">
348
- {/* Modal Header */}
349
- <div className="p-6 border-b border-white/10 flex items-center justify-between">
350
- <h3 className="text-xl font-bold text-white">
351
- {modalMode === 'add' ? t('crm.selectCRM') : `${t('crm.configuring')} ${CRM_CONFIGS[selectedCRM as keyof typeof CRM_CONFIGS]?.name || selectedCRM}`}
352
- </h3>
353
- <button
354
- onClick={() => setShowModal(false)}
355
- className="p-1 text-slate-400 hover:text-white transition-colors"
356
- >
357
- <X className="w-5 h-5" />
358
- </button>
359
- </div>
360
-
361
- {/* Modal Body */}
362
- <div className="p-6">
363
- {modalMode === 'add' ? (
364
- <div className="grid grid-cols-2 gap-4">
365
- {Object.entries(CRM_CONFIGS).map(([key, config]) => (
366
- <button
367
- key={key}
368
- onClick={() => {
369
- setSelectedCRM(key)
370
- setModalMode('configure')
371
- setFormData({
372
- ...formData,
373
- integration_name: config.name
374
- })
375
- }}
376
- className="p-4 bg-slate-800 hover:bg-slate-700 border border-white/10 rounded-xl text-left transition-colors"
377
- >
378
- <div className={`w-10 h-10 rounded-lg bg-gradient-to-br ${config.gradient} flex items-center justify-center mb-3`}>
379
- <span className="text-white text-xs font-bold">
380
- {config.name.slice(0, 3)}
381
- </span>
382
- </div>
383
- <p className="font-medium text-white">{config.name}</p>
384
- </button>
385
- ))}
386
- </div>
387
- ) : (
388
- <div className="space-y-4">
389
- {/* API URL */}
390
- <div>
391
- <label className="block text-sm font-medium text-slate-400 mb-2">
392
- {selectedCRM === 'bitrix24' ? 'Webhook URL' : 'API URL'}
393
- </label>
394
- <input
395
- type="text"
396
- value={formData.api_url || formData.webhook_url}
397
- onChange={(e) => setFormData({
398
- ...formData,
399
- [selectedCRM === 'bitrix24' ? 'webhook_url' : 'api_url']: e.target.value
400
- })}
401
- placeholder={CRM_CONFIGS[selectedCRM as keyof typeof CRM_CONFIGS]?.placeholder_url}
402
- className="w-full px-4 py-3 bg-slate-800 border border-white/10 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50"
403
- />
404
- </div>
405
-
406
- {/* Access Token (not for Bitrix) */}
407
- {selectedCRM !== 'bitrix24' && (
408
- <div>
409
- <label className="block text-sm font-medium text-slate-400 mb-2">
410
- Access Token / API Key
411
- </label>
412
- <div className="relative">
413
- <input
414
- type={showToken ? 'text' : 'password'}
415
- value={formData.access_token}
416
- onChange={(e) => setFormData({ ...formData, access_token: e.target.value })}
417
- placeholder={t('crm.enterAccessToken')}
418
- className="w-full px-4 py-3 pr-12 bg-slate-800 border border-white/10 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 font-mono text-sm"
419
- />
420
- <button
421
- type="button"
422
- onClick={() => setShowToken(!showToken)}
423
- className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-white"
424
- >
425
- {showToken ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
426
- </button>
427
- </div>
428
- </div>
429
- )}
430
-
431
- {/* Auto Sync */}
432
- <div className="flex items-center justify-between py-3">
433
- <div>
434
- <p className="text-sm font-medium text-white">{t('crm.autoSync')}</p>
435
- <p className="text-xs text-slate-500">{t('crm.autoSyncDesc')}</p>
436
- </div>
437
- <button
438
- onClick={() => setFormData({ ...formData, auto_sync: !formData.auto_sync })}
439
- className={`w-12 h-6 rounded-full p-1 transition-colors ${formData.auto_sync ? 'bg-indigo-600' : 'bg-slate-700'}`}
440
- >
441
- <div className={`w-4 h-4 bg-white rounded-full transition-transform ${formData.auto_sync ? 'translate-x-6' : ''}`} />
442
- </button>
443
- </div>
444
-
445
- {/* Sync Interval */}
446
- <div>
447
- <label className="block text-sm font-medium text-slate-400 mb-2">
448
- {t('crm.syncInterval')}
449
- </label>
450
- <select
451
- value={formData.sync_interval_minutes}
452
- onChange={(e) => setFormData({ ...formData, sync_interval_minutes: parseInt(e.target.value) })}
453
- className="w-full px-4 py-3 bg-slate-800 border border-white/10 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50"
454
- >
455
- <option value={5}>{t('time.fiveMinutes')}</option>
456
- <option value={15}>{t('time.fifteenMinutes')}</option>
457
- <option value={30}>{t('time.thirtyMinutes')}</option>
458
- <option value={60}>{t('time.oneHour')}</option>
459
- </select>
460
- </div>
461
- </div>
462
- )}
463
- </div>
464
-
465
- {/* Modal Footer */}
466
- {modalMode === 'configure' && (
467
- <div className="p-6 border-t border-white/10 flex gap-3">
468
- <button
469
- onClick={() => setShowModal(false)}
470
- className="flex-1 py-2.5 border border-white/10 text-slate-400 rounded-lg hover:text-white transition-colors"
471
- >
472
- {t('common.cancel')}
473
- </button>
474
- <button
475
- onClick={handleSaveIntegration}
476
- disabled={saving}
477
- className="flex-1 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
478
- >
479
- {saving ? (
480
- <>
481
- <Loader2 className="w-4 h-4 animate-spin" />
482
- {t('common.saving')}
483
- </>
484
- ) : (
485
- t('crm.connect')
486
- )}
487
- </button>
488
- </div>
489
- )}
490
- </div>
491
- </div>
492
- )}
493
- </div>
494
- </div >
495
- )
496
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/app/settings/team/page.tsx CHANGED
@@ -4,8 +4,8 @@ import { useState } from 'react'
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import { useToast } from '@/contexts/ToastContext'
7
- import { api } from '@/lib/api'
8
- import { Users, Plus, Trash2, Lock, Unlock, Loader2, Mail, User as UserIcon, AlertCircle, CheckCircle2, ShieldCheck, X } from 'lucide-react'
9
  import { motion, AnimatePresence } from 'framer-motion'
10
  import { cn } from '@/lib/utils'
11
  import { useTranslation } from '@/lib/i18n'
@@ -44,6 +44,11 @@ export default function TeamPage() {
44
  })
45
  const members: TeamMember[] = teamData || []
46
 
 
 
 
 
 
47
  const handleCreateManager = async (e: React.FormEvent) => {
48
  e.preventDefault()
49
  if (!formData.email || !formData.full_name || !formData.password) {
@@ -203,10 +208,20 @@ export default function TeamPage() {
203
  </div>
204
  <div>
205
  <h3 className="font-semibold text-white">{member.full_name || t('team.noName')}</h3>
206
- <p className="text-sm text-slate-500 flex items-center gap-1.5">
207
  <Mail className="w-3.5 h-3.5" />
208
  {member.email}
209
  </p>
 
 
 
 
 
 
 
 
 
 
210
  </div>
211
  </div>
212
 
 
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import { useToast } from '@/contexts/ToastContext'
7
+ import { api, bookingsApi } from '@/lib/api'
8
+ import { Users, Plus, Trash2, Lock, Unlock, Loader2, Mail, User as UserIcon, AlertCircle, CheckCircle2, ShieldCheck, X, Cog } from 'lucide-react'
9
  import { motion, AnimatePresence } from 'framer-motion'
10
  import { cn } from '@/lib/utils'
11
  import { useTranslation } from '@/lib/i18n'
 
44
  })
45
  const members: TeamMember[] = teamData || []
46
 
47
+ const { data: resources = [] } = useQuery<any[]>({
48
+ queryKey: ['booking-resources'],
49
+ queryFn: bookingsApi.getResources,
50
+ })
51
+
52
  const handleCreateManager = async (e: React.FormEvent) => {
53
  e.preventDefault()
54
  if (!formData.email || !formData.full_name || !formData.password) {
 
208
  </div>
209
  <div>
210
  <h3 className="font-semibold text-white">{member.full_name || t('team.noName')}</h3>
211
+ <p className="text-sm text-slate-500 flex items-center gap-1.5 mb-1.5">
212
  <Mail className="w-3.5 h-3.5" />
213
  {member.email}
214
  </p>
215
+ {/* Linked Resources */}
216
+ {resources.filter(r => r.user_id === member.id).length > 0 && (
217
+ <div className="flex flex-wrap gap-2">
218
+ {resources.filter(r => r.user_id === member.id).map(r => (
219
+ <span key={r.id} className="px-2 py-0.5 bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 rounded-md text-[10px] uppercase font-bold tracking-wider">
220
+ {r.name}
221
+ </span>
222
+ ))}
223
+ </div>
224
+ )}
225
  </div>
226
  </div>
227
 
frontend/components/ChatWindow/ChatHeader.tsx CHANGED
@@ -33,7 +33,7 @@ export function ChatHeader({
33
  onTrainAI,
34
  }: ChatHeaderProps) {
35
  return (
36
- <div className="bg-black/40 md:bg-gradient-to-b md:from-black/60 md:to-transparent md:backdrop-blur-xl px-4 md:px-6 py-3 flex items-center justify-between flex-shrink-0 fixed md:relative top-16 md:top-0 left-0 right-0 z-20">
37
  <div className="flex items-center gap-4">
38
  {/* Desktop Toggle */}
39
  <button
 
33
  onTrainAI,
34
  }: ChatHeaderProps) {
35
  return (
36
+ <div className="chat-header bg-surface/80 backdrop-blur-xl px-4 md:px-6 py-3 flex items-center justify-between flex-shrink-0 fixed md:relative top-16 md:top-0 left-0 right-0 z-20 border-b border-white/5">
37
  <div className="flex items-center gap-4">
38
  {/* Desktop Toggle */}
39
  <button
frontend/components/LeadsList.tsx CHANGED
@@ -252,10 +252,10 @@ export function LeadsList({
252
  key={lead.id}
253
  onClick={() => onSelectLead(lead)}
254
  className={cn(
255
- "p-3 rounded-xl cursor-pointer transition-all duration-200 group relative border",
256
  isSelected
257
- ? "bg-[#1A1B26] border-white/5 shadow-lg"
258
- : "bg-transparent border-transparent hover:bg-white/5"
259
  )}
260
  >
261
  <div className="flex gap-3">
 
252
  key={lead.id}
253
  onClick={() => onSelectLead(lead)}
254
  className={cn(
255
+ "lead-item p-3 rounded-xl cursor-pointer transition-all duration-200 group relative border",
256
  isSelected
257
+ ? "bg-surface-elevated border-primary/20 shadow-lg shadow-primary/5"
258
+ : "bg-transparent border-transparent hover:bg-white/5 hover:border-white/5"
259
  )}
260
  >
261
  <div className="flex gap-3">
frontend/components/ResourcesManager.tsx CHANGED
@@ -5,7 +5,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { bookingsApi } from '@/lib/api'
7
  import { motion, AnimatePresence } from 'framer-motion'
8
- import { Loader2, Plus, Trash2, Edit2, X, Clock, CheckCircle, XCircle, Save, Send, AlertCircle } from 'lucide-react'
9
  import { cn } from '@/lib/utils'
10
 
11
  interface Resource {
@@ -16,6 +16,7 @@ interface Resource {
16
  sort_order: number
17
  is_active: boolean
18
  telegram_chat_id?: string | null
 
19
  services: { id: string, name: string }[]
20
  }
21
 
@@ -53,6 +54,7 @@ export default function ResourcesManager({ bookingSettings }: ResourcesManagerPr
53
  name: '',
54
  description: '',
55
  telegram_chat_id: '',
 
56
  working_hours: {} as Record<string, { start: string, end: string }>
57
  })
58
 
@@ -62,6 +64,14 @@ export default function ResourcesManager({ bookingSettings }: ResourcesManagerPr
62
  queryFn: bookingsApi.getResources
63
  })
64
 
 
 
 
 
 
 
 
 
65
  // Create mutation
66
  const createMutation = useMutation({
67
  mutationFn: bookingsApi.createResource,
@@ -101,11 +111,12 @@ export default function ResourcesManager({ bookingSettings }: ResourcesManagerPr
101
  name: resource.name,
102
  description: resource.description || '',
103
  telegram_chat_id: resource.telegram_chat_id || '',
 
104
  working_hours: resource.working_hours || {}
105
  })
106
  } else {
107
  setEditingResource(null)
108
- setFormData({ name: '', description: '', telegram_chat_id: '', working_hours: {} })
109
  }
110
  setIsModalOpen(true)
111
  }
@@ -113,7 +124,7 @@ export default function ResourcesManager({ bookingSettings }: ResourcesManagerPr
113
  const closeModal = () => {
114
  setIsModalOpen(false)
115
  setEditingResource(null)
116
- setFormData({ name: '', description: '', telegram_chat_id: '', working_hours: {} })
117
  }
118
 
119
  const handleSave = () => {
@@ -126,6 +137,7 @@ export default function ResourcesManager({ bookingSettings }: ResourcesManagerPr
126
  name: formData.name,
127
  description: formData.description || undefined,
128
  telegram_chat_id: formData.telegram_chat_id || undefined,
 
129
  working_hours: Object.keys(formData.working_hours).length > 0 ? formData.working_hours : undefined
130
  }
131
 
@@ -378,6 +390,29 @@ export default function ResourcesManager({ bookingSettings }: ResourcesManagerPr
378
  </p>
379
  </div>
380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  {/* Working Hours */}
382
  <div>
383
  <label className="block text-sm text-slate-300 mb-2">Рабочие часы</label>
 
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { bookingsApi } from '@/lib/api'
7
  import { motion, AnimatePresence } from 'framer-motion'
8
+ import { Loader2, Plus, Trash2, Edit2, X, Clock, CheckCircle, XCircle, Save, Send, AlertCircle, Users } from 'lucide-react'
9
  import { cn } from '@/lib/utils'
10
 
11
  interface Resource {
 
16
  sort_order: number
17
  is_active: boolean
18
  telegram_chat_id?: string | null
19
+ user_id?: string | null
20
  services: { id: string, name: string }[]
21
  }
22
 
 
54
  name: '',
55
  description: '',
56
  telegram_chat_id: '',
57
+ user_id: '' as string | null,
58
  working_hours: {} as Record<string, { start: string, end: string }>
59
  })
60
 
 
64
  queryFn: bookingsApi.getResources
65
  })
66
 
67
+ const { data: teamMembers } = useQuery<any[]>({
68
+ queryKey: ['team-members'],
69
+ queryFn: async () => {
70
+ const res = await bookingsApi.getTeamMembers()
71
+ return res.members || []
72
+ }
73
+ })
74
+
75
  // Create mutation
76
  const createMutation = useMutation({
77
  mutationFn: bookingsApi.createResource,
 
111
  name: resource.name,
112
  description: resource.description || '',
113
  telegram_chat_id: resource.telegram_chat_id || '',
114
+ user_id: resource.user_id || '',
115
  working_hours: resource.working_hours || {}
116
  })
117
  } else {
118
  setEditingResource(null)
119
+ setFormData({ name: '', description: '', telegram_chat_id: '', user_id: '', working_hours: {} })
120
  }
121
  setIsModalOpen(true)
122
  }
 
124
  const closeModal = () => {
125
  setIsModalOpen(false)
126
  setEditingResource(null)
127
+ setFormData({ name: '', description: '', telegram_chat_id: '', user_id: '', working_hours: {} })
128
  }
129
 
130
  const handleSave = () => {
 
137
  name: formData.name,
138
  description: formData.description || undefined,
139
  telegram_chat_id: formData.telegram_chat_id || undefined,
140
+ user_id: formData.user_id || undefined,
141
  working_hours: Object.keys(formData.working_hours).length > 0 ? formData.working_hours : undefined
142
  }
143
 
 
390
  </p>
391
  </div>
392
 
393
+ {/* Link to Manager */}
394
+ <div>
395
+ <label className="block text-sm text-slate-300 mb-2 flex items-center gap-2">
396
+ <Users className="w-3.5 h-3.5 text-indigo-400" />
397
+ Привязать к менеджеру
398
+ </label>
399
+ <select
400
+ value={formData.user_id || ''}
401
+ onChange={(e) => setFormData({ ...formData, user_id: e.target.value || null })}
402
+ className="w-full px-4 py-3 bg-surface border border-white/10 rounded-lg text-white outline-none focus:border-indigo-500"
403
+ >
404
+ <option value="">Без привязки</option>
405
+ {teamMembers?.map(member => (
406
+ <option key={member.id} value={member.id}>
407
+ {member.full_name || member.email} ({member.role})
408
+ </option>
409
+ ))}
410
+ </select>
411
+ <p className="text-xs text-slate-500 mt-1.5">
412
+ Менеджер сможет управлять записями только этого ресурса
413
+ </p>
414
+ </div>
415
+
416
  {/* Working Hours */}
417
  <div>
418
  <label className="block text-sm text-slate-300 mb-2">Рабочие часы</label>
frontend/components/Sidebar.tsx CHANGED
@@ -63,7 +63,6 @@ const integrationItems = [
63
  const settingsItems = [
64
  { href: '/settings/brain', icon: Brain, labelKey: 'nav.brain', ownerOnly: true },
65
  { href: '/settings/voice', icon: Volume2, labelKey: 'nav.voice', ownerOnly: true },
66
- { href: '/settings/crm', icon: Database, labelKey: 'nav.crm', ownerOnly: true },
67
  { href: '/settings/playbook', icon: FileText, labelKey: 'nav.funnel', ownerOnly: true },
68
  { href: '/settings/team', icon: Users, labelKey: 'nav.team', ownerOnly: true },
69
  { href: '/settings/notifications', icon: Bell, labelKey: 'nav.notifications', ownerOnly: false },
 
63
  const settingsItems = [
64
  { href: '/settings/brain', icon: Brain, labelKey: 'nav.brain', ownerOnly: true },
65
  { href: '/settings/voice', icon: Volume2, labelKey: 'nav.voice', ownerOnly: true },
 
66
  { href: '/settings/playbook', icon: FileText, labelKey: 'nav.funnel', ownerOnly: true },
67
  { href: '/settings/team', icon: Users, labelKey: 'nav.team', ownerOnly: true },
68
  { href: '/settings/notifications', icon: Bell, labelKey: 'nav.notifications', ownerOnly: false },
frontend/components/bookings/CalendarView.tsx CHANGED
@@ -11,7 +11,8 @@ type ViewMode = 'month' | 'day' | 'resources'
11
  interface Resource {
12
  id: string
13
  name: string
14
- working_hours?: Record<string, { start: string; end: string }>
 
15
  is_active?: boolean
16
  }
17
 
@@ -269,27 +270,27 @@ export function CalendarView({
269
  <div className="flex flex-col">
270
  {/* Day Navigation */}
271
  <div className="flex items-center justify-between mb-4 px-2">
272
- <button onClick={prevDay} className="p-2 hover:bg-white/5 rounded-lg">
273
  <ChevronLeft className="w-5 h-5 text-slate-400" />
274
  </button>
275
  <h3 className="text-lg font-bold text-white">
276
  {format(selectedDate, 'd MMMM, EEEE', { locale: ru })}
277
  </h3>
278
- <button onClick={nextDay} className="p-2 hover:bg-white/5 rounded-lg">
279
  <ChevronRight className="w-5 h-5 text-slate-400" />
280
  </button>
281
  </div>
282
 
283
  {/* Resources Columns */}
284
  <div className="overflow-x-auto">
285
- <div className="flex gap-2 min-w-max">
286
  {/* Time Column */}
287
  <div className="w-14 flex-shrink-0">
288
- <div className="h-10 flex items-center justify-center text-xs text-slate-500 font-medium">
289
  Время
290
  </div>
291
  {timeSlots.map(time => (
292
- <div key={time} className="h-10 flex items-center justify-end pr-2 text-xs text-slate-500">
293
  {time}
294
  </div>
295
  ))}
@@ -298,48 +299,59 @@ export function CalendarView({
298
  {/* Resource Columns */}
299
  {activeResources.map(resource => {
300
  const resourceAppts = dayAppointments.filter(apt =>
301
- apt.resource_id === resource.id || apt.resource?.id === resource.id
302
  )
303
 
 
 
 
 
304
  return (
305
- <div key={resource.id} className="w-32 md:w-40 flex-shrink-0">
306
  {/* Resource Header */}
307
- <div className="h-10 flex items-center justify-center bg-indigo-500/10 rounded-t-lg border border-indigo-500/20 text-indigo-400 text-sm font-medium">
308
- {resource.name}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  </div>
310
-
311
- {/* Time Slots */}
312
- {timeSlots.map((time, idx) => {
313
- const slotApt = resourceAppts.find(apt => {
314
- const aptTime = format(new Date(apt.start_time), 'HH:mm')
315
- return aptTime === time
316
- })
317
-
318
- return (
319
- <div
320
- key={time}
321
- className={cn(
322
- "h-10 border-l border-r border-b border-white/5 px-1 flex items-center",
323
- idx % 2 === 0 ? "bg-white/[0.02]" : ""
324
- )}
325
- >
326
- {slotApt ? (
327
- <div
328
- onClick={() => onSelectAppointment?.(slotApt)}
329
- className={cn(
330
- "w-full text-[10px] px-1 py-0.5 rounded truncate cursor-pointer",
331
- STATUS_COLORS[slotApt.status]?.bg || STATUS_COLORS['scheduled'].bg,
332
- STATUS_COLORS[slotApt.status]?.border || STATUS_COLORS['scheduled'].border,
333
- "border"
334
- )}
335
- >
336
- <span className="mr-1">{getChannelIcon(slotApt.lead?.channel)}</span>
337
- {slotApt.lead?.name?.split(' ')[0] || 'Клиент'}
338
- </div>
339
- ) : null}
340
- </div>
341
- )
342
- })}
343
  </div>
344
  )
345
  })}
@@ -352,90 +364,80 @@ export function CalendarView({
352
  return (
353
  <div className="bg-[#1E1F2E] border border-white/5 rounded-xl md:rounded-3xl p-3 md:p-6 shadow-2xl relative overflow-hidden">
354
  {/* Header */}
355
- <div className="flex items-center justify-between mb-4 md:mb-6">
356
- <div className="flex items-center gap-2 md:gap-4">
357
- {viewMode === 'month' && (
358
- <div className="flex gap-1 md:gap-2">
359
- <button onClick={prevMonth} className="p-1.5 md:p-2 hover:bg-white/5 rounded-lg text-slate-400 hover:text-white transition-colors">
360
- <ChevronLeft className="w-4 h-4 md:w-5 md:h-5" />
361
- </button>
362
- <button onClick={nextMonth} className="p-1.5 md:p-2 hover:bg-white/5 rounded-lg text-slate-400 hover:text-white transition-colors">
363
- <ChevronRight className="w-4 h-4 md:w-5 md:h-5" />
364
- </button>
365
- </div>
366
- )}
367
- <h2 className="text-base md:text-xl font-bold text-white capitalize">
368
- {viewMode === 'month' && format(currentMonth, 'LLLL yyyy', { locale: ru })}
369
- {viewMode !== 'month' && format(selectedDate, 'd MMMM', { locale: ru })}
 
 
 
370
  </h2>
371
  </div>
372
 
373
  <div className="flex items-center gap-2">
374
- {/* View Mode Switcher - visible on all screens */}
375
  <div className="flex bg-white/5 rounded-lg p-0.5 border border-white/5">
376
  <button
377
  onClick={() => setViewMode('month')}
378
  className={cn(
379
- "px-2 md:px-3 py-1.5 rounded-md text-xs font-medium transition-all flex items-center gap-1.5",
380
- viewMode === 'month' ? "bg-indigo-500 text-white" : "text-slate-400 hover:text-white"
381
  )}
382
  >
383
- <LayoutGrid className="w-3.5 h-3.5" />
384
- <span className="hidden md:inline">Месяц</span>
385
  </button>
386
  <button
387
  onClick={() => setViewMode('day')}
388
  className={cn(
389
- "px-2 md:px-3 py-1.5 rounded-md text-xs font-medium transition-all flex items-center gap-1.5",
390
- viewMode === 'day' ? "bg-indigo-500 text-white" : "text-slate-400 hover:text-white"
391
  )}
392
  >
393
- <Clock className="w-3.5 h-3.5" />
394
- <span className="hidden md:inline">День</span>
395
  </button>
396
  <button
397
  onClick={() => setViewMode('resources')}
398
  className={cn(
399
- "px-2 md:px-3 py-1.5 rounded-md text-xs font-medium transition-all flex items-center gap-1.5",
400
- viewMode === 'resources' ? "bg-indigo-500 text-white" : "text-slate-400 hover:text-white"
401
  )}
402
  >
403
- <Users className="w-3.5 h-3.5" />
404
- <span className="hidden md:inline">Ресурсы</span>
405
  </button>
406
  </div>
407
 
408
- {/* Today Button */}
409
  <button
410
  onClick={() => {
411
  const now = new Date()
412
  setCurrentMonth(now)
413
  onSelectDate(now)
414
  }}
415
- className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 rounded-lg border border-indigo-500/20 transition-all font-medium text-xs"
416
  >
417
- <CalendarIcon className="w-3.5 h-3.5" />
418
- <span className="hidden sm:inline">Сегодня</span>
419
  </button>
420
-
421
- {/* Timezone & Working Hours Info */}
422
- <div className="hidden md:flex items-center gap-3 text-xs text-slate-400">
423
- <div className="flex items-center gap-1">
424
- <Clock className="w-3.5 h-3.5" />
425
- <span>{workingHours.start}–{workingHours.end}</span>
426
- </div>
427
- <div className="flex items-center gap-1">
428
- <Globe className="w-3.5 h-3.5" />
429
- <span>{timezone.split('/').pop()?.replace('_', ' ')}</span>
430
- </div>
431
- </div>
432
  </div>
433
  </div>
434
 
435
  {/* Content */}
436
- {viewMode === 'month' && renderMonthView()}
437
- {viewMode === 'day' && renderDayView()}
438
- {viewMode === 'resources' && renderResourcesView()}
 
 
439
  </div>
440
  )
441
  }
 
11
  interface Resource {
12
  id: string
13
  name: string
14
+ description?: string | null
15
+ working_hours?: Record<string, { start: string, end: string }> | null
16
  is_active?: boolean
17
  }
18
 
 
270
  <div className="flex flex-col">
271
  {/* Day Navigation */}
272
  <div className="flex items-center justify-between mb-4 px-2">
273
+ <button onClick={prevDay} className="p-2 hover:bg-white/5 rounded-lg transition-colors">
274
  <ChevronLeft className="w-5 h-5 text-slate-400" />
275
  </button>
276
  <h3 className="text-lg font-bold text-white">
277
  {format(selectedDate, 'd MMMM, EEEE', { locale: ru })}
278
  </h3>
279
+ <button onClick={nextDay} className="p-2 hover:bg-white/5 rounded-lg transition-colors">
280
  <ChevronRight className="w-5 h-5 text-slate-400" />
281
  </button>
282
  </div>
283
 
284
  {/* Resources Columns */}
285
  <div className="overflow-x-auto">
286
+ <div className="flex gap-2 min-w-max pb-4">
287
  {/* Time Column */}
288
  <div className="w-14 flex-shrink-0">
289
+ <div className="h-10 flex items-center justify-center text-[10px] text-slate-500 font-bold uppercase tracking-wider">
290
  Время
291
  </div>
292
  {timeSlots.map(time => (
293
+ <div key={time} className="h-10 flex items-center justify-end pr-2 text-[11px] text-slate-500 font-medium">
294
  {time}
295
  </div>
296
  ))}
 
299
  {/* Resource Columns */}
300
  {activeResources.map(resource => {
301
  const resourceAppts = dayAppointments.filter(apt =>
302
+ apt.resource_id === resource.id
303
  )
304
 
305
+ // Get working hours for THIS resource on THIS day
306
+ const dayOfWeek = getDay(selectedDate).toString() // 0=Sun, 1=Mon...
307
+ const resourceDayHours = resource.working_hours?.[dayOfWeek]
308
+
309
  return (
310
+ <div key={resource.id} className="w-40 flex-shrink-0 border-l border-white/10 last:border-r">
311
  {/* Resource Header */}
312
+ <div className="h-10 px-3 flex flex-col justify-center border-b border-white/10 bg-white/5">
313
+ <div className="font-bold text-white text-[13px] truncate">{resource.name}</div>
314
+ {resourceDayHours ? (
315
+ <div className="text-[9px] text-slate-500 font-medium">{resourceDayHours.start}—{resourceDayHours.end}</div>
316
+ ) : (
317
+ <div className="text-[9px] text-red-500 font-bold uppercase tracking-tighter">Выходной</div>
318
+ )}
319
+ </div>
320
+ <div className="relative">
321
+ {timeSlots.map(time => {
322
+ const slotAppts = resourceAppts.filter(apt => {
323
+ const aptTime = format(new Date(apt.start_time), 'HH:mm')
324
+ return aptTime === time || (aptTime >= time && aptTime < (timeSlots[timeSlots.indexOf(time) + 1] || '24:00'))
325
+ })
326
+
327
+ // Check if this slot is a working slot for THIS resource
328
+ let isWorking = !!resourceDayHours
329
+ if (resourceDayHours) {
330
+ const { start, end } = resourceDayHours
331
+ isWorking = time >= start && time < end
332
+ }
333
+
334
+ return (
335
+ <div
336
+ key={time}
337
+ className={cn(
338
+ "h-10 border-b border-white/5 px-1 pt-1 transition-colors relative group",
339
+ !isWorking ? "bg-slate-900/40" : "hover:bg-white/5"
340
+ )}
341
+ >
342
+ {slotAppts.map(apt => (
343
+ <AppointmentCard key={apt.id} apt={apt} onSelect={onSelectAppointment} compact />
344
+ ))}
345
+
346
+ {!isWorking && slotAppts.length === 0 && (
347
+ <div className="absolute inset-0 flex items-center justify-center opacity-20">
348
+ <div className="w-1 h-1 bg-white rounded-full" />
349
+ </div>
350
+ )}
351
+ </div>
352
+ )
353
+ })}
354
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  </div>
356
  )
357
  })}
 
364
  return (
365
  <div className="bg-[#1E1F2E] border border-white/5 rounded-xl md:rounded-3xl p-3 md:p-6 shadow-2xl relative overflow-hidden">
366
  {/* Header */}
367
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
368
+ <div className="flex items-center gap-3">
369
+ <div className="flex gap-1">
370
+ <button
371
+ onClick={viewMode === 'month' ? prevMonth : prevDay}
372
+ className="p-2 hover:bg-white/5 rounded-lg text-slate-400 hover:text-white transition-colors border border-white/5"
373
+ >
374
+ <ChevronLeft className="w-5 h-5" />
375
+ </button>
376
+ <button
377
+ onClick={viewMode === 'month' ? nextMonth : nextDay}
378
+ className="p-2 hover:bg-white/5 rounded-lg text-slate-400 hover:text-white transition-colors border border-white/5"
379
+ >
380
+ <ChevronRight className="w-5 h-5" />
381
+ </button>
382
+ </div>
383
+ <h2 className="text-xl font-bold text-white capitalize">
384
+ {viewMode === 'month' ? format(currentMonth, 'LLLL yyyy', { locale: ru }) : format(selectedDate, 'd MMMM', { locale: ru })}
385
  </h2>
386
  </div>
387
 
388
  <div className="flex items-center gap-2">
 
389
  <div className="flex bg-white/5 rounded-lg p-0.5 border border-white/5">
390
  <button
391
  onClick={() => setViewMode('month')}
392
  className={cn(
393
+ "px-3 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-1.5",
394
+ viewMode === 'month' ? "bg-indigo-600 text-white shadow-lg" : "text-slate-400 hover:text-white"
395
  )}
396
  >
397
+ <LayoutGrid className="w-4 h-4" />
398
+ <span className="hidden lg:inline">Месяц</span>
399
  </button>
400
  <button
401
  onClick={() => setViewMode('day')}
402
  className={cn(
403
+ "px-3 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-1.5",
404
+ viewMode === 'day' ? "bg-indigo-600 text-white shadow-lg" : "text-slate-400 hover:text-white"
405
  )}
406
  >
407
+ <Clock className="w-4 h-4" />
408
+ <span className="hidden lg:inline">День</span>
409
  </button>
410
  <button
411
  onClick={() => setViewMode('resources')}
412
  className={cn(
413
+ "px-3 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-1.5",
414
+ viewMode === 'resources' ? "bg-indigo-600 text-white shadow-lg" : "text-slate-400 hover:text-white"
415
  )}
416
  >
417
+ <Users className="w-4 h-4" />
418
+ <span className="hidden lg:inline">Ресурсы</span>
419
  </button>
420
  </div>
421
 
 
422
  <button
423
  onClick={() => {
424
  const now = new Date()
425
  setCurrentMonth(now)
426
  onSelectDate(now)
427
  }}
428
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 rounded-lg border border-indigo-500/20 transition-all font-bold text-xs"
429
  >
430
+ Сегодня
 
431
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
432
  </div>
433
  </div>
434
 
435
  {/* Content */}
436
+ <div className="overflow-hidden">
437
+ {viewMode === 'month' && renderMonthView()}
438
+ {viewMode === 'day' && renderDayView()}
439
+ {viewMode === 'resources' && renderResourcesView()}
440
+ </div>
441
  </div>
442
  )
443
  }
frontend/lib/api.ts CHANGED
@@ -543,6 +543,11 @@ export const bookingsApi = {
543
  return response.data
544
  },
545
 
 
 
 
 
 
546
  deleteResource: async (resourceId: string, hard: boolean = false) => {
547
  const response = await api.delete(`/api/v1/bookings/resources/${resourceId}`, { params: { hard } })
548
  return response.data
 
543
  return response.data
544
  },
545
 
546
+ getTeamMembers: async () => {
547
+ const response = await api.get('/api/v1/team/members')
548
+ return response.data
549
+ },
550
+
551
  deleteResource: async (resourceId: string, hard: boolean = false) => {
552
  const response = await api.delete(`/api/v1/bookings/resources/${resourceId}`, { params: { hard } })
553
  return response.data
frontend/lib/i18n/translations/en.ts CHANGED
@@ -70,7 +70,6 @@ export const en = {
70
  settings: 'Settings',
71
  brain: 'AI Brain',
72
  voice: 'AI Voice',
73
- crm: 'CRM',
74
  funnel: 'Funnel',
75
  team: 'Team',
76
  notifications: 'Notifications',
@@ -236,7 +235,6 @@ export const en = {
236
  partner: 'Partner Program',
237
  playbook: 'Sales Playbook',
238
  voice: 'AI Voice',
239
- crm: 'CRM Integration',
240
  },
241
 
242
  // Billing
@@ -352,27 +350,6 @@ export const en = {
352
  oneHour: '1 hour',
353
  },
354
 
355
- // CRM Settings
356
- crm: {
357
- integrations: 'CRM Integrations',
358
- availableIntegrations: 'Available Integrations',
359
- active: 'Active',
360
- notConnected: 'Not connected',
361
- configure: 'Configure',
362
- connect: 'Connect',
363
- lastSync: 'Last sync',
364
- neverSynced: 'Never synced',
365
- selectCRM: 'Select CRM',
366
- configuring: 'Configuring',
367
- enterAccessToken: 'Enter access token',
368
- autoSync: 'Auto sync',
369
- autoSyncDesc: 'Sync leads automatically',
370
- syncInterval: 'Sync interval',
371
- integrationConnected: 'Integration connected!',
372
- integrationDeleted: 'Integration deleted',
373
- connectionError: 'Connection error',
374
- deleteConfirmation: 'Delete integration?',
375
- },
376
 
377
  // Voice Settings
378
  voice: {
 
70
  settings: 'Settings',
71
  brain: 'AI Brain',
72
  voice: 'AI Voice',
 
73
  funnel: 'Funnel',
74
  team: 'Team',
75
  notifications: 'Notifications',
 
235
  partner: 'Partner Program',
236
  playbook: 'Sales Playbook',
237
  voice: 'AI Voice',
 
238
  },
239
 
240
  // Billing
 
350
  oneHour: '1 hour',
351
  },
352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
  // Voice Settings
355
  voice: {
frontend/lib/i18n/translations/ky.ts CHANGED
@@ -70,7 +70,6 @@ export const ky = {
70
  settings: 'Жөндөөлөр',
71
  brain: 'AI Мээ',
72
  voice: 'AI Үн',
73
- crm: 'CRM',
74
  funnel: 'Воронка',
75
  team: 'Команда',
76
  notifications: 'Билдирүүлөр',
@@ -236,7 +235,6 @@ export const ky = {
236
  partner: 'Өнөктөштүк программа',
237
  playbook: 'Сатуу скрипти',
238
  voice: 'AI Үн',
239
- crm: 'CRM Интеграция',
240
  },
241
 
242
  // Billing
@@ -352,27 +350,6 @@ export const ky = {
352
  oneHour: '1 саат',
353
  },
354
 
355
- // CRM Settings
356
- crm: {
357
- integrations: 'CRM Интеграциялар',
358
- availableIntegrations: 'Жеткиликтүү интеграциялар',
359
- active: 'Активдүү',
360
- notConnected: 'Туташкан эмес',
361
- configure: 'Жөндөө',
362
- connect: 'Туташтыруу',
363
- lastSync: 'Акыркы синхрондоо',
364
- neverSynced: 'Али болгон эмес',
365
- selectCRM: 'CRM тандоо',
366
- configuring: 'Жөндөө',
367
- enterAccessToken: 'Жетки токенин киргизиңиз',
368
- autoSync: 'Авто синхрондоо',
369
- autoSyncDesc: 'Лиддерди автоматтык түрдө синхрондоо',
370
- syncInterval: 'Синхрондоо аралыгы',
371
- integrationConnected: 'Интеграция туташтырылды!',
372
- integrationDeleted: 'Интеграция өчүрүлдү',
373
- connectionError: 'Туташуу катасы',
374
- deleteConfirmation: 'Интеграцияны өчүрүүнү каалайсызбы?',
375
- },
376
 
377
  // Voice Settings
378
  voice: {
 
70
  settings: 'Жөндөөлөр',
71
  brain: 'AI Мээ',
72
  voice: 'AI Үн',
 
73
  funnel: 'Воронка',
74
  team: 'Команда',
75
  notifications: 'Билдирүүлөр',
 
235
  partner: 'Өнөктөштүк программа',
236
  playbook: 'Сатуу скрипти',
237
  voice: 'AI Үн',
 
238
  },
239
 
240
  // Billing
 
350
  oneHour: '1 саат',
351
  },
352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
  // Voice Settings
355
  voice: {
frontend/lib/i18n/translations/ru.ts CHANGED
@@ -70,7 +70,6 @@ export const ru = {
70
  settings: 'Настройки',
71
  brain: 'ИИ Мозг',
72
  voice: 'Голос AI',
73
- crm: 'CRM',
74
  funnel: 'Воронка',
75
  team: 'Команда',
76
  notifications: 'Уведомления',
@@ -236,7 +235,6 @@ export const ru = {
236
  partner: 'Партнёрская программа',
237
  playbook: 'Скрипт продаж',
238
  voice: 'Голос AI',
239
- crm: 'CRM Интеграция',
240
  },
241
 
242
  // Billing
@@ -352,27 +350,6 @@ export const ru = {
352
  oneHour: '1 час',
353
  },
354
 
355
- // CRM Settings
356
- crm: {
357
- integrations: 'CRM Интеграции',
358
- availableIntegrations: 'Доступные интеграции',
359
- active: 'Активно',
360
- notConnected: 'Не подключено',
361
- configure: 'Настроить',
362
- connect: 'Подключить',
363
- lastSync: 'Последняя синхронизация',
364
- neverSynced: 'Еще не было',
365
- selectCRM: 'Выберите CRM',
366
- configuring: 'Настройка',
367
- enterAccessToken: 'Введите токен доступа',
368
- autoSync: 'Автосинхронизация',
369
- autoSyncDesc: 'Синхронизировать лиды автоматически',
370
- syncInterval: 'Интервал синхронизации',
371
- integrationConnected: 'Интеграция подключена!',
372
- integrationDeleted: 'Интеграция удалена',
373
- connectionError: 'Ошибка подключения',
374
- deleteConfirmation: 'Удалить интеграцию?',
375
- },
376
 
377
  // Voice Settings
378
  voice: {
 
70
  settings: 'Настройки',
71
  brain: 'ИИ Мозг',
72
  voice: 'Голос AI',
 
73
  funnel: 'Воронка',
74
  team: 'Команда',
75
  notifications: 'Уведомления',
 
235
  partner: 'Партнёрская программа',
236
  playbook: 'Скрипт продаж',
237
  voice: 'Голос AI',
 
238
  },
239
 
240
  // Billing
 
350
  oneHour: '1 час',
351
  },
352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
  // Voice Settings
355
  voice: {
frontend/public/crm/amocrm-logo-dark.svg DELETED
frontend/public/crm/bitrix24-logo-eng.svg DELETED
frontend/public/crm/hubspot.svg DELETED
frontend/public/crm/salesforce.svg DELETED
frontend/public/crm/zoho.svg DELETED