Skip to content
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

CCCT-469 || HQ User Invite Connect #2927

Open
wants to merge 22 commits into
base: connect_qa
Choose a base branch
from

Conversation

j13panchal
Copy link

@j13panchal j13panchal commented Dec 19, 2024

https://dimagi.atlassian.net/browse/CCCT-469

Summary

Introduces deep linking for SMS messages that invite ConnectID users to join an HQ domain. The SMS message contains a link with the required info, and when the user clicks on the link the CommCare app is configured to override the action and open the app on a special page instead of opening the link in a web browser.

The new "HQ User Invite" page shows the user info about the HQ domain and allows them to accept or decline the invitation.

cross-request: dimagi/commcare-core#1455

Release Note:
ConnectID users can now receive and accept invitations to HQ domains sent to the user's phone via SMS.

Feature Flag

Connect

Product Description

SMS invitation to HQ domain contains a link with relevant information.
Clicking on link opens CommCare to a page showing the invitation.
The user is provided options to accept or decline the invitation.

PR Checklist

  • If I think the PR is high risk, "High Risk" label is set
  • I have confidence that this PR will not introduce a regression for the reasons below
  • [ x ] Do we need to enhance manual QA test coverage ? If yes, "QA Note" label is set correctly
  • [ x ] Does the PR introduce any major changes worth communicating ? If yes, "Release Note" label is set and a "Release Note" is specified in PR description.

Automated test coverage

No automated tests for Connect yet.

Safety story

Possible error situations that need to be handled:

  • CommCare app is not installed
  • ConnectID not configured on the device
  • SMS does not include correct parameters (artificial/malicious use)
  • User fails to unlock ConnectID
  • Accepting invitation fails (i.e. bad network connection)

Working on HQ user Invitation API integration
Set deep-linking code
Update update invitation logic
Update API logic
Add connect-ID not configure scenario
Set connect user name from url
Set get data from query params instead of URL
Solved user not found issue
Working on API issue
Set loader while API call
Copy link

coderabbitai bot commented Dec 19, 2024

📝 Walkthrough

Walkthrough

This pull request introduces significant enhancements to the CommCare application, focusing on user invitations to the CommCareHQ project domain. Key modifications include the addition of a new HQUserInviteActivity in the AndroidManifest.xml, which specifies new permissions for media access and notifications, as well as the declaration of a new activity and service. A corresponding layout file, activity_hquser_invite.xml, has been created to facilitate the invitation process interface. Localization support is expanded with new string resources added for both French and Portuguese languages, improving user interaction related to invitations. The HQUserInviteActivity.java manages the invitation workflow, including user verification and API interactions, while the ApiConnectId.java class introduces a new method for processing user invitations. These changes collectively enhance the application's functionality regarding user management and invitations.

Possibly related PRs

  • Update component exported attribute #2930: The changes in the main PR are related to the modifications in the AndroidManifest.xml file, specifically regarding the addition of new activities and permissions, which aligns with the updates to exported attributes and permissions in the retrieved PR.
  • CCCT-485 || Connect Messaging Implementation Part-1 #2870: The changes in the main PR, specifically the addition of the HQUserInviteActivity and its associated layout, are directly related to the modifications in the AndroidManifest.xml file of the retrieved PR, which also includes activity declarations and permission adjustments, indicating a focus on user invitation functionalities.

Suggested reviewers

  • shubham1g5

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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

@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: 4

🧹 Nitpick comments (7)
app/src/org/commcare/activities/connect/HQUserInviteActivity.java (2)

86-98: Use descriptive listener method naming
When associating click listeners, consider using clearer method names or lambda expressions with descriptive comments to clarify each button's purpose. This promotes readability and maintainability.


148-155: Potential for centralized error-handling
This method sets an error message UI element. If multiple error states occur in the activity, you might centralize error handling logic (e.g., a dedicated utility method or a shared handler) to streamline user-facing messages and reduce code duplication.

app/res/layout/activity_hquser_invite.xml (2)

1-8: Consider adding accessibility attributes
Ensure that components in this ConstraintLayout have content descriptions or talkback hints for screen readers, especially for any images or interactive elements.


100-112: Progress indicators
Since the ProgressBar is shown after the user clicks "Accept Invitation" or triggers an API call, ensure it’s also hidden if the user navigates back or if an error occurs before the API response. This helps avoid stale loading indicators.

app/res/values-fr/strings.xml (1)

308-313: Review correctness of newly added strings
These invitation-related strings appear clear and contextually correct. Ensure styling is consistent for language-specific formatting, including punctuation and spacing (e.g., “dabord” vs. “d’abord”). Minor grammar improvements can enhance user clarity.

app/AndroidManifest.xml (1)

Line range hint 426-433: Consider adding exported attribute to PaymentAcknowledgeReceiver

The PaymentAcknowledgeReceiver should explicitly declare its exported status for security clarity.

-<receiver android:name="org.commcare.services.PaymentAcknowledgeReceiver" />
+<receiver 
+    android:name="org.commcare.services.PaymentAcknowledgeReceiver"
+    android:exported="false" />
app/res/values/strings.xml (1)

45-45: Consider making the URL configurable per environment

The hardcoded URL might cause issues when switching between environments (staging/production).

Consider moving this to a configuration file or making it environment-aware:

-<string name="ConnectConfirmUserInvitation">https://connectid.dimagi.com/users/confirm_hq_invite</string>
+<string name="ConnectConfirmUserInvitation">@string/connect_base_url/users/confirm_hq_invite</string>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dfb5d64 and 0c8f519.

📒 Files selected for processing (7)
  • app/AndroidManifest.xml (2 hunks)
  • app/res/layout/activity_hquser_invite.xml (1 hunks)
  • app/res/values-fr/strings.xml (1 hunks)
  • app/res/values-pt/strings.xml (1 hunks)
  • app/res/values/strings.xml (2 hunks)
  • app/src/org/commcare/activities/connect/HQUserInviteActivity.java (1 hunks)
  • app/src/org/commcare/connect/network/ApiConnectId.java (9 hunks)
🔇 Additional comments (6)
app/src/org/commcare/activities/connect/HQUserInviteActivity.java (2)

52-72: Validate user identity logic
When verifying the current user (lines 57-60), consider providing a user-friendly message/logging if an unexpected user mismatch occurs, especially if user records in local storage could be outdated or corrupted.


157-169: Finalize activity result workflows
Currently, onActivityResult immediately finishes the activity (lines 166-167). This approach may not notify upstream logic about the outcome if external callbacks or post-processing are needed. Confirm that finishing immediately is the desired flow.

app/res/layout/activity_hquser_invite.xml (1)

33-48: Maintain consistent text sizing
The “roundButtonTextSize” attribute uses a relatively small “6sp”. Confirm that this is legible on all devices. If not, consider sizing up to improve readability.

app/AndroidManifest.xml (1)

Line range hint 25-32: LGTM: Permission changes follow Android best practices

The permission changes properly handle:

  • Media permissions for Android 13+ (READ_MEDIA_*)
  • Notification permission for Android 13+
  • Storage permissions correctly scoped with maxSdkVersion=32
app/res/values-pt/strings.xml (1)

575-582: LGTM: Portuguese translations are complete and accurate

All new strings for the HQ user invitation feature are properly translated to Portuguese.

app/res/values/strings.xml (1)

879-885: LGTM: Invitation strings are complete

The new strings for HQ user invitation provide clear messaging for all user scenarios.

app/src/org/commcare/connect/network/ApiConnectId.java Outdated Show resolved Hide resolved
Comment on lines +137 to +151
<activity
android:name="org.commcare.activities.connect.HQUserInviteActivity"
android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:scheme="https"/>
<data android:host="connectid.dimagi.com"/>
<data android:scheme="http"/>
<data android:host="connectid.dimagi.com"/>
</intent-filter>
</activity>
Copy link

@coderabbitai coderabbitai bot Dec 19, 2024

Choose a reason for hiding this comment

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

💡 Codebase verification

Additional security measures recommended for deep link handling

Based on the code analysis, while the activity implements basic deep link handling, several security improvements are needed:

  1. The activity accepts and processes deep link parameters without any validation of the callback_url parameter, which could lead to potential security vulnerabilities
  2. No null checks are performed on required parameters before processing the invitation
  3. The activity accepts both HTTP and HTTPS schemes without enforcing HTTPS-only communication
  4. No validation exists for the domain of callback URLs to ensure they match expected patterns

Recommended actions:

  • Add URL validation for the callback_url parameter to ensure it points to trusted domains
  • Implement null/empty checks for all required parameters (callback_url, invite_code, etc.)
  • Consider removing the HTTP scheme from the intent filter to enforce secure communications
  • Add path patterns to the intent filter to restrict the accepted URLs to specific endpoints
🔗 Analysis chain

Verify security measures for exported activity handling deep links

The exported activity with deep link handling requires careful security review:

  1. Ensure proper validation of incoming deep link data
  2. Verify that android:autoVerify="true" is intended as it allows automatic verification of deep links
  3. Consider adding intent filters for specific paths rather than allowing all paths
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for URL validation in HQUserInviteActivity
ast-grep --pattern 'class HQUserInviteActivity {
  $$$
  getIntent() {
    $$$
  }
  $$$
}'

Length of output: 93


Script:

#!/bin/bash
# Search for HQUserInviteActivity implementation
fd -e java -e kt "HQUserInviteActivity" --exec cat {}

# Search for URL/URI validation patterns in the activity
rg -l "HQUserInviteActivity" | xargs rg -A 5 "getIntent|getData|parse.*Uri|validate"

Length of output: 7692


Script:

#!/bin/bash
# Check if ConnectManager performs any validation
rg -A 10 "class ConnectManager" 

# Check ApiConnectId implementation for security measures
rg -A 10 "hqUserInvitation.*callback" 

# Look for any URL validation utilities
rg -l "validateUrl|validateUri|isValidUrl|isValidUri"

Length of output: 3910

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree that this is a concern and think we should probably improve both the intent filter and the data validation

Copy link

Choose a reason for hiding this comment

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

@OrangeAndGreen Here are specific recommendations for both areas:

  1. Intent Filter Improvements:
<activity android:name="org.commcare.activities.connect.HQUserInviteActivity"
    android:exported="true">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        
        <!-- Remove HTTP, use only HTTPS -->
        <data android:scheme="https" />
        <data android:host="connectid.dimagi.com" />
        <!-- Add specific paths -->
        <data android:pathPattern="/users/confirm_hq_invite" />
    </intent-filter>
</activity>
  1. Data Validation Improvements:
private void validateAndProcessIntent() {
    Intent intent = getIntent();
    Uri data = intent.getData();
    if (data == null) {
        setErrorMessage("Invalid invitation link");
        return;
    }

    // Validate callback URL
    callBackURL = data.getQueryParameter("callback_url");
    if (callBackURL == null || !isValidCallbackUrl(callBackURL)) {
        setErrorMessage("Invalid callback URL");
        return;
    }

    // Validate required parameters
    username = data.getQueryParameter("hq_username");
    inviteCode = data.getQueryParameter("invite_code");
    domain = data.getQueryParameter("hq_domain");
    connectUserName = data.getQueryParameter("connect_username");

    if (username == null || inviteCode == null || 
        domain == null || connectUserName == null) {
        setErrorMessage("Missing required parameters");
        return;
    }

    handleButtons();
}

private boolean isValidCallbackUrl(String url) {
    try {
        Uri uri = Uri.parse(url);
        String host = uri.getHost();
        return host != null && 
               (host.equals("commcare.dimagi.com") || 
                host.endsWith(".commcare.dimagi.com"));
    } catch (Exception e) {
        return false;
    }
}
  1. Additional Security Measures:
  • Add HTTPS validation for callback URL
  • Implement rate limiting for invitation attempts
  • Add logging for security-related events
  • Consider adding signature verification for the invite parameters

Would you like me to provide more detailed implementation for any of these areas?

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check current implementation of HQUserInviteActivity
fd -e java -e kt "HQUserInviteActivity" --exec cat {}

# Look for any existing URL validation utilities
rg -l "validateUrl|validateUri|isValidUrl|isValidUri"

# Check if there are any similar activities with URL validation
rg -A 10 "android.intent.action.VIEW.*connectid.dimagi.com"

# Check for any existing security utilities
fd -e java -e kt "security|util|validation" --exec rg -l "validate|verify|check"

Length of output: 7592


✏️ Learnings added
Learnt from: OrangeAndGreen
PR: dimagi/commcare-android#2927
File: app/AndroidManifest.xml:151-165
Timestamp: 2025-02-04T19:06:14.404Z
Learning: The HQUserInviteActivity should validate all deep link parameters (callback_url, hq_username, invite_code, hq_domain, connect_username) before processing the invitation. The callback URL should be restricted to trusted domains (commcare.dimagi.com).

Learnt from: OrangeAndGreen
PR: dimagi/commcare-android#2927
File: app/AndroidManifest.xml:151-165
Timestamp: 2025-02-04T19:06:14.404Z
Learning: Deep link intent filters for connectid.dimagi.com should use HTTPS scheme only and specify exact pathPatterns to prevent malicious deep link handling.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor

Choose a reason for hiding this comment

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

I do agree with the suggestions here.

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@shubham1g5
Copy link
Contributor

shubham1g5 commented Jan 8, 2025

@j13panchal Would you be able to take a pass on coderabbit comments here to save time on manual review. You can reply to on those threads if you think the comments are not necessarily applicable here.

Can we also add a feature demo in Product Description section of PR template to showcase what's being achieved in this PR.

@shubham1g5 shubham1g5 added the skip-integration-tests Skip android tests. label Jan 9, 2025
@OrangeAndGreen
Copy link
Contributor

@damagatchi retest this please

@OrangeAndGreen
Copy link
Contributor

@coderabbitai review

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: 0

🧹 Nitpick comments (1)
app/src/org/commcare/activities/connect/HQUserInviteActivity.java (1)

96-146: Enhance error message clarity.

The error messages could be more user-friendly. For example, "Error requesting SMS code(%d)" doesn't provide clear guidance to users.

Consider using more descriptive error messages:

-                setErrorMessage("Error requesting SMS code" + message);
+                setErrorMessage(getString(R.string.error_invitation_failed, message));

Add to strings.xml:

<string name="error_invitation_failed">Failed to process invitation. Please try again. Error: %s</string>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c8f519 and 6bec357.

📒 Files selected for processing (7)
  • app/AndroidManifest.xml (3 hunks)
  • app/res/layout/activity_hquser_invite.xml (1 hunks)
  • app/res/values-fr/strings.xml (1 hunks)
  • app/res/values-pt/strings.xml (1 hunks)
  • app/res/values/strings.xml (2 hunks)
  • app/src/org/commcare/activities/connect/HQUserInviteActivity.java (1 hunks)
  • app/src/org/commcare/connect/network/ApiConnectId.java (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • app/res/layout/activity_hquser_invite.xml
  • app/src/org/commcare/connect/network/ApiConnectId.java
  • app/res/values-fr/strings.xml
  • app/res/values-pt/strings.xml
  • app/res/values/strings.xml
🧰 Additional context used
📓 Learnings (2)
app/src/org/commcare/activities/connect/HQUserInviteActivity.java (1)
Learnt from: OrangeAndGreen
PR: dimagi/commcare-android#2927
File: app/src/org/commcare/activities/connect/HQUserInviteActivity.java:0-0
Timestamp: 2025-02-04T15:29:12.993Z
Learning: In HQUserInviteActivity, parameters from Intent data (domain, inviteCode, username, etc.) are required and the code is designed to fail immediately if they're missing, rather than adding null checks. This helps catch integration issues early.
app/AndroidManifest.xml (1)
Learnt from: OrangeAndGreen
PR: dimagi/commcare-android#2927
File: app/src/org/commcare/activities/connect/HQUserInviteActivity.java:0-0
Timestamp: 2025-02-04T15:29:12.993Z
Learning: In HQUserInviteActivity, parameters from Intent data (domain, inviteCode, username, etc.) are required and the code is designed to fail immediately if they're missing, rather than adding null checks. This helps catch integration issues early.
🔇 Additional comments (5)
app/src/org/commcare/activities/connect/HQUserInviteActivity.java (2)

34-52: LGTM! Fail-fast parameter handling.

The implementation correctly follows the fail-fast approach for required parameters, as confirmed by the learnings.


54-74: LGTM! Clear button handling logic.

The implementation correctly manages button states based on token presence and user verification.

app/AndroidManifest.xml (3)

30-32: LGTM! Required permissions for Android 13+.

The new permissions are correctly added to support:

  • Media access (replacing READ_EXTERNAL_STORAGE)
  • Notification posting

Also applies to: 40-40


587-593: LGTM! Secure Firebase service configuration.

The service is correctly configured:

  • Non-exported for security
  • Proper intent filter for Firebase messaging

151-165: 🛠️ Refactor suggestion

Remove HTTP scheme for secure deep linking.

The activity allows both HTTP and HTTPS schemes. For security:

  1. Remove the HTTP scheme to enforce secure communications
  2. Add path patterns to restrict accepted URLs

Apply this diff:

             <intent-filter android:autoVerify="true">
                 <action android:name="android.intent.action.VIEW" />

                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.BROWSABLE" />

                 <data android:scheme="https"/>
                 <data android:host="connectid.dimagi.com"/>
-                <data android:scheme="http"/>
-                <data android:host="connectid.dimagi.com"/>
+                <data android:pathPattern="/hq/invite/.*"/>
             </intent-filter>
⛔ Skipped due to learnings
Learnt from: OrangeAndGreen
PR: dimagi/commcare-android#2927
File: app/src/org/commcare/activities/connect/HQUserInviteActivity.java:0-0
Timestamp: 2025-02-04T15:29:12.993Z
Learning: In HQUserInviteActivity, parameters from Intent data (domain, inviteCode, username, etc.) are required and the code is designed to fail immediately if they're missing, rather than adding null checks. This helps catch integration issues early.

Comment on lines +137 to +151
<activity
android:name="org.commcare.activities.connect.HQUserInviteActivity"
android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:scheme="https"/>
<data android:host="connectid.dimagi.com"/>
<data android:scheme="http"/>
<data android:host="connectid.dimagi.com"/>
</intent-filter>
</activity>
Copy link
Contributor

Choose a reason for hiding this comment

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

I agree that this is a concern and think we should probably improve both the intent filter and the data validation

try {
String responseAsString = new String(StreamsUtil.inputStreamToByteArray(responseData));
if (responseAsString.length() > 0) {
startActivity(new Intent(HQUserInviteActivity.this, DispatchActivity.class));
Copy link
Contributor

Choose a reason for hiding this comment

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

What should happen when the user accepts the invitation? Seems like ideally we would take them to install an app next, but currently this just launches DispatchActivity and lets it make the call (login page).

Copy link
Contributor

Choose a reason for hiding this comment

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

I would think user should land in some sort of connect workflow that initiates the app install if needed (I would think the install should happen only when they claim an opportunity). Would you be able to describe the user story here more in the PR description. For eg. It's not entirely clear to me when this feature will get used as a whole or when will someone invite a connect user to a project space and what we want to achive with it ?

Added some missing string translations.
@@ -22,6 +22,7 @@
<string name="ConnectClaimJobURL">https://%s/api/opportunity/%d/claim</string>
<string name="ConnectDeliveriesURL">https://%s/api/opportunity/%d/delivery_progress</string>
<string name="ConnectPaymentConfirmationURL">https://%s/api/payment/%s/confirm</string>
<string name="ConnectConfirmUserInvitation">https://connectid.dimagi.com/users/confirm_hq_invite</string>
Copy link
Contributor

Choose a reason for hiding this comment

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

Is it possible to define only the relative url to host ? That makes the code more felxible in event we want to have configurable hosts or test environments.

private void setButtonVisibility(boolean visible) {
binding.btnAcceptInvitation.setVisibility(visible ? View.VISIBLE : View.GONE);
binding.btnDeniedInvitation.setVisibility(visible ? View.VISIBLE : View.GONE);
binding.btnGoToRecovery.setVisibility(visible ? View.GONE : View.VISIBLE);
Copy link
Contributor

Choose a reason for hiding this comment

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

we want to show the recovery button even when the user is incorrect ?

}

private void handleInvitation(String callBackUrl, String inviteCode) {
Logger.log("HQInvite", "User accepted invitation");
Copy link
Contributor

Choose a reason for hiding this comment

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

Use constants for Log Types otherwise we risk having a lot of different scattered categories in logs. You can add a connect specific class to signify logtypes like ConnectLogTypes if it's easier.

try {
String responseAsString = new String(StreamsUtil.inputStreamToByteArray(responseData));
if (responseAsString.length() > 0) {
startActivity(new Intent(HQUserInviteActivity.this, DispatchActivity.class));
Copy link
Contributor

Choose a reason for hiding this comment

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

I would think user should land in some sort of connect workflow that initiates the app install if needed (I would think the install should happen only when they claim an opportunity). Would you be able to describe the user story here more in the PR description. For eg. It's not entirely clear to me when this feature will get used as a whole or when will someone invite a connect user to a project space and what we want to achive with it ?

};
ConnectUserRecord user = ConnectManager.getUser(this);
binding.progressBar.setVisibility(View.VISIBLE);
boolean isBusy = !ApiConnectId.hqUserInvitation(HQUserInviteActivity.this,user.getUserId(),user.getPassword(), callBackUrl, inviteCode, callback);
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: formatting is off


public static void reportHQInvitationResponse(String hqDomain, boolean accepted, String method) {
reportEvent(CCAnalyticsEvent.HQ_INVITE_LINK_RESPONSE,
new String[]{CCAnalyticsParam.CCHQ_DOMAIN, CCAnalyticsParam.ACCEPTED,
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: better to use FirebaseAnalytics.Param.VALUE to signify success as 0 or 1 . That lets us do a simple AVG() operation to get the success rate across events.

CCAnalyticsParam.CCHQ_DOMAIN, hqDomain);
}

public static void reportHQInvitationResponse(String hqDomain, boolean accepted, String method) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I see that we are sending errors for the method parameter. Is that intentional ? If so we should rename the parameter as reason to signify the fail reason.

Comment on lines +132 to +141
public void processNetworkFailure() {
binding.progressBar.setVisibility(View.GONE);
setErrorMessage(getString(R.string.recovery_network_unavailable));
}

@Override
public void processOldApiError() {
binding.progressBar.setVisibility(View.GONE);
setErrorMessage(getString(R.string.recovery_network_outdated));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

should not we be logging reportHQInvitationResponse here as well ?

@Override
public void processFailure(int responseCode, IOException e) {
FirebaseAnalyticsUtil.reportHQInvitationResponse(domain, false, "API error");
Logger.log("HQInvite", "Acceptance failed");
Copy link
Contributor

Choose a reason for hiding this comment

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

probably log the IOException as Logger.exception() instead if it's not happening in the network layer itself.


@Override
public void processFailure(int responseCode, IOException e) {
FirebaseAnalyticsUtil.reportHQInvitationResponse(domain, false, "API error");
Copy link
Contributor

Choose a reason for hiding this comment

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

Instead of using a loose string "API Error", we should use constants for different possible failure causes, This should also log the response code if available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants