#!/usr/bin/env python3
"""Orchestrate the end-to-end application workflow.
Sequential model calls share one cached context prefix (highlights, STARs,
background, cover-letter examples, writing style, and — in Drive mode — the
customized resume). The offline path (``skip_drive=True``) produces local
artifacts and is fully exercised by tests; the Drive path adds Google I/O.
Drive folder per application (``YYYY-MM-DD - Company - Role``) contains exactly:
the README (Google Doc), the JD (``JD_<Company>_<Role>.pdf``), the resume (the
customized Google Doc), and the cover letter (Google Doc).
"""
import dataclasses as dcs
import json
import logging
import re
import shutil
import sys
import tempfile
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Any, Optional
from jobjob.ailib.session import AIClient
from jobjob.apply.generate.archetype import select_template
from jobjob.apply.generate.ats import assess_ats
from jobjob.apply.generate.coverletter import generate_cover_letter_text
from jobjob.apply.generate.highlights import select_highlights
from jobjob.apply.generate.parse import parse_job_description
from jobjob.apply.generate.readme import assess_fit, generate_application_readme
from jobjob.apply.generate.resume import tailor_resume
from jobjob.apply.generate.skills import analyze_skills
from jobjob.apply.output.cover_letter_docx import create_cover_letter_docx
from jobjob.apply.output.cover_letter_pdf import create_cover_letter_pdf
from jobjob.classify.classify import JD, classify_file
from jobjob.gapi import drive as gdrive
from jobjob.gapi.docs import get_document, verify_page_count
from jobjob.gapi.service import build_docs_service, build_drive_service
from jobjob.loader.auth import get_google_credentials
from jobjob.loader.loadcontent import load_highlights, load_skills, load_templates
from jobjob.loader.loadreference import load_reference_documents
from jobjob.storage.base import archive_timestamp
from jobjob.storage.drive import DriveStorageAdapter
from jobjob.storage.local import LocalStorageAdapter
from jobjob.structure.applicant import Applicant, first_last_name
from jobjob.structure.fit import fit_summary
from jobjob.structure.highlight import Highlight, HighlightSet
from jobjob.structure.job_decription import JobDescription
from jobjob.structure.reference import ReferenceDocs
from jobjob.structure.template import ResumeTemplate
RESUME_NAME = "Resume"
COVER_LETTER_NAME = "CoverLetter"
README_NAME = "README"
SKILLS_NAME = "skills_analysis.json"
SUMMARY_NAME = "summary.json"
def _artifact_names(applicant_name: Optional[str]) -> tuple[str, str]:
"""Return ``(resume_name, cover_letter_name)`` for this applicant.
Submitted artifacts (résumé + cover letter only — design D8) are named
``FirstLast_Resume`` / ``FirstLast_CoverLetter``; an applicant with no
derivable name falls back to the bare ``Resume``/``CoverLetter`` names used
historically. README/JD/JSON sidecars are unaffected and keep their names.
"""
first_last = first_last_name(applicant_name)
if not first_last:
return RESUME_NAME, COVER_LETTER_NAME
return f"{first_last}_{RESUME_NAME}", f"{first_last}_{COVER_LETTER_NAME}"
[docs]
def build_cached_context(
highlight_set: HighlightSet,
reference: ReferenceDocs,
resume_text: Optional[str] = None,
) -> str:
"""Assemble the stable, cached system context shared across all calls.
NOTE: order matters for prompt caching — stable content first; the resume
(added in Drive mode) goes last as it is the most volatile prefix piece.
Arguments:
highlight_set: All available highlights.
reference: Loaded reference documents.
resume_text: Customized resume text, if available.
Returns:
The cached-context string.
"""
parts = []
highlights_text = "\n".join(
f"- {h.context}: {h.text}" for h in highlight_set.highlights
)
parts.append(f"=== AVAILABLE RESUME HIGHLIGHTS ===\n{highlights_text}")
if reference.background:
parts.append(f"=== BACKGROUND INFORMATION ===\n{reference.background}")
if reference.star_examples:
parts.append(
f"=== DETAILED EXPERIENCE (STAR FORMAT) ===\n{reference.star_examples}"
)
if reference.cover_letter_examples:
parts.append(
"=== EXAMPLE COVER LETTERS (FOR TONE AND VOICE) ===\n"
f"{reference.cover_letter_examples}"
)
if reference.writing_style:
parts.append(
"=== WRITING STYLE GUIDE ===\n"
"Follow these guidelines for voice, style, and mechanics:\n\n"
f"{reference.writing_style}"
)
if resume_text:
parts.append(f"=== MY RESUME (CUSTOMIZED FOR THIS ROLE) ===\n{resume_text}")
return "\n\n".join(parts)
# summary.json format version; bump only on a breaking shape change. No reader
# migration exists yet — the file is written fresh on every run rather than
# read back and updated in place.
_SUMMARY_SCHEMA_VERSION = 1
def _write_summary(output_dir: Path, results: dict) -> Path:
path = Path(output_dir, SUMMARY_NAME)
payload = {"schema_version": _SUMMARY_SCHEMA_VERSION, **results}
path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
return path
def _identity_services():
"""Best-effort import of the webapp backend's identity-tier services.
jobjob core does not depend on the webapp backend as a normal import (the
dependency runs the other way — see ``webapp/backend/main.py``), but the two
ship side by side (dev checkout and the built wheel both put ``webapp/backend``
beside the ``jobjob`` package; see the pyproject force-include and
``jobjob.launcher``'s identical ``sys.path`` trick). Loaded lazily and
defensively so a build never fails when the backend layout is unusual —
callers treat ``(None, None)`` as "identity bookkeeping unavailable" and skip
it, logging rather than raising.
Returns:
``(application_metadata, application_source)`` modules, or ``(None, None)``.
"""
backend_dir = Path(__file__).resolve().parents[2] / "webapp" / "backend"
if backend_dir.is_dir() and str(backend_dir) not in sys.path:
sys.path.insert(0, str(backend_dir))
try:
from services import application_metadata, application_source
except ImportError:
return None, None
return application_metadata, application_source
# A URL-captured JD snapshot (jobjob.ingest.jd_source.write_snapshot) leads with a
# "<!-- source: URL -->" provenance comment; a paste snapshot or PDF drop has none.
_SNAPSHOT_SOURCE_RE = re.compile(r"^<!--\s*source:\s*(\S+)\s*-->", re.MULTILINE)
def _infer_web_uri(job_description_pdf: Path) -> Optional[str]:
"""Best-effort: recover the source URL from a URL-captured JD snapshot.
Only ``.md`` snapshots can carry the provenance comment (a PDF drop has no
such thing); anything else (wrong suffix, unreadable/binary content) degrades
to None. This is advisory identity metadata, never required for the build to
succeed.
"""
path = Path(job_description_pdf)
if path.suffix.lower() != ".md":
return None
try:
head = path.read_text(encoding="utf-8")[:500]
except (OSError, UnicodeDecodeError):
return None
match = _SNAPSHOT_SOURCE_RE.search(head)
return match.group(1) if match else None
[docs]
class OverwriteConflict(Exception):
"""A fresh apply would overwrite an existing application folder.
Raised when processing a new JD whose target ``Company - Role`` folder already
exists and the caller did not opt into overwriting. The webapp surfaces this so
the user can relaunch with override (acknowledge) or clear the queued JD.
Attributes:
folder_name: The conflicting ``Company - Role`` folder name.
"""
def __init__(self, folder_name: str) -> None:
self.folder_name = folder_name
super().__init__(
f"An application folder already exists for '{folder_name}'. "
"Relaunch with override to overwrite, or clear the queued JD."
)
[docs]
def run_application_workflow(
job_description_pdf: Path,
*,
query_service: AIClient,
applicant: Applicant,
output_dir: Optional[Path] = None,
skip_drive: bool = False,
highlight_set: Optional[HighlightSet] = None,
reference: Optional[ReferenceDocs] = None,
use_cache: bool = True,
template_id: Optional[str] = None,
template_name: Optional[str] = None,
parent_id: Optional[str] = None,
reuse_folder_id: Optional[str] = None,
allow_overwrite: bool = False,
archive_on_conflict: bool = False,
industry: Optional[str] = None,
applications_output_dir: Optional[Path] = None,
entity_dir: Optional[Path] = None,
logger: logging.Logger | None = None,
_credentials_loader: Callable[..., Any] = get_google_credentials,
_drive_builder: Callable[..., Any] = build_drive_service,
_docs_builder: Callable[..., Any] = build_docs_service,
) -> dict:
"""Run the full application workflow and return a results dict.
Arguments:
job_description_pdf: Path to the job-description PDF.
query_service: AIClient (callable + cached context + usage).
applicant: Applicant identity (for cover-letter headers).
output_dir: Local output directory. Used as-is only as a last-resort
fallback (legacy/offline: no ``applications_output_dir`` and no
``entity_dir`` configured); defaults to a fresh temp directory in
that case. Superseded by the entity-folder resolution below.
skip_drive: If True, skip all Google Drive/Docs operations.
highlight_set: Highlights. Loaded from static content if None.
reference: Reference docs. Loaded from static reference if None.
use_cache: Whether the model calls consult/populate the response cache.
template_id: Fallback resume-template Google Doc id when no templates.toml.
template_name: Explicit template name; if None the archetype is auto-detected.
parent_id: Applications-root folder id (Drive mode).
reuse_folder_id: Existing Drive folder id to update in place (re-process mode).
allow_overwrite: Proceed past a name collision with an existing execution
(Drive folder and/or local entity folder) instead of raising
``OverwriteConflict``. Overwrite-in-place stays the default flow.
archive_on_conflict: When ``allow_overwrite`` is set and a prior execution
is found at the resolved entity folder (Drive and/or local), move its
current root artifacts into ``archive/<timestamp>/`` first instead of
overwriting them in place. Ignored when there is no prior execution.
industry: Optional domain/industry context for the active profile, passed to
the resume-objective prompt so the company is described accurately.
applications_output_dir: Root of the local Drive-mirror of application
folders. A build materializes ``<root>/<Company - Role>`` under it and
places **all** of this execution's artifacts there (identity files
and local artifacts alike) — the single entity folder design D7/D2
describe. Superseded by ``entity_dir`` when given.
entity_dir: Explicit persistent entity folder, overriding the resolution
from ``applications_output_dir``. Used by a re-run of a possibly-renamed
application to target the existing folder so its entity_id is reused
and no overwrite guard applies (this is the local-path equivalent of
``reuse_folder_id``).
logger: Optional logger for injection.
_credentials_loader: Injection point for Google credentials (testing).
_drive_builder: Injection point for the Drive service builder (testing).
_docs_builder: Injection point for the Docs service builder (testing).
Returns:
A dict of produced paths/ids, job info, and token usage.
Raises:
OverwriteConflict: A fresh (non-reuse) build resolves to an entity folder
(Drive and/or the local mirror) that already holds a prior execution,
and neither ``allow_overwrite`` is set.
"""
_logger = logger or logging.getLogger(__name__)
results: dict = {}
# Step 1: parse JD (no cached context yet).
_logger.info("Parsing job description: %s", job_description_pdf)
job = parse_job_description(
Path(job_description_pdf), query_service, use_cache=use_cache
)
results["job_info"] = dcs.asdict(job)
_logger.info("Parsed: %s / %s", job.company_name, job.role_title)
# Resolve the ONE entity/output root (design D7): identity (metadata.json /
# source.json) and every local artifact this execution produces land in the
# same directory — a build no longer splits them across an ephemeral
# output_dir and a separately-resolved identity folder. Precedence:
# entity_dir (explicit re-run target; skips the overwrite guard below,
# mirroring reuse_folder_id on the Drive side)
# > applications_output_dir / <Company - Role> (fresh build into the mirror
# — this is the path the overwrite guard protects)
# > output_dir (legacy/offline fallback: CLI with no mirror configured)
# > a fresh tempdir
mirror_resolved = entity_dir is None and applications_output_dir is not None
if entity_dir is not None:
output_dir = Path(entity_dir)
elif mirror_resolved:
output_dir = Path(applications_output_dir) / gdrive.application_folder_name(
job.company_name, job.role_title
)
else:
output_dir = (
Path(output_dir)
if output_dir
else Path(tempfile.mkdtemp(prefix="job_app_"))
)
output_dir.mkdir(parents=True, exist_ok=True)
results["output_dir"] = str(output_dir)
folder_name = gdrive.application_folder_name(job.company_name, job.role_title)
local_storage = LocalStorageAdapter(output_dir)
archive_ts = archive_timestamp()
# Local-path overwrite guard (generalizes the Drive-only OverwriteConflict
# check to the filesystem side of a build): a fresh build into the mirror
# (not an explicit entity_dir reuse target) that lands on a folder already
# holding a prior execution (summary.json — its birth certificate) must not
# silently clobber it without the caller opting in. Only applies to the
# mirror-resolved path; the legacy output_dir-only fallback keeps its
# existing (no-guard) behavior, matching the CLI's plain re-run flow.
if mirror_resolved and local_storage.exists(SUMMARY_NAME):
if not allow_overwrite:
raise OverwriteConflict(folder_name)
if archive_on_conflict:
local_storage.archive_execution(archive_ts)
resume_name, cover_letter_name = _artifact_names(applicant.name)
highlight_set = highlight_set or load_highlights()
reference = reference or load_reference_documents()
context = build_cached_context(highlight_set, reference)
query_service.set_cached_context(context)
_logger.info("Cached context: %d characters", len(context))
# Step 2: select highlights.
selected = select_highlights(job, highlight_set, query_service, use_cache=use_cache)
results["highlights"] = [h.context for h in selected]
_logger.info("Selected %d highlights", len(selected))
resume_text = None
drive_service = None
folder_id = None
resume_doc = None
if not skip_drive:
template = _select_resume_template(
job, query_service, template_id, template_name, use_cache
)
results["template"] = template.name
_logger.info("Selected resume template: %s", template.name)
resume_text, drive_service, folder_id, resume_doc = _run_drive_resume_steps(
job=job,
output_dir=output_dir,
resume_name=resume_name,
query_service=query_service,
highlight_set=highlight_set,
reference=reference,
template=template,
selected_highlights=selected,
parent_id=parent_id,
reuse_folder_id=reuse_folder_id,
allow_overwrite=allow_overwrite,
archive_on_conflict=archive_on_conflict,
archive_ts=archive_ts,
use_cache=use_cache,
industry=industry,
results=results,
logger=_logger,
_credentials_loader=_credentials_loader,
_drive_builder=_drive_builder,
_docs_builder=_docs_builder,
)
# Step 3: cover letter (text + local PDF always; DOCX is either the local
# artifact (skip_drive) or a scratch upload payload converted to a Google Doc
# (Drive mode) — Drive mode does not also keep the DOCX locally, since the
# gdoc *is* the artifact (no local-docx-plus-gdoc duplication).
letter = generate_cover_letter_text(
job, selected, query_service, applicant, use_cache=use_cache
)
pdf_path = create_cover_letter_pdf(
letter,
Path(output_dir, f"{cover_letter_name}.pdf"),
role_title=job.role_title,
company_name=job.company_name,
applicant=applicant,
)
results["cover_letter_pdf"] = str(pdf_path)
scratch_dir = (
Path(tempfile.mkdtemp(prefix="job_app_scratch_")) if not skip_drive else None
)
docx_dest = (
Path(scratch_dir, f"{cover_letter_name}.docx")
if scratch_dir
else Path(output_dir, f"{cover_letter_name}.docx")
)
docx_path = create_cover_letter_docx(
letter,
docx_dest,
role_title=job.role_title,
company_name=job.company_name,
applicant=applicant,
)
if skip_drive:
results["cover_letter_docx"] = str(docx_path)
# Step 4: skills analysis (folded into the README, kept locally as data).
skills = analyze_skills(job, query_service, use_cache=use_cache)
skills_path = Path(output_dir, SKILLS_NAME)
skills_path.write_text(json.dumps(skills, indent=2), encoding="utf-8")
results["skills_analysis"] = str(skills_path)
# Step 4b: ATS assessment of the rendered resume (advisory; None doc =>
# skipped section). Uses the declared skills file as the recommendation
# allowlist -- honesty layer.
try:
skill_set = load_skills(logger=_logger)
except (OSError, ValueError) as exc:
_logger.warning("Skills file unavailable for ATS assessment: %s", exc)
skill_set = None
ats = assess_ats(resume_doc, job, skills, skill_set=skill_set, logger=_logger)
results["ats_coverage"] = ats.coverage_score
# Fit is computed once here so the machine-readable summary block and the
# README render the same assessment.
fit = assess_fit(skills, logger=_logger)
results["fit"] = fit_summary(fit)
# Step 5: README (summary + folded skills + fit + ATS). Same scratch-vs-local
# split as the cover letter: Drive mode uploads it as a Google Doc and does
# not keep the local .docx.
readme_dest = (
Path(scratch_dir, f"{README_NAME}.docx")
if scratch_dir
else Path(output_dir, f"{README_NAME}.docx")
)
readme_path = generate_application_readme(
job,
skills,
readme_dest,
issues=results.get("issues"),
template_name=results.get("template"),
template_archetype=results.get("template_archetype"),
resume_changes=results.get("resume_changes"),
ats=ats,
fit=fit,
)
if skip_drive:
results["readme"] = str(readme_path)
# Copy the JD into the output directory as JD_<Company>_<Role><ext> (PascalCase).
# The source suffix is preserved so a text/Markdown snapshot (URL/paste capture)
# stays a snapshot rather than being mislabeled .pdf.
jd_name = (
f"JD_{gdrive.pascal_case(job.company_name)}_"
f"{gdrive.pascal_case(job.role_title)}"
)
jd_copy = Path(output_dir, f"{jd_name}{Path(job_description_pdf).suffix}")
# NOTE: in re-process mode the input IS this file; don't copy it onto itself.
if Path(job_description_pdf).resolve() != jd_copy.resolve():
shutil.copy2(job_description_pdf, jd_copy)
results["job_description_pdf"] = str(jd_copy)
if not skip_drive:
_upload_outputs(
drive_service=drive_service,
folder_id=folder_id,
readme_path=readme_path,
jd_copy=jd_copy,
cover_letter_docx=docx_path,
cover_letter_name=cover_letter_name,
logger=_logger,
)
# NOTE: no results["readme"]/["cover_letter_docx"] path in Drive mode — the
# gdoc uploaded above IS the artifact; the scratch .docx used to build it
# is discarded rather than also kept as a redundant local copy.
shutil.rmtree(scratch_dir, ignore_errors=True)
usage = getattr(query_service, "usage", None)
if usage is not None:
results["token_usage"] = dcs.asdict(usage)
_logger.info("%s", usage.summary())
# Identity core (application-identity, phase 1): mint/reuse this application's
# entity_id and write its parse-once source fields. ``output_dir`` IS the
# entity folder now (the resolution above), so identity and artifacts always
# share one location — no separate id_dir resolution needed here. Best-effort
# throughout — a read-only dir or an unavailable backend leaves the folder
# legacy (id-less) for this run rather than failing the build.
app_metadata, app_source = _identity_services()
if app_metadata is not None and app_source is not None:
try:
entity_id = app_metadata.ensure_entity_id(output_dir)
results["entity_id"] = entity_id
app_source.ensure_source(
output_dir,
entity_id=entity_id,
company=job.company_name,
role=job.role_title,
description=job.summary,
file_uri=results.get("job_description_pdf"),
web_uri=_infer_web_uri(job_description_pdf),
)
except (
Exception
) as exc: # noqa: BLE001 — identity bookkeeping must never fail a build.
_logger.warning("Could not record application identity: %s", exc)
_write_summary(output_dir, results)
return results
def _select_resume_template(
job: JobDescription,
query_service: AIClient,
template_id: Optional[str],
template_name: Optional[str],
use_cache: bool,
) -> ResumeTemplate:
"""Select the resume template, raising if none is configured."""
template_set = load_templates(fallback_doc_id=template_id)
template = select_template(
job, template_set, query_service, name=template_name, use_cache=use_cache
)
if template is None:
raise ValueError(
"No resume template configured. Add static/content/templates.toml or "
"set RESUME_TEMPLATE_ID."
)
return template
def _run_drive_resume_steps(
job: JobDescription,
output_dir: Path,
resume_name: str,
query_service: AIClient,
highlight_set: HighlightSet,
reference: ReferenceDocs,
template: ResumeTemplate,
selected_highlights: Iterable[Highlight],
parent_id: Optional[str],
reuse_folder_id: Optional[str],
allow_overwrite: bool,
archive_on_conflict: bool,
archive_ts: str,
use_cache: bool,
results: dict,
logger: logging.Logger,
_credentials_loader: Callable[..., Any],
_drive_builder: Callable[..., Any],
_docs_builder: Callable[..., Any],
industry: Optional[str] = None,
) -> tuple[Optional[str], Any, Optional[str]]:
"""Authenticate, find/create the folder, copy and tailor the resume template.
Returns:
``(resume_text, drive_service, folder_id)`` for downstream uploads.
"""
logger.info("Authenticating with Google")
creds = _credentials_loader()
drive_service = _drive_builder(creds)
docs_service = _docs_builder(creds)
if reuse_folder_id:
folder_id = reuse_folder_id
logger.info("Reusing existing Drive folder: %s", folder_id)
else:
# A fresh apply must not silently overwrite an existing application. Reuse
# (reprocess) goes through reuse_folder_id; an explicit override opts in,
# and archive_on_conflict additionally moves the prior execution's Drive
# docs into archive/<timestamp>/ (move-by-id — revision history survives)
# instead of letting the new build overwrite them in place.
existing = gdrive.find_application_folder(
drive_service, job.company_name, job.role_title, parent_id=parent_id
)
if existing:
if not allow_overwrite:
raise OverwriteConflict(
gdrive.application_folder_name(job.company_name, job.role_title)
)
if archive_on_conflict:
DriveStorageAdapter(
drive_service, existing, logger=logger
).archive_execution(archive_ts)
folder_id = gdrive.create_application_folder(
drive_service,
job.company_name,
job.role_title,
parent_id=parent_id,
logger=logger,
)
results["folder_id"] = folder_id
resume_id = gdrive.copy_resume_template(
drive_service, folder_id, template.doc_id, name=resume_name, logger=logger
)
results["resume_id"] = resume_id
results["template_archetype"] = template.archetype
# Tailor the copied template to the role: rewrite the objective and replace the
# Key Career Highlights within their configured sections, recording each edit for
# the application summary and any skipped sections as issues for the README. Only
# enabled sections are tailored; a disabled section is left untouched (its edit is
# simply omitted, so no anchor is searched for).
enabled_sections = tuple(s for s in template.sections if s.enabled)
resume_text, results["resume_changes"], resume_issues = tailor_resume(
docs_service,
resume_id,
job,
selected_highlights,
query_service,
sections=enabled_sections,
use_cache=use_cache,
industry=industry,
logger=logger,
)
if resume_issues:
results.setdefault("issues", []).extend(resume_issues)
# Refresh the cached context to include the tailored resume for later calls.
query_service.set_cached_context(
build_cached_context(highlight_set, reference, resume_text=resume_text)
)
# Quality guard: the resume should fit one page-budget (default 3). Records the
# result and logs a warning when exceeded so it can be caught before sending.
results["resume_within_page_limit"] = verify_page_count(
docs_service, resume_id, logger=logger
)
# NOTE: export a local PDF copy of the resume; the Drive artifact is the Doc.
resume_pdf = gdrive.export_doc_as_pdf(
drive_service, resume_id, Path(output_dir, f"{resume_name}.pdf"), logger=logger
)
results["resume_pdf"] = str(resume_pdf)
# One structural fetch of the updated doc serves the ATS assessment (text
# for keyword coverage, structure for parseability). Best-effort: the
# assessment degrades to skipped rather than failing the application.
resume_doc = None
try:
resume_doc = get_document(docs_service, resume_id)
except Exception as exc: # noqa: BLE001 — assessment is advisory.
logger.warning("Could not fetch resume doc for ATS assessment: %s", exc)
return resume_text, drive_service, folder_id, resume_doc
def _upload_outputs(
drive_service: Any,
folder_id: Optional[str],
readme_path: Path,
jd_copy: Path,
cover_letter_docx: Path,
cover_letter_name: str,
logger: logging.Logger,
) -> None:
"""Upload the README, JD, and cover letter to the application's Drive folder.
NOTE: the resume Google Doc is already in the folder (the template copy), so
the four folder artifacts are README + JD + resume + cover letter. The
JD copy is placed via the storage adapter (a plain file, dispatched the
same way a local-only build would place it); README/cover letter go
through the Docs-specific upload helpers directly, since converting a
.docx into an editable Google Doc in place isn't a plain-file operation.
"""
if drive_service is None or folder_id is None:
return # EARLY EXIT: nothing to upload.
gdrive.upload_docx_as_google_doc(
drive_service, readme_path, folder_id, README_NAME, logger=logger
)
DriveStorageAdapter(drive_service, folder_id, logger=logger).place(
jd_copy, jd_copy.name
)
gdrive.upload_docx_as_google_doc(
drive_service, cover_letter_docx, folder_id, cover_letter_name, logger=logger
)
[docs]
def move_completed_jd(
src: Path,
data_dir: Path,
folder_name: str,
logger: logging.Logger | None = None,
) -> Path:
"""Move a processed JD into ``<data_dir>/completed/jobs/<folder_name><ext>``.
Called on a successful application so the JD leaves the input area — the same
behavior for the CLI and the webapp. Renamed to match the Drive folder.
Arguments:
src: The processed job-description file.
data_dir: Root holding ``jobs/``/``completed/``.
folder_name: Drive application folder name (``YYYY-MM-DD - Company - Role``).
logger: Optional logger for injection.
Returns:
The new path.
"""
_logger = logger or logging.getLogger(__name__)
src = Path(src)
dest_dir = Path(data_dir) / "completed" / "jobs"
dest_dir.mkdir(parents=True, exist_ok=True)
dest = dest_dir / f"{folder_name}{src.suffix}"
src.rename(dest)
_logger.info("Moved JD to completed: %s", dest)
return dest
# __END__