Source code for jitxlib.jlcpcb.export.order

"""The order sheet: what a human needs to place the order correctly.

Documentation, not a machine-readable artifact, and deliberately not a design
rule check. It reports the parameters JLCPCB's form asks you to select; the
runtime already answers whether the design meets them.
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any

from . import lock
from .bom import Line
from .components import Inventory
from .gerber import Board

FINISH = "HASL (with lead)"
"""PRELIMINARY. JITX cannot describe a surface treatment in a stackup, so
there is nothing to read off the substrate and no side channel worth inventing
for designs to adopt; see plans/stackup-revision-plan.md section 4.3. This is
JLCPCB's order-form default so that confirming the form unchanged agrees with
this sheet, and it must be checked against the live form."""

ROGERS_FINISH = "ENIG"
"""PRELIMINARY, for the same reason as `FINISH`. On a Rogers board JLCPCB's
order form allows only ENIG or OSP and selects ENIG when Rogers is chosen
(the form's own script, read 2026-11-08); their capabilities page lists
high-frequency boards among those that do not support HASL. Their
high-frequency PCB page lists ENIG as the only finish, so the two JLCPCB
sources disagree on OSP; the sheet defaults to ENIG, which both allow."""

# Copper weight is read off the material, never derived from its thickness:
# JLCPCB's half-ounce inner copper is 0.0152 mm, not half of the 0.035 mm they
# give for one ounce, so a ratio reports 0.43 oz for a half-ounce layer. See
# the note above `JLCPCBCopper` in materials.py.


[docs] @dataclass class Sheet: """Everything the order sheet reports.""" design: str inventory: Inventory lines: list[Line] board: Board substrate: Any shape: Any = None """The board outline, straight off the design. Dimensions come from here rather than from the gerber result: the shape is what the design states, and the exporter already has it."""
[docs] def write(path: Path, sheet: Sheet) -> None: path.write_text(render(sheet), encoding="utf-8")
[docs] def render(sheet: Sheet) -> str: out: list[str] = [f"# JLCPCB order sheet: {sheet.design}", ""] out += _board(sheet) out += _assembly(sheet) out += _attention(sheet) out += _missing(sheet) out += _conventions() return "\n".join(out) + "\n"
def _board(sheet: Sheet) -> list[str]: stackup = _stackup(sheet.substrate) out = ["## Board", ""] out.append(f"- Stackup: {stackup['name']}") out.append(f"- Layers: {stackup['layers']}") out += _material(stackup["rogers"]) if stackup["thickness"] is not None: out.append( f"- Thickness: {stackup['thickness']:.2f} mm including soldermask, " f"{stackup['laminate']:.2f} mm laminate and copper" ) if stackup["outer_oz"] is not None: out.append(f"- Outer copper: {stackup['outer_oz']:g} oz") if stackup["inner_oz"] is not None: out.append(f"- Inner copper: {stackup['inner_oz']:g} oz") dimensions = _dimensions(sheet.shape) if dimensions is not None: width, height = dimensions out.append(f"- Dimensions: {width:.2f} x {height:.2f} mm") else: out.append("- Dimensions: no board outline in the design") if stackup["rogers"]: out.append( f"- Surface finish: {ROGERS_FINISH} (PRELIMINARY, confirm on the " "form; JLCPCB offers only ENIG or OSP on Rogers)" ) else: out.append(f"- Surface finish: {FINISH} (PRELIMINARY, confirm on the form)") out += _rules(sheet.substrate) out.append("") return out def _material(rogers: list[float]) -> list[str]: """The base material and laminate to select for a Rogers board. `rogers` holds the thicknesses of the stackup's RO4350B layers. JLCPCB's form asks for a Rogers board's thickness as the laminate's, one of 0.51, 0.76 or 1.52 mm, rather than the finished board's, so the line says which thickness that is. An FR-4 board gets no line: its form default is FR-4. """ return [ "- Base material: Rogers, laminate RO4350B, " f"PCB thickness {thickness:.2f} mm on the form (the laminate)" for thickness in rogers ] def _dimensions(shape: Any) -> tuple[float, float] | None: """Bounding-box width and height of the board outline, in millimetres. JLCPCB's form asks for the board size and prices on it, so this is an order parameter rather than a design rule check. The bounding box is what they want even for a shaped board, since that is the panel area it occupies. """ if shape is None: return None try: min_x, min_y, max_x, max_y = shape.to_shapely().bounds except (AttributeError, ValueError): return None return max_x - min_x, max_y - min_y def _rules(substrate: Any) -> list[str]: """Priced tiers the form asks you to select, read off the fab rules.""" constraints = getattr(substrate, "constraints", None) if constraints is None: return [] out = [] drill = getattr(constraints, "min_drill_diameter", None) if drill is not None: out.append(f"- Minimum hole size: {drill:g} mm") width = getattr(constraints, "min_copper_width", None) space = getattr(constraints, "min_copper_copper_space", None) if width is not None and space is not None: out.append(f"- Minimum trace/space: {width:g} / {space:g} mm") return out def _assembly(sheet: Sheet) -> list[str]: parts = sheet.inventory.parts if not parts: return ["## Assembly", "", "- No assembly data in this packet.", ""] top = sum(1 for p in parts if p.layer == "Top") bottom = len(parts) - top tht = sum(1 for p in parts if p.through_hole) matched = sum(1 for line in sheet.lines if line.lcsc) sides = ", ".join( side for side, count in (("top", top), ("bottom", bottom)) if count ) return [ "## Assembly", "", f"- Assemble: {sides}", f"- Placements: {len(parts)} ({top} top, {bottom} bottom)", f"- Mounting: {len(parts) - tht} SMT, {tht} through-hole " "(JLCPCB prices these differently and asks which you want)", f"- BOM lines: {len(sheet.lines)}, {matched} with an LCSC part number, " f"{len(sheet.lines) - matched} needing manual matching", "- Use JLCPCB's Confirm Parts Placement preview. It is the only chance " "to catch a wrong rotation before the boards are built. Correct one " f"by editing that part's `orientation` in `{lock.BASENAME}`.", "", ] def _attention(sheet: Sheet) -> list[str]: guessed = [p.designator for p in sheet.inventory.parts if p.footprint_guessed] defaulted = [p.designator for p in sheet.inventory.parts if p.orientation_default] out: list[str] = [] if guessed: out += [ "## Footprints taken from landpattern class names", "", "JLCPCB will most likely raise a package verification warning on " "each of these, needing a click to confirm. Supply " "`LCSCPart(footprint=...)` to avoid it.", "", "- " + ", ".join(sorted(guessed)), "", ] if defaulted: out += [ "## Placed with no orientation correction", "", "JLCPCB takes a part's tape-and-reel orientation as zero, which is " "a property of the catalogue part rather than of the landpattern " "it sits on. The exporter measures that correction against the " f"catalogue footprint and records it in `{lock.BASENAME}`. These " "parts have no entry there, either because they carry no LCSC " "part number or because the measurement could not be made, so " "they are placed at the design's own rotation and may need " "turning.", "", f"Give a part an entry in `{lock.BASENAME}` to correct it:", "", "```json", '{"version": 1, "parts": {"C2286": {"orientation": 90}}}', "```", "", "Counter-clockwise degrees, added to the design's own rotation. " f"`{lock.BASENAME}` outranks `LCSCPart(orientation=...)`, so it is " "also where to correct a measured value that turns out to be " "wrong on a part that is not in this list.", "", "It is keyed by LCSC part number, so a part that has none cannot " "be corrected there and needs an `LCSCPart` on the component " "first. Note also that a two-terminal part symmetric under a half " "turn cannot be checked this way at all: it looks correct at " "either value.", "", "Check these on JLCPCB's Confirm Parts Placement preview. Their " "engineers also check polarity against the silkscreen and will " "email if they cannot judge it.", "", "- " + ", ".join(sorted(defaulted)), "", ] return out def _missing(sheet: Sheet) -> list[str]: out = ["## Not in this packet", ""] if sheet.inventory.not_soldered: out.append( "- Ordered but not placed, source these elsewhere: " + ", ".join(sorted(sheet.inventory.not_soldered)) ) out.append( "- No drill map or drill drawing. JLCPCB highly recommends one; the " "gerber exporter does not produce one yet." ) out.append("") return out def _conventions() -> list[str]: return [ "## Conventions used", "", "- Coordinates: the design origin, unshifted, matching the gerber image.", "- Positions: the landpattern origin, which is the body centre for " "standard landpatterns but may not be for connectors.", "- Rotation: degrees counter-clockwise. Bottom parts are negated " "against the design rotation, matching the KiCad plugin JLCPCB " "recommends.", "", ] def _stackup(substrate: Any) -> dict[str, Any]: """Layer count, thickness, copper weights and RO4350B laminate thicknesses, read off the stackup.""" empty = { "name": type(substrate).__name__ if substrate is not None else "unknown", "layers": "unknown", "thickness": None, "laminate": None, "outer_oz": None, "inner_oz": None, "rogers": [], } stackup = getattr(substrate, "stackup", None) if stackup is None: return empty from jitx.feature import Soldermask from jitx.inspect import decompose from jitx.stackup import Conductor, Material from ..materials import RO4350B layers = list(decompose(stackup, Material)) if not layers: return empty total = sum(layer.thickness or 0.0 for layer in layers) laminate = sum( layer.thickness or 0.0 for layer in layers if getattr(layer, "representing", None) is not Soldermask ) conductors = [layer for layer in layers if isinstance(layer, Conductor)] empty.update( { "rogers": sorted( { layer.thickness for layer in layers if isinstance(layer, RO4350B) and layer.thickness is not None } ), "layers": len(conductors), "thickness": total, "laminate": laminate, "outer_oz": _oz(conductors[0]) if conductors else None, "inner_oz": _oz(conductors[1]) if len(conductors) > 2 else None, } ) return empty def _oz(conductor: Any) -> float | None: """The copper weight a layer was ordered at, if the material states one.""" return getattr(conductor, "weight_oz", None)