<gh_stars>0
#!/usr/bin/env python3

import json, locale, sys, operator, reports, emails, os
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie


def load_data(filename):
  """Loads the contents of filename as a JSON file."""
  with open(filename) as json_file:
    data = json.load(json_file)
  return data


def format_car(car):
  """Given a car dictionary, returns a nicely formatted name."""
  return "{} {} ({})".format(
      car["car_make"], car["car_model"], car["car_year"])


def process_data(data):
  """Analyzes the data, looking for maximums.

  Returns a list of lines that summarize the information.
  """
  locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
  max_revenue = {"revenue": 0}
  max_sales = {"total_sales": 0}
  year_sales = {}
  best_year = {"Year": 0, "Sales": 0}
  for item in data:
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$"))
    item_revenue = item["total_sales"] * item_price
    item_sales = item["total_sales"]
    if item_revenue > max_revenue["revenue"]:
      item["revenue"] = item_revenue
      max_revenue = item

    # Handle max sales
    if item_sales > max_sales["total_sales"]:
        max_sales = item

    # Handle most popular car_year by getting total sales per year per car
    if item["car"]["car_year"] in year_sales.keys():
        year_sales[item["car"]["car_year"]] += item["total_sales"]
    else:
        year_sales[item["car"]["car_year"]] = item["total_sales"]

  # Handle the year with the highest sales
  best_year["Year"] = max(year_sales.items(), key=operator.itemgetter(1))[0]
  best_year["Sales"] = max(year_sales.values())

  summary = [
        "The {} generated the most revenue: ${}".format( format_car(max_revenue["car"]), max_revenue["revenue"]),

        "The {} had the most sales: {}".format(format_car(max_sales["car"]), max_sales["total_sales"]),

        "The most popular year was {} with {} sales".format(best_year["Year"], best_year["Sales"])
        ]

  return summary

def cars_dict_to_table(data):
  """Turns the data in car_data into a list of lists."""
  table_data = [["ID", "Car", "Price", "Total Sales"]]
  for item in data:
    table_data.append([item["id"], format_car(item["car"]), item["price"], str(item["total_sales"])])
  sorted_table = sorted(table_data, key=operator.itemgetter(3), reverse=True)
  return sorted_table


def main(argv):
  """Process the JSON data and generate a full report out of it."""
  data = load_data("car_sales.json")
  summary = process_data(data)
  sorted_table = cars_dict_to_table(data)

  # Turn this into a PDF report
  reports.generate("cars.pdf", "Sales Summary for last month", summary[0]+"<br/>"+ summary[1]+"<br/>"+summary[2], sorted_table, data)

  # Send the PDF report as an email attachment
  sender = "<EMAIL>"
  receiver = <EMAIL>".format(os.environ.get('USER'))
  subject = "Sales summary for last month"
  body = summary
  attachment = "cars.pdf"
  message = emails.generate(sender, receiver, subject, summary[0]+"\n"+summary[1]+"\n"+summary[2]+"\n\n", attachment)
  emails.send(message)


if __name__ == "__main__":
  main(sys.argv)

#!/usr/bin/env python3

import json, locale, sys, operator, reports, emails, os
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie


def load_data(filename):
  """Loads the contents of filename as a JSON file."""
  with open(filename) as json_file:
    data = json.load(json_file)
  return data


def format_car(car):
  """Given a car dictionary, returns a nicely formatted name."""
  return "{} {} ({})".format(
      car["car_make"], car["car_model"], car["car_year"])


def process_data(data):
  """Analyzes the data, looking for maximums.

  Returns a list of lines that summarize the information.
  """
  locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
  max_revenue = {"revenue": 0}
  max_sales = {"total_sales": 0}
  year_sales = {}
  best_year = {"Year": 0, "Sales": 0}
  for item in data:
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$"))
    item_revenue = item["total_sales"] * item_price
    item_sales = item["total_sales"]
    if item_revenue > max_revenue["revenue"]:
      item["revenue"] = item_revenue
      max_revenue = item

    # Handle max sales
    if item_sales > max_sales["total_sales"]:
        max_sales = item

    # Handle most popular car_year by getting total sales per year per car
    if item["car"]["car_year"] in year_sales.keys():
        year_sales[item["car"]["car_year"]] += item["total_sales"]
    else:
        year_sales[item["car"]["car_year"]] = item["total_sales"]

  # Handle the year with the highest sales
  best_year["Year"] = max(year_sales.items(), key=operator.itemgetter(1))[0]
  best_year["Sales"] = max(year_sales.values())

  summary = [
        "The {} generated the most revenue: ${}".format( format_car(max_revenue["car"]), max_revenue["revenue"]),

        "The {} had the most sales: {}".format(format_car(max_sales["car"]), max_sales["total_sales"]),

        "The most popular year was {} with {} sales".format(best_year["Year"], best_year["Sales"])
        ]

  return summary

def cars_dict_to_table(data):
  """Turns the data in car_data into a list of lists."""
  table_data = [["ID", "Car", "Price", "Total Sales"]]
  for item in data:
    table_data.append([item["id"], format_car(item["car"]), item["price"], str(item["total_sales"])])
  sorted_table = sorted(table_data, key=operator.itemgetter(3), reverse=True)
  return sorted_table


def main(argv):
  """Process the JSON data and generate a full report out of it."""
  data = load_data("car_sales.json")
  summary = process_data(data)
  sorted_table = cars_dict_to_table(data)

  # Turn this into a PDF report
  reports.generate("cars.pdf", "Sales Summary for last month", summary[0]+"<br/>"+ summary[1]+"<br/>"+summary[2], sorted_table, data)

  # Send the PDF report as an email attachment
  sender = "<EMAIL>"
  receiver = <EMAIL>".format(os.environ.get('USER'))
  subject = "Sales summary for last month"
  body = summary
  attachment = "cars.pdf"
  message = emails.generate(sender, receiver, subject, summary[0]+"\n"+summary[1]+"\n"+summary[2]+"\n\n", attachment)
  emails.send(message)


if __name__ == "__main__":
  main(sys.argv)
#!/usr/bin/env python3 Loads the contents of filename as a JSON file. Given a car dictionary, returns a nicely formatted name. Analyzes the data, looking for maximums.    Returns a list of lines that summarize the information. # Calculate the revenue generated by this model (price * total_sales) # We need to convert the price from "$1234.56" to 1234.56 # Handle max sales # Handle most popular car_year by getting total sales per year per car # Handle the year with the highest sales Turns the data in car_data into a list of lists. Process the JSON data and generate a full report out of it. # Turn this into a PDF report # Send the PDF report as an email attachment