Skip to content

add platform_medium field to Conversation model #707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

milovate
Copy link
Contributor

Q/A checklist

  • If you add new dependencies, did you update the lock file?
poetry lock --no-update
  • Run tests
ulimit -n unlimited && ./scripts/run-tests.sh
  • Do a self code review of the changes - Read the diff at least twice.
  • Carefully think about the stuff that might break because of this change - this sounds obvious but it's easy to forget to do "Go to references" on each function you're changing and see if it's used in a way you didn't expect.
  • The relevant pages still run when you press submit
  • The API for those pages still work (API tab)
  • The public API interface doesn't change if you didn't want it to (check API tab > docs page)
  • Do your UI changes (if applicable) look acceptable on mobile?
  • Ensure you have not regressed the import time unless you have a good reason to do so.
    You can visualize this using tuna:
python3 -X importtime -c 'import server' 2> out.log && tuna out.log

To measure import time for a specific library:

$ time python -c 'import pandas'

________________________________________________________
Executed in    1.15 secs    fish           external
   usr time    2.22 secs   86.00 micros    2.22 secs
   sys time    0.72 secs  613.00 micros    0.72 secs

To reduce import times, import libraries that take a long time inside the functions that use them instead of at the top of the file:

def my_function():
    import pandas as pd
    ...

Legal Boilerplate

Look, I get it. The entity doing business as “Gooey.AI” and/or “Dara.network” was incorporated in the State of Delaware in 2020 as Dara Network Inc. and is gonna need some rights from me in order to utilize my contributions in this PR. So here's the deal: I retain all rights, title and interest in and to my contributions, and by keeping this boilerplate intact I confirm that Dara Network Inc can use, modify, copy, and redistribute my contributions, under its choice of terms.

Copy link

coderabbitai bot commented Jun 18, 2025

Walkthrough

A new field named platform_medium was added to the Conversation model in the bots app, implemented as a CharField with a maximum length of 32 characters, allowing blank values and defaulting to an empty string. This field uses an enumeration with choices "SMS" and "VOICE" to specify the communication medium. A database migration was created to support this addition. The TwilioSMS and TwilioVoice classes explicitly set the platform_medium to "SMS" or "VOICE" respectively when handling conversations. The build_system_vars function was updated to include platform_medium in the system variables for the Twilio platform.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 452471a and 7cf9c2a.

📒 Files selected for processing (4)
  • bots/migrations/0104_conversation_platform_medium.py (1 hunks)
  • bots/models/convo_msg.py (2 hunks)
  • daras_ai_v2/bots.py (1 hunks)
  • daras_ai_v2/twilio_bot.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • daras_ai_v2/twilio_bot.py
  • daras_ai_v2/bots.py
🧰 Additional context used
🪛 Pylint (3.3.7)
bots/migrations/0104_conversation_platform_medium.py

[refactor] 6-6: Too few public methods (0/2)

(R0903)

bots/models/convo_msg.py

[refactor] 35-35: Too few public methods (0/2)

(R0903)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: test (3.10.12, 1.8.3)
🔇 Additional comments (3)
bots/models/convo_msg.py (2)

35-37: Excellent implementation of platform medium choices.

The PlatformMedium enumeration properly addresses the previous feedback by using TextChoices to ensure data integrity and validation. The choices are clearly defined and follow Django best practices.


246-252: Perfect implementation addressing previous feedback.

The platform_medium field implementation excellently addresses the previous recommendations by using a CharField with choices for optimal data integrity, performance, and admin experience. The field configuration is appropriate for the use case.

bots/migrations/0104_conversation_platform_medium.py (1)

13-23: Migration correctly implements the improved field design.

The migration properly implements the platform_medium field using CharField with choices, effectively addressing the previous feedback about avoiding free-form text fields. The field configuration matches the model definition and ensures data quality.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Review Summary

🏷️ Draft Comments (2)

Skipped posting 2 drafted comments based on your review threshold. Feel free to update them here.

bots/models/convo_msg.py (1)

241-245: platform_medium is added as a TextField but is not included in user_id_fields, which may cause user identity logic to miss this field for new platforms using this identifier.

Scores:

  • Production Impact: 1
  • Fix Specificity: 1
  • Urgency Impact: 1
  • Total Score: 3

Reason for filtering: The commitable suggestion would break the code by attempting to redefine the user_id_fields list inside the model class after it's already defined at line 260-267. This would cause a syntax error. Additionally, the technical premise is flawed - platform_medium is described as 'Platform medium Voice / SMS' which indicates it's a communication method descriptor, not a user identifier. User identification fields should uniquely identify users, while platform_medium appears to distinguish between voice calls and SMS messages on the same platform.

Analysis: The suggestion misunderstands the purpose of platform_medium (communication method vs user identity) and provides a fix that would break the code structure by redefining an existing class attribute.


daras_ai_v2/twilio_bot.py (1)

179-179: convo.platform_medium = "Voice" in TwilioVoice.__init__ sets the attribute only on the instance, not in the database, so the value is not persisted and will be lost after the request.

Scores:

  • Production Impact: 3
  • Fix Specificity: 4
  • Urgency Impact: 3
  • Total Score: 10

Reason for filtering: This is a valid issue. The code at line 179 sets convo.platform_medium = "Voice" which only modifies the in-memory Django model instance without persisting to the database. The commitable suggestion properly adds a save() call with update_fields to persist the change, and includes a safety check with hasattr().

Analysis: This identifies a real data persistence issue where platform_medium changes are lost after request completion. The fix is specific and safe, using update_fields for efficiency and hasattr() for safety. Moderate production impact as it affects data consistency but won't cause crashes.


Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
daras_ai_v2/twilio_bot.py (1)

28-33: platform_medium in lookup will duplicate conversations

Passing platform_medium="SMS" directly to get_or_create makes it part of the lookup
criteria. Existing SMS conversations created before this change (with an empty value)
will no longer match – a new row is created every message.

-        self.convo = Conversation.objects.get_or_create(
-            bot_integration=bi,
-            twilio_phone_number=data["From"][0],
-            twilio_call_sid="",
-            platform_medium="SMS",
-        )[0]
+        self.convo, created = Conversation.objects.get_or_create(
+            bot_integration=bi,
+            twilio_phone_number=data["From"][0],
+            twilio_call_sid="",
+            defaults={"platform_medium": "SMS"},
+        )
+        if not created and self.convo.platform_medium != "SMS":
+            self.convo.platform_medium = "SMS"
+            self.convo.save(update_fields=["platform_medium"])

Prevents duplicate rows and retro-fills the new field for legacy conversations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b06798e and 294744f.

📒 Files selected for processing (4)
  • bots/migrations/0104_conversation_platform_medium.py (1 hunks)
  • bots/models/convo_msg.py (1 hunks)
  • daras_ai_v2/bots.py (1 hunks)
  • daras_ai_v2/twilio_bot.py (2 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
bots/migrations/0104_conversation_platform_medium.py

[refactor] 6-6: Too few public methods (0/2)

(R0903)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: test (3.10.12, 1.8.3)
🔇 Additional comments (3)
bots/models/convo_msg.py (1)

241-245: Prefer CharField + choices over unrestricted TextField for a finite set

platform_medium appears to take on only a handful of values ("SMS", "Voice", maybe "MMS" in future).
Using TextField (unbounded, no validation) risks accidental typos and wastes space.

-platform_medium = models.TextField(
-    blank=True,
-    default="",
-    help_text="Platform medium Voice / SMS ",
-)
+class PlatformMedium(models.TextChoices):
+    SMS = "SMS", "SMS"
+    VOICE = "Voice", "Voice"
+
+platform_medium = models.CharField(
+    max_length=10,
+    choices=PlatformMedium.choices,
+    blank=True,
+    default="",
+    help_text="Platform medium (Voice / SMS)",
+)

Keeps storage small, enforces valid values and improves admin UX.
[ suggest_optional_refactor ]

daras_ai_v2/bots.py (1)

592-593: LGTM – new variable correctly surfaced to recipes

The Twilio-only branch now exposes platform_medium; this slots neatly into the existing schema generation logic.
No further action required.

bots/migrations/0104_conversation_platform_medium.py (1)

1-20: Migration looks correct but remember to back-fill existing rows

The new column defaults to '', so historical Twilio conversations will keep an empty value.
If analytics or recipes rely on a non-empty platform_medium, consider a data-migration to set:

UPDATE bots_conversation
SET platform_medium = 'SMS'
WHERE platform = 'TWILIO' AND twilio_call_sid = '';
UPDATE bots_conversation
SET platform_medium = 'Voice'
WHERE platform = 'TWILIO' AND twilio_call_sid <> '';

(Not needed if downstream code gracefully handles empty strings.)

@milovate milovate marked this pull request as draft June 18, 2025 10:42
@milovate milovate force-pushed the convo-platform-medium branch from 294744f to 452471a Compare June 18, 2025 10:48
@milovate milovate self-assigned this Jun 18, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
bots/migrations/0104_conversation_platform_medium.py (1)

16-18: Nit: polish help text

Add parentheses or a verb for clarity.

-help_text="Platform medium Voice / SMS"
+help_text="Platform medium (Voice / SMS)"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 294744f and 452471a.

📒 Files selected for processing (4)
  • bots/migrations/0104_conversation_platform_medium.py (1 hunks)
  • bots/models/convo_msg.py (1 hunks)
  • daras_ai_v2/bots.py (1 hunks)
  • daras_ai_v2/twilio_bot.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • daras_ai_v2/bots.py
  • daras_ai_v2/twilio_bot.py
  • bots/models/convo_msg.py
🧰 Additional context used
🪛 Pylint (3.3.7)
bots/migrations/0104_conversation_platform_medium.py

[refactor] 6-6: Too few public methods (0/2)

(R0903)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (3.10.12, 1.8.3)

@milovate milovate requested review from devxpy June 18, 2025 10:55
@milovate milovate marked this pull request as ready for review June 18, 2025 10:55
@devxpy devxpy assigned devxpy and unassigned milovate Jun 19, 2025
@@ -238,6 +238,12 @@ class Conversation(models.Model):
help_text="Twilio call sid (only used if each call is a new conversation)",
)

platform_medium = models.TextField(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is best to use an integer enum (or at least a CharField with choices) for platform_medium instead of a free-form TextField.

Why:

  • Data integrity: An int enum restricts values to a known set, preventing typos and inconsistent data (e.g., 'voice', 'Voice', 'VOICE', 'sms', etc.).
  • Performance: Integer fields are more efficient for storage and queries than text fields, especially as the table grows.
  • Validation: Enums make it easy to validate and enforce allowed values at both the database and application level.
  • Admin UX: Django admin and forms will automatically provide dropdowns for enums, making it clear what values are valid.
  • Future-proofing: If you ever need to add more mediums, you can do so in a controlled way without risking legacy data issues.

A TextField allows any string, which can lead to data quality problems and makes analytics or filtering harder. Using an enum ensures consistency and reliability.

@devxpy devxpy assigned milovate and unassigned devxpy Jun 19, 2025
@milovate milovate force-pushed the convo-platform-medium branch from 452471a to 7cf9c2a Compare June 19, 2025 14:02
@milovate milovate marked this pull request as draft June 27, 2025 11:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants