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

Feat: Usage Calculator #102

Merged
merged 14 commits into from
Apr 17, 2024
Merged

Feat: Usage Calculator #102

merged 14 commits into from
Apr 17, 2024

Conversation

GuyKh
Copy link
Owner

@GuyKh GuyKh commented Apr 17, 2024

User description

What changes do you are proposing?

How did you test these changes?

Closing issues


Type

enhancement, bug_fix


Description

  • Introduced UsageCalculator with functionality to calculate electricity consumption and costs.
  • Fixed incorrect timeout handling in send_post_request method.
  • Added new constants and removed outdated kWh tariff fetching logic.
  • Enhanced iec_client.py with async file writing and usage calculator integration.
  • Implemented static data handling for usage calculator in static_data.py.
  • Added various dataclasses (Consumption, ElectricDevice, GetCalculatorResponse, Rates) to support the usage calculator functionality.

Changes walkthrough

Relevant files
Enhancement
10 files
example.py
Demonstrate UsageCalculator in Main Function                         

example.py

  • Added an example usage of UsageCalculator in the main function.
  • Demonstrated how to calculate kWh tariff, get device names, and
    calculate consumption for a specific device.
  • +43/-0   
    const.py
    Add Constant for Calculator Gadget URL                                     

    iec_api/const.py

  • Added GET_CALCULATOR_GADGET_URL constant for the new calculator gadget
    endpoint.
  • +1/-0     
    data.py
    Code Cleanup and Removal of get_kwh_tariff Function           

    iec_api/data.py

  • Removed unused import and redundant code.
  • Updated get_efs_messages to use formatted string for service code.
  • Removed get_kwh_tariff function as it's now handled in static_data.py.

  • +2/-14   
    iec_client.py
    Integrate UsageCalculator and Async File Writing                 

    iec_api/iec_client.py

  • Added get_usage_calculator method to obtain the UsageCalculator
    instance.
  • Refactored save_invoice_pdf_to_file to use aiofiles for asynchronous
    file writing.
  • Removed outdated kWh tariff fetching logic.
  • +16/-14 
    static_data.py
    Implement Static Data Handling for Usage Calculator           

    iec_api/static_data.py

  • Implemented get_usage_calculator and get_kwh_tariff functions for
    handling calculator data.
  • +19/-0   
    calculator.py
    Add UsageCalculator Class with Consumption Calculation     

    iec_api/usage_calculator/calculator.py

  • Added UsageCalculator class with methods to load data, get kWh tariff,
    device names, device info, and calculate consumption.
  • +89/-0   
    consumption.py
    Introduce Consumption Dataclass                                                   

    iec_api/usage_calculator/consumption.py

  • Introduced Consumption dataclass to represent power consumption data.
  • +17/-0   
    electric_device.py
    Define ElectricDevice Dataclass and Enums                               

    iec_api/usage_calculator/electric_device.py

  • Defined ElectricDevice dataclass and related enums for device
    information.
  • +33/-0   
    get_calculator_response.py
    Add GetCalculatorResponse Dataclass                                           

    iec_api/usage_calculator/get_calculator_response.py

  • Added GetCalculatorResponse dataclass to parse calculator gadget API
    response.
  • +14/-0   
    rates.py
    Add Rates Dataclass for Calculator                                             

    iec_api/usage_calculator/rates.py

  • Added Rates dataclass to represent calculator rates including VAT.
  • +15/-0   
    Bug fix
    1 files
    commons.py
    Fix Timeout Assignment in send_post_request                           

    iec_api/commons.py

  • Fixed a bug where timeout was incorrectly assigned to headers instead
    of being properly set.
  • +1/-1     

    PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @GuyKh GuyKh changed the title Feat: Usage Calculator Feat: Usage Calculator leftovers Apr 17, 2024
    Copy link

    what-the-diff bot commented Apr 17, 2024

    PR Summary

    • Improved Utility of The 'example.py' File
      The example.py file was updated for better usage of the UsageCalculator class. This included adding several new methods and modifying some existing logic. This will allow us to perform a range of tasks such as loading data, finding tariff information, retrieving device names and details, and calculating consumption for specific devices within a time period.

    • Bug Fix in 'commons.py' File
      There was an identified issue in the commons.py file where a timeout variable was not correctly assigned in a specific function. This problem was addressed and remedied.

    • New Feature Added in 'const.py' File
      A new feature was added into the const.py file. This new constant helps us fetch calculator gadget details efficiently.

    • Enhancements to 'data.py' File
      The data.py file was updated - a function related to getting kWh tariff information was removed and transferred to a new file static_data.py. A new function get_billing_invoices was added, which helps us fetch invoice information seamlessly.

    • Updating the 'iec_client.py' File
      In the iec_client.py file, a new method was added to retrieve the UsageCalculator class and the method to save invoice PDF was modified to perform the task asynchronously. This will help us fetch and use usage data quicker and more efficiently.

    • Addition of New File: 'static_data.py'
      A new file, named static_data.py, was introduced. It takes care of the functions for getting the kWh tariff and retrieving the UsageCalculator class, providing an organized way to access these features.

    • Introduction of New Files for 'UsageCalculator' Class Definition
      For better structure and organization, several new files such as __init__.py, calculator.py, consumption.py, electric_device.py, get_calculator_response.py, and rates.py were introduced. These files define the UsageCalculator class and related data classes for clean and efficient management of tasks related to usage calculation.

    @GuyKh GuyKh merged commit c0864cd into main Apr 17, 2024
    1 check passed
    @GuyKh GuyKh deleted the usage-calculator branch April 17, 2024 14:09
    @codiumai-pr-agent-pro codiumai-pr-agent-pro bot added enhancement New feature or request bug_fix labels Apr 17, 2024
    @codiumai-pr-agent-pro codiumai-pr-agent-pro bot changed the title Feat: Usage Calculator leftovers Feat: Usage Calculator Apr 17, 2024
    Copy link

    PR Description updated to latest commit (eed1d3c)

    Copy link

    PR Review

    ⏱️ Estimated effort to review [1-5]

    4, due to the introduction of a new feature with multiple components, including data classes, API integration, and asynchronous operations. The PR spans across several files, introducing new functionalities and modifying existing ones, which requires a thorough understanding of the existing codebase and the new feature's architecture.

    🧪 Relevant tests

    No

    🔍 Possible issues

    Possible Bug: The UsageCalculator assumes all data loading is successful without handling potential exceptions from the API call in load_data. Consider adding error handling to manage scenarios where the API call fails.

    Performance Concern: The UsageCalculator class is loaded with data every time an instance is created and load_data is called. If this class is instantiated multiple times, it could lead to unnecessary API calls. Consider implementing a caching mechanism or a singleton pattern to mitigate this.

    Data Integrity: The removal of the GET_KWH_TARIFF_URL and its associated logic in iec_api/data.py without a clear replacement in the new UsageCalculator could lead to loss of functionality unless fully replicated by the new implementation. Ensure all previous capabilities are maintained or appropriately deprecated.

    🔒 Security concerns

    No


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible PR issues, security threats and relevant test in the PR. More feedbacks can be added by configuring the tool.

    The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.

    • When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:
    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    
    [pr_reviewer]
    some_config1=...
    some_config2=...
    

    See the review usage page for a comprehensive guide on using this tool.

    Copy link

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Add exception handling for UsageCalculator operations.

    Consider handling exceptions for the UsageCalculator operations to gracefully manage
    potential runtime errors, such as connectivity issues or unexpected API changes.

    example.py [100-101]

    -usage_calculator = UsageCalculator()
    -await usage_calculator.load_data(session)
    +try:
    +    usage_calculator = UsageCalculator()
    +    await usage_calculator.load_data(session)
    +except Exception as e:
    +    logger.error(f"Failed to load usage calculator data: {e}")
    +    # Handle the error appropriately
     
    Maintainability
    Replace hardcoded device index with dynamic selection.

    Avoid hardcoding the index for selecting a device. Consider using a more dynamic approach
    to select the device, such as searching by name.

    example.py [112]

    -device_name = device_names[8]
    +device_name = next((name for name in device_names if "Air-conditioner" in name), None)
     
    Bug
    Correctly apply the timeout parameter in the post request.

    Ensure that the timeout parameter is correctly applied to the session.post call to prevent
    unintended behavior.

    iec_api/commons.py [161]

    -timeout = session.timeout
    +timeout = timeout or session.timeout
     
    Performance
    Use async file operations to avoid blocking the event loop.

    Use asynchronous file operations (aiofiles) consistently to avoid blocking the event loop,
    especially in an async function.

    iec_api/iec_client.py [256-258]

    -f = open(file_path, "wb")
    -f.write(response_bytes)
    -f.close()
    +async with aiofiles.open(file_path, "wb") as f:
    +    await f.write(response_bytes)
     
    Best practice
    Use f-strings for consistent and readable string formatting.

    Refactor the string formatting for service_code to use f-strings for consistency and
    readability.

    iec_api/data.py [160]

    -req = EfsRequestSingleService(contract_number=contract_id, process_type=1, service_code=f"EFS{service_code:03}")
    +req = EfsRequestSingleService(contract_number=contract_id, process_type=1, service_code=f"EFS{service_code:03d}")
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

    • When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:
    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    
    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    

    See the improve usage page for a comprehensive guide on using this tool.

    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.

    None yet

    1 participant