sku_catalog 1.2.0
sku_catalog: ^1.2.0 copied to clipboard
A catalog model for physical parts: SKUs with traits and typed attributes, assemblies of SKUs, manufacturers, places, and the instances that instantiate them.
example/sku_catalog_example.dart
// A runnable tour of the package: classify, value, assemble, place,
// instantiate, fold.
//
// It ships with a tiny in-memory backend so you can see the whole shape at
// once. Copy it as a starting point, or implement the same contracts over your
// own store — the use cases cannot tell the difference.
//
// dart run example/sku_catalog_example.dart
import 'package:fpdart/fpdart.dart';
import 'package:sku_catalog/sku_catalog.dart';
Future<void> main() async {
final traits = _Table<Trait>(
Trait.fromJson,
(t) => t.meta.id,
(t) => t.toJson(),
);
final attributes = _Table<TraitAttributeDefinition>(
TraitAttributeDefinition.fromJson,
(a) => a.meta.id,
(a) => a.toJson(),
);
final skus = _Table<Sku>(Sku.fromJson, (s) => s.meta.id, (s) => s.toJson());
final assemblies = _Table<SkuComponent>(
SkuComponent.fromJson,
(c) => c.meta.id,
(c) => c.toJson(),
);
final locates = _Table<Locate>(
Locate.fromJson,
(l) => l.meta.id,
(l) => l.toJson(),
);
final instances = _Table<Instance>(
Instance.fromJson,
(d) => d.meta.id,
(d) => d.toJson(),
);
final traitRepository = _Traits(traits);
final attributeRepository = _Attributes(attributes);
final skuRepository = _Skus(skus);
final assemblyRepository = _Components(assemblies);
final locateRepository = _Locates(locates);
final instanceRepository = _Instances(instances);
// 1. Classify. Traits form a tree: Breaker is a Switch with more to say.
final switchTrait = Trait(
meta: _meta('switch'),
name: 'Switch',
scope: const [TraitScope.sku],
);
final breakerTrait = Trait(
meta: _meta('breaker'),
name: 'Breaker',
parentTraitId: switchTrait.meta.id,
scope: const [TraitScope.sku],
);
await CreateTrait(traitRepository)(trait: switchTrait).run();
await CreateTrait(traitRepository)(trait: breakerTrait).run();
// 2. Value: each trait contributes typed fields, and a child overrides them.
await CreateTraitAttributeDefinition(attributeRepository)(
attribute: TraitAttributeDefinition(
meta: _meta('switch-rated_amps'),
traitId: switchTrait.meta.id,
key: 'rated_amps',
displayLabel: 'Rated Amperage',
dataType: DataType.number,
unit: 'A',
isRequired: true,
),
).run();
await CreateTraitAttributeDefinition(attributeRepository)(
attribute: TraitAttributeDefinition(
meta: _meta('breaker-trip_amperage'),
traitId: breakerTrait.meta.id,
key: 'trip_amperage',
displayLabel: 'Trip Amperage',
dataType: DataType.number,
unit: 'A',
),
).run();
// 3. Catalogue the SKUs. A panel and a breaker are both products.
final breakerModel = Sku(
meta: _meta('qo120'),
manufacturerId: 'square-d',
modelNumber: 'QO120',
traitIds: [breakerTrait.meta.id],
attributeValues: const {'rated_amps': 20, 'trip_amperage': 20},
);
final panelModel = Sku(
meta: _meta('qo-16'),
manufacturerId: 'square-d',
modelNumber: 'QO-16',
);
await CreateSku(skuRepository)(sku: breakerModel).run();
await CreateSku(skuRepository)(sku: panelModel).run();
final subPanelModel = Sku(
meta: _meta('qo-4'),
manufacturerId: 'square-d',
modelNumber: 'QO-4',
);
await CreateSku(skuRepository)(sku: subPanelModel).run();
// 4. Assemble: the panel holds eight breakers and four sub-panels, and each
// sub-panel holds four breakers — so a build consumes the breaker two
// ways. On purpose the edge is then tried the other way round, to show the
// cycle guard refuse it.
final addComponent = AddSkuComponent(
repository: assemblyRepository,
skuRepository: skuRepository,
);
await addComponent(
parentSkuId: panelModel.meta.id,
childSkuId: breakerModel.meta.id,
quantity: 8,
).run();
await addComponent(
parentSkuId: panelModel.meta.id,
childSkuId: subPanelModel.meta.id,
quantity: 4,
).run();
await addComponent(
parentSkuId: subPanelModel.meta.id,
childSkuId: breakerModel.meta.id,
quantity: 4,
).run();
final loop = await addComponent(
parentSkuId: breakerModel.meta.id,
childSkuId: panelModel.meta.id,
quantity: 1,
).run();
// 5. Place: a Locate is a place, and places nest. The panel goes in a room.
final garage = Locate(meta: _meta('garage'), name: 'Garage');
final panelPlace = Locate(
meta: _meta('garage.panel'),
name: 'Panel Position',
parentLocateId: garage.meta.id,
);
await CreateLocate(locateRepository)(locate: garage).run();
await CreateLocate(locateRepository)(locate: panelPlace).run();
// 6. Instantiate: an instance is one article of a SKU, at one place.
final panelInstance = Instance(
meta: _meta('pnl-1'),
skuId: panelModel.meta.id,
locateId: panelPlace.meta.id,
name: 'Garage Panel 1',
);
await CreateInstance(instanceRepository)(instance: panelInstance).run();
// 7. Ask the model what it knows. Traits inherit, so the breaker's schema
// carries Switch's attributes too.
final schema = await ResolveSchema(
traitRepository: traitRepository,
attributeRepository: attributeRepository,
)(traitIds: breakerModel.traitIds).run();
final schemaLine = schema.fold(
(failure) => 'failed: ${failure.message}',
(resolved) => resolved
.map((a) => '${a.name}${a.def.unit == null ? '' : ' (${a.def.unit})'}')
.join(', '),
);
final partsCount = await FetchComponentsBySku(assemblyRepository)(
skuId: panelModel.meta.id,
).run();
final breakersDirect = partsCount.fold(
(failure) => '?',
(rows) =>
'${rows.firstWhere((c) => c.childSkuId == breakerModel.meta.id).quantity}',
);
final subPanelsDirect = partsCount.fold(
(failure) => '?',
(rows) =>
'${rows.firstWhere((c) => c.childSkuId == subPanelModel.meta.id).quantity}',
);
final instancesAtPlace = await FetchInstancesByLocate(instanceRepository)(
locateId: panelPlace.meta.id,
).run();
print(
'SKU ${panelModel.modelNumber} — holds $breakersDirect × '
'${breakerModel.modelNumber} directly, plus $subPanelsDirect × '
'${subPanelModel.modelNumber}',
);
print('Schema ${breakerModel.modelNumber} → $schemaLine');
print(
'Place ${garage.name} / ${panelPlace.name} → '
'${instancesAtPlace.fold((f) => '?', (rows) => rows.single.name)}',
);
print(
'Assembly panel in breaker? '
'${loop.fold((failure) => 'refused (${failure.message})', (_) => 'allowed — BUG')}',
);
// 8. Fold: what does a build of two panels consume? This is not resolution —
// that merges the layers describing one thing. This folds the tree that
// builds one thing: quantities multiply down the levels, and the breaker,
// reached directly and through a sub-panel, is one line with the total.
final bom = await AggregateBillOfMaterials(
skuRepository: skuRepository,
skuComponentRepository: assemblyRepository,
)(skuId: panelModel.meta.id, units: 2).run();
final bomLine = bom.fold(
(failure) => 'failed: ${failure.message}',
(bill) => bill.lines
.map(
(line) =>
'${line.quantity} × ${line.modelNumber} '
'(level ${line.depth}${line.isAssembly ? ', itself an assembly' : ''})',
)
.join(', '),
);
print('Parts 2 × ${panelModel.modelNumber} → $bomLine');
// 9. An instance carries its own classification and values, independent of the
// model it came from — which is what lets one SKU be wired two ways.
final spare = panelInstance.copyWith(
name: 'Spare Panel',
locateId: null,
traitIds: const ['spare'],
attributeValues: const {'note': 'not yet fitted'},
);
print('Instance ${spare.name} is placed? ${spare.isPlaced}');
}
Meta _meta(String id) => Meta(
id: id,
notes: '',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
);
/// A trivial map-backed store, enough to demonstrate the contracts.
class _Table<T> {
_Table(this.decode, this.idOf, this.encode);
final T Function(Map<String, dynamic>) decode;
final String Function(T) idOf;
final Map<String, dynamic> Function(T) encode;
final Map<String, Map<String, dynamic>> rows = {};
Iterable<Map<String, dynamic>> all() => rows.values;
void put(T entity) => rows[idOf(entity)] = encode(entity);
bool remove(String id) => rows.remove(id) != null;
T get(String id) => decode(rows[id]!);
bool has(String id) => rows.containsKey(id);
}
class _Traits implements ITraitRepository {
_Traits(this.table);
final _Table<Trait> table;
@override
TaskEither<DomainFailure, List<Trait>> fetchAll() =>
TaskEither.of(table.all().map(Trait.fromJson).toList());
@override
TaskEither<DomainFailure, Trait> fetchById({required String id}) =>
table.has(id)
? TaskEither.of(table.get(id))
: _missing<Trait>('Trait', id);
@override
TaskEither<DomainFailure, Trait> create({
required Trait trait,
IUnitOfWork? uow,
}) {
table.put(trait);
return TaskEither.of(trait);
}
@override
TaskEither<DomainFailure, Trait> update({
required Trait trait,
IUnitOfWork? uow,
}) => create(trait: trait);
@override
TaskEither<DomainFailure, void> delete({
required String id,
IUnitOfWork? uow,
}) {
table.remove(id);
return TaskEither.of(null);
}
@override
TaskEither<DomainFailure, void> clearAll({IUnitOfWork? uow}) {
table.rows.clear();
return TaskEither.of(null);
}
}
class _Attributes implements ITraitAttributeDefinitionRepository {
_Attributes(this.table);
final _Table<TraitAttributeDefinition> table;
@override
TaskEither<DomainFailure, List<TraitAttributeDefinition>> fetchAll() =>
TaskEither.of(
table.all().map(TraitAttributeDefinition.fromJson).toList(),
);
@override
TaskEither<DomainFailure, List<TraitAttributeDefinition>> fetchByTrait({
required String traitId,
}) => TaskEither.of(
table
.all()
.map(TraitAttributeDefinition.fromJson)
.where((a) => a.traitId == traitId)
.toList(),
);
@override
TaskEither<DomainFailure, TraitAttributeDefinition> fetchById({
required String id,
}) => table.has(id)
? TaskEither.of(table.get(id))
: _missing<TraitAttributeDefinition>('Attribute', id);
@override
TaskEither<DomainFailure, TraitAttributeDefinition> create({
required TraitAttributeDefinition attribute,
IUnitOfWork? uow,
}) {
table.put(attribute);
return TaskEither.of(attribute);
}
@override
TaskEither<DomainFailure, TraitAttributeDefinition> update({
required TraitAttributeDefinition attribute,
IUnitOfWork? uow,
}) => create(attribute: attribute);
@override
TaskEither<DomainFailure, void> delete({
required String id,
IUnitOfWork? uow,
}) {
table.remove(id);
return TaskEither.of(null);
}
@override
TaskEither<DomainFailure, void> clearAll({IUnitOfWork? uow}) {
table.rows.clear();
return TaskEither.of(null);
}
}
class _Skus implements ISkuRepository {
_Skus(this.table);
final _Table<Sku> table;
@override
TaskEither<DomainFailure, List<Sku>> fetchAll() =>
TaskEither.of(table.all().map(Sku.fromJson).toList());
@override
TaskEither<DomainFailure, Sku> fetchById({required String id}) =>
table.has(id) ? TaskEither.of(table.get(id)) : _missing<Sku>('SKU', id);
@override
TaskEither<DomainFailure, Sku> create({required Sku sku, IUnitOfWork? uow}) {
table.put(sku);
return TaskEither.of(sku);
}
@override
TaskEither<DomainFailure, Sku> update({required Sku sku, IUnitOfWork? uow}) =>
create(sku: sku);
@override
TaskEither<DomainFailure, void> delete({
required String id,
IUnitOfWork? uow,
}) {
table.remove(id);
return TaskEither.of(null);
}
@override
TaskEither<DomainFailure, void> clearAll({IUnitOfWork? uow}) {
table.rows.clear();
return TaskEither.of(null);
}
}
class _Components implements ISkuComponentRepository {
_Components(this.table);
final _Table<SkuComponent> table;
@override
TaskEither<DomainFailure, List<SkuComponent>> fetchAll() =>
TaskEither.of(table.all().map(SkuComponent.fromJson).toList());
@override
TaskEither<DomainFailure, List<SkuComponent>> fetchBySku({
required String skuId,
}) => TaskEither.of(
table
.all()
.map(SkuComponent.fromJson)
.where((c) => c.parentSkuId == skuId)
.toList(),
);
@override
TaskEither<DomainFailure, SkuComponent> fetchById({required String id}) =>
table.has(id)
? TaskEither.of(table.get(id))
: _missing<SkuComponent>('Assembly edge', id);
@override
TaskEither<DomainFailure, SkuComponent> create({
required SkuComponent component,
IUnitOfWork? uow,
}) {
table.put(component);
return TaskEither.of(component);
}
@override
TaskEither<DomainFailure, void> delete({
required String id,
IUnitOfWork? uow,
}) {
table.remove(id);
return TaskEither.of(null);
}
@override
TaskEither<DomainFailure, void> clearAll({IUnitOfWork? uow}) {
table.rows.clear();
return TaskEither.of(null);
}
}
class _Locates implements ILocateRepository {
_Locates(this.table);
final _Table<Locate> table;
@override
TaskEither<DomainFailure, List<Locate>> fetchAll() =>
TaskEither.of(table.all().map(Locate.fromJson).toList());
@override
TaskEither<DomainFailure, Locate> fetchById({required String id}) =>
table.has(id)
? TaskEither.of(table.get(id))
: _missing<Locate>('Locate', id);
@override
TaskEither<DomainFailure, Locate> create({
required Locate locate,
IUnitOfWork? uow,
}) {
table.put(locate);
return TaskEither.of(locate);
}
@override
TaskEither<DomainFailure, Locate> update({
required Locate locate,
IUnitOfWork? uow,
}) => create(locate: locate);
@override
TaskEither<DomainFailure, void> delete({
required String id,
IUnitOfWork? uow,
}) {
table.remove(id);
return TaskEither.of(null);
}
@override
TaskEither<DomainFailure, void> clearAll({IUnitOfWork? uow}) {
table.rows.clear();
return TaskEither.of(null);
}
}
class _Instances implements IInstanceRepository {
_Instances(this.table);
final _Table<Instance> table;
@override
TaskEither<DomainFailure, List<Instance>> fetchAll() =>
TaskEither.of(table.all().map(Instance.fromJson).toList());
@override
TaskEither<DomainFailure, List<Instance>> fetchByLocate({
required String locateId,
}) => TaskEither.of(
table
.all()
.map(Instance.fromJson)
.where((d) => d.locateId == locateId)
.toList(),
);
@override
TaskEither<DomainFailure, Instance> fetchById({required String id}) =>
table.has(id)
? TaskEither.of(table.get(id))
: _missing<Instance>('Instance', id);
@override
TaskEither<DomainFailure, Instance> create({
required Instance instance,
IUnitOfWork? uow,
}) {
table.put(instance);
return TaskEither.of(instance);
}
@override
TaskEither<DomainFailure, Instance> update({
required Instance instance,
IUnitOfWork? uow,
}) => create(instance: instance);
@override
TaskEither<DomainFailure, void> delete({
required String id,
IUnitOfWork? uow,
}) {
table.remove(id);
return TaskEither.of(null);
}
@override
TaskEither<DomainFailure, void> clearAll({IUnitOfWork? uow}) {
table.rows.clear();
return TaskEither.of(null);
}
}
TaskEither<DomainFailure, T> _missing<T>(String what, String id) =>
TaskEither<DomainFailure, T>.left(NotFoundFailure('$what "$id" not found'));