Extreme Programming - Contact Management System Functional Improvement

JiayaoHu_832301310 2025-12-12 09:24:44

目录

  • Project Information
  • Project Addresses
  • GitHub Submission Log
  • Assignment Description
  • Project Summary
  • Feature Implementation
  • 1. Bookmark/Favorite Contacts
  • 2. Multiple Contact Methods
  • 3. Import and Export Functionality
  • Export Feature
  • Import Feature
  • 4. Web Interface
  • Feature Demonstration
  • 1. Application Home Page
  • 2. Contact List View
  • 3. Add New Contact Form
  • 4. Edit Contact Form
  • 5. Toggle Starred Status
  • 6. Starred Contacts Filter
  • 7. Export to Excel
  • 8. Import from Excel
  • 9. Delete Contact Confirmation
  • Project Demo Video
  • Technical Architecture
  • Database Design
  • Backend Implementation
  • Frontend Implementation
  • Key Code Explanations
  • 1. Starred Contacts Implementation
  • 2. Excel Export Functionality
  • 3. Excel Import Functionality
  • 4. Multiple Contact Methods Implementation
  • Team Collaboration
  • Division of Labor
  • Contribution Ratio
  • Challenges and Solutions
  • Jiayao Hu
  • Hantao Wu
  • PSP Tables
  • Jiayao Hu
  • Hantao Wu
  • Conclusion

Project Information

Course for This Assignment2501_MU_SE_FZU
Assignment RequirementsExtreme Programming
AuthorJiayao Hu (832301310); Hantao Wu (832302129)
Objectives of This AssignmentLearn team collaboration, practice software development lifecycle, implement full-stack web application
Other ReferencesFlask Documentation, Bootstrap Documentation, Pandas Documentation

Project Addresses

Note:
1. Please use Watt Toolkit in case that the GitHub repositories are blocked by the GFW.
2. This project site will be expired after 5/6/2026.

GitHub Submission Log

img

Assignment Description

This project implements a comprehensive Contact Management System with the following features:

  1. Bookmark/favorite contacts functionality
  2. Multiple contact methods per contact
  3. Excel import and export capabilities
  4. Web-based interface with responsive design

Project Summary

This Contact Management System is a web-based application built with Python/Flask backend and a Bootstrap frontend. It provides users with a comprehensive set of tools to manage their contacts efficiently, including bookmarking important contacts, adding multiple contact methods, and importing/exporting data in Excel format.

Feature Implementation

1. Bookmark/Favorite Contacts

The bookmarking functionality allows users to mark important contacts for quick access. Star icons are displayed next to each contact, and users can toggle the starred status with a single click.

Implementation Details:

  • Added is_starred field in the contacts table (boolean type)
  • Implemented API endpoint for toggling starred status
  • Starred contacts are displayed at the top of the contact list
  • Visual indicators show which contacts are starred

2. Multiple Contact Methods

Users can add multiple phone numbers, email addresses, and social media handles for each contact.

Implementation Details:

  • Extended database schema to support multiple contact methods
  • Created a relational structure between contacts and their methods
  • Implemented dynamic form fields in the frontend for adding multiple methods
  • API endpoints support creating, updating, and deleting individual contact methods

3. Import and Export Functionality

Export Feature

Contacts can be exported to an Excel spreadsheet with properly formatted columns for each contact attribute.

Implementation Details:

  • Used pandas library to create Excel files
  • Customized column widths for better readability
  • Included starred indicator and formatted contact details
  • Implemented as a download endpoint with proper MIME types

Import Feature

The system can import contacts from Excel files with the correct format.

Implementation Details:

  • Parsed Excel files using pandas and openpyxl
  • Validated data format before importing
  • Handled duplicate contacts gracefully
  • Batch import functionality for efficient processing

4. Web Interface

The application features a responsive web interface built with Bootstrap, providing an intuitive user experience across devices.

Key Interface Elements:

  • Contact list with search and filter capabilities
  • Add/Edit forms with validation
  • Delete confirmation dialogs
  • Toast notifications for user feedback
  • Loading indicators for async operations

Feature Demonstration

1. Application Home Page

img

The home page provides a clean, organized interface with navigation options, search functionality, and quick access to all main features. The contact list is displayed in the main content area with star indicators for bookmarked contacts.

2. Contact List View

img

All contacts are displayed in a responsive table format. Each row includes contact information, star status, and action buttons (edit, delete, star). Starred contacts appear at the top of the list for easy access.

3. Add New Contact Form

img

img

The add contact form allows users to enter basic contact information including first name, last name, category, institution, and address. The form includes validation to ensure required fields are completed. Users can add multiple phone numbers, email addresses, and social media handles for each contact. The form dynamically adds fields as needed, allowing flexible contact information management.

4. Edit Contact Form

img

img

The edit form pre-populates with existing contact information, making it easy to update details. Users can modify any field including basic information and contact methods.

5. Toggle Starred Status

img

img

Users can click the star icon next to any contact to toggle its starred status. Starred contacts are visually highlighted with a yellow star and appear at the top of the contact list.

6. Starred Contacts Filter

img

The filter option allows users to view only starred contacts, making it easy to find important contacts quickly.

7. Export to Excel

img

img

The export feature generates an Excel file with all contacts and their information properly formatted in columns. Users can download the file with a single click.

8. Import from Excel

img

img

img

Users can upload Excel files containing contact information. The system validates the data format and imports all valid contacts into the database.

9. Delete Contact Confirmation

img

A confirmation dialog appears when users attempt to delete a contact, preventing accidental deletions. Users must confirm their action before the contact is removed.

Project Demo Video

To watch the project demo video to show how this project operates, please click HERE for more information.

Technical Architecture

The system follows a client-server architecture with clear separation of concerns:

┌─────────────────┐     HTTP Requests     ┌─────────────────┐
│   Frontend                 │─────────────>│   Backend                   │
│   (HTML/CSS/JS)            │<─────────────│   (Python/Flask)            │
└─────────────────┘                       └──────────┬──────┘
                                                                         │
                                                            ┌───────▼───────┐
                                                            │  SQLite                 │
                                                            │  Database               │
                                                            └───────────────┘

Database Design

The database uses a normalized structure with two main tables:

  1. contacts table:

    • id (Primary Key)
    • first_name
    • last_name
    • category
    • institution
    • address
    • is_starred
  2. contact_methods table:

    • id (Primary Key)
    • contact_id (Foreign Key referencing contacts.id)
    • method_type (phone, email, social_media)
    • method_value
    • is_primary (boolean)

Backend Implementation

The backend is built with Flask and provides RESTful API endpoints for all contact management operations:

  • GET /contacts - Retrieve all contacts
  • POST /contacts - Create a new contact
  • PUT /contacts/{first_name}/{last_name} - Update a contact
  • DELETE /contacts/{first_name}/{last_name} - Delete a contact
  • PUT /contacts/{first_name}/{last_name}/star - Toggle starred status
  • GET /contacts/export - Export contacts to Excel
  • POST /contacts/import - Import contacts from Excel

Frontend Implementation

The frontend uses Bootstrap for responsive design and JavaScript for interactive features:

  • Dynamic contact list rendering
  • Form validation and submission
  • Real-time search and filtering
  • Toast notifications for user feedback
  • Modal dialogs for add/edit operations

Key Code Explanations

1. Starred Contacts Implementation

Backend API (App.py)

# Toggle contact starred status
@app.route('/contacts/<first_name>/<last_name>/star', methods=['PUT'])
def toggle_star(first_name, last_name):
    if address_book.toggle_starred(first_name, last_name):
        return jsonify({'message': f'Contact {first_name} {last_name} starred status toggled successfully'})
    else:
        return jsonify({'error': f'Contact {first_name} {last_name} not found'}), 404

Database Implementation (database.py)

# Update contact starred status
def toggle_starred(self, first_name, last_name):
    conn = sqlite3.connect(self.db_file)
    cursor = conn.cursor()
    
    # Get current starred status
    cursor.execute('SELECT is_starred FROM contacts WHERE first_name=? AND last_name=?', (first_name, last_name))
    row = cursor.fetchone()
    
    if not row:
        conn.close()
        return False
    
    # Toggle the status
    new_starred = 0 if row[0] else 1
    cursor.execute('UPDATE contacts SET is_starred=? WHERE first_name=? AND last_name=?', 
                  (new_starred, first_name, last_name))
    conn.commit()
    conn.close()
    return True

2. Excel Export Functionality

# Export contacts to Excel
@app.route('/contacts/export', methods=['GET'])
def export_contacts():
    contacts = address_book.load_contacts()
    
    # Convert contacts to export format
    export_data = []
    for contact in contacts:
        export_data.append({
            'Starred': '★' if contact['is_starred'] else '',
            'Name': f"{contact['first_name']} {contact['last_name']}",
            'Category': contact['category'],
            'Institution': contact['institution'],
            'Phone Number': contact['phone_number'],
            'Email': contact['email'],
            'Address': contact['address']
        })
    
    # Create DataFrame and Excel file
    df = pd.DataFrame(export_data)
    output = BytesIO()
    
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='Contact List')
        
        # Adjust column widths
        worksheet = writer.sheets['Contact List']
        worksheet.column_dimensions['A'].width = 10
        worksheet.column_dimensions['B'].width = 20
        worksheet.column_dimensions['C'].width = 15
        worksheet.column_dimensions['D'].width = 30
        worksheet.column_dimensions['E'].width = 20
        worksheet.column_dimensions['F'].width = 30
        worksheet.column_dimensions['G'].width = 40
    
    output.seek(0)
    
    # Return Excel file as response
    response = make_response(output.getvalue())
    response.headers["Content-Disposition"] = "attachment; filename=contacts_export.xlsx"
    response.headers["Content-type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    
    return response

3. Excel Import Functionality

@app.route('/contacts/import', methods=['POST'])
def import_contacts():
    if 'file' not in request.files:
        return jsonify({'success': False, 'error': 'No file part in the request'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'success': False, 'error': 'No file selected for uploading'}), 400
    
    if not (file.filename.endswith('.xlsx') or file.filename.endswith('.xls')):
        return jsonify({'success': False, 'error': 'Only Excel files (.xlsx or .xls) are allowed'}), 400
    
    try:
        df = pd.read_excel(file, header=None)
        if df.shape[1] != 8:
            return jsonify({'success': False, 'error': f'Excel file must have exactly 8 columns, but found {df.shape[1]} columns'}), 400
        contacts_data = []
        invalid_count = 0
        for index, row in df.iterrows():
            try:
                is_starred = 1 if row[0] == '★' else 0
                contact_data = {
                    'first_name': str(row[1]) if pd.notna(row[1]) else '',
                    'last_name': str(row[2]) if pd.notna(row[2]) else '',
                    'category': str(row[3]) if pd.notna(row[3]) else '',
                    'institution': str(row[4]) if pd.notna(row[4]) else '',
                    'phone_number': str(row[5]) if pd.notna(row[5]) else '',
                    'email': str(row[6]) if pd.notna(row[6]) else '',
                    'address': str(row[7]) if pd.notna(row[7]) else '',
                    'is_starred': is_starred
                }
                if not (contact_data['first_name'] or contact_data['last_name']):
                    invalid_count += 1
                    continue
                
                contacts_data.append(contact_data)
            except Exception as e:
                invalid_count += 1
                continue
        
        if contacts_data:
            if hasattr(address_book.db, 'bulk_add_contacts'):
                added_count, duplicate_contacts = address_book.db.bulk_add_contacts(contacts_data)
            else:
                added_count = 0
                duplicate_contacts = []
                for contact_data in contacts_data:
                    contact = Contacts(
                        contact_data['first_name'], 
                        contact_data['last_name'], 
                        contact_data['category'],
                        contact_data['phone_number'],
                        contact_data['email'],
                        contact_data['address'],
                        contact_data['institution'],
                        contact_data['is_starred']
                    )
                    if address_book.add_contact(contact):
                        added_count += 1
                    else:
                        duplicate_contacts.append(f"{contact_data['first_name']} {contact_data['last_name']}")
            
            return jsonify({
                'success': True,
                'imported': added_count,
                'duplicates': len(duplicate_contacts),
                'invalid': invalid_count
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': 'No valid contacts found in the Excel file'
            }), 400
            
    except Exception as e:
        print(f"Import error: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'Error processing Excel file: {str(e)}'
        }), 500

4. Multiple Contact Methods Implementation

The system allows users to store multiple contact methods per contact, including phone numbers and email addresses. Here's how this functionality is implemented:

Database Design (database.py)

def init_db(self):
    conn = sqlite3.connect(self.db_file)
    cursor = conn.cursor()

    # Create contacts table with fields for multiple contact methods
    cursor.execute("""
        CREATE TABLE contacts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            first_name TEXT NOT NULL,
            last_name TEXT NOT NULL,
            category TEXT,
            phone_number TEXT,  -- Primary phone number
            email TEXT,         -- Primary email address
            address TEXT,
            institution TEXT,
            is_starred INTEGER DEFAULT 0,
            UNIQUE(first_name, last_name)
        )
    """)
    conn.commit()
    conn.close()

Contact Model (app.py)

class Contacts:
    def __init__(self, first_name, last_name, category="", phone_number="", email="", address="", institution="", is_starred=False):
        self.first_name = first_name
        self.last_name = last_name
        self.category = category
        self.phone_number = phone_number  # Store primary phone number
        self.email = email                # Store primary email address
        self.address = address
        self.institution = institution
        self.is_starred = is_starred

    def to_dict(self):
        return {
            "first_name": self.first_name,
            "last_name": self.last_name,
            "category": self.category,
            "phone_number": self.phone_number,
            "email": self.email,
            "address": self.address,
            "institution": self.institution,
            "is_starred": self.is_starred
        }

Team Collaboration

Division of Labor

  • Jiayao Hu: Backend development, database design, Excel import/export functionality
  • Hantao Wu: Frontend development, UI/UX design, testing and debugging

Contribution Ratio

  • Jiayao Hu: 50%
  • Hantao Wu: 50%

Challenges and Solutions

Jiayao Hu

Challenge: Implementing the Excel import functionality with proper data validation
Solution: Used pandas to read the Excel file, then implemented a validation layer to check for required fields and proper data formats before inserting into the database.

Hantao Wu

Challenge: Creating a responsive design that works well on both desktop and mobile devices
Solution: Utilized Bootstrap's grid system and responsive utilities, and tested the interface on multiple device sizes to ensure consistent user experience.

PSP Tables

Jiayao Hu

TaskEstimated TimeActual TimeNotes
Project Setup0.5 hour0.5 hoursInitialized repository and virtual environment
Database Design0.5 hours0.5 hoursCreated tables and relationships for contacts and methods
Backend Implementation1 hour0.5 hoursImplemented API endpoints and business logic
Excel Import/Export0.5 hours0.5 hoursUsed pandas for file processing and validation
Testing1 hour1.5 hoursTested API endpoints and database operations
Documentation0.5 hours0.5 hoursWrote technical documentation
Total4 hours4 hours-

Hantao Wu

TaskEstimated TimeActual TimeNotes
UI Design0.5 hours0.5 hoursCreated wireframes and design mockups
Frontend Implementation1 hour0.5 hoursBuilt HTML/CSS/JS interface with Bootstrap
API Integration1 hour1 hourConnected frontend to backend APIs
Optimization0.5 hours1 hourEnsured compatibility
Testing & Debugging0.5 hours0.5 hoursTested user workflows and interface
Documentation0.5 hours0.5 hoursCreated user documentation and blog content
Total4 hours4 hours-

Conclusion

This Contact Management System successfully implements all the required features, providing users with a robust tool for managing their contacts. The project demonstrates effective team collaboration, proper software engineering practices, and the ability to integrate multiple technologies to create a functional application.

Key achievements include:

  • Fully implemented bookmarking functionality for quick access to important contacts
  • Support for multiple contact methods per contact
  • Excel import/export capabilities for data management
  • Responsive web interface with intuitive user experience

Future enhancements could include user authentication, contact groups, and more advanced search capabilities.


If you like this project, please give it 5 stars for this blog and on GitHub, and donate a few to give us great support and confidence in the coming software development.

...全文
71 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

164

社区成员

发帖
与我相关
我的任务
社区描述
2501_MU_SE_FZU
软件工程 高校
社区管理员
  • FZU_SE_LQF
  • 助教_林日臻
  • 朱仕君
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧