Spaces:
Sleeping

axeronis commited on
Commit
560824b
·
1 Parent(s): b34de88

feat: add PaymentMethod and KnowledgeFile models with CRUD API endpoints for payment requisites and info files

Browse files
backend/alembic/versions/2025_12_30_add_payment_knowledge.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """add payment_methods and knowledge_files tables
2
+
3
+ Revision ID: add_payment_knowledge
4
+ Revises: add_stock_quantity
5
+ Create Date: 2025-12-30
6
+
7
+ """
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+
11
+ revision = 'add_payment_knowledge'
12
+ down_revision = 'add_stock_quantity'
13
+ branch_labels = None
14
+ depends_on = None
15
+
16
+
17
+ def upgrade():
18
+ conn = op.get_bind()
19
+
20
+ # Check if payment_methods table exists
21
+ result = conn.execute(sa.text("""
22
+ SELECT EXISTS (
23
+ SELECT FROM information_schema.tables
24
+ WHERE table_name = 'payment_methods'
25
+ )
26
+ """))
27
+ if not result.scalar():
28
+ op.create_table(
29
+ 'payment_methods',
30
+ sa.Column('id', sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),
31
+ sa.Column('tenant_id', sa.dialects.postgresql.UUID(as_uuid=True), sa.ForeignKey('tenants.id'), nullable=False, index=True),
32
+ sa.Column('name', sa.String(255), nullable=False),
33
+ sa.Column('payment_type', sa.String(50), default='requisites'),
34
+ sa.Column('requisites_text', sa.Text(), nullable=True),
35
+ sa.Column('payment_link', sa.String(500), nullable=True),
36
+ sa.Column('image_url', sa.String(500), nullable=True),
37
+ sa.Column('send_condition', sa.String(50), default='on_request'),
38
+ sa.Column('ai_instruction', sa.Text(), nullable=True),
39
+ sa.Column('is_active', sa.Boolean(), default=True),
40
+ sa.Column('sort_order', sa.Integer(), default=0),
41
+ sa.Column('created_at', sa.DateTime(), nullable=True),
42
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
43
+ )
44
+
45
+ # Check if knowledge_files table exists
46
+ result = conn.execute(sa.text("""
47
+ SELECT EXISTS (
48
+ SELECT FROM information_schema.tables
49
+ WHERE table_name = 'knowledge_files'
50
+ )
51
+ """))
52
+ if not result.scalar():
53
+ op.create_table(
54
+ 'knowledge_files',
55
+ sa.Column('id', sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),
56
+ sa.Column('tenant_id', sa.dialects.postgresql.UUID(as_uuid=True), sa.ForeignKey('tenants.id'), nullable=False, index=True),
57
+ sa.Column('name', sa.String(255), nullable=False),
58
+ sa.Column('file_type', sa.String(50), default='document'),
59
+ sa.Column('file_url', sa.String(500), nullable=True),
60
+ sa.Column('external_link', sa.String(500), nullable=True),
61
+ sa.Column('description', sa.Text(), nullable=True),
62
+ sa.Column('send_condition', sa.String(50), default='on_request'),
63
+ sa.Column('trigger_keywords', sa.String(500), nullable=True),
64
+ sa.Column('trigger_stage', sa.String(100), nullable=True),
65
+ sa.Column('ai_instruction', sa.Text(), nullable=True),
66
+ sa.Column('is_active', sa.Boolean(), default=True),
67
+ sa.Column('sort_order', sa.Integer(), default=0),
68
+ sa.Column('created_at', sa.DateTime(), nullable=True),
69
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
70
+ )
71
+
72
+
73
+ def downgrade():
74
+ op.drop_table('knowledge_files')
75
+ op.drop_table('payment_methods')
backend/app/api/knowledge.py CHANGED
@@ -375,3 +375,267 @@ async def update_knowledge(
375
  }
376
 
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  }
376
 
377
 
378
+ # ============================================================================
379
+ # PAYMENT METHODS API
380
+ # ============================================================================
381
+
382
+ class PaymentMethodInput(BaseModel):
383
+ """Input for creating/updating payment method."""
384
+ name: str
385
+ payment_type: str = "requisites" # requisites, link, qr_code, image
386
+ requisites_text: Optional[str] = None
387
+ payment_link: Optional[str] = None
388
+ image_url: Optional[str] = None
389
+ send_condition: str = "on_request" # on_request, after_agreement, always
390
+ ai_instruction: Optional[str] = None
391
+ sort_order: int = 0
392
+
393
+ @router.get("/payment-methods")
394
+ async def list_payment_methods(
395
+ current_user: User = Depends(get_current_user),
396
+ session = Depends(get_session)
397
+ ):
398
+ """List all payment methods for tenant."""
399
+ from app.models.knowledge import PaymentMethod
400
+
401
+ stmt = select(PaymentMethod).where(
402
+ PaymentMethod.tenant_id == current_user.tenant_id,
403
+ PaymentMethod.is_active == True
404
+ ).order_by(PaymentMethod.sort_order)
405
+
406
+ result = await session.execute(stmt)
407
+ methods = result.scalars().all()
408
+
409
+ return [
410
+ {
411
+ "id": str(m.id),
412
+ "name": m.name,
413
+ "payment_type": m.payment_type,
414
+ "requisites_text": m.requisites_text,
415
+ "payment_link": m.payment_link,
416
+ "image_url": m.image_url,
417
+ "send_condition": m.send_condition,
418
+ "ai_instruction": m.ai_instruction,
419
+ "sort_order": m.sort_order
420
+ }
421
+ for m in methods
422
+ ]
423
+
424
+ @router.post("/payment-methods")
425
+ async def create_payment_method(
426
+ data: PaymentMethodInput,
427
+ current_user: User = Depends(get_current_user),
428
+ session = Depends(get_session)
429
+ ):
430
+ """Create new payment method."""
431
+ from app.models.knowledge import PaymentMethod
432
+
433
+ method = PaymentMethod(
434
+ tenant_id=current_user.tenant_id,
435
+ name=data.name,
436
+ payment_type=data.payment_type,
437
+ requisites_text=data.requisites_text,
438
+ payment_link=data.payment_link,
439
+ image_url=data.image_url,
440
+ send_condition=data.send_condition,
441
+ ai_instruction=data.ai_instruction,
442
+ sort_order=data.sort_order
443
+ )
444
+
445
+ session.add(method)
446
+ await session.commit()
447
+ await session.refresh(method)
448
+
449
+ return {"ok": True, "id": str(method.id)}
450
+
451
+ @router.patch("/payment-methods/{method_id}")
452
+ async def update_payment_method(
453
+ method_id: UUID,
454
+ data: PaymentMethodInput,
455
+ current_user: User = Depends(get_current_user),
456
+ session = Depends(get_session)
457
+ ):
458
+ """Update payment method."""
459
+ from app.models.knowledge import PaymentMethod
460
+
461
+ stmt = select(PaymentMethod).where(
462
+ PaymentMethod.id == method_id,
463
+ PaymentMethod.tenant_id == current_user.tenant_id
464
+ )
465
+ result = await session.execute(stmt)
466
+ method = result.scalar_one_or_none()
467
+
468
+ if not method:
469
+ raise HTTPException(status_code=404, detail="Payment method not found")
470
+
471
+ method.name = data.name
472
+ method.payment_type = data.payment_type
473
+ method.requisites_text = data.requisites_text
474
+ method.payment_link = data.payment_link
475
+ method.image_url = data.image_url
476
+ method.send_condition = data.send_condition
477
+ method.ai_instruction = data.ai_instruction
478
+ method.sort_order = data.sort_order
479
+
480
+ await session.commit()
481
+ return {"ok": True, "id": str(method.id)}
482
+
483
+ @router.delete("/payment-methods/{method_id}")
484
+ async def delete_payment_method(
485
+ method_id: UUID,
486
+ current_user: User = Depends(get_current_user),
487
+ session = Depends(get_session)
488
+ ):
489
+ """Delete payment method (soft delete)."""
490
+ from app.models.knowledge import PaymentMethod
491
+
492
+ stmt = select(PaymentMethod).where(
493
+ PaymentMethod.id == method_id,
494
+ PaymentMethod.tenant_id == current_user.tenant_id
495
+ )
496
+ result = await session.execute(stmt)
497
+ method = result.scalar_one_or_none()
498
+
499
+ if not method:
500
+ raise HTTPException(status_code=404, detail="Payment method not found")
501
+
502
+ method.is_active = False
503
+ await session.commit()
504
+ return {"ok": True}
505
+
506
+
507
+ # ============================================================================
508
+ # KNOWLEDGE FILES API
509
+ # ============================================================================
510
+
511
+ class KnowledgeFileInput(BaseModel):
512
+ """Input for creating/updating knowledge file."""
513
+ name: str
514
+ file_type: str = "document" # document, image, video, link
515
+ file_url: Optional[str] = None
516
+ external_link: Optional[str] = None
517
+ description: Optional[str] = None
518
+ send_condition: str = "on_request" # on_request, after_purchase, after_booking, on_stage, on_keyword
519
+ trigger_keywords: Optional[str] = None
520
+ trigger_stage: Optional[str] = None
521
+ ai_instruction: Optional[str] = None
522
+ sort_order: int = 0
523
+
524
+ @router.get("/files")
525
+ async def list_knowledge_files(
526
+ current_user: User = Depends(get_current_user),
527
+ session = Depends(get_session)
528
+ ):
529
+ """List all knowledge files for tenant."""
530
+ from app.models.knowledge import KnowledgeFile
531
+
532
+ stmt = select(KnowledgeFile).where(
533
+ KnowledgeFile.tenant_id == current_user.tenant_id,
534
+ KnowledgeFile.is_active == True
535
+ ).order_by(KnowledgeFile.sort_order)
536
+
537
+ result = await session.execute(stmt)
538
+ files = result.scalars().all()
539
+
540
+ return [
541
+ {
542
+ "id": str(f.id),
543
+ "name": f.name,
544
+ "file_type": f.file_type,
545
+ "file_url": f.file_url,
546
+ "external_link": f.external_link,
547
+ "description": f.description,
548
+ "send_condition": f.send_condition,
549
+ "trigger_keywords": f.trigger_keywords,
550
+ "trigger_stage": f.trigger_stage,
551
+ "ai_instruction": f.ai_instruction,
552
+ "sort_order": f.sort_order
553
+ }
554
+ for f in files
555
+ ]
556
+
557
+ @router.post("/files")
558
+ async def create_knowledge_file(
559
+ data: KnowledgeFileInput,
560
+ current_user: User = Depends(get_current_user),
561
+ session = Depends(get_session)
562
+ ):
563
+ """Create new knowledge file."""
564
+ from app.models.knowledge import KnowledgeFile
565
+
566
+ file = KnowledgeFile(
567
+ tenant_id=current_user.tenant_id,
568
+ name=data.name,
569
+ file_type=data.file_type,
570
+ file_url=data.file_url,
571
+ external_link=data.external_link,
572
+ description=data.description,
573
+ send_condition=data.send_condition,
574
+ trigger_keywords=data.trigger_keywords,
575
+ trigger_stage=data.trigger_stage,
576
+ ai_instruction=data.ai_instruction,
577
+ sort_order=data.sort_order
578
+ )
579
+
580
+ session.add(file)
581
+ await session.commit()
582
+ await session.refresh(file)
583
+
584
+ return {"ok": True, "id": str(file.id)}
585
+
586
+ @router.patch("/files/{file_id}")
587
+ async def update_knowledge_file(
588
+ file_id: UUID,
589
+ data: KnowledgeFileInput,
590
+ current_user: User = Depends(get_current_user),
591
+ session = Depends(get_session)
592
+ ):
593
+ """Update knowledge file."""
594
+ from app.models.knowledge import KnowledgeFile
595
+
596
+ stmt = select(KnowledgeFile).where(
597
+ KnowledgeFile.id == file_id,
598
+ KnowledgeFile.tenant_id == current_user.tenant_id
599
+ )
600
+ result = await session.execute(stmt)
601
+ file = result.scalar_one_or_none()
602
+
603
+ if not file:
604
+ raise HTTPException(status_code=404, detail="Knowledge file not found")
605
+
606
+ file.name = data.name
607
+ file.file_type = data.file_type
608
+ file.file_url = data.file_url
609
+ file.external_link = data.external_link
610
+ file.description = data.description
611
+ file.send_condition = data.send_condition
612
+ file.trigger_keywords = data.trigger_keywords
613
+ file.trigger_stage = data.trigger_stage
614
+ file.ai_instruction = data.ai_instruction
615
+ file.sort_order = data.sort_order
616
+
617
+ await session.commit()
618
+ return {"ok": True, "id": str(file.id)}
619
+
620
+ @router.delete("/files/{file_id}")
621
+ async def delete_knowledge_file(
622
+ file_id: UUID,
623
+ current_user: User = Depends(get_current_user),
624
+ session = Depends(get_session)
625
+ ):
626
+ """Delete knowledge file (soft delete)."""
627
+ from app.models.knowledge import KnowledgeFile
628
+
629
+ stmt = select(KnowledgeFile).where(
630
+ KnowledgeFile.id == file_id,
631
+ KnowledgeFile.tenant_id == current_user.tenant_id
632
+ )
633
+ result = await session.execute(stmt)
634
+ file = result.scalar_one_or_none()
635
+
636
+ if not file:
637
+ raise HTTPException(status_code=404, detail="Knowledge file not found")
638
+
639
+ file.is_active = False
640
+ await session.commit()
641
+ return {"ok": True}
backend/app/models/__init__.py CHANGED
@@ -11,7 +11,7 @@ from app.models.lead import (
11
  Psychotype,
12
  ProcessingStatus
13
  )
14
- from app.models.knowledge import KnowledgeBase, SalesScript
15
  from app.models.sales_stage import SalesStage
16
  from app.models.notification import Notification, NotificationSettings
17
  from app.models.booking import Service, Availability, Appointment, AppointmentStatus, Resource, ResourceService
@@ -47,6 +47,8 @@ __all__ = [
47
  "KnowledgeBase",
48
  "SalesScript",
49
  "SalesStage",
 
 
50
 
51
  # Notifications
52
  "Notification",
 
11
  Psychotype,
12
  ProcessingStatus
13
  )
14
+ from app.models.knowledge import KnowledgeBase, SalesScript, PaymentMethod, KnowledgeFile
15
  from app.models.sales_stage import SalesStage
16
  from app.models.notification import Notification, NotificationSettings
17
  from app.models.booking import Service, Availability, Appointment, AppointmentStatus, Resource, ResourceService
 
47
  "KnowledgeBase",
48
  "SalesScript",
49
  "SalesStage",
50
+ "PaymentMethod",
51
+ "KnowledgeFile",
52
 
53
  # Notifications
54
  "Notification",
backend/app/models/knowledge.py CHANGED
@@ -85,3 +85,63 @@ class SalesScript(SQLModel, table=True):
85
 
86
  # Relationships
87
  tenant: Optional["Tenant"] = Relationship(back_populates="sales_scripts")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  # Relationships
87
  tenant: Optional["Tenant"] = Relationship(back_populates="sales_scripts")
88
+
89
+
90
+ class PaymentMethod(SQLModel, table=True):
91
+ """Payment methods and requisites for the tenant."""
92
+ __tablename__ = "payment_methods"
93
+
94
+ id: UUID = Field(default_factory=uuid4, primary_key=True)
95
+ tenant_id: UUID = Field(foreign_key="tenants.id", index=True)
96
+
97
+ # Payment Details
98
+ name: str # "Банковская карта", "Kaspi QR", "Реквизиты компании"
99
+ payment_type: str = "requisites" # "requisites", "link", "qr_code", "image"
100
+
101
+ # Content (depends on type)
102
+ requisites_text: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # Bank details text
103
+ payment_link: Optional[str] = None # Payment URL
104
+ image_url: Optional[str] = None # QR code or card image
105
+
106
+ # AI Instructions
107
+ send_condition: str = "on_request" # "on_request", "after_agreement", "always"
108
+ ai_instruction: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # When/how to send
109
+
110
+ # Status
111
+ is_active: bool = Field(default=True)
112
+ sort_order: int = Field(default=0)
113
+
114
+ created_at: datetime = Field(default_factory=datetime.utcnow)
115
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
116
+
117
+
118
+ class KnowledgeFile(SQLModel, table=True):
119
+ """Informational files for coaches, courses, etc."""
120
+ __tablename__ = "knowledge_files"
121
+
122
+ id: UUID = Field(default_factory=uuid4, primary_key=True)
123
+ tenant_id: UUID = Field(foreign_key="tenants.id", index=True)
124
+
125
+ # File Info
126
+ name: str # "Инструкция по курсу", "Схема работы"
127
+ file_type: str = "document" # "document", "image", "video", "link"
128
+
129
+ # Content (depends on type)
130
+ file_url: Optional[str] = None # S3/CDN URL for uploaded files
131
+ external_link: Optional[str] = None # YouTube, Google Drive, etc.
132
+ description: Optional[str] = Field(default=None, sa_column=Column(TEXT))
133
+
134
+ # Send Conditions
135
+ send_condition: str = "on_request" # "on_request", "after_purchase", "after_booking", "on_stage", "on_keyword"
136
+ trigger_keywords: Optional[str] = None # Comma-separated keywords
137
+ trigger_stage: Optional[str] = None # Funnel stage to trigger
138
+
139
+ # AI Instructions
140
+ ai_instruction: Optional[str] = Field(default=None, sa_column=Column(TEXT))
141
+
142
+ # Status
143
+ is_active: bool = Field(default=True)
144
+ sort_order: int = Field(default=0)
145
+
146
+ created_at: datetime = Field(default_factory=datetime.utcnow)
147
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
frontend/lib/api.ts CHANGED
@@ -207,6 +207,48 @@ export const knowledgeApi = {
207
  update: async (knowledgeId: string, data: { content?: string; category?: string }) => {
208
  const response = await api.put(`/api/v1/knowledge/${knowledgeId}`, data)
209
  return response.data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  }
211
  }
212
 
 
207
  update: async (knowledgeId: string, data: { content?: string; category?: string }) => {
208
  const response = await api.put(`/api/v1/knowledge/${knowledgeId}`, data)
209
  return response.data
210
+ },
211
+
212
+ // Payment Methods
213
+ getPaymentMethods: async () => {
214
+ const response = await api.get('/api/v1/knowledge/payment-methods')
215
+ return response.data
216
+ },
217
+
218
+ createPaymentMethod: async (data: any) => {
219
+ const response = await api.post('/api/v1/knowledge/payment-methods', data)
220
+ return response.data
221
+ },
222
+
223
+ updatePaymentMethod: async (id: string, data: any) => {
224
+ const response = await api.patch(`/api/v1/knowledge/payment-methods/${id}`, data)
225
+ return response.data
226
+ },
227
+
228
+ deletePaymentMethod: async (id: string) => {
229
+ const response = await api.delete(`/api/v1/knowledge/payment-methods/${id}`)
230
+ return response.data
231
+ },
232
+
233
+ // Knowledge Files
234
+ getKnowledgeFiles: async () => {
235
+ const response = await api.get('/api/v1/knowledge/files')
236
+ return response.data
237
+ },
238
+
239
+ createKnowledgeFile: async (data: any) => {
240
+ const response = await api.post('/api/v1/knowledge/files', data)
241
+ return response.data
242
+ },
243
+
244
+ updateKnowledgeFile: async (id: string, data: any) => {
245
+ const response = await api.patch(`/api/v1/knowledge/files/${id}`, data)
246
+ return response.data
247
+ },
248
+
249
+ deleteKnowledgeFile: async (id: string) => {
250
+ const response = await api.delete(`/api/v1/knowledge/files/${id}`)
251
+ return response.data
252
  }
253
  }
254